Example usage for java.util Arrays binarySearch

List of usage examples for java.util Arrays binarySearch

Introduction

In this page you can find the example usage for java.util Arrays binarySearch.

Prototype

public static int binarySearch(Object[] a, Object key) 

Source Link

Document

Searches the specified array for the specified object using the binary search algorithm.

Usage

From source file:com.opengamma.financial.analytics.timeseries.YieldCurveHistoricalTimeSeriesFunction.java

@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context,
        final ComputationTarget target, final ValueRequirement desiredValue) {
    ValueProperties.Builder constraints = null;
    if (_excludedCurves.length != 0) {
        final Set<String> curveNames = desiredValue.getConstraints().getValues(ValuePropertyNames.CURVE);
        if (curveNames != null && curveNames.size() == 1) {
            final String curveName = Iterables.getOnlyElement(curveNames);
            final int index = Arrays.binarySearch(_excludedCurves, curveName);
            if (index >= 0) {
                return null;
            }/*from www. ja  v  a 2  s  . c om*/
        }
    }
    Set<String> values = desiredValue.getConstraints()
            .getValues(HistoricalTimeSeriesFunctionUtils.DATA_FIELD_PROPERTY);
    if ((values == null) || values.isEmpty()) {
        constraints = desiredValue.getConstraints().copy().with(
                HistoricalTimeSeriesFunctionUtils.DATA_FIELD_PROPERTY, MarketDataRequirementNames.MARKET_VALUE);
    } else if (values.size() > 1) {
        constraints = desiredValue.getConstraints().copy()
                .withoutAny(HistoricalTimeSeriesFunctionUtils.DATA_FIELD_PROPERTY)
                .with(HistoricalTimeSeriesFunctionUtils.DATA_FIELD_PROPERTY, values.iterator().next());
    }
    values = desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.RESOLUTION_KEY_PROPERTY);
    if ((values == null) || values.isEmpty()) {
        if (constraints == null) {
            constraints = desiredValue.getConstraints().copy();
        }
        constraints.with(HistoricalTimeSeriesFunctionUtils.RESOLUTION_KEY_PROPERTY, "");
    } else if (values.size() > 1) {
        if (constraints == null) {
            constraints = desiredValue.getConstraints().copy();
        }
        constraints.withoutAny(HistoricalTimeSeriesFunctionUtils.RESOLUTION_KEY_PROPERTY)
                .with(HistoricalTimeSeriesFunctionUtils.RESOLUTION_KEY_PROPERTY, values.iterator().next());
    }
    values = desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY);
    if ((values == null) || values.isEmpty()) {
        if (constraints == null) {
            constraints = desiredValue.getConstraints().copy();
        }
        constraints.with(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY, "Null");
    }
    values = desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.INCLUDE_START_PROPERTY);
    if ((values == null) || (values.size() != 1)) {
        if (constraints == null) {
            constraints = desiredValue.getConstraints().copy();
        }
        constraints.with(HistoricalTimeSeriesFunctionUtils.INCLUDE_START_PROPERTY,
                HistoricalTimeSeriesFunctionUtils.YES_VALUE);
    }
    values = desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.END_DATE_PROPERTY);
    if ((values == null) || values.isEmpty()) {
        if (constraints == null) {
            constraints = desiredValue.getConstraints().copy();
        }
        constraints.with(HistoricalTimeSeriesFunctionUtils.END_DATE_PROPERTY, "Now");
    }
    values = desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.INCLUDE_END_PROPERTY);
    if ((values == null) || (values.size() != 1)) {
        if (constraints == null) {
            constraints = desiredValue.getConstraints().copy();
        }
        constraints.with(HistoricalTimeSeriesFunctionUtils.INCLUDE_END_PROPERTY,
                HistoricalTimeSeriesFunctionUtils.YES_VALUE);
    }
    if (constraints == null) {
        // We can satisfy the desired value as-is, just ask for the yield curve specification to drive our behavior
        final ValueProperties curveConstraints;
        values = desiredValue.getConstraints().getValues(ValuePropertyNames.CURVE);
        if (values != null) {
            if (values.isEmpty()) {
                curveConstraints = ValueProperties.withAny(ValuePropertyNames.CURVE).get();
            } else {
                curveConstraints = ValueProperties.with(ValuePropertyNames.CURVE, values).get();
            }
        } else {
            curveConstraints = ValueProperties.none();
        }
        return Collections.singleton(new ValueRequirement(ValueRequirementNames.YIELD_CURVE_SPEC,
                target.toSpecification(), curveConstraints));
    }
    // We need to substitute ourselves with the adjusted constraints
    return Collections.singleton(new ValueRequirement(ValueRequirementNames.YIELD_CURVE_HISTORICAL_TIME_SERIES,
            target.toSpecification(), constraints.get()));
}

