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:org.apache.tajo.worker.TaskAttemptContext.java

public void setProgress(float progress) {
    float previousProgress = this.progress;

    if (Float.isNaN(progress) || Float.isInfinite(progress)) {
        this.progress = 0.0f;
    } else {//  w  w w  .j a v  a  2 s.  co  m
        this.progress = progress;
    }

    this.progressChanged = previousProgress != progress;
}

From source file:norbert.mynemo.core.evaluation.PersonnalRecommenderEvaluator.java

/**
 * Evaluates the given preferences according to the given recommender using the given training
 * model./* ww w.java 2s .co  m*/
 *
 * <p>
 * The resulting errors are added to {@link #errorStats} and {@link #squaredErrorStats}.
 */
private void evaluate(DataModel trainingModel, Recommender recommender, List<Preference> preferencesToEvaluate)
        throws TasteException {
    for (Preference preference : preferencesToEvaluate) {
        float error = getError(trainingModel, recommender, preference);
        if (!Float.isNaN(error)) {
            errorStats.addValue(error);
            squaredErrorStats.addValue(error * error);
        }
    }
}

From source file:nl.uva.illc.dataselection.InvitationModel.java

public static void burnIN() throws IOException, InterruptedException {

    log.info("BurnIN started ... ");

    HashIntObjMap<Result> results = null;

    for (int i = 1; i <= 1; i++) {

        log.info("Iteration " + i);

        results = HashIntObjMaps.newMutableMap();

        float sPD[][] = new float[2][src_mixdomain.length];

        int split = (int) Math.ceil(src_mixdomain.length / 100000d);

        latch = new CountDownLatch(split);
        for (int sent = 0; sent < src_mixdomain.length; sent += 100000) {
            int end = sent + 100000;
            if (end > src_mixdomain.length) {
                end = src_mixdomain.length;
            }//from   w w w.  j av  a  2 s .  co m
            calcualteBurnInScore(sent, end, sPD);
        }
        latch.await();

        float countPD[] = new float[2];
        countPD[0] = Float.NEGATIVE_INFINITY;
        countPD[1] = Float.NEGATIVE_INFINITY;

        for (int sent = 0; sent < src_mixdomain.length; sent++) {

            if (ignore.containsKey(sent))
                continue;

            if (Float.isNaN(sPD[0][sent]) || Float.isNaN(sPD[1][sent])) {
                ignore.put(sent, sent);
                log.info("Ignoring " + (sent + 1));
                continue;
            }

            countPD[0] = logAdd(countPD[0], sPD[0][sent]);
            countPD[1] = logAdd(countPD[1], sPD[1][sent]);

            results.put(sent, new Result(sent, sPD[0][sent]));

        }

    }

    log.info("BurnIN DONE");

    log.info("Writing outdomain corpus ... ");

    ArrayList<Result> sortedResult = new ArrayList<Result>(results.values());
    Collections.sort(sortedResult);

    PrintWriter src_out = new PrintWriter("outdomain." + SRC + ".encoded");
    PrintWriter trg_out = new PrintWriter("outdomain." + TRG + ".encoded");

    PrintWriter out_score = new PrintWriter("outdomain.scores");

    src_outdomain = new int[src_indomain.length][];
    trg_outdomain = new int[trg_indomain.length][];

    int j = 0;

    for (Result r : sortedResult) {

        int sentIndex = r.sentenceNumber - 1;

        int ssent[] = src_mixdomain[sentIndex];
        int tsent[] = trg_mixdomain[sentIndex];

        out_score.println(r.sentenceNumber + "\t" + r.score);

        src_outdomain[j] = ssent;
        trg_outdomain[j] = tsent;

        for (int w = 1; w < ssent.length; w++) {
            src_out.print(ssent[w]);
            src_out.print(" ");
        }
        src_out.println();
        for (int w = 1; w < tsent.length; w++) {
            trg_out.print(tsent[w]);
            trg_out.print(" ");
        }
        trg_out.println();

        j++;

        if (j == src_indomain.length) {
            break;
        }
    }

    out_score.close();

    src_out.close();
    trg_out.close();

    log.info("DONE");

}

From source file:io.github.gjyaiya.stetho.realm.Database.java

private List<Object> flattenRows(Table table, long limit, boolean addRowIndex) {
    Util.throwIfNot(limit >= 0);
    final List<Object> flatList = new ArrayList<>();
    long numColumns = table.getColumnCount();

    final RowFetcher rowFetcher = RowFetcher.getInstance();
    final long tableSize = table.size();
    for (long index = 0; index < limit && index < tableSize; index++) {
        final long row = ascendingOrder ? index : (tableSize - index - 1);
        final RowWrapper rowData = RowWrapper.wrap(rowFetcher.getRow(table, row));
        if (addRowIndex) {
            flatList.add(rowData.getIndex());
        }/*from   w ww.j  a  v  a 2  s.com*/
        for (int column = 0; column < numColumns; column++) {
            switch (rowData.getColumnType(column)) {
            case INTEGER:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    flatList.add(rowData.getLong(column));
                }
                break;
            case BOOLEAN:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    flatList.add(rowData.getBoolean(column));
                }
                break;
            case STRING:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    flatList.add(rowData.getString(column));
                }
                break;
            case BINARY:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    flatList.add(rowData.getBinaryByteArray(column));
                }
                break;
            case FLOAT:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    final float aFloat = rowData.getFloat(column);
                    if (Float.isNaN(aFloat)) {
                        flatList.add("NaN");
                    } else if (aFloat == Float.POSITIVE_INFINITY) {
                        flatList.add("Infinity");
                    } else if (aFloat == Float.NEGATIVE_INFINITY) {
                        flatList.add("-Infinity");
                    } else {
                        flatList.add(aFloat);
                    }
                }
                break;
            case DOUBLE:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    final double aDouble = rowData.getDouble(column);
                    if (Double.isNaN(aDouble)) {
                        flatList.add("NaN");
                    } else if (aDouble == Double.POSITIVE_INFINITY) {
                        flatList.add("Infinity");
                    } else if (aDouble == Double.NEGATIVE_INFINITY) {
                        flatList.add("-Infinity");
                    } else {
                        flatList.add(aDouble);
                    }
                }
                break;
            case OLD_DATE:
            case DATE:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    flatList.add(formatDate(rowData.getDate(column)));
                }
                break;
            case OBJECT:
                if (rowData.isNullLink(column)) {
                    flatList.add(NULL);
                } else {
                    flatList.add(rowData.getLink(column));
                }
                break;
            case LIST:
                // LIST never be null
                flatList.add(formatList(rowData.getLinkList(column)));
                break;
            default:
                flatList.add("unknown column type: " + rowData.getColumnType(column));
                break;
            }
        }
    }

    if (limit < table.size()) {
        for (int column = 0; column < numColumns; column++) {
            flatList.add("{truncated}");
        }
    }

    return flatList;
}

