Example usage for java.lang Math signum

List of usage examples for java.lang Math signum

Introduction

In this page you can find the example usage for java.lang Math signum.

Prototype

public static float signum(float f) 

Source Link

Document

Returns the signum function of the argument; zero if the argument is zero, 1.0f if the argument is greater than zero, -1.0f if the argument is less than zero.

Usage

From source file:com.androzic.waypoint.WaypointProperties.java

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    int degrees, minutes;
    double mins, seconds;

    View rootView = getView();/*from   w w  w. j  a v a 2  s . c  o m*/
    Angle[] coords = getLatLon();

    switch (position) {
    case 0:
        coordUtm.setVisibility(View.GONE);
        coordMgrs.setVisibility(View.GONE);
        coordDeg.setVisibility(View.VISIBLE);
        ((TextView) rootView.findViewById(R.id.lat_dd_text))
                .setText(StringFormatter.coordinate(0, coords[0].degrees));
        coordLatMin.setVisibility(View.GONE);
        coordLatSec.setVisibility(View.GONE);
        coordLatDeg.setVisibility(View.VISIBLE);
        ((TextView) rootView.findViewById(R.id.lon_dd_text))
                .setText(StringFormatter.coordinate(0, coords[1].degrees));
        coordLonMin.setVisibility(View.GONE);
        coordLonSec.setVisibility(View.GONE);
        coordLonDeg.setVisibility(View.VISIBLE);
        break;
    case 1:
        coordUtm.setVisibility(View.GONE);
        coordMgrs.setVisibility(View.GONE);
        coordDeg.setVisibility(View.VISIBLE);
        degrees = (int) Math.floor(Math.abs(coords[0].degrees));
        mins = (Math.abs(coords[0].degrees) - degrees) * 60;
        degrees *= Math.signum(coords[0].degrees);
        ((TextView) rootView.findViewById(R.id.lat_md_text)).setText(String.valueOf(degrees));
        ((TextView) rootView.findViewById(R.id.lat_mm_text)).setText(String.valueOf(mins));
        coordLatDeg.setVisibility(View.GONE);
        coordLatSec.setVisibility(View.GONE);
        coordLatMin.setVisibility(View.VISIBLE);
        degrees = (int) Math.floor(Math.abs(coords[1].degrees));
        mins = (Math.abs(coords[1].degrees) - degrees) * 60;
        degrees *= Math.signum(coords[1].degrees);
        ((TextView) rootView.findViewById(R.id.lon_md_text)).setText(String.valueOf(degrees));
        ((TextView) rootView.findViewById(R.id.lon_mm_text)).setText(String.valueOf(mins));
        coordLonDeg.setVisibility(View.GONE);
        coordLonSec.setVisibility(View.GONE);
        coordLonMin.setVisibility(View.VISIBLE);
        break;
    case 2:
        coordUtm.setVisibility(View.GONE);
        coordMgrs.setVisibility(View.GONE);
        coordDeg.setVisibility(View.VISIBLE);
        degrees = (int) Math.floor(Math.abs(coords[0].degrees));
        mins = (Math.abs(coords[0].degrees) - degrees) * 60;
        degrees *= Math.signum(coords[0].degrees);
        minutes = (int) Math.floor(mins);
        seconds = (mins - minutes) * 60;
        ((TextView) rootView.findViewById(R.id.lat_sd_text)).setText(String.valueOf(degrees));
        ((TextView) rootView.findViewById(R.id.lat_sm_text)).setText(String.valueOf(minutes));
        ((TextView) rootView.findViewById(R.id.lat_ss_text)).setText(String.valueOf(seconds));
        coordLatDeg.setVisibility(View.GONE);
        coordLatMin.setVisibility(View.GONE);
        coordLatSec.setVisibility(View.VISIBLE);
        degrees = (int) Math.floor(Math.abs(coords[1].degrees));
        mins = (Math.abs(coords[1].degrees) - degrees) * 60;
        degrees *= Math.signum(coords[1].degrees);
        minutes = (int) Math.floor(mins);
        seconds = (mins - minutes) * 60;
        ((TextView) rootView.findViewById(R.id.lon_sd_text)).setText(String.valueOf(degrees));
        ((TextView) rootView.findViewById(R.id.lon_sm_text)).setText(String.valueOf(minutes));
        ((TextView) rootView.findViewById(R.id.lon_ss_text)).setText(String.valueOf(seconds));
        coordLonDeg.setVisibility(View.GONE);
        coordLonMin.setVisibility(View.GONE);
        coordLonSec.setVisibility(View.VISIBLE);
        break;
    case 3:
        try {
            coordDeg.setVisibility(View.GONE);
            coordMgrs.setVisibility(View.GONE);
            coordUtm.setVisibility(View.VISIBLE);
            if (coords[0].degrees < 84 && coords[0].degrees > -80) {
                UTMCoord utm = UTMCoord.fromLatLon(coords[0], coords[1]);
                ((TextView) rootView.findViewById(R.id.utm_easting_text))
                        .setText(String.valueOf(Math.round(utm.getEasting())));
                ((TextView) rootView.findViewById(R.id.utm_northing_text))
                        .setText(String.valueOf(Math.round(utm.getNorthing())));
                ((TextView) rootView.findViewById(R.id.utm_zone_text)).setText(String.valueOf(utm.getZone()));
                if (AVKey.SOUTH.equals(utm.getHemisphere()))
                    ((RadioButton) rootView.findViewById(R.id.utm_hemi_s)).setChecked(true);
                else
                    ((RadioButton) rootView.findViewById(R.id.utm_hemi_n)).setChecked(true);
            } else {
                UPSCoord ups = UPSCoord.fromLatLon(coords[0], coords[1]);
                ((TextView) rootView.findViewById(R.id.utm_easting_text))
                        .setText(String.valueOf(Math.round(ups.getEasting())));
                ((TextView) rootView.findViewById(R.id.utm_northing_text))
                        .setText(String.valueOf(Math.round(ups.getNorthing())));
                if (AVKey.SOUTH.equals(ups.getHemisphere()))
                    ((RadioButton) rootView.findViewById(R.id.utm_hemi_s)).setChecked(true);
                else
                    ((RadioButton) rootView.findViewById(R.id.utm_hemi_n)).setChecked(true);
            }
            tooltipCallback.postDelayed(showTooltip, TooltipManager.TOOLTIP_DELAY_SHORT);
        } catch (IllegalArgumentException e) {
            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        break;
    case 4:
        try {
            MGRSCoord mgrs = MGRSCoord.fromLatLon(coords[0], coords[1]);
            coordDeg.setVisibility(View.GONE);
            coordUtm.setVisibility(View.GONE);
            coordMgrs.setVisibility(View.VISIBLE);
            ((TextView) rootView.findViewById(R.id.mgrs_text)).setText(mgrs.toString());
        } catch (IllegalArgumentException e) {
            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        break;
    }
    curFormat = position;
}

From source file:atownsend.swipeopenhelper.SwipeOpenItemTouchHelper.java

/**
 * Starts dragging or swiping the given View. Call with null if you want to clear it.
 *
 * @param selected The ViewHolder to swipe. Can be null if you want to cancel the
 * current action/*  w w  w. j  a  v  a2s .  c o  m*/
 * @param actionState The type of action
 */
private void select(SwipeOpenViewHolder selected, int actionState) {
    if (selected == this.selected && actionState == this.actionState) {
        return;
    }
    final int prevActionState = this.actionState;
    // prevent duplicate animations
    endRecoverAnimation(selected, true);
    this.actionState = actionState;
    int actionStateMask = (1 << (DIRECTION_FLAG_COUNT + DIRECTION_FLAG_COUNT * actionState)) - 1;
    boolean preventLayout = false;

    // close the previously selected view holder if we're swiping a new one and the flag is true
    if (closeOnAction && selected != null && prevSelected != null && selected != prevSelected) {
        closeOpenHolder(prevSelected);
        prevSelected = null;
        preventLayout = true;
    }

    // if we've got any opened positions, and closeOnAction is true, close them
    // NOTE: only real way for this to happen is to have a view opened during configuration change
    // that then has its' state saved
    if (closeOnAction && openedPositions.size() > 0) {
        for (int i = 0; i < openedPositions.size(); i++) {
            View child = recyclerView.getChildAt(openedPositions.keyAt(0));
            if (child.getParent() != null) {
                RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(child);
                // if our selected isn't the opened position, close it
                if (holder instanceof SwipeOpenViewHolder && (selected == null
                        || holder.getAdapterPosition() != selected.getViewHolder().getAdapterPosition())) {
                    closeOpenHolder((SwipeOpenViewHolder) holder);
                }
            }
            openedPositions.removeAt(i);
        }
    }

    if (this.selected != null) {
        prevSelected = this.selected;
        // we've changed selection, we need to animate it back
        if (prevSelected.getViewHolder().itemView.getParent() != null) {
            final int swipeDir = checkPreviousSwipeDirection(prevSelected.getViewHolder());
            releaseVelocityTracker();
            // find where we should animate to
            final float targetTranslateX, targetTranslateY;
            getSelectedDxDy(tmpPosition);

            final float currentTranslateX = tmpPosition[0];
            final float currentTranslateY = tmpPosition[1];
            final float absTranslateX = Math.abs(currentTranslateX);
            final float absTranslateY = Math.abs(currentTranslateY);
            final SavedOpenState state;
            switch (swipeDir) {
            case LEFT:
            case START:
                targetTranslateY = 0;
                // check if we need to close or go to the open position
                if (absTranslateX > prevSelected.getEndHiddenViewSize() / 2) {
                    targetTranslateX = prevSelected.getEndHiddenViewSize() * Math.signum(dX);
                    state = SavedOpenState.END_OPEN;
                } else {
                    targetTranslateX = 0;
                    state = null;
                }
                break;
            case RIGHT:
            case END:
                targetTranslateY = 0;
                if (absTranslateX > prevSelected.getStartHiddenViewSize() / 2) {
                    targetTranslateX = prevSelected.getStartHiddenViewSize() * Math.signum(dX);
                    state = SavedOpenState.START_OPEN;
                } else {
                    targetTranslateX = 0;
                    state = null;
                }
                break;
            case UP:
                targetTranslateX = 0;
                if (absTranslateY > prevSelected.getEndHiddenViewSize() / 2) {
                    targetTranslateY = prevSelected.getEndHiddenViewSize() * Math.signum(dY);
                    state = SavedOpenState.END_OPEN;
                } else {
                    targetTranslateY = 0;
                    state = null;
                }
                break;
            case DOWN:
                targetTranslateX = 0;
                if (absTranslateY > prevSelected.getStartHiddenViewSize() / 2) {
                    targetTranslateY = prevSelected.getStartHiddenViewSize() * Math.signum(dY);
                    state = SavedOpenState.START_OPEN;
                } else {
                    targetTranslateY = 0;
                    state = null;
                }
                break;
            default:
                state = null;
                targetTranslateX = 0;
                targetTranslateY = 0;
            }
            // if state == null, we're closing it
            if (state == null) {
                openedPositions.remove(prevSelected.getViewHolder().getAdapterPosition());
            } else {
                openedPositions.put(prevSelected.getViewHolder().getAdapterPosition(), state);
            }

            final RecoverAnimation rv = new RecoverAnimation(prevSelected, prevActionState, currentTranslateX,
                    currentTranslateY, targetTranslateX, targetTranslateY);
            final long duration = callback.getAnimationDuration(recyclerView, ANIMATION_TYPE_SWIPE,
                    targetTranslateX - currentTranslateX, targetTranslateY - currentTranslateY);
            rv.setDuration(duration);
            recoverAnimations.add(rv);
            rv.start();
            preventLayout = true;
        } else {
            callback.clearView(recyclerView, prevSelected);
        }
        this.selected = null;
    }
    if (selected != null) {
        selectedFlags = (callback.getAbsoluteMovementFlags(recyclerView, selected.getViewHolder())
                & actionStateMask) >> (this.actionState * DIRECTION_FLAG_COUNT);
        selectedStartX = selected.getViewHolder().itemView.getLeft()
                + ViewCompat.getTranslationX(selected.getSwipeView());
        selectedStartY = selected.getViewHolder().itemView.getTop()
                + ViewCompat.getTranslationY(selected.getSwipeView());
        this.selected = selected;
    }
    final ViewParent rvParent = recyclerView.getParent();
    if (rvParent != null) {
        rvParent.requestDisallowInterceptTouchEvent(this.selected != null);
    }
    if (!preventLayout) {
        recyclerView.getLayoutManager().requestSimpleAnimationsInNextLayout();
    }
    callback.onSelectedChanged(this.selected, this.actionState);
    recyclerView.invalidate();
}

From source file:com.google.android.exoplayer2.demo.MediaPlayerFragment.java

private void doSeekTouch(int coef, float gesturesize, boolean seek) {

    if (coef == 0) {
        coef = 1;/*from   w  w  w  .  ja  v  a  2 s .c  om*/
    }

    // No seek action if coef > 0.5 and gesturesize < 1cm

    if (Math.abs(gesturesize) < 1) {// || !canSeek()
        return;
    }

    if (mTouchAction != TOUCH_NONE && mTouchAction != TOUCH_SEEK) {
        return;
    }

    mTouchAction = TOUCH_SEEK;

    long length = player.getDuration();
    long time = player.getCurrentPosition();

    // Size of the jump, 10 minutes max (600000), with a bi-cubic progression, for a 8cm gesture
    int jump = (int) ((Math.signum(gesturesize) * ((600000 * Math.pow((gesturesize / 8), 4)) + 3000)) / coef);

    // Adjust the jump
    if ((jump > 0) && ((time + jump) > length)) {
        jump = (int) (length - time);
    }

    if ((jump < 0) && ((time + jump) < 0)) {
        jump = (int) -time;
    }

    //Jump !
    if (seek && length > 0) {
        seek(time + jump);
    }

    if (length > 0) {
        //Show the jump's size
        setFastForwardOrRewind(time + jump,
                jump > 0 ? R.drawable.ic_fast_forward_white_36dp : R.drawable.ic_fast_rewind_white_36dp);
    }
}

From source file:android.support.v7.widget.helper.ItemTouchHelper.java

/**
 * Starts dragging or swiping the given View. Call with null if you want to clear it.
 *
 * @param selected    The ViewHolder to drag or swipe. Can be null if you want to cancel the
 *                    current action/*from w w w.j  a  v  a 2 s .  c  o  m*/
 * @param actionState The type of action
 */
private void select(ViewHolder selected, int actionState) {
    if (selected == mSelected && actionState == mActionState) {
        return;
    }
    mDragScrollStartTimeInMs = Long.MIN_VALUE;
    final int prevActionState = mActionState;
    // prevent duplicate animations
    endRecoverAnimation(selected, true);
    mActionState = actionState;
    if (actionState == ACTION_STATE_DRAG) {
        // we remove after animation is complete. this means we only elevate the last drag
        // child but that should perform good enough as it is very hard to start dragging a
        // new child before the previous one settles.
        mOverdrawChild = selected.itemView;
        addChildDrawingOrderCallback();
    }
    int actionStateMask = (1 << (DIRECTION_FLAG_COUNT + DIRECTION_FLAG_COUNT * actionState)) - 1;
    boolean preventLayout = false;

    if (mSelected != null) {
        final ViewHolder prevSelected = mSelected;
        if (prevSelected.itemView.getParent() != null) {
            final int swipeDir = prevActionState == ACTION_STATE_DRAG ? 0 : swipeIfNecessary(prevSelected);
            releaseVelocityTracker();
            // find where we should animate to
            final float targetTranslateX, targetTranslateY;
            int animationType;
            switch (swipeDir) {
            case LEFT:
            case RIGHT:
            case START:
            case END:
                targetTranslateY = 0;
                targetTranslateX = Math.signum(mDx) * mRecyclerView.getWidth();
                break;
            case UP:
            case DOWN:
                targetTranslateX = 0;
                targetTranslateY = Math.signum(mDy) * mRecyclerView.getHeight();
                break;
            default:
                targetTranslateX = 0;
                targetTranslateY = 0;
            }
            if (prevActionState == ACTION_STATE_DRAG) {
                animationType = ANIMATION_TYPE_DRAG;
            } else if (swipeDir > 0) {
                animationType = ANIMATION_TYPE_SWIPE_SUCCESS;
            } else {
                animationType = ANIMATION_TYPE_SWIPE_CANCEL;
            }
            getSelectedDxDy(mTmpPosition);
            final float currentTranslateX = mTmpPosition[0];
            final float currentTranslateY = mTmpPosition[1];
            final RecoverAnimation rv = new RecoverAnimation(prevSelected, animationType, prevActionState,
                    currentTranslateX, currentTranslateY, targetTranslateX, targetTranslateY) {
                @Override
                public void onAnimationEnd(ValueAnimatorCompat animation) {
                    super.onAnimationEnd(animation);
                    if (this.mOverridden) {
                        return;
                    }
                    if (swipeDir <= 0) {
                        // this is a drag or failed swipe. recover immediately
                        mCallback.clearView(mRecyclerView, prevSelected);
                        // full cleanup will happen on onDrawOver
                    } else {
                        // wait until remove animation is complete.
                        mPendingCleanup.add(prevSelected.itemView);
                        mIsPendingCleanup = true;
                        if (swipeDir > 0) {
                            // Animation might be ended by other animators during a layout.
                            // We defer callback to avoid editing adapter during a layout.
                            postDispatchSwipe(this, swipeDir);
                        }
                    }
                    // removed from the list after it is drawn for the last time
                    if (mOverdrawChild == prevSelected.itemView) {
                        removeChildDrawingOrderCallbackIfNecessary(prevSelected.itemView);
                    }
                }
            };
            final long duration = mCallback.getAnimationDuration(mRecyclerView, animationType,
                    targetTranslateX - currentTranslateX, targetTranslateY - currentTranslateY);
            rv.setDuration(duration);
            mRecoverAnimations.add(rv);
            rv.start();
            preventLayout = true;
        } else {
            removeChildDrawingOrderCallbackIfNecessary(prevSelected.itemView);
            mCallback.clearView(mRecyclerView, prevSelected);
        }
        mSelected = null;
    }
    if (selected != null) {
        mSelectedFlags = (mCallback.getAbsoluteMovementFlags(mRecyclerView, selected)
                & actionStateMask) >> (mActionState * DIRECTION_FLAG_COUNT);
        mSelectedStartX = selected.itemView.getLeft();
        mSelectedStartY = selected.itemView.getTop();
        mSelected = selected;

        if (actionState == ACTION_STATE_DRAG) {
            mSelected.itemView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        }
    }
    final ViewParent rvParent = mRecyclerView.getParent();
    if (rvParent != null) {
        rvParent.requestDisallowInterceptTouchEvent(mSelected != null);
    }
    if (!preventLayout) {
        mRecyclerView.getLayoutManager().requestSimpleAnimationsInNextLayout();
    }
    mCallback.onSelectedChanged(mSelected, mActionState);
    mRecyclerView.invalidate();
}

From source file:com.panahit.telegramma.support.widget.helper.ItemTouchHelper.java

/**
 * Starts dragging or swiping the given View. Call with null if you want to clear it.
 *
 * @param selected    The ViewHolder to drag or swipe. Can be null if you want to cancel the
 *                    current action//  ww  w  . ja  va 2s.co  m
 * @param actionState The type of action
 */
private void select(RecyclerView.ViewHolder selected, int actionState) {
    if (selected == mSelected && actionState == mActionState) {
        return;
    }
    mDragScrollStartTimeInMs = Long.MIN_VALUE;
    final int prevActionState = mActionState;
    // prevent duplicate animations
    endRecoverAnimation(selected, true);
    mActionState = actionState;
    if (actionState == ACTION_STATE_DRAG) {
        // we remove after animation is complete. this means we only elevate the last drag
        // child but that should perform good enough as it is very hard to start dragging a
        // new child before the previous one settles.
        mOverdrawChild = selected.itemView;
        addChildDrawingOrderCallback();
    }
    int actionStateMask = (1 << (DIRECTION_FLAG_COUNT + DIRECTION_FLAG_COUNT * actionState)) - 1;
    boolean preventLayout = false;

    if (mSelected != null) {
        final RecyclerView.ViewHolder prevSelected = mSelected;
        if (prevSelected.itemView.getParent() != null) {
            final int swipeDir = prevActionState == ACTION_STATE_DRAG ? 0 : swipeIfNecessary(prevSelected);
            releaseVelocityTracker();
            // find where we should animate to
            final float targetTranslateX, targetTranslateY;
            int animationType;
            switch (swipeDir) {
            case LEFT:
            case RIGHT:
            case START:
            case END:
                targetTranslateY = 0;
                targetTranslateX = Math.signum(mDx) * mRecyclerView.getWidth();
                break;
            case UP:
            case DOWN:
                targetTranslateX = 0;
                targetTranslateY = Math.signum(mDy) * mRecyclerView.getHeight();
                break;
            default:
                targetTranslateX = 0;
                targetTranslateY = 0;
            }
            if (prevActionState == ACTION_STATE_DRAG) {
                animationType = ANIMATION_TYPE_DRAG;
            } else if (swipeDir > 0) {
                animationType = ANIMATION_TYPE_SWIPE_SUCCESS;
            } else {
                animationType = ANIMATION_TYPE_SWIPE_CANCEL;
            }
            getSelectedDxDy(mTmpPosition);
            final float currentTranslateX = mTmpPosition[0];
            final float currentTranslateY = mTmpPosition[1];
            final RecoverAnimation rv = new RecoverAnimation(prevSelected, animationType, prevActionState,
                    currentTranslateX, currentTranslateY, targetTranslateX, targetTranslateY) {
                @Override
                public void onAnimationEnd(ValueAnimatorCompat animation) {
                    super.onAnimationEnd(animation);
                    if (this.mOverridden) {
                        return;
                    }
                    if (swipeDir <= 0) {
                        // this is a drag or failed swipe. recover immediately
                        mCallback.clearView(mRecyclerView, prevSelected);
                        // full cleanup will happen on onDrawOver
                    } else {
                        // wait until remove animation is complete.
                        mPendingCleanup.add(prevSelected.itemView);
                        mIsPendingCleanup = true;
                        if (swipeDir > 0) {
                            // Animation might be ended by other animators during a layout.
                            // We defer callback to avoid editing adapter during a layout.
                            postDispatchSwipe(this, swipeDir);
                        }
                    }
                    // removed from the list after it is drawn for the last time
                    if (mOverdrawChild == prevSelected.itemView) {
                        removeChildDrawingOrderCallbackIfNecessary(prevSelected.itemView);
                    }
                }
            };
            final long duration = mCallback.getAnimationDuration(mRecyclerView, animationType,
                    targetTranslateX - currentTranslateX, targetTranslateY - currentTranslateY);
            rv.setDuration(duration);
            mRecoverAnimations.add(rv);
            rv.start();
            preventLayout = true;
        } else {
            removeChildDrawingOrderCallbackIfNecessary(prevSelected.itemView);
            mCallback.clearView(mRecyclerView, prevSelected);
        }
        mSelected = null;
    }
    if (selected != null) {
        mSelectedFlags = (mCallback.getAbsoluteMovementFlags(mRecyclerView, selected)
                & actionStateMask) >> (mActionState * DIRECTION_FLAG_COUNT);
        mSelectedStartX = selected.itemView.getLeft();
        mSelectedStartY = selected.itemView.getTop();
        mSelected = selected;

        if (actionState == ACTION_STATE_DRAG) {
            mSelected.itemView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        }
    }
    final ViewParent rvParent = mRecyclerView.getParent();
    if (rvParent != null) {
        rvParent.requestDisallowInterceptTouchEvent(mSelected != null);
    }
    if (!preventLayout) {
        mRecyclerView.getLayoutManager().requestSimpleAnimationsInNextLayout();
    }
    mCallback.onSelectedChanged(mSelected, mActionState);
    mRecyclerView.invalidate();
}

From source file:com.yahoo.labs.yamall.local.Yamall.java

private static double evalHoldoutError() throws FileNotFoundException, IOException, ClassNotFoundException {
    double cumLoss = 0;
    double weightedSampleSum = 0;
    ObjectInputStream oin = new ObjectInputStream(new FileInputStream("cache_holdout.bin"));

    Instance testSample;/*from ww w  .j a va2 s.c  o m*/
    while ((testSample = (Instance) oin.readObject()) != null) {
        weightedSampleSum += testSample.getWeight();
        double score = learner.predict(testSample);
        score = Math.min(Math.max(score, minPrediction), maxPrediction);
        if (!binary)
            cumLoss += learner.getLoss().lossValue(score, testSample.getLabel()) * testSample.getWeight();
        else if (Math.signum(score) != testSample.getLabel())
            cumLoss += testSample.getWeight();
    }
    oin.close();

    return cumLoss / weightedSampleSum;
}

From source file:nl.strohalm.cyclos.services.stats.StatisticalResultDTO.java

/**
 * Allows you to order the series according to an array of bytes with order numbers. Of course, this can only be done after the tableCells and
 * seriesNames have been set to the graph/table. All corresponding headers and keys, as well as the data is reordered.<br>
 * Example:<br>//from  w ww .java  2 s.co m
 * Suppose the tableCells contain the following points:
 * 
 * <pre>
 * { { 5, 7, 2 }, { 5, 7, 2 }, { 5, 7, 2 }, { 5, 7, 2 }, { 5, 7, 2 } }
 * </pre>
 * 
 * Suppose the seriesOrder param is {2, 1, 3};<br>
 * After running this method, the tableCells will look like this:
 * 
 * <pre>
 * { { 7, 5, 2 }, { 7, 5, 2 }, { 7, 5, 2 }, { 7, 5, 2 }, { 7, 5, 2 } }
 * </pre>
 * 
 * @param seriesOrder an array of bytes containing the index numbers of the series. The values do not need to be subsequent numbers; also {16, 8,
 * 10} would be possible. If a value is encountered more than once, corresponding elements are considered equal at ordering.
 */
public void orderSeries(final byte[] seriesOrder) {
    // helper class for bundling all relevant elements in order to index them in one go, with one rule
    class IndexedSerie {
        private Number[] numbers;
        private String seriesHeader;
        private String seriesSubHeader;
        private String seriesKey;
        private byte index;

        IndexedSerie(final Number[] numbers, final int originalIndex, final byte index) {
            this.numbers = numbers;
            if (columnHeaders != null && columnHeaders.length > 0) {
                seriesHeader = columnHeaders[originalIndex];
            }
            // the key by def exists, else IllegalArgumentException
            seriesKey = columnKeys[originalIndex];
            if (columnSubHeaders != null && columnSubHeaders.length > 0) {
                seriesSubHeader = columnSubHeaders[originalIndex];
            }
            this.index = index;
        }
    }

    final Comparator<IndexedSerie> comparator = new Comparator<IndexedSerie>() {
        public int compare(final IndexedSerie o1, final IndexedSerie o2) {
            if (o1.index == o2.index) {
                // first the smallest
                final double result = o1.numbers[0].doubleValue() - o2.numbers[0].doubleValue();
                return (int) Math.signum(result);
            }
            // first the one with the lowest index
            return o1.index - o2.index;
        }
    };

    // first some checks
    if (tableCells == null || columnKeys == null) {
        throw new IllegalArgumentException("Method orderSeries may only be called after setting columnKeys.");
    }
    if (tableCells.length == 0 || tableCells[0] == null || tableCells[0].length == 0) {
        // nothing to order, so return
        return;
    }
    if (seriesOrder == null || seriesOrder.length != columnKeys.length
            || seriesOrder.length != tableCells[0].length) {
        throw new InconsistentDataDimensionsException(
                "SeriesNames / dataset length does not match order length.");
    }

    // transpose so that we get an array of different series, in stead of an array of points
    final Number[][] transposedMatrix = ListOperations.transposeMatrix(tableCells);
    // rewrite transposed Matrix as an array of series and add the indexes
    final IndexedSerie[] arrayOfSeries = new IndexedSerie[seriesOrder.length];
    for (int i = 0; i < seriesOrder.length; i++) {
        arrayOfSeries[i] = new IndexedSerie(transposedMatrix[i], i, seriesOrder[i]);
    }
    // sort array of series on their added index
    Arrays.sort(arrayOfSeries, comparator);
    // write back the array of series to a matrix
    final Number[][] transposedOrderedMatrix = new Number[seriesOrder.length][transposedMatrix[0].length];
    for (int i = 0; i < seriesOrder.length; i++) {
        transposedOrderedMatrix[i] = arrayOfSeries[i].numbers;
        // keys and headers can already be written back
        columnKeys[i] = arrayOfSeries[i].seriesKey;
        if (columnHeaders != null && columnHeaders.length > 0) {
            columnHeaders[i] = arrayOfSeries[i].seriesHeader;
        }
        if (columnSubHeaders != null && columnSubHeaders.length > 0) {
            columnSubHeaders[i] = arrayOfSeries[i].seriesSubHeader;
        }
    }
    // transpose back
    final Number[][] orderedMatrix = ListOperations.transposeMatrix(transposedOrderedMatrix);
    // write back
    tableCells = orderedMatrix;
}

From source file:com.anarchy.classify.library.helper.ClassifyItemTouchHelper.java

/**
 * Starts dragging or swiping the given View. Call with null if you want to clear it.
 *
 * @param selected    The ViewHolder to drag or swipe. Can be null if you want to cancel the
 *                    current action/*from  ww  w  . ja v a  2s  . co  m*/
 * @param actionState The type of action
 */
private void select(RecyclerView.ViewHolder selected, int actionState) {
    if (selected == mSelected && actionState == mActionState) {
        return;
    }
    if (mCallback.getMergeStatus()) {
        if (mSelected != null) {
            mCallback.onMerged(mSelected);
            mSelected = null;
            return;
        }
    }
    mDragScrollStartTimeInMs = Long.MIN_VALUE;
    final int prevActionState = mActionState;
    // prevent duplicate animations
    endRecoverAnimation(selected, true);
    mActionState = actionState;
    if (actionState == ACTION_STATE_DRAG) {
        // we remove after animation is complete. this means we only elevate the last drag
        // child but that should perform good enough as it is very hard to start dragging a
        // new child before the previous one settles.
        mOverdrawChild = selected.itemView;
        addChildDrawingOrderCallback();
    }
    int actionStateMask = (1 << (DIRECTION_FLAG_COUNT + DIRECTION_FLAG_COUNT * actionState)) - 1;
    boolean preventLayout = false;

    if (mSelected != null) {
        final RecyclerView.ViewHolder prevSelected = mSelected;
        if (prevSelected.itemView.getParent() != null) {
            final int swipeDir = prevActionState == ACTION_STATE_DRAG ? 0 : swipeIfNecessary(prevSelected);
            releaseVelocityTracker();
            // find where we should animate to
            final float targetTranslateX, targetTranslateY;
            int animationType;
            switch (swipeDir) {
            case LEFT:
            case RIGHT:
            case START:
            case END:
                targetTranslateY = 0;
                targetTranslateX = Math.signum(mDx) * mRecyclerView.getWidth();
                break;
            case UP:
            case DOWN:
                targetTranslateX = 0;
                targetTranslateY = Math.signum(mDy) * mRecyclerView.getHeight();
                break;
            default:
                targetTranslateX = 0;
                targetTranslateY = 0;
            }
            if (prevActionState == ACTION_STATE_DRAG) {
                animationType = ANIMATION_TYPE_DRAG;
            } else if (swipeDir > 0) {
                animationType = ANIMATION_TYPE_SWIPE_SUCCESS;
            } else {
                animationType = ANIMATION_TYPE_SWIPE_CANCEL;
            }
            getSelectedDxDy(mTmpPosition);
            final float currentTranslateX = mTmpPosition[0];
            final float currentTranslateY = mTmpPosition[1];
            final RecoverAnimation rv = new RecoverAnimation(prevSelected, animationType, prevActionState,
                    currentTranslateX, currentTranslateY, targetTranslateX, targetTranslateY) {
                @Override
                public void onAnimationEnd(ValueAnimatorCompat animation) {
                    super.onAnimationEnd(animation);
                    if (this.mOverridden) {
                        return;
                    }
                    if (swipeDir <= 0) {
                        // this is a drag or failed swipe. recover immediately
                        mCallback.clearView(mRecyclerView, prevSelected);
                        // full cleanup will happen on onDrawOver
                    } else {
                        // wait until remove animation is complete.
                        mPendingCleanup.add(prevSelected.itemView);
                        mIsPendingCleanup = true;
                        if (swipeDir > 0) {
                            // Animation might be ended by other animators during a layout.
                            // We defer callback to avoid editing adapter during a layout.
                            postDispatchSwipe(this, swipeDir);
                        }
                    }
                    // removed from the list after it is drawn for the last time
                    if (mOverdrawChild == prevSelected.itemView) {
                        removeChildDrawingOrderCallbackIfNecessary(prevSelected.itemView);
                    }
                }
            };
            final long duration = mCallback.getAnimationDuration(mRecyclerView, animationType,
                    targetTranslateX - currentTranslateX, targetTranslateY - currentTranslateY);
            rv.setDuration(duration);
            mRecoverAnimations.add(rv);
            rv.start();
            preventLayout = true;
        } else {
            removeChildDrawingOrderCallbackIfNecessary(prevSelected.itemView);
            mCallback.clearView(mRecyclerView, prevSelected);
        }
        mSelected = null;
    }
    if (selected != null) {
        mSelectedFlags = (mCallback.getAbsoluteMovementFlags(mRecyclerView, selected)
                & actionStateMask) >> (mActionState * DIRECTION_FLAG_COUNT);
        mSelectedStartX = selected.itemView.getLeft();
        mSelectedStartY = selected.itemView.getTop();
        mSelected = selected;

        if (actionState == ACTION_STATE_DRAG) {
            mSelected.itemView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        }
    }
    final ViewParent rvParent = mRecyclerView.getParent();
    if (rvParent != null) {
        rvParent.requestDisallowInterceptTouchEvent(mSelected != null);
    }
    if (!preventLayout) {
        mRecyclerView.getLayoutManager().requestSimpleAnimationsInNextLayout();
    }
    mCallback.onSelectedChanged(mSelected, mActionState);
    mRecyclerView.invalidate();
}

From source file:com.ferdi2005.secondgram.support.widget.helper.ItemTouchHelper.java

/**
 * Starts dragging or swiping the given View. Call with null if you want to clear it.
 *
 * @param selected    The ViewHolder to drag or swipe. Can be null if you want to cancel the
 *                    current action/* w w w . j ava2  s .c  om*/
 * @param actionState The type of action
 */
void select(ViewHolder selected, int actionState) {
    if (selected == mSelected && actionState == mActionState) {
        return;
    }
    mDragScrollStartTimeInMs = Long.MIN_VALUE;
    final int prevActionState = mActionState;
    // prevent duplicate animations
    endRecoverAnimation(selected, true);
    mActionState = actionState;
    if (actionState == ACTION_STATE_DRAG) {
        // we remove after animation is complete. this means we only elevate the last drag
        // child but that should perform good enough as it is very hard to start dragging a
        // new child before the previous one settles.
        mOverdrawChild = selected.itemView;
        addChildDrawingOrderCallback();
    }
    int actionStateMask = (1 << (DIRECTION_FLAG_COUNT + DIRECTION_FLAG_COUNT * actionState)) - 1;
    boolean preventLayout = false;

    if (mSelected != null) {
        final ViewHolder prevSelected = mSelected;
        if (prevSelected.itemView.getParent() != null) {
            final int swipeDir = prevActionState == ACTION_STATE_DRAG ? 0 : swipeIfNecessary(prevSelected);
            releaseVelocityTracker();
            // find where we should animate to
            final float targetTranslateX, targetTranslateY;
            int animationType;
            switch (swipeDir) {
            case LEFT:
            case RIGHT:
            case START:
            case END:
                targetTranslateY = 0;
                targetTranslateX = Math.signum(mDx) * mRecyclerView.getWidth();
                break;
            case UP:
            case DOWN:
                targetTranslateX = 0;
                targetTranslateY = Math.signum(mDy) * mRecyclerView.getHeight();
                break;
            default:
                targetTranslateX = 0;
                targetTranslateY = 0;
            }
            if (prevActionState == ACTION_STATE_DRAG) {
                animationType = ANIMATION_TYPE_DRAG;
            } else if (swipeDir > 0) {
                animationType = ANIMATION_TYPE_SWIPE_SUCCESS;
            } else {
                animationType = ANIMATION_TYPE_SWIPE_CANCEL;
            }
            getSelectedDxDy(mTmpPosition);
            final float currentTranslateX = mTmpPosition[0];
            final float currentTranslateY = mTmpPosition[1];
            final RecoverAnimation rv = new RecoverAnimation(prevSelected, animationType, prevActionState,
                    currentTranslateX, currentTranslateY, targetTranslateX, targetTranslateY) {
                @Override
                public void onAnimationEnd(ValueAnimatorCompat animation) {
                    super.onAnimationEnd(animation);
                    if (this.mOverridden) {
                        return;
                    }
                    if (swipeDir <= 0) {
                        // this is a drag or failed swipe. recover immediately
                        mCallback.clearView(mRecyclerView, prevSelected);
                        // full cleanup will happen on onDrawOver
                    } else {
                        // wait until remove animation is complete.
                        mPendingCleanup.add(prevSelected.itemView);
                        mIsPendingCleanup = true;
                        if (swipeDir > 0) {
                            // Animation might be ended by other animators during a layout.
                            // We defer callback to avoid editing adapter during a layout.
                            postDispatchSwipe(this, swipeDir);
                        }
                    }
                    // removed from the list after it is drawn for the last time
                    if (mOverdrawChild == prevSelected.itemView) {
                        removeChildDrawingOrderCallbackIfNecessary(prevSelected.itemView);
                    }
                }
            };
            final long duration = mCallback.getAnimationDuration(mRecyclerView, animationType,
                    targetTranslateX - currentTranslateX, targetTranslateY - currentTranslateY);
            rv.setDuration(duration);
            mRecoverAnimations.add(rv);
            rv.start();
            preventLayout = true;
        } else {
            removeChildDrawingOrderCallbackIfNecessary(prevSelected.itemView);
            mCallback.clearView(mRecyclerView, prevSelected);
        }
        mSelected = null;
    }
    if (selected != null) {
        mSelectedFlags = (mCallback.getAbsoluteMovementFlags(mRecyclerView, selected)
                & actionStateMask) >> (mActionState * DIRECTION_FLAG_COUNT);
        mSelectedStartX = selected.itemView.getLeft();
        mSelectedStartY = selected.itemView.getTop();
        mSelected = selected;

        if (actionState == ACTION_STATE_DRAG) {
            mSelected.itemView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        }
    }
    final ViewParent rvParent = mRecyclerView.getParent();
    if (rvParent != null) {
        rvParent.requestDisallowInterceptTouchEvent(mSelected != null);
    }
    if (!preventLayout) {
        mRecyclerView.getLayoutManager().requestSimpleAnimationsInNextLayout();
    }
    mCallback.onSelectedChanged(mSelected, mActionState);
    mRecyclerView.invalidate();
}

From source file:com.opengamma.analytics.financial.model.volatility.BlackScholesFormulaRepository.java

/**
* The cross gamma - the sensitity of the delta to the strike $\frac{\partial^2 V}{\partial f \partial K}$
* @param spot The spot value of the underlying
* @param strike The Strike/*from   w  w  w.j  a v  a2 s .c  o  m*/
* @param timeToExpiry The time-to-expiry
* @param lognormalVol The log-normal volatility
* @param interestRate The interest rate 
* @param costOfCarry The cost-of-carry  rate
* @return The dual gamma
*/
@ExternalFunction
public static double crossGamma(final double spot, final double strike, final double timeToExpiry,
        final double lognormalVol, final double interestRate, final double costOfCarry) {
    ArgumentChecker.isTrue(spot >= 0.0, "negative/NaN spot; have {}", spot);
    ArgumentChecker.isTrue(strike >= 0.0, "negative/NaN strike; have {}", strike);
    ArgumentChecker.isTrue(timeToExpiry >= 0.0, "negative/NaN timeToExpiry; have {}", timeToExpiry);
    ArgumentChecker.isTrue(lognormalVol >= 0.0, "negative/NaN lognormalVol; have {}", lognormalVol);
    ArgumentChecker.isFalse(Double.isNaN(interestRate), "interestRate is NaN");
    ArgumentChecker.isFalse(Double.isNaN(costOfCarry), "costOfCarry is NaN");

    if (-interestRate > LARGE) {
        return costOfCarry > LARGE ? 0. : Double.NEGATIVE_INFINITY;
    }
    if (interestRate > LARGE) {
        return 0.;
    }
    double discount = (Math.abs(interestRate) < SMALL && timeToExpiry > LARGE) ? 1.
            : Math.exp(-interestRate * timeToExpiry);

    final double rootT = Math.sqrt(timeToExpiry);
    double sigmaRootT = lognormalVol * rootT;
    if (Double.isNaN(sigmaRootT)) {
        sigmaRootT = 1.; //ref value is returned
    }
    if (spot > LARGE * strike || spot < SMALL * strike || sigmaRootT > LARGE) {
        return 0.;
    }

    double factor = Math.exp(costOfCarry * timeToExpiry);
    if (Double.isNaN(factor)) {
        factor = 1.; //ref value is returned
    }

    double d2 = 0.;
    if (Math.abs(spot - strike) < SMALL || (spot > LARGE && strike > LARGE)) {
        final double coefD1 = (Math.abs(costOfCarry) < SMALL && lognormalVol < SMALL)
                ? Math.signum(costOfCarry) - 0.5 * lognormalVol
                : (costOfCarry / lognormalVol - 0.5 * lognormalVol);
        final double tmp = coefD1 * rootT;
        d2 = Double.isNaN(tmp) ? 0. : tmp;
    } else {
        if (sigmaRootT < SMALL) {
            final double scnd = (Math.abs(costOfCarry) > LARGE && rootT < SMALL) ? Math.signum(costOfCarry)
                    : costOfCarry * rootT;
            final double tmp = (Math.log(spot / strike) / rootT + scnd) / lognormalVol;
            d2 = Double.isNaN(tmp) ? 0. : tmp;
        } else {
            final double tmp = costOfCarry * rootT / lognormalVol;
            final double sig = (costOfCarry >= 0.) ? 1. : -1.;
            final double scnd = Double.isNaN(tmp)
                    ? ((lognormalVol < LARGE && lognormalVol > SMALL) ? sig / lognormalVol : sig * rootT)
                    : tmp;
            d2 = Math.log(spot / strike) / sigmaRootT + scnd - 0.5 * sigmaRootT;
        }
    }
    //    if (Double.isNaN(d2)) {
    //      throw new IllegalArgumentException("NaN found");
    //    }
    final double norm = NORMAL.getPDF(d2);

    final double res = norm < SMALL ? 0. : -discount * norm / spot / sigmaRootT;
    return Double.isNaN(res) ? Double.NEGATIVE_INFINITY : res;
}