From source file:com.indoqa.lang.util.StringUtils.java

public static String sanitzeHtmlId(String id) {
    if (org.apache.commons.lang3.StringUtils.isBlank(id)) {
        return "";
    }/*from  w  ww.  ja  va2 s  .  c  om*/

    StringBuilder stringBuilder = new StringBuilder(id);

    for (int i = 0; i < stringBuilder.length(); i++) {
        char character = stringBuilder.charAt(i);

        if (Arrays.binarySearch(ILLEGAL_HTML_ID_CHARACTERS, character) >= 0) {
            stringBuilder.setCharAt(i, '_');
        }
    }

    return stringBuilder.toString();
}

From source file:jsat.distributions.empirical.MyKernelDensityEstimator.java

/**
 * Computes the Leave One Out PDF of the estimator
 * /*from   w  w w . j  a va  2 s  .co m*/
 * @param x
 *            the value to get the pdf of
 * @param j
 *            the sorted index of the value to leave. If a negative value is given, the PDF with all values is returned
 * @return the pdf with the given index left out
 */
private double pdf(double x, int j) {
    /*
     * n ===== /x - x \ 1 \ | i| f(x) = --- > K|------| n h / \ h / ===== i = 1
     */

    // Only values within a certain range will have an effect on the result, so we will skip to that range!
    int from = Arrays.binarySearch(X, x - h * k.cutOff());
    int to = Arrays.binarySearch(X, x + h * k.cutOff());
    // Mostly likely the exact value of x is not in the list, so it returns the inseration points
    from = from < 0 ? -from - 1 : from;
    to = to < 0 ? -to - 1 : to;

    // Univariate opt, if uniform weights, the sum is just the number of elements divide by half
    if (weights.length == 0 && k instanceof UniformKF) {
        return (to - from) * 0.5 / (sumOFWeights * h);
    }

    double sum = 0;
    for (int i = Math.max(0, from); i < Math.min(X.length, to + 1); i++) {
        if (i != j) {
            sum += k.k((x - X[i]) / h) * getWeight(i);
        }
    }

    return sum / (sumOFWeights * h);
}

From source file:com.linkedin.pinot.core.segment.index.readers.ImmutableDictionaryReaderTest.java

@Test
public void testLongDictionary() throws Exception {
    try (LongDictionary longDictionary = new LongDictionary(
            PinotDataBuffer.fromFile(new File(TEMP_DIR, LONG_COLUMN_NAME + V1Constants.Dict.FILE_EXTENSION),
                    ReadMode.mmap, FileChannel.MapMode.READ_ONLY, LONG_COLUMN_NAME),
            NUM_VALUES)) {//from   ww w.ja  v a2s. com
        for (int i = 0; i < NUM_VALUES; i++) {
            Assert.assertEquals(longDictionary.get(i).longValue(), _longValues[i]);
            Assert.assertEquals(longDictionary.getIntValue(i), (int) _longValues[i]);
            Assert.assertEquals(longDictionary.getLongValue(i), _longValues[i]);
            Assert.assertEquals(longDictionary.getFloatValue(i), _longValues[i], 0.0f);
            Assert.assertEquals(longDictionary.getDoubleValue(i), _longValues[i], 0.0);
            Assert.assertEquals(Long.parseLong(longDictionary.getStringValue(i)), _longValues[i]);

            Assert.assertEquals(longDictionary.indexOf(_longValues[i]), i);

            long randomLong = RANDOM.nextLong();
            Assert.assertEquals(longDictionary.insertionIndexOf(randomLong),
                    Arrays.binarySearch(_longValues, randomLong));
        }
    }
}