From source file:com.google.android.car.kitchensink.sensor.SensorsTestFragment.java

private void refreshUi() {
    String summaryString;//  www.ja v  a 2s  .  c om
    synchronized (this) {
        List<String> summary = new ArrayList<>();
        for (Integer i : supportedSensors) {
            CarSensorEvent event = mEventMap.get(i);
            switch (i) {
            case CarSensorManager.SENSOR_TYPE_COMPASS:
                summary.add(getCompassString(event));
                break;
            case CarSensorManager.SENSOR_TYPE_CAR_SPEED:
                summary.add(getContext().getString(R.string.sensor_speed, getTimestamp(event),
                        event == null ? mNaString : event.getCarSpeedData().carSpeed));
                break;
            case CarSensorManager.SENSOR_TYPE_RPM:
                summary.add(getContext().getString(R.string.sensor_rpm, getTimestamp(event),
                        event == null ? mNaString : event.getRpmData().rpm));
                break;
            case CarSensorManager.SENSOR_TYPE_ODOMETER:
                summary.add(getContext().getString(R.string.sensor_odometer, getTimestamp(event),
                        event == null ? mNaString : event.getOdometerData().kms));
                break;
            case CarSensorManager.SENSOR_TYPE_FUEL_LEVEL:
                String level = mNaString;
                String range = mNaString;
                String lowFuelWarning = mNaString;
                if (event != null) {
                    CarSensorEvent.FuelLevelData fuelData = event.getFuelLevelData();
                    level = fuelData.level == -1 ? level : String.valueOf(fuelData.level);
                    range = fuelData.range == -1 ? range : String.valueOf(fuelData.range);
                    lowFuelWarning = String.valueOf(fuelData.lowFuelWarning);
                }
                summary.add(getContext().getString(R.string.sensor_fuel_level, getTimestamp(event), level,
                        range, lowFuelWarning));
                break;
            case CarSensorManager.SENSOR_TYPE_PARKING_BRAKE:
                summary.add(getContext().getString(R.string.sensor_parking_brake, getTimestamp(event),
                        event == null ? mNaString : event.getParkingBrakeData().isEngaged));
                break;
            case CarSensorManager.SENSOR_TYPE_GEAR:
                summary.add(getContext().getString(R.string.sensor_gear, getTimestamp(event),
                        event == null ? mNaString : event.getGearData().gear));
                break;
            case CarSensorManager.SENSOR_TYPE_NIGHT:
                summary.add(getContext().getString(R.string.sensor_night, getTimestamp(event),
                        event == null ? mNaString : event.getNightData().isNightMode));
                break;
            case CarSensorManager.SENSOR_TYPE_LOCATION:
                summary.add(getLocationString(event));
                break;
            case CarSensorManager.SENSOR_TYPE_DRIVING_STATUS:
                String drivingStatus = mNaString;
                String binDrivingStatus = mNaString;
                if (event != null) {
                    CarSensorEvent.DrivingStatusData drivingStatusData = event.getDrivingStatusData();
                    drivingStatus = String.valueOf(drivingStatusData.status);
                    binDrivingStatus = Integer.toBinaryString(drivingStatusData.status);
                }
                summary.add(getContext().getString(R.string.sensor_driving_status, getTimestamp(event),
                        drivingStatus, binDrivingStatus));
                break;
            case CarSensorManager.SENSOR_TYPE_ENVIRONMENT:
                String temperature = mNaString;
                String pressure = mNaString;
                if (event != null) {
                    CarSensorEvent.EnvironmentData env = event.getEnvironmentData();
                    temperature = Float.isNaN(env.temperature) ? temperature : String.valueOf(env.temperature);
                    pressure = Float.isNaN(env.pressure) ? pressure : String.valueOf(env.pressure);
                }
                summary.add(getContext().getString(R.string.sensor_environment, getTimestamp(event),
                        temperature, pressure));
                break;
            case CarSensorManager.SENSOR_TYPE_ACCELEROMETER:
                summary.add(getAccelerometerString(event));
                break;
            case CarSensorManager.SENSOR_TYPE_GPS_SATELLITE:
                summary.add(getGpsSatelliteString(event));
                break;
            case CarSensorManager.SENSOR_TYPE_GYROSCOPE:
                summary.add(getGyroscopeString(event));
                break;
            case CarSensorManager.SENSOR_TYPE_WHEEL_TICK_DISTANCE:
                if (event != null) {
                    CarSensorEvent.CarWheelTickDistanceData d = event.getCarWheelTickDistanceData();
                    summary.add(getContext().getString(R.string.sensor_wheel_ticks, getTimestamp(event),
                            d.sensorResetCount, d.frontLeftWheelDistanceMm, d.frontRightWheelDistanceMm,
                            d.rearLeftWheelDistanceMm, d.rearRightWheelDistanceMm));
                } else {
                    summary.add(getContext().getString(R.string.sensor_wheel_ticks, getTimestamp(event),
                            mNaString, mNaString, mNaString, mNaString, mNaString));
                }
                // Get the config data
                try {
                    CarSensorConfig c = mSensorManager
                            .getSensorConfig(CarSensorManager.SENSOR_TYPE_WHEEL_TICK_DISTANCE);
                    summary.add(getContext().getString(R.string.sensor_wheel_ticks_cfg,
                            c.getInt(CarSensorConfig.WHEEL_TICK_DISTANCE_SUPPORTED_WHEELS),
                            c.getInt(CarSensorConfig.WHEEL_TICK_DISTANCE_FRONT_LEFT_UM_PER_TICK),
                            c.getInt(CarSensorConfig.WHEEL_TICK_DISTANCE_FRONT_RIGHT_UM_PER_TICK),
                            c.getInt(CarSensorConfig.WHEEL_TICK_DISTANCE_REAR_LEFT_UM_PER_TICK),
                            c.getInt(CarSensorConfig.WHEEL_TICK_DISTANCE_REAR_RIGHT_UM_PER_TICK)));
                } catch (CarNotConnectedException e) {
                    Log.e(TAG, "Car not connected or not supported", e);
                }
                break;
            case CarSensorManager.SENSOR_TYPE_ABS_ACTIVE:
                summary.add(getContext().getString(R.string.sensor_abs_is_active, getTimestamp(event),
                        event == null ? mNaString : event.getCarAbsActiveData().absIsActive));
                break;

            case CarSensorManager.SENSOR_TYPE_TRACTION_CONTROL_ACTIVE:
                summary.add(getContext().getString(R.string.sensor_traction_control_is_active,
                        getTimestamp(event), event == null ? mNaString
                                : event.getCarTractionControlActiveData().tractionControlIsActive));
                break;
            default:
                // Should never happen.
                Log.w(TAG, "Unrecognized event type: " + i);
            }
        }
        summaryString = TextUtils.join("\n", summary);
    }
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            mSensorInfo.setText(summaryString);
        }
    });
}

