Example usage for java.lang Float MIN_VALUE

List of usage examples for java.lang Float MIN_VALUE

Introduction

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

Prototype

float MIN_VALUE

To view the source code for java.lang Float MIN_VALUE.

Click Source Link

Document

A constant holding the smallest positive nonzero value of type float , 2-149.

Usage

From source file:org.noise_planet.noisecapture.CalibrationLinearityActivity.java

private void updateLineChart() {
    LineChart lineChart = getLineChart();
    if (lineChart == null) {
        return;//from w w  w  . j av  a  2s .co m
    }
    if (freqLeqStats.isEmpty()) {
        return;
    }
    float YMin = Float.MAX_VALUE;
    float YMax = Float.MIN_VALUE;

    ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();

    // Read all white noise values for indexing before usage
    int idStep = 0;
    double referenceLevel = freqLeqStats.get(0).whiteNoiseLevel.getGlobaldBaValue();
    for (LinearCalibrationResult result : freqLeqStats) {
        ArrayList<Entry> yMeasure = new ArrayList<Entry>();
        int idfreq = 0;
        for (LeqStats leqStat : result.measure) {
            float dbLevel = (float) leqStat.getLeqMean();
            YMax = Math.max(YMax, dbLevel);
            YMin = Math.min(YMin, dbLevel);
            yMeasure.add(new Entry(dbLevel, idfreq++));
        }
        LineDataSet freqSet = new LineDataSet(yMeasure, String.format(Locale.getDefault(), "%d dB",
                (int) (result.whiteNoiseLevel.getGlobaldBaValue() - referenceLevel)));
        freqSet.setColor(ColorTemplate.COLORFUL_COLORS[idStep % ColorTemplate.COLORFUL_COLORS.length]);
        freqSet.setFillColor(ColorTemplate.COLORFUL_COLORS[idStep % ColorTemplate.COLORFUL_COLORS.length]);
        freqSet.setValueTextColor(Color.WHITE);
        freqSet.setCircleColorHole(
                ColorTemplate.COLORFUL_COLORS[idStep % ColorTemplate.COLORFUL_COLORS.length]);
        freqSet.setDrawValues(false);
        freqSet.setDrawFilled(true);
        freqSet.setFillAlpha(255);
        freqSet.setDrawCircles(true);
        freqSet.setMode(LineDataSet.Mode.LINEAR);
        dataSets.add(freqSet);
        idStep++;
    }

    ArrayList<String> xVals = new ArrayList<String>();
    double[] freqs = FFTSignalProcessing
            .computeFFTCenterFrequency(AudioProcess.REALTIME_SAMPLE_RATE_LIMITATION);
    for (double freqValue : freqs) {
        xVals.add(Spectrogram.formatFrequency((int) freqValue));
    }

    // create a data object with the datasets
    LineData data = new LineData(xVals, dataSets);
    lineChart.setData(data);
    YAxis yl = lineChart.getAxisLeft();
    yl.setAxisMinValue(YMin - 3);
    yl.setAxisMaxValue(YMax + 3);
    lineChart.invalidate();
}

From source file:com.dngames.mobilewebcam.PhotoSettings.java