From source file:com.android.contacts.SimImportFragment.java

private void showSelectionsForCurrentAccount() {
    final long[] ids = mPerAccountCheckedIds.get(mAdapter.getAccount());
    if (ids == null) {
        selectAll();//  ww  w . jav  a  2s  .  c o  m
        return;
    }
    for (int i = 0, len = mListView.getCount(); i < len; i++) {
        mListView.setItemChecked(i, Arrays.binarySearch(ids, mListView.getItemIdAtPosition(i)) >= 0);
    }
}

From source file:org.jtheque.movies.services.MoviesServiceTest.java

License:asdf

@Test
public void getMoviesOfNotLeafCategory2() {
    Collection<Movie> movies = moviesService.getMovies(daoCategories.getCategory("Category 5"), true);

    assertEquals(3, movies.size());//from   w  w w .j a va2s  .  c om

    String[] moviesCategory4 = { "Movie 2", "Movie 3", "Movie 4" };

    for (Movie movie : movies) {
        if (Arrays.binarySearch(moviesCategory4, movie.getTitle()) == -1) {
            fail("Movie not in results");
        }
    }
}

From source file:com.sun.faces.config.rules.ManagedBeanRule.java

/**
 * <p>Provides simple sanity checks.</p>
 *
 * @param bean the <code>ManagedBeanBean</code> instance to validate
 *///w  w  w. j a v  a  2s  .c  o m
private void validate(ManagedBeanBean bean) {

    String val = bean.getManagedBeanName();
    if (val == null || val.length() == 0) {
        Locator locator = digester.getDocumentLocator();
        String documentName = "UNKNOWN";
        String lineNumber = "UNKNWOWN";

        if (locator != null) {
            documentName = locator.getSystemId();
            lineNumber = Integer.toString(locator.getLineNumber());
        }

        throw new IllegalStateException(ToolsUtil.getMessage(ToolsUtil.MANAGED_BEAN_NO_MANAGED_BEAN_NAME_ID,
                new Object[] { documentName, lineNumber }));
    }

    val = bean.getManagedBeanClass();
    if (val == null || val.length() == 0) {
        throw new IllegalStateException(ToolsUtil.getMessage(ToolsUtil.MANAGED_BEAN_NO_MANAGED_BEAN_CLASS_ID,
                new Object[] { bean.getManagedBeanName() }));
    }

    val = bean.getManagedBeanScope();
    if (val == null || val.length() == 0) {
        throw new IllegalStateException(ToolsUtil.getMessage(ToolsUtil.MANAGED_BEAN_NO_MANAGED_BEAN_SCOPE_ID,
                new Object[] { bean.getManagedBeanName() }));
    }

    if (Arrays.binarySearch(SCOPES, val) < 0) {
        throw new IllegalStateException(ToolsUtil.getMessage(ToolsUtil.MANAGED_BEAN_INVALID_SCOPE_ID,
                new Object[] { val, bean.getManagedBeanName() }));
    }

    // - if the managed bean is itself a List, make sure it has no
    //   map entries or managed properties
    // - if the managed bean is itself a Map, make sure it has no
    //   managed properties
    if (bean.getListEntries() != null) {
        if (bean.getMapEntries() != null || bean.getManagedProperties().length != 0) {
            throw new IllegalStateException(ToolsUtil.getMessage(ToolsUtil.MANAGED_BEAN_AS_LIST_CONFIG_ERROR_ID,
                    new Object[] { bean.getManagedBeanName() }));
        }
    } else if (bean.getMapEntries() != null) {
        if (bean.getManagedProperties().length != 0) {
            throw new IllegalStateException(ToolsUtil.getMessage(ToolsUtil.MANAGED_BEAN_AS_MAP_CONFIG_ERROR_ID,
                    new Object[] { bean.getManagedBeanName() }));
        }
    }

}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.inference.BlockStateService.java

/****
 * Private Methods//w  ww  . jav a  2 s.  c  o m
 ****/