From source file:org.codelibs.fess.api.gsa.GsaApiManager.java

protected void processSearchRequest(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) {
    final SearchService searchService = ComponentUtil.getComponent(SearchService.class);
    final FessConfig fessConfig = ComponentUtil.getFessConfig();
    final boolean xmlDtd = OUTPUT_XML.equals(request.getParameter("output"));

    if (!fessConfig.isAcceptedSearchReferer(request.getHeader("referer"))) {
        writeXmlResponse(99, xmlDtd, StringUtil.EMPTY, "Referer is invalid.");
        return;/*from w w w  .j  a v  a  2 s .c o  m*/
    }

    int status = 0;
    String errMsg = StringUtil.EMPTY;
    String query = null;
    final StringBuilder buf = new StringBuilder(1000);
    request.setAttribute(Constants.SEARCH_LOG_ACCESS_TYPE, Constants.SEARCH_LOG_ACCESS_TYPE_GSA);
    try {
        final SearchRenderData data = new SearchRenderData();
        final GsaRequestParams params = new GsaRequestParams(request, fessConfig);
        query = params.getQuery();
        searchService.search(params, data, OptionalThing.empty());
        final String execTime = data.getExecTime();
        final long allRecordCount = data.getAllRecordCount();
        final List<Map<String, Object>> documentItems = data.getDocumentItems();

        final List<String> getFields = new ArrayList<>();
        // meta tags should be returned
        final String getFieldsParam = request.getParameter("getfields");
        if (StringUtil.isNotBlank(getFieldsParam)) {
            getFields.addAll(Arrays.asList(getFieldsParam.split("\\.")));
        }
        final StringBuilder requestUri = new StringBuilder(request.getRequestURI());
        if (request.getQueryString() != null) {
            requestUri.append("?").append(request.getQueryString());
        }
        final String uriQueryString = requestUri.toString();
        // Input/Output encoding
        final String ie = request.getCharacterEncoding();
        final String oe = "UTF-8";
        // IP address
        final String ip = ComponentUtil.getViewHelper().getClientIp(request);

        buf.append("<TM>");
        buf.append(execTime);
        buf.append("</TM>");
        buf.append("<Q>");
        buf.append(escapeXml(query));
        buf.append("</Q>");
        for (final Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            final String[] values = entry.getValue();
            if (values == null) {
                continue;
            }
            final String key = entry.getKey();
            if ("sort".equals(key)) {
                continue;
            }
            for (final String value : values) {
                appendParam(buf, key, value);
            }
        }
        appendParam(buf, "ie", ie);
        if (request.getParameter("oe") == null) {
            appendParam(buf, "oe", oe);
        }
        final String[] langs = params.getLanguages();
        if (langs.length > 0) {
            appendParam(buf, "inlang", langs[0]);
            appendParam(buf, "ulang", langs[0]);
        }
        appendParam(buf, "ip", ip);
        appendParam(buf, "access", "p");
        appendParam(buf, "sort", params.getSortParam(), params.getSortParam());
        appendParam(buf, "entqr", "3");
        appendParam(buf, "entqrm", "0");
        appendParam(buf, "wc", "200");
        appendParam(buf, "wc_mc", "1");
        if (!documentItems.isEmpty()) {
            buf.append("<RES SN=\"");
            buf.append(data.getCurrentStartRecordNumber());
            buf.append("\" EN=\"");
            buf.append(data.getCurrentEndRecordNumber());
            buf.append("\">");
            buf.append("<M>");
            buf.append(allRecordCount);
            buf.append("</M>");
            if (data.isExistPrevPage() || data.isExistNextPage()) {
                buf.append("<NB>");
                if (data.isExistPrevPage()) {
                    long s = data.getCurrentStartRecordNumber() - data.getPageSize() - 1;
                    if (s < 0) {
                        s = 0;
                    }
                    buf.append("<PU>");
                    buf.append(escapeXml(uriQueryString.replaceFirst("start=([0-9]+)", "start=" + s)));
                    buf.append("</PU>");
                }
                if (data.isExistNextPage()) {
                    buf.append("<NU>");
                    buf.append(escapeXml(uriQueryString.replaceFirst("start=([0-9]+)",
                            "start=" + data.getCurrentEndRecordNumber())));
                    buf.append("</NU>");
                }
                buf.append("</NB>");
            }
            long recordNumber = data.getCurrentStartRecordNumber();
            for (final Map<String, Object> document : documentItems) {
                buf.append("<R N=\"");
                buf.append(recordNumber);
                buf.append("\">");
                final String url = DocumentUtil.getValue(document, fessConfig.getIndexFieldUrl(), String.class);
                document.put("UE", url);
                document.put("U", URLDecoder.decode(url, Constants.UTF_8));
                document.put("T", DocumentUtil.getValue(document, fessConfig.getResponseFieldContentTitle(),
                        String.class));
                final float score = DocumentUtil.getValue(document, Constants.SCORE, Float.class, Float.NaN);
                int rk = 10;
                if (!Float.isNaN(score)) {
                    if (score < 0.0) {
                        rk = 0;
                    } else if (score > 1.0) {
                        rk = 10;
                    } else {
                        rk = (int) (score * 10.0);
                    }
                }
                document.put("RK", rk);
                document.put("S", DocumentUtil.getValue(document,
                        fessConfig.getResponseFieldContentDescription(), String.class, StringUtil.EMPTY));
                final String lang = DocumentUtil.getValue(document, fessConfig.getIndexFieldLang(),
                        String.class);
                if (StringUtil.isNotBlank(lang)) {
                    document.put("LANG", lang);
                    document.remove(fessConfig.getIndexFieldLang());
                }
                final String gsaMetaPrefix = fessConfig.getQueryGsaMetaPrefix();
                for (final Map.Entry<String, Object> entry : document.entrySet()) {
                    final String name = entry.getKey();
                    if (StringUtil.isNotBlank(name) && entry.getValue() != null
                            && fessConfig.isGsaResponseFields(name)) {
                        if (name.startsWith(gsaMetaPrefix)) {
                            final String tagName = name.replaceFirst("^" + gsaMetaPrefix, StringUtil.EMPTY);
                            if (getFields.contains(tagName)) {
                                buf.append("<MT N=\"");
                                buf.append(tagName);
                                buf.append("\" V=\"");
                                buf.append(escapeXml(entry.getValue()));
                                buf.append("\"/>");
                            }
                        } else {
                            final String tagName = name;
                            buf.append('<');
                            buf.append(tagName);
                            buf.append('>');
                            buf.append(escapeXml(entry.getValue()));
                            buf.append("</");
                            buf.append(tagName);
                            buf.append('>');
                        }
                    }
                }
                buf.append("<ENT_SOURCE>").append(escapeXml("FESS")).append("</ENT_SOURCE>");
                String lastModified = DocumentUtil.getValue(document, fessConfig.getIndexFieldLastModified(),
                        String.class);
                if (StringUtil.isBlank(lastModified)) {
                    lastModified = StringUtil.EMPTY;
                }
                lastModified = lastModified.split("T")[0];
                buf.append("<FS NAME=\"date\" VALUE=\"").append(escapeXml(lastModified)).append("\"/>");

                buf.append("<HAS>");
                buf.append("<L/>");
                buf.append("<C SZ=\"");
                buf.append(DocumentUtil.getValue(document, fessConfig.getIndexFieldContentLength(), Long.class,
                        Long.valueOf(0)).longValue() / 1000);
                document.remove(fessConfig.getIndexFieldContentLength());
                buf.append("k\" CID=\"");
                buf.append(DocumentUtil.getValue(document, fessConfig.getIndexFieldDocId(), String.class));
                document.remove(fessConfig.getIndexFieldDocId());
                buf.append("\" ENC=\"");
                final String charsetField = fessConfig.getQueryGsaIndexFieldCharset();
                String charset = DocumentUtil.getValue(document, charsetField, String.class);
                document.remove(charsetField);
                if (StringUtil.isBlank(charset)) {
                    final String contentTypeField = fessConfig.getQueryGsaIndexFieldContentType();
                    charset = DocumentUtil.getValue(document, contentTypeField, String.class);
                    document.remove(contentTypeField);
                    if (StringUtil.isNotBlank(charset)) {
                        final Matcher m = Pattern.compile(".*;\\s*charset=(.+)").matcher(charset);
                        if (m.matches()) {
                            charset = m.group(1);
                        }
                    }
                    if (StringUtil.isBlank(charset)) {
                        charset = Constants.UTF_8;
                    }
                }
                buf.append(charset);
                buf.append("\"/>");
                buf.append("</HAS>");
                buf.append("</R>");
                recordNumber++;
            }
            buf.append("</RES>");
        }
    } catch (final Exception e) {
        status = 1;
        errMsg = e.getMessage();
        if (errMsg == null) {
            errMsg = e.getClass().getName();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to process a search request.", e);
        }
        if (e instanceof InvalidAccessTokenException) {
            final InvalidAccessTokenException iate = (InvalidAccessTokenException) e;
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setHeader("WWW-Authenticate", "Bearer error=\"" + iate.getType() + "\"");
        }
    }

    writeXmlResponse(status, xmlDtd, buf.toString(), errMsg);
}