@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    if (key == "cam_refresh") {
        int new_refresh = getEditInt(mContext, prefs, "cam_refresh", 60);
        String msg = "Camera refresh set to " + new_refresh + " seconds!";
        if (MobileWebCam.gIsRunning) {
            if (!mNoToasts && new_refresh != mRefreshDuration) {
                try {
                    Toast.makeText(mContext.getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                } catch (RuntimeException e) {
                    e.printStackTrace();
                }/*from   w  ww  .  j  ava2s .com*/
            }
        } else if (new_refresh != mRefreshDuration) {
            MobileWebCam.LogI(msg);
        }
    }

    // get all preferences
    for (Field f : getClass().getFields()) {
        {
            BooleanPref bp = f.getAnnotation(BooleanPref.class);
            if (bp != null) {
                try {
                    f.setBoolean(this, prefs.getBoolean(bp.key(), bp.val()));
                } catch (Exception e) {
                    Log.e("MobileWebCam", "Exception: " + bp.key() + " <- " + bp.val());
                    e.printStackTrace();
                }
            }
        }
        {
            EditIntPref ip = f.getAnnotation(EditIntPref.class);
            if (ip != null) {
                try {
                    int eval = getEditInt(mContext, prefs, ip.key(), ip.val()) * ip.factor();
                    if (ip.max() != Integer.MAX_VALUE)
                        eval = Math.min(eval, ip.max());
                    if (ip.min() != Integer.MIN_VALUE)
                        eval = Math.max(eval, ip.min());
                    f.setInt(this, eval);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        {
            IntPref ip = f.getAnnotation(IntPref.class);
            if (ip != null) {
                try {
                    int eval = prefs.getInt(ip.key(), ip.val()) * ip.factor();
                    if (ip.max() != Integer.MAX_VALUE)
                        eval = Math.min(eval, ip.max());
                    if (ip.min() != Integer.MIN_VALUE)
                        eval = Math.max(eval, ip.min());
                    f.setInt(this, eval);
                } catch (Exception e) {
                    // handle wrong set class
                    e.printStackTrace();
                    Editor edit = prefs.edit();
                    edit.remove(ip.key());
                    edit.putInt(ip.key(), ip.val());
                    edit.commit();
                    try {
                        f.setInt(this, ip.val());
                    } catch (IllegalArgumentException e1) {
                        e1.printStackTrace();
                    } catch (IllegalAccessException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
        {
            EditFloatPref fp = f.getAnnotation(EditFloatPref.class);
            if (fp != null) {
                try {
                    float eval = getEditFloat(mContext, prefs, fp.key(), fp.val());
                    if (fp.max() != Float.MAX_VALUE)
                        eval = Math.min(eval, fp.max());
                    if (fp.min() != Float.MIN_VALUE)
                        eval = Math.max(eval, fp.min());
                    f.setFloat(this, eval);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        {
            StringPref sp = f.getAnnotation(StringPref.class);
            if (sp != null) {
                try {
                    f.set(this, prefs.getString(sp.key(), getDefaultString(mContext, sp)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    mCustomImageScale = Enum.valueOf(ImageScaleMode.class, prefs.getString("custompicscale", "CROP"));

    mAutoStart = prefs.getBoolean("autostart", false);
    mCameraStartupEnabled = prefs.getBoolean("cam_autostart", true);
    mShutterSound = prefs.getBoolean("shutter", true);
    mDateTimeColor = GetPrefColor(prefs, "datetime_color", "#FFFFFFFF", Color.WHITE);
    mDateTimeShadowColor = GetPrefColor(prefs, "datetime_shadowcolor", "#FF000000", Color.BLACK);
    mDateTimeBackgroundColor = GetPrefColor(prefs, "datetime_backcolor", "#80FF0000",
            Color.argb(0x80, 0xFF, 0x00, 0x00));
    mDateTimeBackgroundLine = prefs.getBoolean("datetime_fillline", true);
    mDateTimeX = prefs.getInt("datetime_x", 98);
    mDateTimeY = prefs.getInt("datetime_y", 98);
    mDateTimeAlign = Paint.Align.valueOf(prefs.getString("datetime_imprintalign", "RIGHT"));

    mDateTimeFontScale = (float) prefs.getInt("datetime_fontsize", 6);

    mTextColor = GetPrefColor(prefs, "text_color", "#FFFFFFFF", Color.WHITE);
    mTextShadowColor = GetPrefColor(prefs, "text_shadowcolor", "#FF000000", Color.BLACK);
    mTextBackgroundColor = GetPrefColor(prefs, "text_backcolor", "#80FF0000",
            Color.argb(0x80, 0xFF, 0x00, 0x00));
    mTextBackgroundLine = prefs.getBoolean("text_fillline", true);
    mTextX = prefs.getInt("text_x", 2);
    mTextY = prefs.getInt("text_y", 2);
    mTextAlign = Paint.Align.valueOf(prefs.getString("text_imprintalign", "LEFT"));
    mTextFontScale = (float) prefs.getInt("infotext_fontsize", 6);
    mTextFontname = prefs.getString("infotext_fonttypeface", "");

    mStatusInfoColor = GetPrefColor(prefs, "statusinfo_color", "#FFFFFFFF", Color.WHITE);
    mStatusInfoShadowColor = GetPrefColor(prefs, "statusinfo_shadowcolor", "#FF000000", Color.BLACK);
    mStatusInfoX = prefs.getInt("statusinfo_x", 2);
    mStatusInfoY = prefs.getInt("statusinfo_y", 98);
    mStatusInfoAlign = Paint.Align.valueOf(prefs.getString("statusinfo_imprintalign", "LEFT"));
    mStatusInfoBackgroundColor = GetPrefColor(prefs, "statusinfo_backcolor", "#00000000", Color.TRANSPARENT);
    mStatusInfoFontScale = (float) prefs.getInt("statusinfo_fontsize", 6);
    mStatusInfoBackgroundLine = prefs.getBoolean("statusinfo_fillline", false);

    mGPSColor = GetPrefColor(prefs, "gps_color", "#FFFFFFFF", Color.WHITE);
    mGPSShadowColor = GetPrefColor(prefs, "gps_shadowcolor", "#FF000000", Color.BLACK);
    mGPSX = prefs.getInt("gps_x", 98);
    mGPSY = prefs.getInt("gps_y", 2);
    mGPSAlign = Paint.Align.valueOf(prefs.getString("gps_imprintalign", "RIGHT"));
    mGPSBackgroundColor = GetPrefColor(prefs, "gps_backcolor", "#00000000", Color.TRANSPARENT);
    mGPSFontScale = (float) prefs.getInt("gps_fontsize", 6);
    mGPSBackgroundLine = prefs.getBoolean("gps_fillline", false);

    mImprintPictureX = prefs.getInt("imprint_picture_x", 0);
    mImprintPictureY = prefs.getInt("imprint_picture_y", 0);

    mNightAutoConfigEnabled = prefs.getBoolean("night_auto_enabled", false);

    mSetNightConfiguration = prefs.getBoolean("cam_nightconfiguration", false);
    // override night camera parameters (read again with postfix)
    getCurrentNightSettings();

    mFilterPicture = false; //***prefs.getBoolean("filter_picture", false);
    mFilterType = getEditInt(mContext, prefs, "filter_sel", 0);

    if (mImprintPicture) {
        if (mImprintPictureURL.length() == 0) {
            // sdcard image
            File path = new File(Environment.getExternalStorageDirectory() + "/MobileWebCam/");
            if (path.exists()) {
                synchronized (gImprintBitmapLock) {
                    if (gImprintBitmap != null)
                        gImprintBitmap.recycle();
                    gImprintBitmap = null;

                    File file = new File(path, "imprint.png");
                    try {
                        FileInputStream in = new FileInputStream(file);
                        gImprintBitmap = BitmapFactory.decodeStream(in);
                        in.close();
                    } catch (IOException e) {
                        Toast.makeText(mContext, "Error: unable to read imprint bitmap " + file.getName() + "!",
                                Toast.LENGTH_SHORT).show();
                        gImprintBitmap = null;
                    } catch (OutOfMemoryError e) {
                        Toast.makeText(mContext, "Error: imprint bitmap " + file.getName() + " too large!",
                                Toast.LENGTH_LONG).show();
                        gImprintBitmap = null;
                    }
                }
            }
        } else {
            DownloadImprintBitmap();
        }

        synchronized (gImprintBitmapLock) {
            if (gImprintBitmap == null) {
                // last resort: resource default
                try {
                    gImprintBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.imprint);
                } catch (OutOfMemoryError e) {
                    Toast.makeText(mContext, "Error: default imprint bitmap too large!", Toast.LENGTH_LONG)
                            .show();
                    gImprintBitmap = null;
                }
            }
        }
    }

    mNoToasts = prefs.getBoolean("no_messages", false);
    mFullWakeLock = prefs.getBoolean("full_wakelock", true);

    switch (getEditInt(mContext, prefs, "camera_mode", 1)) {
    case 0:
        mMode = Mode.MANUAL;
        break;
    case 2:
        mMode = Mode.HIDDEN;
        break;
    case 3:
        mMode = Mode.BACKGROUND;
        break;
    case 1:
    default:
        mMode = Mode.NORMAL;
        break;
    }
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#contains(java.lang.Object, java.lang.Number, java.lang.Number)}.
 *///from  ww  w.  j  a  va2 s .  c om
@SuppressWarnings("unchecked")
@Test
public void testContains() {
    assertEquals("null", false, contains(null, null, null));
    assertEquals("null", false, contains(null, 0, null));
    assertEquals("null", false, contains(null, null, 10));
    assertEquals("null", false, contains(null, 0, 10));
    assertEquals("null: from", true, contains(0, null, 10));
    assertEquals("null: from: overflow", false, contains(11, null, 10));
    assertEquals("null: to", true, contains(0, 0, null));
    assertEquals("null: to", true, contains(11, 10, null));
    assertEquals("null: to: less", false, contains(1, 10, null));
    assertEquals("fraction: Double", true, contains(Math.PI, 0, 10));
    assertEquals("fraction: Float", true, contains(Float.MIN_VALUE, 0, 10));
    assertEquals("NaN", false, contains(Float.NaN, -Float.MAX_VALUE, Float.MAX_VALUE));
    assertEquals("NaN", false, contains(Float.NaN, null, Float.POSITIVE_INFINITY));
    assertEquals("NaN", true, contains(Float.NaN, Float.NaN, Float.POSITIVE_INFINITY));
    assertEquals("NaN", true, contains(Float.NaN, null, Float.NaN));
    assertEquals("NaN", true, contains(Float.NaN, Double.NaN, Float.NaN));
    assertEquals("-Infinity: from", true, contains(1, Float.NEGATIVE_INFINITY, null));
    assertEquals("-Infinity: to", false, contains(1, null, Float.NEGATIVE_INFINITY));
    assertEquals("Infinity: from", false, contains(1, Float.POSITIVE_INFINITY, null));
    assertEquals("Infinity: to", true, contains(1, null, Float.POSITIVE_INFINITY));
    assertEquals("Infinity: only", false, contains(1, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY));
    assertEquals("Infinity: only", true,
            contains(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY));
    assertEquals("Infinity: only", true,
            contains(Double.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY));
    for (Class<?> type : NUMBERS) {
        Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
        Object o = null;
        try {
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                o = wrapper.getField("MAX_VALUE").get(null);
            } else {
                o = INFINITY_DOUBLE.pow(2);
                if (BigInteger.class.equals(type))
                    o = ((BigDecimal) o).toBigInteger();
            }
            assertEquals("Infinity: all: " + type.getSimpleName(), true,
                    contains(o, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY));
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}

From source file:org.noise_planet.noisecapture.CalibrationLinearityActivity.java

private void updateScatterChart() {
    ScatterChart scatterChart = getScatterChart();
    if (scatterChart == null) {
        return;//from   w  ww.  j  a v a  2 s  .  c o m
    }
    if (freqLeqStats.isEmpty()) {
        return;
    }
    float YMin = Float.MAX_VALUE;
    float YMax = Float.MIN_VALUE;
    float XMin = Float.MAX_VALUE;
    float XMax = Float.MIN_VALUE;

    ArrayList<IScatterDataSet> dataSets = new ArrayList<IScatterDataSet>();

    // Frequency count, one dataset by frequency
    int dataSetCount = freqLeqStats.get(freqLeqStats.size() - 1).whiteNoiseLevel.getdBaLevels().length;

    Set<Integer> whiteNoiseValuesSet = new TreeSet<Integer>();

    // Read all white noise values for indexing before usage
    for (LinearCalibrationResult result : freqLeqStats) {
        for (int idFreq = 0; idFreq < result.whiteNoiseLevel.getdBaLevels().length; idFreq++) {
            float dbLevel = result.whiteNoiseLevel.getdBaLevels()[idFreq];
            float referenceDbLevel = freqLeqStats.get(0).whiteNoiseLevel.getdBaLevels()[idFreq];
            whiteNoiseValuesSet.add((int) (dbLevel - referenceDbLevel));
        }
    }
    // Convert into ordered list
    int[] whiteNoiseValues = new int[whiteNoiseValuesSet.size()];

    ArrayList<String> xVals = new ArrayList<String>();
    int i = 0;
    for (int dbValue : whiteNoiseValuesSet) {
        whiteNoiseValues[i++] = dbValue;
        xVals.add(String.valueOf(dbValue));
        XMax = Math.max(XMax, dbValue);
        XMin = Math.min(XMin, dbValue);
    }

    double[] freqs = FFTSignalProcessing
            .computeFFTCenterFrequency(AudioProcess.REALTIME_SAMPLE_RATE_LIMITATION);
    for (int freqId = 0; freqId < dataSetCount; freqId += 1) {
        int freqValue = (int) freqs[freqId];
        if (selectedFrequencies.contains(freqValue)) {
            ArrayList<Entry> yMeasure = new ArrayList<Entry>();
            for (LinearCalibrationResult result : freqLeqStats) {
                float dbLevel = (float) result.measure[freqId].getLeqMean();
                float referenceDbLevel = freqLeqStats.get(0).whiteNoiseLevel.getdBaLevels()[freqId];
                int whiteNoise = (int) (result.whiteNoiseLevel.getdBaLevels()[freqId] - referenceDbLevel);
                YMax = Math.max(YMax, dbLevel);
                YMin = Math.min(YMin, dbLevel);
                yMeasure.add(new Entry(dbLevel, Arrays.binarySearch(whiteNoiseValues, whiteNoise)));
            }
            ScatterDataSet freqSet = new ScatterDataSet(yMeasure, Spectrogram
                    .formatFrequency((int) ThirdOctaveBandsFiltering.STANDARD_FREQUENCIES_REDUCED[freqId]));
            freqSet.setScatterShape(ScatterChart.ScatterShape.CIRCLE);
            freqSet.setColor(ColorTemplate.COLORFUL_COLORS[freqId % ColorTemplate.COLORFUL_COLORS.length]);
            freqSet.setScatterShapeSize(8f);
            freqSet.setValueTextColor(Color.WHITE);
            freqSet.setDrawValues(false);
            dataSets.add(freqSet);
        }
    }

    // create a data object with the datasets
    ScatterData data = new ScatterData(xVals, dataSets);
    scatterChart.setData(data);
    YAxis yl = scatterChart.getAxisLeft();
    yl.setAxisMinValue(YMin - 3);
    yl.setAxisMaxValue(YMax + 3);
    scatterChart.invalidate();
}

From source file:trendplot.TrendPlot.java

private void findMinMax(String datFileName) throws FileNotFoundException, IOException {
    File datFile = new File(datFileName);
    try (BufferedInputStream ins = new BufferedInputStream(new FileInputStream(datFile))) {
        boolean eof = false;
        min = Float.MAX_VALUE;//from w ww  .  java2  s  .  c o  m
        minMax = Float.MIN_VALUE;
        max = Float.MIN_VALUE;
        maxMin = Float.MAX_VALUE;
        tmin = Float.MAX_VALUE;
        tmax = Float.MIN_VALUE;
        byte[] b = new byte[Float.SIZE / 8];
        int count = 0;
        int nread;
        while (!eof) {
            try {
                nread = ins.read(b);
                float time = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();
                nread += ins.read(b);
                float inmin = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();
                nread += ins.read(b);
                float mean = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();
                nread += ins.read(b);
                float inmax = ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getFloat();
                if (nread == Float.SIZE / 8 * 4) {
                    count++;
                    tmin = Math.min(tmin, time);
                    tmax = Math.max(tmax, time);
                    min = Math.min(min, inmin);
                    minMax = Math.max(minMax, inmin);
                    max = Math.max(max, inmax);
                    maxMin = Math.min(maxMin, inmax);
                } else {
                    eof = true;
                    ins.close();
                }
            } catch (EOFException ex) {
                eof = true;
                ins.close();
            } catch (IOException ex) {
                ins.close();
                throw ex;
            }
        }
    }
}

From source file:com.epam.catgenome.dao.index.FeatureIndexDao.java

private void setMissingValuesOrder(SortField sf, SortField.Type type, boolean desc) {
    switch (type) {
    case STRING:/*  ww  w.  j av  a  2  s . c om*/
        sf.setMissingValue(desc ? SortField.STRING_FIRST : SortField.STRING_LAST);
        break;
    case FLOAT:
        sf.setMissingValue(Float.MIN_VALUE);
        break;
    case INT:
        sf.setMissingValue(Integer.MIN_VALUE);
        break;
    default:
        throw new IllegalArgumentException("Unexpected sort type: " + type);
    }
}

From source file:MSUmpire.DIA.TargetMatchScoring.java

public void MixtureModeling() throws IOException {
    if (libTargetMatches.isEmpty()) {
        return;//from   ww  w. ja v a 2 s.  co m
    }
    int IDNo = 0;
    int decoyNo = 0;
    int modelNo = 0;
    double IDmean = 0d;
    double Decoymean = 0d;

    for (UmpireSpecLibMatch match : libIDMatches) {
        if (match.BestHit != null) {
            IDNo++;
            IDmean += match.BestHit.UmpireScore;
        }
    }

    decoyNo = decoyModelingList.size();
    for (PeakGroupScore peakGroupScore : decoyModelingList) {
        Decoymean += peakGroupScore.UmpireScore;
    }

    for (UmpireSpecLibMatch match : libTargetMatches) {
        //modelNo+= match.TargetHits.size();
        if (match.BestMS1Hit != null) {
            modelNo++;
        }
        if (match.BestMS2Hit != null) {
            modelNo++;
        }
    }

    Decoymean /= decoyNo;
    IDmean /= IDNo;

    PVector[] points = new PVector[modelNo];
    PVector[] centroids = new PVector[2];

    int idx = 0;
    for (UmpireSpecLibMatch match : libTargetMatches) {
        if (match.BestMS1Hit != null) {
            points[idx] = new PVector(1);
            points[idx].array[0] = match.BestMS1Hit.UmpireScore;
            idx++;
        }
        if (match.BestMS2Hit != null) {
            points[idx] = new PVector(1);
            points[idx].array[0] = match.BestMS2Hit.UmpireScore;
            idx++;
        }
        //            for(PeakGroupScore peakGroupScore : match.TargetHits){
        //                points[idx] = new PVector(1);
        //                points[idx].array[0] = match.BestMS2Hit.UmpireScore;
        //                idx++;
        //            }
    }

    MixtureModel mmc;
    centroids[0] = new PVector(1);
    centroids[0].array[0] = Decoymean;
    centroids[1] = new PVector(1);
    centroids[1].array[0] = IDmean;
    Vector<PVector>[] clusters = KMeans.run(points, 2, centroids);
    MixtureModel mm = ExpectationMaximization1D.initialize(clusters);
    mmc = ExpectationMaximization1D.run(points, mm);
    DecimalFormat df = new DecimalFormat("#.####");
    Logger.getRootLogger()
            .debug("----------------------------------------------------------------------------------------");
    Logger.getRootLogger().debug("No. of modeling points=" + modelNo);
    Logger.getRootLogger().debug("ID hits mean=" + df.format(IDmean));
    Logger.getRootLogger().debug("Decoy hits mean=" + df.format(Decoymean));
    //System.out.print("T-test: p-value=" + df.format(model.ttest.pValue).toString() + "\n");
    Logger.getRootLogger()
            .debug("Incorrect hits model mean=" + df.format(((PVector) mmc.param[0]).array[0]) + " variance="
                    + df.format(((PVector) mmc.param[0]).array[1]) + " weight=" + df.format(mmc.weight[0]));
    Logger.getRootLogger()
            .debug("Correct hits model mean=" + df.format(((PVector) mmc.param[1]).array[0]) + " variance="
                    + df.format(((PVector) mmc.param[1]).array[1]) + " weight=" + df.format(mmc.weight[1]));

    if (((PVector) mmc.param[0]).array[0] > ((PVector) mmc.param[1]).array[0]) {
        return;
    }

    float max = (float) (((PVector) mmc.param[1]).array[0] + 4 * Math.sqrt(((PVector) mmc.param[1]).array[1]));
    float min = (float) (((PVector) mmc.param[0]).array[0] - 4 * Math.sqrt(((PVector) mmc.param[0]).array[1]));

    IDNo = 0;
    decoyNo = 0;
    modelNo = 0;

    for (PeakGroupScore peakGroupScore : decoyModelingList) {
        if (peakGroupScore.UmpireScore > min && peakGroupScore.UmpireScore < max) {
            decoyNo++;
        }
    }

    for (UmpireSpecLibMatch match : libIDMatches) {
        if (match.BestHit != null && match.BestHit.UmpireScore > min && match.BestHit.UmpireScore < max) {
            IDNo++;
        }
    }

    for (UmpireSpecLibMatch match : libTargetMatches) {
        //targetNo += match.TargetHits.size();
        //decoyNo += match.DecoyHits.size();
        if (match.BestMS1Hit != null && match.BestMS1Hit.UmpireScore > min
                && match.BestMS1Hit.UmpireScore < max) {
            modelNo++;
        }
        if (match.BestMS2Hit != null && match.BestMS2Hit.UmpireScore > min
                && match.BestMS2Hit.UmpireScore < max) {
            modelNo++;
        }
        //modelNo += match.TargetHits.size();            
    }

    double[] IDObs = new double[IDNo];
    double[] DecoyObs = new double[decoyNo];
    double[] ModelObs = new double[modelNo];
    idx = 0;
    int didx = 0;
    int midx = 0;
    for (UmpireSpecLibMatch match : libIDMatches) {
        if (match.BestHit != null && match.BestHit.UmpireScore > min && match.BestHit.UmpireScore < max) {
            IDObs[idx++] = match.BestHit.UmpireScore;
        }
    }
    for (PeakGroupScore peakGroupScore : decoyModelingList) {
        if (peakGroupScore.UmpireScore > min && peakGroupScore.UmpireScore < max) {
            DecoyObs[didx++] = peakGroupScore.UmpireScore;
        }
    }

    for (UmpireSpecLibMatch match : libTargetMatches) {
        //            for(PeakGroupScore peak : match.TargetHits){
        //                ModelObs[midx++]=peak.UmpireScore;
        //            }
        if (match.BestMS1Hit != null && match.BestMS1Hit.UmpireScore > min
                && match.BestMS1Hit.UmpireScore < max) {
            ModelObs[midx++] = match.BestMS1Hit.UmpireScore;
        }
        if (match.BestMS2Hit != null && match.BestMS2Hit.UmpireScore > min
                && match.BestMS2Hit.UmpireScore < max) {
            ModelObs[midx++] = match.BestMS2Hit.UmpireScore;
        }
    }

    String pngfile = FilenameUtils.getFullPath(Filename) + "/" + FilenameUtils.getBaseName(Filename) + "_"
            + LibID + "_LibMatchModel.png";
    XYSeries model1 = new XYSeries("Incorrect matches");
    XYSeries model2 = new XYSeries("Correct matches");
    XYSeries model3 = new XYSeries("All target hits");

    String modelfile = FilenameUtils.getFullPath(pngfile) + "/" + FilenameUtils.getBaseName(pngfile)
            + "_ModelPoints.txt";
    FileWriter writer = new FileWriter(modelfile);
    writer.write("UScore\tModel\tCorrect\tDecoy\n");

    int NoPoints = 1000;
    double[] model_kde_x = new double[NoPoints];
    float intv = (max - min) / NoPoints;
    PVector point = new PVector(2);
    for (int i = 0; i < NoPoints; i++) {
        point.array[0] = max - i * intv;
        model_kde_x[i] = point.array[0];
        point.array[1] = mmc.EF.density(point, mmc.param[0]) * mmc.weight[0];
        model1.add(point.array[0], point.array[1]);
        point.array[1] = mmc.EF.density(point, mmc.param[1]) * mmc.weight[1];
        model2.add(point.array[0], point.array[1]);

    }

    KernelDensityEstimator kde = new KernelDensityEstimator();
    kde.SetData(ModelObs);
    double[] model_kde_y = kde.Density(model_kde_x);

    for (int i = 0; i < NoPoints; i++) {
        if (model_kde_x[i] > min && model_kde_x[i] < max) {
            point.array[0] = max - i * intv;
            model_kde_x[i] = point.array[0];
            model3.add(model_kde_x[i], model_kde_y[i]);
            writer.write(point.array[0] + "\t" + mmc.EF.density(point, mmc.param[0]) * mmc.weight[0] + "\t"
                    + mmc.EF.density(point, mmc.param[1]) * mmc.weight[1] + "\t" + model_kde_y[i] + "\n");
        }
    }
    writer.close();
    MixtureModelProb = new float[NoPoints + 1][3];
    float positiveaccu = 0f;
    float negativeaccu = 0f;

    MixtureModelProb[0][0] = (float) model2.getMaxX() + Float.MIN_VALUE;
    MixtureModelProb[0][1] = 1f;
    MixtureModelProb[0][2] = 1f;

    for (int i = 1; i < NoPoints + 1; i++) {
        float positiveNumber = model2.getY(NoPoints - i).floatValue();
        float negativeNumber = model1.getY(NoPoints - i).floatValue();
        MixtureModelProb[i][0] = model2.getX(NoPoints - i).floatValue();
        positiveaccu += positiveNumber;
        negativeaccu += negativeNumber;
        MixtureModelProb[i][2] = positiveNumber / (negativeNumber + positiveNumber);
        MixtureModelProb[i][1] = positiveaccu / (negativeaccu + positiveaccu);
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(model1);
    dataset.addSeries(model2);
    dataset.addSeries(model3);

    HistogramDataset histogramDataset = new HistogramDataset();
    histogramDataset.setType(HistogramType.SCALE_AREA_TO_1);
    histogramDataset.addSeries("ID hits", IDObs, 100);
    histogramDataset.addSeries("Decoy hits", DecoyObs, 100);
    //histogramDataset.addSeries("Model hits", ModelObs, 100);

    JFreeChart chart = ChartFactory.createHistogram(FilenameUtils.getBaseName(pngfile), "Score", "Hits",
            histogramDataset, PlotOrientation.VERTICAL, true, false, false);
    XYPlot plot = chart.getXYPlot();

    NumberAxis domain = (NumberAxis) plot.getDomainAxis();
    domain.setRange(min, max);
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setForegroundAlpha(0.8f);
    chart.setBackgroundPaint(Color.white);

    XYLineAndShapeRenderer render = new XYLineAndShapeRenderer();
    //        render.setSeriesPaint(0, Color.DARK_GRAY);
    //        render.setSeriesPaint(1, Color.DARK_GRAY); 
    //        render.setSeriesPaint(2, Color.GREEN); 
    //        render.setSeriesShape(0, new Ellipse2D.Double(0, 0, 2, 2));
    //        render.setSeriesShape(1, new Ellipse2D.Double(0, 0, 2, 2));
    //        render.setSeriesShape(2, new Ellipse2D.Double(0, 0, 2.5f, 2.5f));
    //        render.setSeriesStroke(1, new BasicStroke(1.0f));
    //        render.setSeriesStroke(0, new BasicStroke(1.0f));
    //        render.setSeriesStroke(2, new BasicStroke(2.0f));
    plot.setDataset(1, dataset);
    plot.setRenderer(1, render);
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    try {
        ChartUtilities.saveChartAsPNG(new File(pngfile), chart, 1000, 600);
    } catch (IOException e) {
    }
}

From source file:org.stockchart.StockChartView.java

private float[] getLeftRightMargins() {
    float leftMargin = Float.MIN_VALUE;
    float rightMargin = Float.MIN_VALUE;

    for (Area a : fAreas) {
        if (!a.isVisible())
            continue;

        RectF r = a.getSideMargins();//from w ww .  j a v a2 s  .co m

        if (r.left > leftMargin)
            leftMargin = r.left;

        if (r.right > rightMargin)
            rightMargin = r.right;
    }

    return new float[] { leftMargin, rightMargin };
}

From source file:com.sun.faces.util.Util.java

/**
 * @return true if and only if the argument
 *         <code>attributeVal</code> is an instance of a wrapper for a
 *         primitive type and its value is equal to the default value for
 *         that type as given in the spec.
 *///from   w  ww. ja va2 s  .  co  m

private static boolean shouldRenderAttribute(Object attributeVal) {
    if (attributeVal instanceof Boolean
            && ((Boolean) attributeVal).booleanValue() == Boolean.FALSE.booleanValue()) {
        return false;
    } else if (attributeVal instanceof Integer && ((Integer) attributeVal).intValue() == Integer.MIN_VALUE) {
        return false;
    } else if (attributeVal instanceof Double && ((Double) attributeVal).doubleValue() == Double.MIN_VALUE) {
        return false;
    } else if (attributeVal instanceof Character
            && ((Character) attributeVal).charValue() == Character.MIN_VALUE) {
        return false;
    } else if (attributeVal instanceof Float && ((Float) attributeVal).floatValue() == Float.MIN_VALUE) {
        return false;
    } else if (attributeVal instanceof Short && ((Short) attributeVal).shortValue() == Short.MIN_VALUE) {
        return false;
    } else if (attributeVal instanceof Byte && ((Byte) attributeVal).byteValue() == Byte.MIN_VALUE) {
        return false;
    } else if (attributeVal instanceof Long && ((Long) attributeVal).longValue() == Long.MIN_VALUE) {
        return false;
    }
    return true;
}

From source file:com.telefonica.iot.cygnus.sinks.NGSICartoDBSink.java

private void persistDistanceEvent(NGSIEvent event) throws CygnusBadConfiguration, CygnusPersistenceError {
    // Get some values
    String schema = buildSchemaName(event.getServiceForNaming(enableNameMappings));
    String service = event.getServiceForData();
    String servicePath = event.getServicePathForData();
    String entityId = event.getContextElement().getId();
    String entityType = event.getContextElement().getType();

    // Iterate on all this context element attributes, if there are attributes
    ArrayList<ContextAttribute> contextAttributes = event.getContextElement().getAttributes();

    if (contextAttributes == null || contextAttributes.isEmpty()) {
        return;//  ww  w.j  a v  a2s.  co  m
    } // if

    ((CartoDBBackendImpl) backends.get(schema)).startTransaction();

    for (ContextAttribute contextAttribute : contextAttributes) {
        long recvTimeTs = event.getRecvTimeTs();
        String attrType = contextAttribute.getType();
        String attrValue = contextAttribute.getContextValue(false);
        String attrMetadata = contextAttribute.getContextMetadata();
        ImmutablePair<String, Boolean> location = NGSIUtils.getGeometry(attrValue, attrType, attrMetadata,
                swapCoordinates);
        String tableName = buildTableName(event.getServicePathForNaming(enableGrouping, enableNameMappings),
                event.getEntityForNaming(enableGrouping, enableNameMappings, enableEncoding),
                event.getAttributeForNaming(enableNameMappings)) + CommonConstants.CONCATENATOR + "distance";

        if (location.getRight()) {
            // Try creating the table... the cost of checking if it exists and creating it is higher than directly
            // attempting to create it. If existing, nothing will be re-created and the new values will be inserted

            try {
                String typedFields = "(recvTimeMs bigint, fiwareServicePath text, entityId text, entityType text, "
                        + "stageDistance float, stageTime float, stageSpeed float, sumDistance float, "
                        + "sumTime float, sumSpeed float, sum2Distance float, sum2Time float, sum2Speed float, "
                        + "maxDistance float, minDistance float, maxTime float, minTime float, maxSpeed float, "
                        + "minSpeed float, numSamples bigint)";
                backends.get(schema).createTable(schema, tableName, typedFields);

                // Once created, insert the first row
                String withs = "";
                String fields = "(recvTimeMs, fiwareServicePath, entityId, entityType, the_geom, stageDistance,"
                        + "stageTime, stageSpeed, sumDistance, sumTime, sumSpeed, sum2Distance, sum2Time,"
                        + "sum2Speed, maxDistance, minDistance, maxTime, mintime, maxSpeed, minSpeed, numSamples)";
                String rows = "(" + recvTimeTs + ",'" + servicePath + "','" + entityId + "','" + entityType
                        + "'," + location.getLeft() + ",0,0,0,0,0,0,0,0,0," + Float.MIN_VALUE + ","
                        + Float.MAX_VALUE + "," + Float.MIN_VALUE + "," + Float.MAX_VALUE + ","
                        + Float.MIN_VALUE + "," + Float.MAX_VALUE + ",1)";
                LOGGER.info("[" + this.getName() + "] Persisting data at NGSICartoDBSink. Schema (" + schema
                        + "), Table (" + tableName + "), Data (" + rows + ")");
                backends.get(schema).insert(schema, tableName, withs, fields, rows);
            } catch (Exception e1) {
                String withs = "" + "WITH geom AS (" + "   SELECT " + location.getLeft() + " AS point"
                        + "), calcs AS (" + "   SELECT" + "      cartodb_id,"
                        + "      ST_Distance(the_geom::geography, geom.point::geography) AS stage_distance,"
                        + "      (" + recvTimeTs + " - recvTimeMs) AS stage_time" + "   FROM " + tableName
                        + ", geom" + "   ORDER BY cartodb_id DESC" + "   LIMIT 1" + "), speed AS ("
                        + "   SELECT"
                        + "      (calcs.stage_distance / NULLIF(calcs.stage_time, 0)) AS stage_speed"
                        + "   FROM calcs" + "), inserts AS (" + "   SELECT"
                        + "      (-1 * ((-1 * t1.sumDistance) - calcs.stage_distance)) AS sum_dist,"
                        + "      (-1 * ((-1 * t1.sumTime) - calcs.stage_time)) AS sum_time,"
                        + "      (-1 * ((-1 * t1.sumSpeed) - speed.stage_speed)) AS sum_speed,"
                        + "      (-1 * ((-1 * t1.sumDistance) - calcs.stage_distance)) "
                        + "          * (-1 * ((-1 * t1.sumDistance) - calcs.stage_distance)) AS sum2_dist,"
                        + "      (-1 * ((-1 * t1.sumTime) - calcs.stage_time)) "
                        + "          * (-1 * ((-1 * t1.sumTime) - calcs.stage_time)) AS sum2_time,"
                        + "      (-1 * ((-1 * t1.sumSpeed) - speed.stage_speed)) "
                        + "          * (-1 * ((-1 * t1.sumSpeed) - speed.stage_speed)) AS sum2_speed,"
                        + "      t1.max_distance," + "      t1.min_distance," + "      t1.max_time,"
                        + "      t1.min_time," + "      t1.max_speed," + "      t1.min_speed,"
                        + "      t2.num_samples" + "   FROM" + "      (" + "         SELECT"
                        + "            GREATEST(calcs.stage_distance, maxDistance) AS max_distance,"
                        + "            LEAST(calcs.stage_distance, minDistance) AS min_distance,"
                        + "            GREATEST(calcs.stage_time, maxTime) AS max_time,"
                        + "            LEAST(calcs.stage_time, minTime) AS min_time,"
                        + "            GREATEST(speed.stage_speed, maxSpeed) AS max_speed,"
                        + "            LEAST(speed.stage_speed, minSpeed) AS min_speed,"
                        + "            sumDistance," + "            sumTime," + "            sumSpeed"
                        + "         FROM " + tableName + ", speed, calcs" + "         ORDER BY " + tableName
                        + ".cartodb_id DESC" + "         LIMIT 1" + "      ) AS t1," + "      ("
                        + "         SELECT (-1 * ((-1 * COUNT(*)) - 1)) AS num_samples" + "         FROM "
                        + tableName + "      ) AS t2," + "      speed," + "      calcs" + ")";
                String fields = "(recvTimeMs, fiwareServicePath, entityId, entityType, the_geom, stageDistance,"
                        + "stageTime, stageSpeed, sumDistance, sumTime, sumSpeed, sum2Distance, sum2Time,"
                        + "sum2Speed, maxDistance, minDistance, maxTime, mintime, maxSpeed, minSpeed, numSamples)";
                String rows = "(" + recvTimeTs + ",'" + servicePath + "','" + entityId + "','" + entityType
                        + "'," + "(SELECT point FROM geom),(SELECT stage_distance FROM calcs),"
                        + "(SELECT stage_time FROM calcs),(SELECT stage_speed FROM speed),"
                        + "(SELECT sum_dist FROM inserts),(SELECT sum_time FROM inserts),"
                        + "(SELECT sum_speed FROM inserts),(SELECT sum2_dist FROM inserts),"
                        + "(SELECT sum2_time FROM inserts),(SELECT sum2_speed FROM inserts),"
                        + "(SELECT max_distance FROM inserts),(SELECT min_distance FROM inserts),"
                        + "(SELECT max_time FROM inserts),(SELECT min_time FROM inserts),"
                        + "(SELECT max_speed FROM inserts),(SELECT min_speed FROM inserts),"
                        + "(SELECT num_samples FROM inserts))";
                LOGGER.info("[" + this.getName() + "] Persisting data at NGSICartoDBSink. Schema (" + schema
                        + "), Table (" + tableName + "), Data (" + rows + ")");

                try {
                    backends.get(schema).insert(schema, tableName, withs, fields, rows);
                } catch (Exception e2) {
                    ImmutablePair<Long, Long> bytes = ((CartoDBBackendImpl) backends.get(schema))
                            .finishTransaction();
                    serviceMetrics.add(service, servicePath, 0, 0, 0, 0, 0, 0, bytes.left, bytes.right, 0);
                    throw new CygnusPersistenceError("-, " + e2.getMessage());
                } // try catch
            } // try catch
        } // if
    } // for

    ImmutablePair<Long, Long> bytes = ((CartoDBBackendImpl) backends.get(schema)).finishTransaction();
    serviceMetrics.add(service, servicePath, 0, 0, 0, 0, 0, 0, bytes.left, bytes.right, 0);
}