private BlockState getUncachedBestBlockLocation(Observation observation, BlockInstance blockInstance,
        double blockDistanceFrom, double blockDistanceTo) {

    long timestamp = observation.getTime();
    ProjectedPoint targetPoint = observation.getPoint();

    BlockConfigurationEntry block = blockInstance.getBlock();

    List<AgencyAndId> shapePointIds = MappingLibrary.map(block.getTrips(), "trip.shapeId");

    T2<List<XYPoint>, double[]> tuple = _projectedShapePointService.getProjectedShapePoints(shapePointIds,
            targetPoint.getSrid());

    if (tuple == null) {
        throw new IllegalStateException("block had no shape points: " + block.getBlock().getId());
    }

    List<XYPoint> projectedShapePoints = tuple.getFirst();
    double[] distances = tuple.getSecond();

    int fromIndex = 0;
    int toIndex = distances.length;

    if (blockDistanceFrom > 0) {
        fromIndex = Arrays.binarySearch(distances, blockDistanceFrom);
        if (fromIndex < 0) {
            fromIndex = -(fromIndex + 1);
            // Include the previous point if we didn't get an exact match
            if (fromIndex > 0)
                fromIndex--;
        }
    }

    if (blockDistanceTo < distances[distances.length - 1]) {
        toIndex = Arrays.binarySearch(distances, blockDistanceTo);
        if (toIndex < 0) {
            toIndex = -(toIndex + 1);
            // Include the previous point if we didn't get an exact match
            if (toIndex < distances.length)
                toIndex++;
        }
    }

    XYPoint xyPoint = new XYPoint(targetPoint.getX(), targetPoint.getY());

    List<PointAndIndex> assignments = _shapePointsLibrary.computePotentialAssignments(projectedShapePoints,
            distances, xyPoint, fromIndex, toIndex);

    if (assignments.size() == 0) {
        return getAsState(blockInstance, blockDistanceFrom);
    } else if (assignments.size() == 1) {
        PointAndIndex pIndex = assignments.get(0);
        return getAsState(blockInstance, pIndex.distanceAlongShape);
    }

    Min<PointAndIndex> best = new Min<PointAndIndex>();

    for (PointAndIndex index : assignments) {

        double distanceAlongBlock = index.distanceAlongShape;

        if (distanceAlongBlock > block.getTotalBlockDistance())
            distanceAlongBlock = block.getTotalBlockDistance();

        ScheduledBlockLocation location = _scheduledBlockLocationService
                .getScheduledBlockLocationFromDistanceAlongBlock(block, distanceAlongBlock);

        if (location != null) {
            int scheduledTime = location.getScheduledTime();
            long scheduleTimestamp = blockInstance.getServiceDate() + scheduledTime * 1000;

            double delta = Math.abs(scheduleTimestamp - timestamp);
            best.add(delta, index);
        }
    }

    PointAndIndex index = best.getMinElement();
    return getAsState(blockInstance, index.distanceAlongShape);
}

From source file:cn.vstore.appserver.apilog.ApiInfo.java

boolean isSecretParam(String pname) {
    if (secretParams == null || StringUtils.isBlank(pname) || secretParams.length == 0)
        return false;

    return Arrays.binarySearch(secretParams, pname) > -1;
}

From source file:master.utilities.PopulationFunctionFromJSON.java

@Override
public double getInverseIntensity(double intensity) {

    if (intensity < intensities[times.length - 1])
        return convertTime(times[times.length - 1])
                + popSizeEndInput.get() * (intensity - intensities[times.length - 1]);

    if (intensity > intensities[0])
        return convertTime(times[0]) + popSizeStartInput.get() * (intensity - intensities[0]);

    int idx = Arrays.binarySearch(intensitiesRev, intensity);
    if (idx < 0) {
        idx = -(idx + 1);//from   www  .  jav  a2s .  c o  m
        int tidx = times.length - 1 - idx; // index into forward-time array
        return convertTime(times[tidx]) + (intensity - intensities[tidx]) * popSizes[tidx];
    } else
        return convertTime(times[times.length - 1 - idx]);
}