From source file:com.alibaba.android.vlayout.layout.StaggeredGridLayoutHelper.java

@Override
public void layoutViews(RecyclerView.Recycler recycler, RecyclerView.State state,
        LayoutStateWrapper layoutState, LayoutChunkResult result, LayoutManagerHelper helper) {
    if (isOutOfRange(layoutState.getCurrentPosition())) {
        return;//  ww w.  j a  va 2 s . c om
    }

    ensureLanes();

    final boolean layoutInVertical = helper.getOrientation() == VERTICAL;
    final OrientationHelper orientationHelper = helper.getMainOrientationHelper();
    final OrientationHelper secondaryOrientationHelper = helper.getSecondaryOrientationHelper();

    mRemainingSpans.set(0, mNumLanes, true);

    final int targetLine;
    final int recycleLine;

    // Line of the furthest row.
    if (layoutState.getLayoutDirection() == LAYOUT_END) {
        // ignore padding for recycler
        recycleLine = layoutState.getOffset() + layoutState.getAvailable();
        targetLine = recycleLine + layoutState.getExtra() + orientationHelper.getEndPadding();
    } else { // LAYOUT_START
        // ignore padding for recycler
        recycleLine = layoutState.getOffset() - layoutState.getAvailable();
        targetLine = recycleLine - layoutState.getExtra() - orientationHelper.getStartAfterPadding();
    }

    updateAllRemainingSpans(layoutState.getLayoutDirection(), targetLine, orientationHelper);

    final int defaultNewViewLine = layoutState.getOffset();

    while (layoutState.hasMore(state) && !mRemainingSpans.isEmpty()
            && !isOutOfRange(layoutState.getCurrentPosition())) {
        boolean isStartLine = false, isEndLine = false;
        View view = layoutState.next(recycler);

        if (view == null) {
            break;
        }

        VirtualLayoutManager.LayoutParams lp = (VirtualLayoutManager.LayoutParams) view.getLayoutParams();

        // find the span to put the view
        final int position = lp.getViewPosition();
        final int spanIndex = mLazySpanLookup.getSpan(position);
        Span currentSpan;
        boolean assignSpan = spanIndex == INVALID_SPAN_ID;
        if (assignSpan) {
            currentSpan = getNextSpan(defaultNewViewLine, layoutState, helper);
            mLazySpanLookup.setSpan(position, currentSpan);
        } else {
            currentSpan = mSpans[spanIndex];
        }
        // handle margin for start/end line
        isStartLine = position - getRange().getLower() < mNumLanes;
        isEndLine = getRange().getUpper() - position - 1 < mNumLanes;

        helper.addChildView(layoutState, view);

        if (layoutInVertical) {
            int widthSpec = helper.getChildMeasureSpec(mColLength, lp.width, false);
            int heightSpec = helper
                    .getChildMeasureSpec(orientationHelper.getTotalSpace(),
                            Float.isNaN(lp.mAspectRatio) ? lp.height
                                    : (int) (View.MeasureSpec.getSize(widthSpec) / lp.mAspectRatio + 0.5f),
                            true);
            helper.measureChild(view, widthSpec, heightSpec);
        } else {
            int heightSpec = helper.getChildMeasureSpec(mColLength, lp.height, false);
            int widthSpec = helper
                    .getChildMeasureSpec(orientationHelper.getTotalSpace(),
                            Float.isNaN(lp.mAspectRatio) ? lp.width
                                    : (int) (View.MeasureSpec.getSize(heightSpec) * lp.mAspectRatio + 0.5f),
                            true);
            helper.measureChild(view, widthSpec, heightSpec);
        }

        int start;
        int end;

        if (layoutState.getLayoutDirection() == LAYOUT_END) {
            start = currentSpan.getEndLine(defaultNewViewLine, orientationHelper);

            if (isStartLine) {
                start += layoutInVertical ? mMarginTop + mPaddingTop : mMarginLeft + mPaddingLeft;
                //Log.d(TAG", "startLine " + position + " " + start);
            } else {
                start += (layoutInVertical ? mVGap : mHGap);
                //Log.d(TAG", "normalStartLine " + position + " " + start);
            }
            end = start + orientationHelper.getDecoratedMeasurement(view);
        } else {
            if (isEndLine) {
                end = currentSpan.getStartLine(defaultNewViewLine, orientationHelper)
                        - (layoutInVertical ? mMarginBottom + mPaddingRight : mMarginRight + mPaddingRight);
                //Log.d(TAG", "endLine " + position + " " + end);
            } else {
                end = currentSpan.getStartLine(defaultNewViewLine, orientationHelper)
                        - (layoutInVertical ? mVGap : mHGap);
                //Log.d(TAG", "normalEndLine " + position + " " + end);
            }
            start = end - orientationHelper.getDecoratedMeasurement(view);
        }

        // lp.mSpan = currentSpan;
        if (layoutState.getLayoutDirection() == LAYOUT_END) {
            currentSpan.appendToSpan(view, orientationHelper);
        } else {
            currentSpan.prependToSpan(view, orientationHelper);
        }

        // left, right in vertical layout
        int otherStart = ((currentSpan.mIndex == mNumLanes - 1)
                ? currentSpan.mIndex * (mColLength + mEachGap) - mEachGap + mLastGap
                : currentSpan.mIndex * (mColLength + mEachGap))
                + secondaryOrientationHelper.getStartAfterPadding();

        if (layoutInVertical) {
            otherStart += mMarginLeft + mPaddingLeft;
        } else {
            otherStart += mMarginTop + mPaddingTop;
        }

        int otherEnd = otherStart + orientationHelper.getDecoratedMeasurementInOther(view);

        if (layoutInVertical) {
            layoutChild(view, otherStart, start, otherEnd, end, helper);
        } else {
            layoutChild(view, start, otherStart, end, otherEnd, helper);
        }

        updateRemainingSpans(currentSpan, layoutState.getLayoutDirection(), targetLine, orientationHelper);

        recycle(recycler, layoutState, currentSpan, recycleLine, helper);

        handleStateOnResult(result, view);
    }

    if (isOutOfRange(layoutState.getCurrentPosition())) {
        // reach the end of layout, cache the gap
        // TODO: how to retain gap
        if (layoutState.getLayoutDirection() == LayoutStateWrapper.LAYOUT_START) {
            for (Span span : mSpans) {
                if (span.mCachedStart != INVALID_LINE) {
                    span.mLastEdgeStart = span.mCachedStart;
                }
            }
        } else {
            for (Span span : mSpans) {
                if (span.mCachedEnd != INVALID_LINE) {
                    span.mLastEdgeEnd = span.mCachedEnd;
                }
            }
        }
    }

    if (layoutState.getLayoutDirection() == LayoutStateWrapper.LAYOUT_START) {
        if (!isOutOfRange(layoutState.getCurrentPosition()) && layoutState.hasMore(state)) {
            final int maxStart = getMaxStart(orientationHelper.getStartAfterPadding(), orientationHelper);
            result.mConsumed = layoutState.getOffset() - maxStart;
        } else {
            final int minStart = getMinStart(orientationHelper.getEndAfterPadding(), orientationHelper);
            result.mConsumed = layoutState.getOffset() - minStart
                    + (layoutInVertical ? mMarginTop + mPaddingTop : mMarginLeft + mPaddingLeft);
        }
    } else {
        if (!isOutOfRange(layoutState.getCurrentPosition()) && layoutState.hasMore(state)) {
            final int minEnd = getMinEnd(orientationHelper.getEndAfterPadding(), orientationHelper);
            result.mConsumed = minEnd - layoutState.getOffset();
        } else {
            final int maxEnd = getMaxEnd(orientationHelper.getEndAfterPadding(), orientationHelper);
            result.mConsumed = maxEnd - layoutState.getOffset()
                    + (layoutInVertical ? mMarginBottom + mPaddingBottom : mMarginRight + mPaddingRight);
        }

    }
}

