Example usage for java.lang Double doubleToRawLongBits

List of usage examples for java.lang Double doubleToRawLongBits

Introduction

In this page you can find the example usage for java.lang Double doubleToRawLongBits.

Prototype

@HotSpotIntrinsicCandidate
public static native long doubleToRawLongBits(double value);

Source Link

Document

Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "double format" bit layout, preserving Not-a-Number (NaN) values.

Usage

From source file:com.SecUpwN.AIMSICD.fragments.MapFragment.java

/**
 * Description:    Loads Signal Strength Database details to plot on the map,
 * only entries which have a location (lon, lat) are used.
 *///from w ww  .  ja v a 2  s .com
private void loadEntries() {

    new AsyncTask<Void, Void, GeoPoint>() {
        @Override
        protected GeoPoint doInBackground(Void... voids) {
            //int signal;

            mCellTowerGridMarkerClusterer.getItems().clear();

            //New function only gets bts from DBe_import by sim network
            loadOcidMarkersByNetwork();

            List<CellTowerMarker> items = new LinkedList<>();

            Cursor c = null;
            try {
                // Grab cell data from CELL_TABLE (cellinfo) --> DBi_bts
                c = mDbHelper.getCellData();
            } catch (IllegalStateException ix) {
                log.error("Problem getting data from CELL_TABLE", ix);
            }

            /*
            This function is getting cells we logged from DBi_bts
             */
            if (c != null && c.moveToFirst()) {
                do {
                    if (isCancelled()) {
                        return null;
                    }
                    // The indexing here is that of DB table
                    final int cellID = c.getInt(c.getColumnIndex(DBTableColumnIds.DBI_BTS_CID)); // CID
                    final int lac = c.getInt(c.getColumnIndex(DBTableColumnIds.DBI_BTS_LAC)); // LAC
                    final int mcc = c.getInt(c.getColumnIndex(DBTableColumnIds.DBI_BTS_MCC)); // MCC
                    final int mnc = c.getInt(c.getColumnIndex(DBTableColumnIds.DBI_BTS_MNC)); // MNC
                    final double dLat = c.getDouble(c.getColumnIndex(DBTableColumnIds.DBI_BTS_LAT)); // Lat
                    final double dLng = c.getDouble(c.getColumnIndex(DBTableColumnIds.DBI_BTS_LON)); // Lon

                    if (Double.doubleToRawLongBits(dLat) == 0 && Double.doubleToRawLongBits(dLng) == 0) {
                        continue;
                    }
                    // TODO this (signal) is not in DBi_bts
                    // signal = 1;
                    //c.getInt(c.getColumnIndex(DBTableColumnIds.DBE_IMPORT_AVG_SIGNAL));  // signal
                    // In case of missing or negative signal, set a default fake signal,
                    // so that we can still draw signal circles.  ?
                    //if (signal <= 0) {
                    //    signal = 20;
                    //}

                    if (Double.doubleToRawLongBits(dLat) != 0 || Double.doubleToRawLongBits(dLng) != 0) {
                        loc = new GeoPoint(dLat, dLng);

                        CellTowerMarker ovm = new CellTowerMarker(getActivity(), mMap, "Cell ID: " + cellID, "",
                                loc,
                                new MarkerData(String.valueOf(cellID), String.valueOf(loc.getLatitude()),
                                        String.valueOf(loc.getLongitude()), String.valueOf(lac),
                                        String.valueOf(mcc), String.valueOf(mnc), "", false));
                        // The pin of our current position
                        ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_blue));

                        items.add(ovm);
                    }

                } while (c.moveToNext());
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Helpers.msgLong(getActivity(), getString(R.string.no_tracked_locations_found));
                    }
                });
            }

            GeoPoint ret = new GeoPoint(0, 0);
            if (mBound) {
                try {
                    int mcc = mAimsicdService.getCell().getMCC();
                    double[] d = mDbHelper.getDefaultLocation(mcc);
                    ret = new GeoPoint(d[0], d[1]);
                } catch (Exception e) {
                    log.error("Error getting default location!", e);
                }
            }
            if (c != null) {
                c.close();
            }
            // plot neighbouring cells
            while (mAimsicdService == null) {
                try {
                    if (isCancelled()) {
                        return null;
                    }
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    log.warn("thread interrupted", e);
                }
            }
            List<Cell> nc = mAimsicdService.getCellTracker().updateNeighbouringCells();
            for (Cell cell : nc) {
                if (isCancelled()) {
                    return null;
                }
                try {
                    loc = new GeoPoint(cell.getLat(), cell.getLon());
                    CellTowerMarker ovm = new CellTowerMarker(getActivity(), mMap,
                            getString(R.string.cell_id_label) + cell.getCID(), "", loc,
                            new MarkerData(String.valueOf(cell.getCID()), String.valueOf(loc.getLatitude()),
                                    String.valueOf(loc.getLongitude()), String.valueOf(cell.getLAC()),
                                    String.valueOf(cell.getMCC()), String.valueOf(cell.getMNC()), "", false));

                    // The pin of other BTS
                    ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_orange));
                    items.add(ovm);
                } catch (Exception e) {
                    log.error("Error plotting neighbouring cells", e);
                }
            }

            mCellTowerGridMarkerClusterer.addAll(items);

            return ret;
        }

        /**
         *  TODO:  We need a manual way to add our own location in case:
         *          a) GPS is jammed or not working
         *          b) WiFi location is not used
         *          c) Default MCC is too far off
         *
         * @param defaultLoc Default location to open map on
         */
        @Override
        protected void onPostExecute(GeoPoint defaultLoc) {
            if (loc != null && (Double.doubleToRawLongBits(loc.getLatitude()) != 0
                    && Double.doubleToRawLongBits(loc.getLongitude()) != 0)) {
                mMap.getController().setZoom(16);
                mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
            } else {
                if (mBound) {
                    // Try and find last known location and zoom there
                    GeoLocation lastLoc = mAimsicdService.lastKnownLocation();
                    if (lastLoc != null) {
                        loc = new GeoPoint(lastLoc.getLatitudeInDegrees(), lastLoc.getLongitudeInDegrees());

                        mMap.getController().setZoom(16);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    } else {
                        //Use MCC to move camera to an approximate location near Countries Capital
                        loc = defaultLoc;

                        mMap.getController().setZoom(12);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    }
                }
            }
            if (mCellTowerGridMarkerClusterer != null) {
                if (BuildConfig.DEBUG && mCellTowerGridMarkerClusterer.getItems() != null) {
                    log.verbose("CellTowerMarkers.invalidate() markers.size():"
                            + mCellTowerGridMarkerClusterer.getItems().size());
                }
                //Drawing markers of cell tower immediately as possible
                mCellTowerGridMarkerClusterer.invalidate();
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:com.secupwn.aimsicd.ui.fragments.MapFragment.java

/**
 * Description:    Loads Signal Strength Database details to plot on the map,
 * only entries which have a location (lon, lat) are used.
 *//* ww w. j  a v a 2  s . c  om*/
private void loadEntries() {

    new AsyncTask<Void, Void, GeoPoint>() {
        @Override
        protected GeoPoint doInBackground(Void... voids) {
            //int signal;
            @Cleanup
            Realm realm = Realm.getDefaultInstance();

            mCellTowerGridMarkerClusterer.getItems().clear();

            loadOcidMarkersByNetwork();

            List<CellTowerMarker> items = new LinkedList<>();

            RealmResults<BaseTransceiverStation> baseStations = realm.where(BaseTransceiverStation.class)
                    .findAll();

            /*
            This function is getting cells we logged from DBi_bts
             */
            if (baseStations.size() > 0) {
                for (BaseTransceiverStation baseStation : baseStations) {

                    if (isCancelled() || !isAdded()) {
                        return null;
                    }
                    // The indexing here is that of DB table
                    final int cellID = baseStation.getCellId();
                    final int lac = baseStation.getLocationAreaCode();
                    final int mcc = baseStation.getMobileCountryCode();
                    final int mnc = baseStation.getMobileNetworkCode();
                    final int psc = baseStation.getPrimaryScramblingCode();

                    Measure first = realm.where(Measure.class)
                            .equalTo("baseStation.cellId", baseStation.getCellId()).findFirst();
                    final String rat = first.getRadioAccessTechnology();
                    final double dLat = baseStation.getGpsLocation().getLatitude();
                    final double dLng = baseStation.getGpsLocation().getLongitude();

                    if (Double.doubleToRawLongBits(dLat) == 0 && Double.doubleToRawLongBits(dLng) == 0) {
                        continue;
                    }
                    // TODO this (signal) is not in DBi_bts
                    // signal = 1;
                    //c.getInt(c.getColumnIndex(DBTableColumnIds.DBE_IMPORT_AVG_SIGNAL));  // signal
                    // In case of missing or negative signal, set a default fake signal,
                    // so that we can still draw signal circles.  ?
                    //if (signal <= 0) {
                    //    signal = 20;
                    //}

                    if (Double.doubleToRawLongBits(dLat) != 0 || Double.doubleToRawLongBits(dLng) != 0) {
                        loc = new GeoPoint(dLat, dLng);

                        CellTowerMarker ovm = new CellTowerMarker(getActivity(), mMap, "Cell ID: " + cellID, "",
                                loc,
                                new MarkerData(getContext(), String.valueOf(cellID),
                                        String.valueOf(loc.getLatitude()), String.valueOf(loc.getLongitude()),
                                        String.valueOf(lac), String.valueOf(mcc), String.valueOf(mnc),
                                        String.valueOf(psc), rat, "", false));
                        // The pin of our current position
                        ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_blue));

                        items.add(ovm);
                    }
                }
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Helpers.msgLong(getActivity(), getString(R.string.no_tracked_locations_found));
                    }
                });
            }

            GeoPoint ret = new GeoPoint(0, 0);
            if (mBound) {
                try {
                    int mcc = mAimsicdService.getCell().getMobileCountryCode();
                    GpsLocation d = mDbHelper.getDefaultLocation(realm, mcc);
                    ret = new GeoPoint(d.getLatitude(), d.getLongitude());
                } catch (Exception e) {
                    log.error("Error getting default location!", e);
                }
            }
            // plot neighboring cells
            while (mAimsicdService == null) {
                try {
                    if (isCancelled() || !isAdded()) {
                        return null;
                    }
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    log.warn("thread interrupted", e);
                }
            }
            List<Cell> nc = mAimsicdService.getCellTracker().updateNeighboringCells();
            for (Cell cell : nc) {
                if (isCancelled() || !isAdded()) {
                    return null;
                }
                try {
                    loc = new GeoPoint(cell.getLat(), cell.getLon());
                    CellTowerMarker ovm = new CellTowerMarker(getActivity(), mMap,
                            getString(R.string.cell_id_label) + cell.getCellId(), "", loc,
                            new MarkerData(getContext(), String.valueOf(cell.getCellId()),
                                    String.valueOf(loc.getLatitude()), String.valueOf(loc.getLongitude()),
                                    String.valueOf(cell.getLocationAreaCode()),
                                    String.valueOf(cell.getMobileCountryCode()),
                                    String.valueOf(cell.getMobileNetworkCode()),
                                    String.valueOf(cell.getPrimaryScramblingCode()),
                                    String.valueOf(cell.getRat()), "", false));

                    // The pin of other BTS
                    ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_orange));
                    items.add(ovm);
                } catch (Exception e) {
                    log.error("Error plotting neighboring cells", e);
                }
            }

            mCellTowerGridMarkerClusterer.addAll(items);

            return ret;
        }

        /**
         *  TODO:  We need a manual way to add our own location in case:
         *          a) GPS is jammed or not working
         *          b) WiFi location is not used
         *          c) Default MCC is too far off
         *
         * @param defaultLoc Default location to open map on
         */
        @Override
        protected void onPostExecute(GeoPoint defaultLoc) {
            if (loc != null && (Double.doubleToRawLongBits(loc.getLatitude()) != 0
                    && Double.doubleToRawLongBits(loc.getLongitude()) != 0)) {
                mMap.getController().setZoom(16);
                mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
            } else {
                if (mBound) {
                    // Try and find last known location and zoom there
                    GeoLocation lastLoc = mAimsicdService.lastKnownLocation();
                    if (lastLoc != null) {
                        loc = new GeoPoint(lastLoc.getLatitudeInDegrees(), lastLoc.getLongitudeInDegrees());

                        mMap.getController().setZoom(16);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    } else {
                        //Use MCC to move camera to an approximate location near Countries Capital
                        loc = defaultLoc;

                        mMap.getController().setZoom(12);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    }
                }
            }
            if (mCellTowerGridMarkerClusterer != null) {
                if (BuildConfig.DEBUG && mCellTowerGridMarkerClusterer.getItems() != null) {
                    log.verbose("CellTowerMarkers.invalidate() markers.size():"
                            + mCellTowerGridMarkerClusterer.getItems().size());
                }
                //Drawing markers of cell tower immediately as possible
                mCellTowerGridMarkerClusterer.invalidate();
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:cn.iie.haiep.hbase.value.Bytes.java

/**
 * Serialize a double as the IEEE 754 double format output. The resultant
 * array will be 8 bytes long.//from  w  ww .  ja v  a2 s.  co  m
 *
 * @param d value
 * @return the double represented as byte []
 */
public static byte[] toBytes(final double d) {
    // Encode it as a long
    return Bytes.toBytes(Double.doubleToRawLongBits(d));
}

From source file:com.iteye.wwwcomy.lxn.utils.BytesUtil.java

/**
 * Serialize a double as the IEEE 754 double format output. The resultant
 * array will be 8 bytes long./*from w ww. j  ava2  s.  c  o m*/
 * 
 * @param d
 *            value
 * @return the double represented as byte []
 */
public static byte[] toBytes(final double d) {
    // Encode it as a long
    return BytesUtil.toBytes(Double.doubleToRawLongBits(d));
}

From source file:sphericalGeo.SphericalDiffusionModel.java

/** Fast approximation of 1.0 / sqrt(x).
   * See <a href="http://www.beyond3d.com/content/articles/8/">http://www.beyond3d.com/content/articles/8/</a>
   * @param x Positive value to estimate inverse of square root of
   * @return Approximately 1.0 / sqrt(x)
   **//*from  www.  j a  va  2 s  . com*/
public static double invSqrt(double x) {
    double xhalf = 0.5 * x;
    long i = Double.doubleToRawLongBits(x);
    i = 0x5FE6EB50C7B537AAL - (i >> 1);
    x = Double.longBitsToDouble(i);
    x = x * (1.5 - xhalf * x * x);
    return x;
}

From source file:org.renjin.parser.NumericLiterals.java

/**
 * Finds the closest double-precision floating point number to the given decimal string, parsed by
 * {@link #parseDoubleDecimal(CharSequence, int, int, int, char)} above.
 *
 * <p>This implementation is based on OpenJDK's {@code com.sun.misc.FloatingDecimal.ASCIIToBinaryBuffer.doubleValue()},
 * but included here nearly verbatim to avoid a dependency on an internal SDK class. The original code
 * is copyright 1996, 2013, Oracle and/or its affiliates and licensed under the GPL v2.</p></p>
 *
 * @param in the input string// w w w  . j a  va 2  s  .  co  m
 * @param sign the sign, -1 or +1, parsed above in {@link #parseDouble(CharSequence, int, int, char, boolean)}
 * @param startIndex the index at which to start parsing
 * @param endIndex the index, exclusive, at which to stop parsing
 * @param decimalPoint the decimal point character to use. Generally either '.' or ','
 * @return the number as a {@code double}, or {@code NA} if the string is malformatted.
 */
public static double doubleValue(boolean isNegative, int decExponent, char[] digits, int nDigits) {
    int kDigits = Math.min(nDigits, MAX_DECIMAL_DIGITS + 1);
    //
    // convert the lead kDigits to a long integer.
    //
    // (special performance hack: start to do it using int)
    int iValue = (int) digits[0] - (int) '0';
    int iDigits = Math.min(kDigits, INT_DECIMAL_DIGITS);
    for (int i = 1; i < iDigits; i++) {
        iValue = iValue * 10 + (int) digits[i] - (int) '0';
    }
    long lValue = (long) iValue;
    for (int i = iDigits; i < kDigits; i++) {
        lValue = lValue * 10L + (long) ((int) digits[i] - (int) '0');
    }
    double dValue = (double) lValue;
    int exp = decExponent - kDigits;
    //
    // lValue now contains a long integer with the value of
    // the first kDigits digits of the number.
    // dValue contains the (double) of the same.
    //

    if (nDigits <= MAX_DECIMAL_DIGITS) {
        //
        // possibly an easy case.
        // We know that the digits can be represented
        // exactly. And if the exponent isn't too outrageous,
        // the whole thing can be done with one operation,
        // thus one rounding error.
        // Note that all our constructors trim all leading and
        // trailing zeros, so simple values (including zero)
        // will always end up here
        //
        if (exp == 0 || dValue == 0.0) {
            return (isNegative) ? -dValue : dValue; // small floating integer
        } else if (exp >= 0) {
            if (exp <= MAX_SMALL_TEN) {
                //
                // Can get the answer with one operation,
                // thus one roundoff.
                //
                double rValue = dValue * SMALL_10_POW[exp];
                return (isNegative) ? -rValue : rValue;
            }
            int slop = MAX_DECIMAL_DIGITS - kDigits;
            if (exp <= MAX_SMALL_TEN + slop) {
                //
                // We can multiply dValue by 10^(slop)
                // and it is still "small" and exact.
                // Then we can multiply by 10^(exp-slop)
                // with one rounding.
                //
                dValue *= SMALL_10_POW[slop];
                double rValue = dValue * SMALL_10_POW[exp - slop];
                return (isNegative) ? -rValue : rValue;
            }
            //
            // Else we have a hard case with a positive exp.
            //
        } else {
            if (exp >= -MAX_SMALL_TEN) {
                //
                // Can get the answer in one division.
                //
                double rValue = dValue / SMALL_10_POW[-exp];
                return (isNegative) ? -rValue : rValue;
            }
            //
            // Else we have a hard case with a negative exp.
            //
        }
    }

    //
    // Harder cases:
    // The sum of digits plus exponent is greater than
    // what we think we can do with one error.
    //
    // Start by approximating the right answer by,
    // naively, scaling by powers of 10.
    //
    if (exp > 0) {
        if (decExponent > MAX_DECIMAL_EXPONENT + 1) {
            //
            // Lets face it. This is going to be
            // Infinity. Cut to the chase.
            //
            return (isNegative) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
        }
        if ((exp & 15) != 0) {
            dValue *= SMALL_10_POW[exp & 15];
        }
        if ((exp >>= 4) != 0) {
            int j;
            for (j = 0; exp > 1; j++, exp >>= 1) {
                if ((exp & 1) != 0) {
                    dValue *= BIG_10_POW[j];
                }
            }
            //
            // The reason for the weird exp > 1 condition
            // in the above loop was so that the last multiply
            // would get unrolled. We handle it here.
            // It could overflow.
            //
            double t = dValue * BIG_10_POW[j];
            if (Double.isInfinite(t)) {
                //
                // It did overflow.
                // Look more closely at the result.
                // If the exponent is just one too large,
                // then use the maximum finite as our estimate
                // value. Else call the result infinity
                // and punt it.
                // ( I presume this could happen because
                // rounding forces the result here to be
                // an ULP or two larger than
                // Double.MAX_VALUE ).
                //
                t = dValue / 2.0;
                t *= BIG_10_POW[j];
                if (Double.isInfinite(t)) {
                    return (isNegative) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
                }
                t = Double.MAX_VALUE;
            }
            dValue = t;
        }
    } else if (exp < 0) {
        exp = -exp;
        if (decExponent < MIN_DECIMAL_EXPONENT - 1) {
            //
            // Lets face it. This is going to be
            // zero. Cut to the chase.
            //
            return (isNegative) ? -0.0 : 0.0;
        }
        if ((exp & 15) != 0) {
            dValue /= SMALL_10_POW[exp & 15];
        }
        if ((exp >>= 4) != 0) {
            int j;
            for (j = 0; exp > 1; j++, exp >>= 1) {
                if ((exp & 1) != 0) {
                    dValue *= TINY_10_POW[j];
                }
            }
            //
            // The reason for the weird exp > 1 condition
            // in the above loop was so that the last multiply
            // would get unrolled. We handle it here.
            // It could underflow.
            //
            double t = dValue * TINY_10_POW[j];
            if (t == 0.0) {
                //
                // It did underflow.
                // Look more closely at the result.
                // If the exponent is just one too small,
                // then use the minimum finite as our estimate
                // value. Else call the result 0.0
                // and punt it.
                // ( I presume this could happen because
                // rounding forces the result here to be
                // an ULP or two less than
                // Double.MIN_VALUE ).
                //
                t = dValue * 2.0;
                t *= TINY_10_POW[j];
                if (t == 0.0) {
                    return (isNegative) ? -0.0 : 0.0;
                }
                t = Double.MIN_VALUE;
            }
            dValue = t;
        }
    }

    //
    // dValue is now approximately the result.
    // The hard part is adjusting it, by comparison
    // with FDBigInteger arithmetic.
    // Formulate the EXACT big-number result as
    // bigD0 * 10^exp
    //
    if (nDigits > MAX_NDIGITS) {
        nDigits = MAX_NDIGITS + 1;
        digits[MAX_NDIGITS] = '1';
    }
    FDBigInteger bigD0 = new FDBigInteger(lValue, digits, kDigits, nDigits);
    exp = decExponent - nDigits;

    long ieeeBits = Double.doubleToRawLongBits(dValue); // IEEE-754 bits of double candidate
    final int B5 = Math.max(0, -exp); // powers of 5 in bigB, value is not modified inside correctionLoop
    final int D5 = Math.max(0, exp); // powers of 5 in bigD, value is not modified inside correctionLoop
    bigD0 = bigD0.multByPow52(D5, 0);
    bigD0.makeImmutable(); // prevent bigD0 modification inside correctionLoop
    FDBigInteger bigD = null;
    int prevD2 = 0;

    correctionLoop: while (true) {
        // here ieeeBits can't be NaN, Infinity or zero
        int binexp = (int) (ieeeBits >>> EXP_SHIFT);
        long bigBbits = ieeeBits & SIGNIF_BIT_MASK;
        if (binexp > 0) {
            bigBbits |= FRACT_HOB;
        } else { // Normalize denormalized numbers.
            assert bigBbits != 0L : bigBbits; // doubleToBigInt(0.0)
            int leadingZeros = Long.numberOfLeadingZeros(bigBbits);
            int shift = leadingZeros - (63 - EXP_SHIFT);
            bigBbits <<= shift;
            binexp = 1 - shift;
        }
        binexp -= EXP_BIAS;
        int lowOrderZeros = Long.numberOfTrailingZeros(bigBbits);
        bigBbits >>>= lowOrderZeros;
        final int bigIntExp = binexp - EXP_SHIFT + lowOrderZeros;
        final int bigIntNBits = EXP_SHIFT + 1 - lowOrderZeros;

        //
        // Scale bigD, bigB appropriately for
        // big-integer operations.
        // Naively, we multiply by powers of ten
        // and powers of two. What we actually do
        // is keep track of the powers of 5 and
        // powers of 2 we would use, then factor out
        // common divisors before doing the work.
        //
        int B2 = B5; // powers of 2 in bigB
        int D2 = D5; // powers of 2 in bigD
        int Ulp2; // powers of 2 in halfUlp.
        if (bigIntExp >= 0) {
            B2 += bigIntExp;
        } else {
            D2 -= bigIntExp;
        }
        Ulp2 = B2;
        // shift bigB and bigD left by a number s. t.
        // halfUlp is still an integer.
        int hulpbias;
        if (binexp <= -EXP_BIAS) {
            // This is going to be a denormalized number
            // (if not actually zero).
            // half an ULP is at 2^-(DoubleConsts.EXP_BIAS+EXP_SHIFT+1)
            hulpbias = binexp + lowOrderZeros + EXP_BIAS;
        } else {
            hulpbias = 1 + lowOrderZeros;
        }
        B2 += hulpbias;
        D2 += hulpbias;
        // if there are common factors of 2, we might just as well
        // factor them out, as they add nothing useful.
        int common2 = Math.min(B2, Math.min(D2, Ulp2));
        B2 -= common2;
        D2 -= common2;
        Ulp2 -= common2;
        // do multiplications by powers of 5 and 2
        FDBigInteger bigB = FDBigInteger.valueOfMulPow52(bigBbits, B5, B2);
        if (bigD == null || prevD2 != D2) {
            bigD = bigD0.leftShift(D2);
            prevD2 = D2;
        }
        //
        // to recap:
        // bigB is the scaled-big-int version of our floating-point
        // candidate.
        // bigD is the scaled-big-int version of the exact value
        // as we understand it.
        // halfUlp is 1/2 an ulp of bigB, except for special cases
        // of exact powers of 2
        //
        // the plan is to compare bigB with bigD, and if the difference
        // is less than halfUlp, then we're satisfied. Otherwise,
        // use the ratio of difference to halfUlp to calculate a fudge
        // factor to add to the floating value, then go 'round again.
        //
        FDBigInteger diff;
        int cmpResult;
        boolean overvalue;
        if ((cmpResult = bigB.cmp(bigD)) > 0) {
            overvalue = true; // our candidate is too big.
            diff = bigB.leftInplaceSub(bigD); // bigB is not user further - reuse
            if ((bigIntNBits == 1) && (bigIntExp > -EXP_BIAS + 1)) {
                // candidate is a normalized exact power of 2 and
                // is too big (larger than Double.MIN_NORMAL). We will be subtracting.
                // For our purposes, ulp is the ulp of the
                // next smaller range.
                Ulp2 -= 1;
                if (Ulp2 < 0) {
                    // rats. Cannot de-scale ulp this far.
                    // must scale diff in other direction.
                    Ulp2 = 0;
                    diff = diff.leftShift(1);
                }
            }
        } else if (cmpResult < 0) {
            overvalue = false; // our candidate is too small.
            diff = bigD.rightInplaceSub(bigB); // bigB is not user further - reuse
        } else {
            // the candidate is exactly right!
            // this happens with surprising frequency
            break correctionLoop;
        }
        cmpResult = diff.cmpPow52(B5, Ulp2);
        if ((cmpResult) < 0) {
            // difference is small.
            // this is close enough
            break correctionLoop;
        } else if (cmpResult == 0) {
            // difference is exactly half an ULP
            // round to some other value maybe, then finish
            if ((ieeeBits & 1) != 0) { // half ties to even
                ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp
            }
            break correctionLoop;
        } else {
            // difference is non-trivial.
            // could scale addend by ratio of difference to
            // halfUlp here, if we bothered to compute that difference.
            // Most of the time ( I hope ) it is about 1 anyway.
            ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp
            if (ieeeBits == 0 || ieeeBits == EXP_BIT_MASK) { // 0.0 or Double.POSITIVE_INFINITY
                break correctionLoop; // oops. Fell off end of range.
            }
            continue; // try again.
        }

    }
    if (isNegative) {
        ieeeBits |= SIGN_BIT_MASK;
    }
    return Double.longBitsToDouble(ieeeBits);
}

From source file:org.freedesktop.dbus.Message.java

/**
 * Appends a value to the message./*  ww  w  .ja va 2 s. c o  m*/
 * The type of the value is read from a D-Bus signature and used to marshall
 * the value.
 * 
 * @param sigb
 *            A buffer of the D-Bus signature.
 * @param sigofs
 *            The offset into the signature corresponding to this value.
 * @param data
 *            The value to marshall.
 * @return The offset into the signature of the end of this value's type.
 */
@SuppressWarnings("unchecked")
private int appendone(byte[] sigb, int sigofs, Object data) throws DBusException {
    try {
        int i = sigofs;
        if (log.isTraceEnabled()) {
            log.trace(this.bytecounter);
            log.trace("Appending type: " + ((char) sigb[i]) + " value: " + data);
        }

        // pad to the alignment of this type.
        pad(sigb[i]);
        switch (sigb[i]) {
        case ArgumentType.BYTE:
            appendByte(((Number) data).byteValue());
            break;
        case ArgumentType.BOOLEAN:
            appendint(((Boolean) data).booleanValue() ? 1 : 0, 4);
            break;
        case ArgumentType.DOUBLE:
            long l = Double.doubleToLongBits(((Number) data).doubleValue());
            appendint(l, 8);
            break;
        case ArgumentType.FLOAT:
            int rf = Float.floatToIntBits(((Number) data).floatValue());
            appendint(rf, 4);
            break;
        case ArgumentType.UINT32:
            appendint(((Number) data).longValue(), 4);
            break;
        case ArgumentType.INT64:
            appendint(((Number) data).longValue(), 8);
            break;
        case ArgumentType.UINT64:
            if (this.big) {
                appendint(((UInt64) data).top(), 4);
                appendint(((UInt64) data).bottom(), 4);
            } else {
                appendint(((UInt64) data).bottom(), 4);
                appendint(((UInt64) data).top(), 4);
            }
            break;
        case ArgumentType.INT32:
            appendint(((Number) data).intValue(), 4);
            break;
        case ArgumentType.UINT16:
            appendint(((Number) data).intValue(), 2);
            break;
        case ArgumentType.INT16:
            appendint(((Number) data).shortValue(), 2);
            break;
        case ArgumentType.STRING:
        case ArgumentType.OBJECT_PATH:
            // Strings are marshalled as a UInt32 with the length,
            // followed by the String, followed by a null byte.
            String payload = data.toString();
            byte[] payloadbytes = null;
            try {
                payloadbytes = payload.getBytes("UTF-8");
            } catch (UnsupportedEncodingException UEe) {
                throw new DBusException("System does not support UTF-8 encoding", UEe);
            }
            if (log.isTraceEnabled()) {
                log.trace("Appending String of length " + payloadbytes.length);
            }
            appendint(payloadbytes.length, 4);
            appendBytes(payloadbytes);
            appendBytes(padding[1]);
            // pad(ArgumentType.STRING);? do we need this?
            break;
        case ArgumentType.SIGNATURE:
            // Signatures are marshalled as a byte with the length,
            // followed by the String, followed by a null byte.
            // Signatures are generally short, so preallocate the array
            // for the string, length and null byte.
            if (data instanceof Type[])
                payload = Marshalling.getDBusType((Type[]) data);
            else
                payload = (String) data;
            byte[] pbytes = payload.getBytes();
            preallocate(2 + pbytes.length);
            appendByte((byte) pbytes.length);
            appendBytes(pbytes);
            appendByte((byte) 0);
            break;
        case ArgumentType.ARRAY:
            // Arrays are given as a UInt32 for the length in bytes,
            // padding to the element alignment, then elements in
            // order. The length is the length from the end of the
            // initial padding to the end of the last element.

            if (log.isTraceEnabled()) {
                if (data instanceof Object[])
                    log.trace("Appending array: " + Arrays.deepToString((Object[]) data));
            }

            byte[] alen = new byte[4];
            appendBytes(alen);
            pad(sigb[++i]);
            long c = this.bytecounter;

            // optimise primatives
            if (data.getClass().isArray() && data.getClass().getComponentType().isPrimitive()) {
                byte[] primbuf;
                int algn = getAlignment(sigb[i]);
                int len = Array.getLength(data);
                switch (sigb[i]) {
                case ArgumentType.BYTE:
                    primbuf = (byte[]) data;
                    break;
                case ArgumentType.INT16:
                case ArgumentType.INT32:
                case ArgumentType.INT64:
                    primbuf = new byte[len * algn];
                    for (int j = 0, k = 0; j < len; j++, k += algn)
                        marshallint(Array.getLong(data, j), primbuf, k, algn);
                    break;
                case ArgumentType.BOOLEAN:
                    primbuf = new byte[len * algn];
                    for (int j = 0, k = 0; j < len; j++, k += algn)
                        marshallint(Array.getBoolean(data, j) ? 1 : 0, primbuf, k, algn);
                    break;
                case ArgumentType.DOUBLE:
                    primbuf = new byte[len * algn];
                    if (data instanceof float[])
                        for (int j = 0, k = 0; j < len; j++, k += algn)
                            marshallint(Double.doubleToRawLongBits(((float[]) data)[j]), primbuf, k, algn);
                    else
                        for (int j = 0, k = 0; j < len; j++, k += algn)
                            marshallint(Double.doubleToRawLongBits(((double[]) data)[j]), primbuf, k, algn);
                    break;
                case ArgumentType.FLOAT:
                    primbuf = new byte[len * algn];
                    for (int j = 0, k = 0; j < len; j++, k += algn)
                        marshallint(Float.floatToRawIntBits(((float[]) data)[j]), primbuf, k, algn);
                    break;
                default:
                    throw new MarshallingException("Primative array being sent as non-primative array.");
                }
                appendBytes(primbuf);
            } else if (data instanceof List) {
                Object[] contents = ((List<Object>) data).toArray();
                int diff = i;
                ensureBuffers(contents.length * 4);
                for (Object o : contents)
                    diff = appendone(sigb, i, o);
                i = diff;
            } else if (data instanceof Map) {
                int diff = i;
                ensureBuffers(((Map<Object, Object>) data).size() * 6);
                for (Map.Entry<Object, Object> o : ((Map<Object, Object>) data).entrySet())
                    diff = appendone(sigb, i, o);
                if (i == diff) {
                    // advance the type parser even on 0-size arrays.
                    Vector<Type> temp = new Vector<>();
                    byte[] temp2 = new byte[sigb.length - diff];
                    System.arraycopy(sigb, diff, temp2, 0, temp2.length);
                    String temp3 = new String(temp2);
                    int temp4 = Marshalling.getJavaType(temp3, temp, 1);
                    diff += temp4;
                }
                i = diff;
            } else {
                Object[] contents = (Object[]) data;
                ensureBuffers(contents.length * 4);
                int diff = i;
                for (Object o : contents)
                    diff = appendone(sigb, i, o);
                i = diff;
            }
            if (log.isTraceEnabled()) {
                log.trace("start: " + c + " end: " + this.bytecounter + " length: " + (this.bytecounter - c));
            }
            marshallint(this.bytecounter - c, alen, 0, 4);
            break;
        case ArgumentType.STRUCT1:
            // Structs are aligned to 8 bytes
            // and simply contain each element marshalled in order
            Object[] contents;
            if (data instanceof Container)
                contents = ((Container) data).getParameters();
            else
                contents = (Object[]) data;
            ensureBuffers(contents.length * 4);
            int j = 0;
            for (i++; sigb[i] != ArgumentType.STRUCT2; i++)
                i = appendone(sigb, i, contents[j++]);
            break;
        case ArgumentType.DICT_ENTRY1:
            // Dict entries are the same as structs.
            if (data instanceof Map.Entry) {
                i++;
                i = appendone(sigb, i, ((Map.Entry<Object, Object>) data).getKey());
                i++;
                i = appendone(sigb, i, ((Map.Entry<Object, Object>) data).getValue());
                i++;
            } else {
                contents = (Object[]) data;
                j = 0;
                for (i++; sigb[i] != ArgumentType.DICT_ENTRY2; i++)
                    i = appendone(sigb, i, contents[j++]);
            }
            break;
        case ArgumentType.VARIANT:
            // Variants are marshalled as a signature
            // followed by the value.
            if (data instanceof Variant) {
                Variant<?> var = (Variant<?>) data;
                appendone(new byte[] { ArgumentType.SIGNATURE }, 0, var.getSig());
                appendone((var.getSig()).getBytes(), 0, var.getValue());
            } else if (data instanceof Object[]) {
                contents = (Object[]) data;
                appendone(new byte[] { ArgumentType.SIGNATURE }, 0, contents[0]);
                appendone(((String) contents[0]).getBytes(), 0, contents[1]);
            } else {
                String sig = Marshalling.getDBusType(data.getClass())[0];
                appendone(new byte[] { ArgumentType.SIGNATURE }, 0, sig);
                appendone((sig).getBytes(), 0, data);
            }
            break;
        }
        return i;
    } catch (ClassCastException CCe) {
        throw new MarshallingException(
                String.format("Trying to marshall to unconvertable type (from %s to %s).",
                        data.getClass().getName(), sigb[sigofs]),
                CCe);
    }
}

From source file:it.unibo.alchemist.model.implementations.actions.SocialForceAgent.java

@Override
public void execute() {
    // Retrieve the local neighborhood
    final Neighborhood<List<ILsaMolecule>> neigh = getLocalNeighborhood();
    targetPositions = null;/*from  w  w  w .java2s  . c o  m*/
    bestNode = null;

    // If a group doesn't exists
    if (groupId == 0) {
        // Execute only the minimum gradient value search
        minimumGradientSearch(neigh);
    } else { // If a group exist
        // If minimum gradient value search is selected
        if (getMinimumGradient) {
            // For each node in the neighborhood
            minimumGradientSearch(neigh);

            // If there aren't any minimum gradient node, return
            if (bestNode == null || bestNode.contains(ACTIVE)) {
                return;
            }
            releasepheromone();
        } else {
            // If the maximum pheromone value search
            maximumpheromoneSearch(neigh);

            // If there aren't any minumum gradient node, return
            if (bestNode == null || bestNode.contains(ACTIVE)) {
                /*
                 * TODO: the pedestrian may loop in here. This is a bug.
                 */
                return;
            }
            checkMaxpheromoneNodeDistance();
        }
    }

    // If there aren't any minumum gradient node, return
    if (bestNode == null || bestNode.contains(ACTIVE)) {
        return;
    }

    if (targetPositions != null) {
        // Get target x and y coordinates
        final double x = targetPositions.getCartesianCoordinates()[0];
        final double y = targetPositions.getCartesianCoordinates()[1];
        double dx = 0;
        double dy = 0;
        double ax = 0;
        double ay = 0;

        // TARGET FORCE - Compute the target node attractive force
        // contribution
        final Position mypos = getCurrentPosition();
        final double myx = mypos.getCartesianCoordinates()[0];
        final double myy = mypos.getCartesianCoordinates()[1];
        final double distancex = x - myx;
        final double distancey = y - myy;
        final double dist = env.getDistanceBetweenNodes(bestNode, getNode());
        final double targetForceX = distancex / dist; // vector components
        final double targetForceY = distancey / dist;

        // DESIRED FORCE - Compute the desired force starting from the
        // target force and the agent's speed
        final Position desiredForce = new Continuous2DEuclidean(targetForceX * vmax, targetForceY * vmax);

        // SOCIAL FORCE - Compute neighbors pedestrians repulsive force
        // contribution
        final Position socialForce = computeInteractions(desiredForce, myx, myy);

        /*
         * DODGE FORCE - Compute the force contribution that makes
         * pedestrian turn rightor left in order to dodge other pedestrians
         */
        final Position dodgeForce = computeDodgeForce(neigh, desiredForce, mypos);

        // OBSTACLE FORCE - Compute near obstacles repulsive force
        // contribution
        final Position obstacleForce = computeObstacleForce(myx, myy, mypos);

        // Compute acceleration components as a sum between all forces
        // acting on the agent
        ax = desiredForceFactor * desiredForce.getCartesianCoordinates()[0]
                + socialForceFactor * socialForce.getCartesianCoordinates()[0]
                + dodgeForceFactor * dodgeForce.getCartesianCoordinates()[0]
                + obstacleForceFactor * obstacleForce.getCartesianCoordinates()[0];

        ay = desiredForceFactor * desiredForce.getCartesianCoordinates()[1]
                + socialForceFactor * socialForce.getCartesianCoordinates()[1]
                + dodgeForceFactor * dodgeForce.getCartesianCoordinates()[1]
                + obstacleForceFactor * obstacleForce.getCartesianCoordinates()[1];

        // Compute new speed components
        vx = momentumFactor * vx + ax;
        vy = momentumFactor * vy + ay;

        // Check if new speed is greater than max speed, adjust it
        final double speed = Math.sqrt(vx * vx + vy * vy);
        if (speed > vmax) {
            vx = (vx / speed) * vmax; // compute the vector components
            vy = (vy / speed) * vmax;
        }

        // Compute displacement components
        dx = deltaT * vx;
        dy = deltaT * vy;

        // DIRECTION ADJUSTMENT
        /*
         * Check if both new displacement components aren't opposite to
         * previous displacement components.So an agent ignore those
         * displacement that lead him to make a step back.
         */
        if ((Double.longBitsToDouble(Double.doubleToRawLongBits(dxOld) ^ Double.doubleToRawLongBits(dx))) < 0
                && (Double.longBitsToDouble(
                        Double.doubleToRawLongBits(dyOld) ^ Double.doubleToRawLongBits(dy))) < 0) {
            if (rs.nextDouble() > 1 - pejorativeMoveProbability) {
                dx = 0;
                dy = 0;
            }
        } else {
            // Compute the new direction components as a weighted average
            // between old and freshly computed direction components.
            dx = (dxOld * oldW + dx * newW) / (oldW + newW);
            dy = (dyOld * oldW + dy * newW) / (oldW + newW);
        }
        // Store new direction components for the next cycle
        dxOld = dx;
        dyOld = dy;

        // BODY-TO-BODY INTERACION ADJUSTMENT
        // For each node in the neighborhood
        for (final Node<List<ILsaMolecule>> node : neigh.getNeighbors()) {
            final ILsaNode n = (ILsaNode) node;
            // If the current node is a person
            if (n.getConcentration(PERSON).size() != 0) {
                final Position pos = env.getPosition(n);
                double xOther = 0, yOther = 0;
                // If the distance between me and the current person is
                // less than a certain range
                if (pos.getDistanceTo(mypos) < proximityDecelerationRange) {
                    xOther = pos.getCartesianCoordinates()[0];
                    yOther = pos.getCartesianCoordinates()[1];
                    // If the current person is in front of me, so
                    // decelerate
                    if ((dx > 0 && xOther > myx) || (dx < 0 && xOther < myx)) {
                        dx = dx * decelerationFactor;
                    }
                    if ((dy > 0 && yOther > myy) || (dy < 0 && yOther < myy)) {
                        dy = dy * decelerationFactor;
                    }
                }
            }
        }

        // STOPPING THE MOVEMENT AT THE DESTINATION
        // If the final target node is in line of sight
        if (stopAtTarget && targetInLineOfSight) {
            /*
             * If the displacement is too little means that the agent is
             * very near to the destination butcan't proceed because of the
             * presence of other pedestrians
             */
            if (dx < minDisplacement && dx > -minDisplacement && dy < minDisplacement
                    && dy > -minDisplacement) {
                minDisplacementCycleCount++;
            }
            // If the count of cycles in which the displacement is
            // negligible is greater than a certain threshold
            if (minDisplacementCycleCount > minDispCycTh) {
                // Don't move anymore
                dx = 0;
                dy = 0;
            }
        }

        // If displacement components are greater than zero, check if they
        // aren't over the limit
        dx = dx > 0 ? Math.min(LIMIT, dx) : Math.max(-LIMIT, dx);
        dy = dy > 0 ? Math.min(LIMIT, dy) : Math.max(-LIMIT, dy);

        // If displacement components are greater than zero perform a
        // movement
        final boolean moveH = dx > 0 || dx < 0;
        final boolean moveV = dy > 0 || dy < 0;
        if (moveH || moveV) {
            move(new Continuous2DEuclidean(moveH ? dx : 0, moveV ? dy : 0));
        }
    }
}

From source file:it.geosolutions.geocollect.android.core.mission.PendingMissionListActivity.java

@Override
public void onLocationChanged(Location location) {
    Log.v(TAG, "Location: \n lat  " + location.getLatitude() + "\n lon  " + location.getLongitude());

    SharedPreferences sp = getSharedPreferences(SQLiteCascadeFeatureLoader.PREF_NAME, Context.MODE_PRIVATE);
    // If it is the first time we get a Location, and the list is ordered by distance, refresh the list automatically 
    boolean needRefresh = sp.getBoolean(SQLiteCascadeFeatureLoader.ORDER_BY_DISTANCE, false)
            && (!sp.contains(SQLiteCascadeFeatureLoader.LOCATION_X)
                    || sp.getLong(SQLiteCascadeFeatureLoader.LOCATION_X, 0) == 0);

    SharedPreferences.Editor editor = sp.edit();
    // Set position
    editor.putLong(SQLiteCascadeFeatureLoader.LOCATION_X, Double.doubleToRawLongBits(location.getLongitude()));
    editor.putLong(SQLiteCascadeFeatureLoader.LOCATION_Y, Double.doubleToRawLongBits(location.getLatitude()));
    editor.apply();/*from  www.j  av  a  2  s  . c o m*/

    if (needRefresh) {
        PendingMissionListFragment listFragment = ((PendingMissionListFragment) getSupportFragmentManager()
                .findFragmentById(R.id.pendingmission_list));
        if (listFragment != null) {
            listFragment.onRefresh();
        }
    }
}

From source file:com.secupwn.aimsicd.service.CellTracker.java

/**
 * Add entries to the {@link com.secupwn.aimsicd.data.model.Measure Measure} realm
 *///from   ww w  . java 2  s.  c o  m
public void onLocationChanged(Location loc) {
    // TODO: See issue #555 (DeviceApi17.java is using API 18 CellInfoWcdma calls.
    if (Build.VERSION.SDK_INT > 17) {
        DeviceApi18.loadCellInfo(tm, device);
    }

    if (!device.cell.isValid()) {
        CellLocation cellLocation = tm.getCellLocation();
        if (cellLocation != null) {
            switch (device.getPhoneId()) {

            case TelephonyManager.PHONE_TYPE_NONE:
            case TelephonyManager.PHONE_TYPE_SIP:
            case TelephonyManager.PHONE_TYPE_GSM:
                GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
                device.cell.setCellId(gsmCellLocation.getCid()); // CID
                device.cell.setLocationAreaCode(gsmCellLocation.getLac()); // LAC
                device.cell.setPrimaryScramblingCode(gsmCellLocation.getPsc()); // PSC
                break;

            case TelephonyManager.PHONE_TYPE_CDMA:
                CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) cellLocation;
                device.cell.setCellId(cdmaCellLocation.getBaseStationId()); // BSID ??
                device.cell.setLocationAreaCode(cdmaCellLocation.getNetworkId()); // NID
                device.cell.setSid(cdmaCellLocation.getSystemId()); // SID
                device.cell.setMobileNetworkCode(cdmaCellLocation.getSystemId()); // MNC <== BUG!??

                break;
            }
        }
    }

    if (loc != null && (Double.doubleToRawLongBits(loc.getLatitude()) != 0
            && Double.doubleToRawLongBits(loc.getLongitude()) != 0)) {

        device.cell.setLon(loc.getLongitude()); // gpsd_lon
        device.cell.setLat(loc.getLatitude()); // gpsd_lat
        device.cell.setSpeed(loc.getSpeed()); // speed        // TODO: Remove, we're not using it!
        device.cell.setAccuracy(loc.getAccuracy()); // gpsd_accu
        device.cell.setBearing(loc.getBearing()); // -- [deg]??   // TODO: Remove, we're not using it!
        device.setLastLocation(loc); //

        // Store last known location in preference
        SharedPreferences.Editor prefsEditor;
        prefsEditor = prefs.edit();
        prefsEditor.putString(context.getString(R.string.data_last_lat_lon),
                String.valueOf(loc.getLatitude()) + ":" + String.valueOf(loc.getLongitude()));
        prefsEditor.apply();

        // This only logs a BTS if we have GPS lock
        // TODO: Is correct behaviour? We should consider logging all cells, even without GPS.
        if (trackingCell) {
            // This also checks that the locationAreaCode are cid are not in DB before inserting
            @Cleanup
            Realm realm = Realm.getDefaultInstance();
            dbHelper.insertBTS(realm, device.cell);
        }
    }
}