From source file:com.alibaba.android.layoutmanager.layoutmanager.StaggeredGridLayoutHelper.java

@Override
public void layoutViews(RecyclerView.Recycler recycler, RecyclerView.State state,
        LayoutStateWrapper layoutState, LayoutChunkResult result, LayoutManagerHelper helper) {
    if (isOutOfRange(layoutState.getCurrentPosition())) {
        return;/*from  ww  w .j a  v  a2 s . c  om*/
    }

    ensureLanes();

    final boolean layoutInVertical = helper.getOrientation() == VERTICAL;
    final OrientationHelper orientationHelper = helper.getMainOrientationHelper();
    final OrientationHelper secondaryOrientationHelper = helper.getSecondaryOrientationHelper();

    mRemainingSpans.set(0, mNumLanes, true);

    final int targetLine;
    final int recycleLine;

    // Line of the furthest row.
    if (layoutState.getLayoutDirection() == LAYOUT_END) {
        // ignore padding for recycler
        recycleLine = layoutState.getOffset() + layoutState.getAvailable();
        targetLine = recycleLine + layoutState.getExtra() + orientationHelper.getEndPadding();
    } else { // LAYOUT_START
        // ignore padding for recycler
        recycleLine = layoutState.getOffset() - layoutState.getAvailable();
        targetLine = recycleLine - layoutState.getExtra() - orientationHelper.getStartAfterPadding();
    }

    updateAllRemainingSpans(layoutState.getLayoutDirection(), targetLine, orientationHelper);

    final int defaultNewViewLine = layoutState.getOffset();

    while (layoutState.hasMore(state) && !mRemainingSpans.isEmpty()
            && !isOutOfRange(layoutState.getCurrentPosition())) {
        boolean isStartLine = false, isEndLine = false;
        View view = layoutState.next(recycler);

        if (view == null) {
            break;
        }

        VirtualLayoutManager.LayoutParams lp = (VirtualLayoutManager.LayoutParams) view.getLayoutParams();

        // find the span to put the view
        final int position = lp.getViewPosition();
        final int spanIndex = mLazySpanLookup.getSpan(position);
        Span currentSpan;
        boolean assignSpan = spanIndex == INVALID_SPAN_ID;
        if (assignSpan) {
            currentSpan = getNextSpan(defaultNewViewLine, layoutState, helper);
            mLazySpanLookup.setSpan(position, currentSpan);
        } else {
            currentSpan = mSpans[spanIndex];
        }
        // handle margin for start/end line
        isStartLine = position - getRange().getLower() < mNumLanes;
        isEndLine = getRange().getUpper() - position - 1 < mNumLanes;

        helper.addChildView(layoutState, view);

        if (layoutInVertical) {
            int widthSpec = helper.getChildMeasureSpec(mColLength, lp.width, false);
            int heightSpec = helper
                    .getChildMeasureSpec(orientationHelper.getTotalSpace(),
                            Float.isNaN(lp.mAspectRatio) ? lp.height
                                    : (int) (View.MeasureSpec.getSize(widthSpec) / lp.mAspectRatio + 0.5f),
                            true);
            helper.measureChild(view, widthSpec, heightSpec);
        } else {
            int heightSpec = helper.getChildMeasureSpec(mColLength, lp.height, false);
            int widthSpec = helper
                    .getChildMeasureSpec(orientationHelper.getTotalSpace(),
                            Float.isNaN(lp.mAspectRatio) ? lp.width
                                    : (int) (View.MeasureSpec.getSize(heightSpec) * lp.mAspectRatio + 0.5f),
                            true);
            helper.measureChild(view, widthSpec, heightSpec);
        }

        int start;
        int end;

        if (layoutState.getLayoutDirection() == LAYOUT_END) {
            start = currentSpan.getEndLine(defaultNewViewLine, orientationHelper);

            if (isStartLine) {
                start += layoutInVertical ? mMarginTop + mPaddingTop : mMarginLeft + mPaddingLeft;
                //Log.d(TAG", "startLine " + position + " " + start);
            } else {
                start += (layoutInVertical ? mVGap : mHGap);
                //Log.d(TAG", "normalStartLine " + position + " " + start);
            }
            end = start + orientationHelper.getDecoratedMeasurement(view);
        } else {
            if (isEndLine) {
                end = currentSpan.getStartLine(defaultNewViewLine, orientationHelper)
                        - (layoutInVertical ? mMarginBottom + mPaddingRight : mMarginRight + mPaddingRight);
                //Log.d(TAG", "endLine " + position + " " + end);
            } else {
                end = currentSpan.getStartLine(defaultNewViewLine, orientationHelper)
                        - (layoutInVertical ? mVGap : mHGap);
                //Log.d(TAG", "normalEndLine " + position + " " + end);
            }
            start = end - orientationHelper.getDecoratedMeasurement(view);
        }

        // lp.mSpan = currentSpan;
        if (layoutState.getLayoutDirection() == LAYOUT_END) {
            currentSpan.appendToSpan(view, orientationHelper);
        } else {
            currentSpan.prependToSpan(view, orientationHelper);
        }

        // left, right in vertical layout
        int otherStart = ((currentSpan.mIndex == mNumLanes - 1)
                ? currentSpan.mIndex * (mColLength + mEachGap) - mEachGap + mLastGap
                : currentSpan.mIndex * (mColLength + mEachGap))
                + secondaryOrientationHelper.getStartAfterPadding();

        if (layoutInVertical) {
            otherStart += mMarginLeft + mPaddingLeft;
        } else {
            otherStart += mMarginTop + mPaddingTop;
        }

        int otherEnd = otherStart + orientationHelper.getDecoratedMeasurementInOther(view);

        if (layoutInVertical) {
            layoutChild(view, otherStart, start, otherEnd, end, helper);
        } else {
            layoutChild(view, start, otherStart, end, otherEnd, helper);
        }

        updateRemainingSpans(currentSpan, layoutState.getLayoutDirection(), targetLine, orientationHelper);

        recycle(recycler, layoutState, currentSpan, recycleLine, helper);

        handleStateOnResult(result, view);
    }

    if (isOutOfRange(layoutState.getCurrentPosition())) {
        // reach the end of layout, cache the gap
        // TODO: how to retain gap
        if (layoutState.getLayoutDirection() == LayoutStateWrapper.LAYOUT_START) {
            for (Span span : mSpans) {
                if (span.mCachedStart != INVALID_LINE) {
                    span.mLastEdgeStart = span.mCachedStart;
                }
            }
        } else {
            for (Span span : mSpans) {
                if (span.mCachedEnd != INVALID_LINE) {
                    span.mLastEdgeEnd = span.mCachedEnd;
                }
            }
        }
    }

    if (layoutState.getLayoutDirection() == LayoutStateWrapper.LAYOUT_START) {
        if (!isOutOfRange(layoutState.getCurrentPosition()) && layoutState.hasMore(state)) {
            final int maxStart = getMaxStart(orientationHelper.getStartAfterPadding(), orientationHelper);
            result.mConsumed = layoutState.getOffset() - maxStart;
        } else {
            final int minStart = getMinStart(orientationHelper.getEndAfterPadding(), orientationHelper);
            result.mConsumed = layoutState.getOffset() - minStart
                    + (layoutInVertical ? mMarginTop + mPaddingTop : mMarginLeft + mPaddingLeft);
        }
    } else {
        if (!isOutOfRange(layoutState.getCurrentPosition()) && layoutState.hasMore(state)) {
            Log.d("Longer", "in range ");
            final int minEnd = getMinEnd(orientationHelper.getEndAfterPadding(), orientationHelper);
            result.mConsumed = minEnd - layoutState.getOffset();
        } else {
            Log.d("Longer", "out range ");
            final int maxEnd = getMaxEnd(orientationHelper.getEndAfterPadding(), orientationHelper);
            result.mConsumed = maxEnd - layoutState.getOffset()
                    + (layoutInVertical ? mMarginBottom + mPaddingBottom : mMarginRight + mPaddingRight);
            Log.d("Longer", "consumed " + result.mConsumed);
        }

    }
}

From source file:org.apache.tajo.worker.TaskAttemptContext.java

public void setExecutorProgress(float executorProgress) {
    if (Float.isNaN(executorProgress) || Float.isInfinite(executorProgress)) {
        executorProgress = 0.0f;/*from   w  ww  . java2  s .c  om*/
    }

    if (hasFetchPhase()) {
        setProgress(fetcherProgress + (executorProgress * 0.5f));
    } else {
        setProgress(executorProgress);
    }
}

From source file:com.jjoe64.graphview.series.LineGraphSeries.java

/**
 * plots the series/* ww  w.  ja v a2 s .c om*/
 * draws the line and the background
 *
 * @param graphView graphview
 * @param canvas canvas
 * @param isSecondScale flag if it is the second scale
 */
@Override
public void draw(GraphView graphView, Canvas canvas, boolean isSecondScale) {
    resetDataPoints();

    // get data
    double maxX = graphView.getViewport().getMaxX(false);
    double minX = graphView.getViewport().getMinX(false);

    double maxY;
    double minY;
    if (isSecondScale) {
        maxY = graphView.getSecondScale().getMaxY(false);
        minY = graphView.getSecondScale().getMinY(false);
    } else {
        maxY = graphView.getViewport().getMaxY(false);
        minY = graphView.getViewport().getMinY(false);
    }

    Iterator<E> values = getValues(minX, maxX);

    // draw background
    double lastEndY = 0;
    double lastEndX = 0;

    // draw data
    mPaint.setStrokeWidth(mStyles.thickness);
    mPaint.setColor(getColor());
    mPaintBackground.setColor(mStyles.backgroundColor);

    Paint paint;
    if (mCustomPaint != null) {
        paint = mCustomPaint;
    } else {
        paint = mPaint;
    }

    mPath.reset();

    if (mStyles.drawBackground) {
        mPathBackground.reset();
    }

    double diffY = maxY - minY;
    double diffX = maxX - minX;

    float graphHeight = graphView.getGraphContentHeight();
    float graphWidth = graphView.getGraphContentWidth();
    float graphLeft = graphView.getGraphContentLeft();
    float graphTop = graphView.getGraphContentTop();

    lastEndY = 0;
    lastEndX = 0;

    // needed to end the path for background
    double lastUsedEndX = 0;
    double lastUsedEndY = 0;
    float firstX = -1;
    float firstY = -1;
    float lastRenderedX = Float.NaN;
    int i = 0;
    float lastAnimationReferenceX = graphLeft;

    boolean sameXSkip = false;
    float minYOnSameX = 0f;
    float maxYOnSameX = 0f;

    while (values.hasNext()) {
        E value = values.next();

        double valY = value.getY() - minY;
        double ratY = valY / diffY;
        double y = graphHeight * ratY;

        double valueX = value.getX();
        double valX = valueX - minX;
        double ratX = valX / diffX;
        double x = graphWidth * ratX;

        double orgX = x;
        double orgY = y;

        if (i > 0) {
            // overdraw
            boolean isOverdrawY = false;
            boolean isOverdrawEndPoint = false;
            boolean skipDraw = false;

            if (x > graphWidth) { // end right
                double b = ((graphWidth - lastEndX) * (y - lastEndY) / (x - lastEndX));
                y = lastEndY + b;
                x = graphWidth;
                isOverdrawEndPoint = true;
            }
            if (y < 0) { // end bottom
                // skip when previous and this point is out of bound
                if (lastEndY < 0) {
                    skipDraw = true;
                } else {
                    double b = ((0 - lastEndY) * (x - lastEndX) / (y - lastEndY));
                    x = lastEndX + b;
                }
                y = 0;
                isOverdrawY = isOverdrawEndPoint = true;
            }
            if (y > graphHeight) { // end top
                // skip when previous and this point is out of bound
                if (lastEndY > graphHeight) {
                    skipDraw = true;
                } else {
                    double b = ((graphHeight - lastEndY) * (x - lastEndX) / (y - lastEndY));
                    x = lastEndX + b;
                }
                y = graphHeight;
                isOverdrawY = isOverdrawEndPoint = true;
            }
            if (lastEndX < 0) { // start left
                double b = ((0 - x) * (y - lastEndY) / (lastEndX - x));
                lastEndY = y - b;
                lastEndX = 0;
            }

            // we need to save the X before it will be corrected when overdraw y
            float orgStartX = (float) lastEndX + (graphLeft + 1);

            if (lastEndY < 0) { // start bottom
                if (!skipDraw) {
                    double b = ((0 - y) * (x - lastEndX) / (lastEndY - y));
                    lastEndX = x - b;
                }
                lastEndY = 0;
                isOverdrawY = true;
            }
            if (lastEndY > graphHeight) { // start top
                // skip when previous and this point is out of bound
                if (!skipDraw) {
                    double b = ((graphHeight - y) * (x - lastEndX) / (lastEndY - y));
                    lastEndX = x - b;
                }
                lastEndY = graphHeight;
                isOverdrawY = true;
            }

            float startX = (float) lastEndX + (graphLeft + 1);
            float startY = (float) (graphTop - lastEndY) + graphHeight;
            float endX = (float) x + (graphLeft + 1);
            float endY = (float) (graphTop - y) + graphHeight;
            float startXAnimated = startX;
            float endXAnimated = endX;

            if (endX < startX) {
                // dont draw from right to left
                skipDraw = true;
            }

            // NaN can happen when previous and current value is out of y bounds
            if (!skipDraw && !Float.isNaN(startY) && !Float.isNaN(endY)) {
                // animation
                if (mAnimated) {
                    if ((Double.isNaN(mLastAnimatedValue) || mLastAnimatedValue < valueX)) {
                        long currentTime = System.currentTimeMillis();
                        if (mAnimationStart == 0) {
                            // start animation
                            mAnimationStart = currentTime;
                            mAnimationStartFrameNo = 0;
                        } else {
                            // anti-lag: wait a few frames
                            if (mAnimationStartFrameNo < 15) {
                                // second time
                                mAnimationStart = currentTime;
                                mAnimationStartFrameNo++;
                            }
                        }
                        float timeFactor = (float) (currentTime - mAnimationStart) / ANIMATION_DURATION;
                        float factor = mAnimationInterpolator.getInterpolation(timeFactor);
                        if (timeFactor <= 1.0) {
                            startXAnimated = (startX - lastAnimationReferenceX) * factor
                                    + lastAnimationReferenceX;
                            startXAnimated = Math.max(startXAnimated, lastAnimationReferenceX);
                            endXAnimated = (endX - lastAnimationReferenceX) * factor + lastAnimationReferenceX;
                            ViewCompat.postInvalidateOnAnimation(graphView);
                        } else {
                            // animation finished
                            mLastAnimatedValue = valueX;
                        }
                    } else {
                        lastAnimationReferenceX = endX;
                    }
                }

                // draw data point
                if (!isOverdrawEndPoint) {
                    if (mStyles.drawDataPoints) {
                        // draw first datapoint
                        Paint.Style prevStyle = paint.getStyle();
                        paint.setStyle(Paint.Style.FILL);
                        canvas.drawCircle(endXAnimated, endY, mStyles.dataPointsRadius, paint);
                        paint.setStyle(prevStyle);
                    }
                    registerDataPoint(endX, endY, value);
                }

                if (mDrawAsPath) {
                    mPath.moveTo(startXAnimated, startY);
                }
                // performance opt.
                if (Float.isNaN(lastRenderedX) || Math.abs(endX - lastRenderedX) > .3f) {
                    if (mDrawAsPath) {
                        mPath.lineTo(endXAnimated, endY);
                    } else {
                        // render vertical lines that were skipped
                        if (sameXSkip) {
                            sameXSkip = false;
                            renderLine(canvas,
                                    new float[] { lastRenderedX, minYOnSameX, lastRenderedX, maxYOnSameX },
                                    paint);
                        }
                        renderLine(canvas, new float[] { startXAnimated, startY, endXAnimated, endY }, paint);
                    }
                    lastRenderedX = endX;
                } else {
                    // rendering on same x position
                    // save min+max y position and render it as line
                    if (sameXSkip) {
                        minYOnSameX = Math.min(minYOnSameX, endY);
                        maxYOnSameX = Math.max(maxYOnSameX, endY);
                    } else {
                        // first
                        sameXSkip = true;
                        minYOnSameX = Math.min(startY, endY);
                        maxYOnSameX = Math.max(startY, endY);
                    }
                }

            }

            if (mStyles.drawBackground) {
                if (isOverdrawY) {
                    // start draw original x
                    if (firstX == -1) {
                        firstX = orgStartX;
                        firstY = startY;
                        mPathBackground.moveTo(orgStartX, startY);
                    }
                    // from original start to new start
                    mPathBackground.lineTo(startXAnimated, startY);
                }
                if (firstX == -1) {
                    firstX = startXAnimated;
                    firstY = startY;
                    mPathBackground.moveTo(startXAnimated, startY);
                }
                mPathBackground.lineTo(startXAnimated, startY);
                mPathBackground.lineTo(endXAnimated, endY);
            }

            lastUsedEndX = endXAnimated;
            lastUsedEndY = endY;
        } else if (mStyles.drawDataPoints) {
            //fix: last value not drawn as datapoint. Draw first point here, and then on every step the end values (above)
            float first_X = (float) x + (graphLeft + 1);
            float first_Y = (float) (graphTop - y) + graphHeight;

            if (first_X >= graphLeft && first_Y <= (graphTop + graphHeight)) {
                if (mAnimated && (Double.isNaN(mLastAnimatedValue) || mLastAnimatedValue < valueX)) {
                    long currentTime = System.currentTimeMillis();
                    if (mAnimationStart == 0) {
                        // start animation
                        mAnimationStart = currentTime;
                    }
                    float timeFactor = (float) (currentTime - mAnimationStart) / ANIMATION_DURATION;
                    float factor = mAnimationInterpolator.getInterpolation(timeFactor);
                    if (timeFactor <= 1.0) {
                        first_X = (first_X - lastAnimationReferenceX) * factor + lastAnimationReferenceX;
                        ViewCompat.postInvalidateOnAnimation(graphView);
                    } else {
                        // animation finished
                        mLastAnimatedValue = valueX;
                    }
                }

                Paint.Style prevStyle = paint.getStyle();
                paint.setStyle(Paint.Style.FILL);
                canvas.drawCircle(first_X, first_Y, mStyles.dataPointsRadius, paint);
                paint.setStyle(prevStyle);
            }
        }
        lastEndY = orgY;
        lastEndX = orgX;
        i++;
    }

    if (mDrawAsPath) {
        // draw at the end
        canvas.drawPath(mPath, paint);
    }

    if (mStyles.drawBackground && firstX != -1) {
        // end / close path
        if (lastUsedEndY != graphHeight + graphTop) {
            // dont draw line to same point, otherwise the path is completely broken
            mPathBackground.lineTo((float) lastUsedEndX, graphHeight + graphTop);
        }
        mPathBackground.lineTo(firstX, graphHeight + graphTop);
        if (firstY != graphHeight + graphTop) {
            // dont draw line to same point, otherwise the path is completely broken
            mPathBackground.lineTo(firstX, firstY);
        }
        //mPathBackground.close();
        canvas.drawPath(mPathBackground, mPaintBackground);
    }
}