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.dotmarketing.business.MemcachedCacheAdministratorImpl.java

private boolean canSerialize(String key, String group) {

    if (Arrays.binarySearch(_ignoreRegion, group) > -1) {
        return false;
    }//from  www . j  a  va 2  s.c o m
    if (key.startsWith("velocitycache")) {
        if (!(key.contains("live") || key.contains("working"))) {
            return false;
        }
    } else if (key.endsWith(".vm")) {
        return false;
    }
    return true;
}

From source file:fr.landel.utils.commons.StringFormatUtils.java

/**
 * Parse the string to find parameters and arguments expressions, changes
 * the index to match the combining of the two arrays and removes expression
 * with unavailable parameters or arguments.
 * /*from w ww .  ja  va 2s  .c  o m*/
 * <p>
 * Examples:
 * </p>
 * 
 * <pre>
 * "%s '%s*' '%s*' '%1$.2f' '%1$s*' '%s' '%s'"
 * 
 * // is equal to (if we specify position)
 * 
 * "%1$s '%1$s*' '%2$s*' '%1$.2f' '%1$s*' '%3$s' '%4$s'"
 * 
 * // will become with 3 parameters and 2 arguments
 * 
 * "%4$s '%1$s' '%2$s' '%4$.2f' '%1$s' '%5$s' ''"
 * </pre>
 * 
 * @param text
 *            the text where to search
 * @param nbParameters
 *            the number of parameters
 * @param startParameters
 *            the position of the parameter found
 * @param nbArguments
 *            the number of arguments
 * @param startArguments
 *            the position of the first arguments (after parameters)
 * @return the new char sequence
 */
public static CharSequence prepareFormat(final CharSequence text, final int nbParameters,
        final int startParameters, final int nbArguments, final int startArguments) {

    final char[] chars = StringUtils.toChars(text);

    int start = -1;
    int state = STATE_NOTHING;

    final Set<Group> groups = new TreeSet<>();

    int i;
    Group group = null;

    for (i = 0; i < chars.length; i++) {
        if (group == null && chars[i] == PREFIX) {
            start = i;
            group = new Group(start);
        } else if (group != null) {
            if (state < STATE_INDEX && AsciiUtils.IS_NUMERIC.test(chars[i])) {
                // (\\d+\\$)? ; the number
                if (state == STATE_NOTHING) {
                    state = STATE_NUMBER;
                    group.index = 0;
                }
                // shift left from 1 number and add the number (convert char
                // into number)
                group.index = group.index * SHIFT_LEFT + chars[i] - AsciiUtils.NUM_FIRST;
            } else if (state < STATE_INDEX && chars[i] == INDEX_SUFFIX) {
                // (\\d+\\$)? ; the dollar
                state |= STATE_INDEX;
            } else if (state < STATE_INTEGER && Arrays.binarySearch(FLAGS, chars[i]) > -1) {
                // ([-#+ 0,(\\<]*)?
                state |= STATE_FLAGS;
                group.flags.append((char) chars[i]);
            } else if (state < STATE_DOT && chars[i] == DOT) {
                // (\\d+)?(\\.\\d+)? ; the dot
                state |= STATE_DOT;
                group.number.append((char) chars[i]);
            } else if (state < STATE_TIME && AsciiUtils.IS_NUMERIC.test(chars[i])) {
                // (\\d+)?(\\.\\d+)? ; 8 (integer) for numbers before dot
                // and 32 (decimal) for numbers after
                if ((state & STATE_DOT) == STATE_DOT) {
                    state |= STATE_DECIMAL;
                } else {
                    state |= STATE_INTEGER;
                }
                group.number.append((char) chars[i]);
            } else if (state < STATE_TIME && chars[i] == TIME_UPPERCASE || chars[i] == TIME_LOWERCASE) {
                // [tT]
                state |= STATE_TIME;
                group.time = (char) chars[i];
            } else if (state < STATE_TYPE && (AsciiUtils.IS_ALPHA.test(chars[i]) || chars[i] == PERCENT)) {
                // [a-zA-Z%]
                state |= STATE_TYPE;
                group.type.append((char) chars[i]);
            } else if (state < STATE_SUFFIX && chars[i] == PARAM_SUFFIX) {
                // to detect internal parameter form
                state |= STATE_SUFFIX;
                group.asterisk = true;
            } else {
                if ((state & STATE_INDEX) != STATE_INDEX && group.index > -1) {
                    // no index, so first number detected is the format, not
                    // a number
                    group.number.insert(0, String.valueOf(group.index));
                    group.index = -1;
                }
                if ((state & STATE_TYPE) == STATE_TYPE) {
                    // complete
                    group.end = i;
                    groups.add(group);
                }
                if (chars[i] == PREFIX) {
                    // prepare the next expression
                    start = i;
                    state = STATE_NOTHING;
                    group = new Group(start);
                } else {
                    group = null;
                    state = STATE_NOTHING;
                }
            }
        }
    }

    if (group != null) {
        if ((state & 2) != 2 && group.index > -1) {
            // no index, so first number detected is the format, not a
            // number
            group.number.insert(0, String.valueOf(group.index));
            group.index = -1;
        }

        group.end = i;
        groups.add(group);
    }

    return replaceAndClear(groups,
            reindex(groups, text, nbParameters, startParameters, nbArguments, startArguments));
}

From source file:com.sun.faces.el.ValueBindingImpl.java

/**
 * <p>Returns true if the profivided identifier is a reserved identifier,
 * otherwise false.</p>/* w ww  .j  a v a 2s. c  o m*/
 *
 * @param identifier the identifier to check
 * @return returns true if the profivided identifier is a
 *         reserved identifier, otherwisefalse
 */
private boolean isReservedIdentifier(String identifier) {
    return (Arrays.binarySearch(FACES_IMPLICIT_OBJECTS, identifier) >= 0);
}

From source file:com.cloudera.sqoop.manager.PostgresqlImportTest.java

@Test
public void testListTables() throws IOException {
    SqoopOptions options = new SqoopOptions(new Configuration());
    options.setConnectString(CONNECT_STRING);
    options.setUsername(DATABASE_USER);/*from   w w  w  .jav a  2 s  .com*/

    ConnManager mgr = new PostgresqlManager(options);
    String[] tables = mgr.listTables();
    Arrays.sort(tables);
    assertTrue(TABLE_NAME + " is not found!", Arrays.binarySearch(tables, TABLE_NAME) >= 0);
}

From source file:com.opengamma.analytics.financial.credit.creditdefaultswap.pricing.vanilla.isdanew.ISDACompliantCurve.java

/**
 * get the sensitivity of the interpolated zero rate at time t to the value of the zero rate at a given node (knot).  For a
 * given index, i, this is zero unless $$t_{i-1} < t < t_{i+1}$$ since the interpolation is highly local.
 * @param t The time//  www  .ja  va 2s. co m
 * @param nodeIndex The node index
 * @return sensitivity to a single node
 */
public double getSingleNodeSensitivity(final double t, final int nodeIndex) {
    ArgumentChecker.isTrue(t >= 0, "require t >= 0.0");
    ArgumentChecker.isTrue(nodeIndex >= 0 && nodeIndex < _n, "index out of range");

    if (t <= _t[0]) {
        return nodeIndex == 0 ? 1.0 : 0.0;
    }
    //    if (t >= _t[_n - 1]) {
    //      
    //      return nodeIndex == _n - 1 ? 1.0 : 0.0;
    //    }

    final int index = Arrays.binarySearch(_t, t);
    if (index >= 0) {
        return nodeIndex == index ? 1.0 : 0.0;
    }

    final int insertionPoint = Math.min(_n - 1, -(1 + index));
    if (nodeIndex != insertionPoint && nodeIndex != insertionPoint - 1) {
        return 0.0;
    }

    final double t1 = _t[insertionPoint - 1];
    final double t2 = _t[insertionPoint];
    final double dt = t2 - t1;
    if (nodeIndex == insertionPoint) {
        return t2 * (t - t1) / dt / t;
    }

    return t1 * (t2 - t) / dt / t;
}

From source file:net.sf.mzmine.modules.visualization.spectra.SpectraVisualizerWindow.java

public void actionPerformed(ActionEvent event) {

    String command = event.getActionCommand();

    if (command.equals("PEAKLIST_CHANGE")) {

        // If no scan is loaded yet, ignore
        if (currentScan == null)
            return;

        PeakList selectedPeakList = bottomPanel.getSelectedPeakList();
        loadPeaks(selectedPeakList);//ww  w  .ja va2s . co  m

    }

    if (command.equals("PREVIOUS_SCAN")) {

        if (dataFile == null)
            return;

        int msLevel = currentScan.getMSLevel();
        int scanNumbers[] = dataFile.getScanNumbers(msLevel);
        int scanIndex = Arrays.binarySearch(scanNumbers, currentScan.getScanNumber());
        if (scanIndex > 0) {
            final int prevScanIndex = scanNumbers[scanIndex - 1];

            Runnable newThreadRunnable = new Runnable() {

                public void run() {
                    loadRawData(dataFile.getScan(prevScanIndex));
                }

            };

            Thread newThread = new Thread(newThreadRunnable);
            newThread.start();

        }
    }

    if (command.equals("NEXT_SCAN")) {

        if (dataFile == null)
            return;

        int msLevel = currentScan.getMSLevel();
        int scanNumbers[] = dataFile.getScanNumbers(msLevel);
        int scanIndex = Arrays.binarySearch(scanNumbers, currentScan.getScanNumber());

        if (scanIndex < (scanNumbers.length - 1)) {
            final int nextScanIndex = scanNumbers[scanIndex + 1];

            Runnable newThreadRunnable = new Runnable() {

                public void run() {
                    loadRawData(dataFile.getScan(nextScanIndex));
                }

            };

            Thread newThread = new Thread(newThreadRunnable);
            newThread.start();

        }
    }

    if (command.equals("SHOW_MSMS")) {

        String selectedScanString = (String) bottomPanel.getMSMSSelector().getSelectedItem();
        if (selectedScanString == null)
            return;

        int sharpIndex = selectedScanString.indexOf('#');
        int commaIndex = selectedScanString.indexOf(',');
        selectedScanString = selectedScanString.substring(sharpIndex + 1, commaIndex);
        int selectedScan = Integer.valueOf(selectedScanString);

        SpectraVisualizerModule.showNewSpectrumWindow(dataFile, selectedScan);
    }

    if (command.equals("TOGGLE_PLOT_MODE")) {
        if (spectrumPlot.getPlotMode() == PlotMode.CONTINUOUS) {
            spectrumPlot.setPlotMode(PlotMode.CENTROID);
            toolBar.setCentroidButton(false);
        } else {
            spectrumPlot.setPlotMode(PlotMode.CONTINUOUS);
            toolBar.setCentroidButton(true);
        }
    }

    if (command.equals("SHOW_DATA_POINTS")) {
        spectrumPlot.switchDataPointsVisible();
    }

    if (command.equals("SHOW_ANNOTATIONS")) {
        spectrumPlot.switchItemLabelsVisible();
    }

    if (command.equals("SHOW_PICKED_PEAKS")) {
        spectrumPlot.switchPickedPeaksVisible();
    }

    if (command.equals("SHOW_ISOTOPE_PEAKS")) {
        spectrumPlot.switchIsotopePeaksVisible();
    }

    if (command.equals("SETUP_AXES")) {
        AxesSetupDialog dialog = new AxesSetupDialog(spectrumPlot.getXYPlot());
        dialog.setVisible(true);
    }

    if (command.equals("ADD_ISOTOPE_PATTERN")) {

        IsotopePattern newPattern = IsotopePatternCalculator.showIsotopePredictionDialog();

        if (newPattern == null)
            return;

        loadIsotopes(newPattern);

    }

    if ((command.equals("ZOOM_IN")) || (command.equals("ZOOM_IN_BOTH_COMMAND"))) {
        spectrumPlot.getXYPlot().getDomainAxis().resizeRange(1 / zoomCoefficient);
    }

    if ((command.equals("ZOOM_OUT")) || (command.equals("ZOOM_OUT_BOTH_COMMAND"))) {
        spectrumPlot.getXYPlot().getDomainAxis().resizeRange(zoomCoefficient);
    }

    if (command.equals("SET_SAME_RANGE")) {

        // Get current axes range
        NumberAxis xAxis = (NumberAxis) spectrumPlot.getXYPlot().getDomainAxis();
        NumberAxis yAxis = (NumberAxis) spectrumPlot.getXYPlot().getRangeAxis();
        double xMin = (double) xAxis.getRange().getLowerBound();
        double xMax = (double) xAxis.getRange().getUpperBound();
        double xTick = (double) xAxis.getTickUnit().getSize();
        double yMin = (double) yAxis.getRange().getLowerBound();
        double yMax = (double) yAxis.getRange().getUpperBound();
        double yTick = (double) yAxis.getTickUnit().getSize();

        // Get all frames of my class
        Window spectraFrames[] = JFrame.getWindows();

        // Set the range of these frames
        for (Window frame : spectraFrames) {
            if (!(frame instanceof SpectraVisualizerWindow))
                continue;
            SpectraVisualizerWindow spectraFrame = (SpectraVisualizerWindow) frame;
            spectraFrame.setAxesRange(xMin, xMax, xTick, yMin, yMax, yTick);
        }

    }

}

From source file:geovista.readers.csv.GeogCSVReader_old.java

public Object[] readFile(InputStream is) {

    // CSVParser shredder = new CSVParser(is);
    // shredder.setCommentStart("#;!");
    // shredder.setEscapes("nrtf", "\n\r\t\f");
    String[] headers = null;/*from   ww w . jav a2  s. c  om*/
    String[] types = null;
    int[] dataTypes = null;
    String[][] fileContent = null;
    int dataBegin;
    Object[] data;
    try {
        // fileContent = shredder.getAllValues();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    types = fileContent[0];// first line tells us types
    dataTypes = new int[types.length];
    int len;
    if (types[0].equalsIgnoreCase("int") || types[0].equalsIgnoreCase("double")
            || types[0].equalsIgnoreCase("string")) {
        dataBegin = 2;
        headers = fileContent[1];
        data = new Object[headers.length + 1];// plus one for the headers
        // themselves
        len = fileContent.length - dataBegin;
        for (int i = 0; i < headers.length; i++) {
            if (types[i].equalsIgnoreCase("int")) {
                data[i + 1] = new int[len];
                dataTypes[i] = GeogCSVReader_old.DATA_TYPE_INT;
            } else if (types[i].equalsIgnoreCase("double")) {
                data[i + 1] = new double[len];
                dataTypes[i] = GeogCSVReader_old.DATA_TYPE_DOUBLE;
            } else if (types[i].equalsIgnoreCase("string")) {
                data[i + 1] = new String[len];
                dataTypes[i] = GeogCSVReader_old.DATA_TYPE_STRING;
            } else {
                throw new IllegalArgumentException("GeogCSVReader.readFile, unknown type = " + types[i]);
            }
        }
    } else {
        dataBegin = 1;
        headers = fileContent[0];
        data = new Object[headers.length + 1];// plus one for the headers
        // themselves
        len = fileContent.length - dataBegin;
        for (int i = 0; i < headers.length; i++) {
            String firstString = fileContent[1][i];
            String secondString = fileContent[2][i];
            String thirdString = fileContent[3][i];
            int lastRowNum = fileContent.length - 1;
            String lastString = fileContent[lastRowNum][i];

            if (isNumeric(firstString) && isNumeric(secondString) && isNumeric(thirdString)
                    && isNumeric(lastString)) {
                if (isInt(fileContent, i) == false) {
                    // if (isDouble(firstString) || isDouble(secondString)
                    // || isDouble(thirdString) || isDouble(lastString)) {
                    data[i + 1] = new double[len];
                    dataTypes[i] = GeogCSVReader_old.DATA_TYPE_DOUBLE;
                } else {
                    data[i + 1] = new int[len];
                    dataTypes[i] = GeogCSVReader_old.DATA_TYPE_INT;
                }
            } else {
                data[i + 1] = new String[len];
                dataTypes[i] = GeogCSVReader_old.DATA_TYPE_STRING;
            }
        }
    }
    data[0] = headers;

    String[] line = null;

    for (int row = dataBegin; row < len + dataBegin; row++) {

        line = fileContent[row];

        int[] ints = null;
        double[] doubles = null;
        String[] strings = null;

        for (int column = 0; column < line.length; column++) {
            String item = line[column];
            if (dataTypes[column] == GeogCSVReader_old.DATA_TYPE_INT) {

                if (Arrays.binarySearch(GeogCSVReader_old.NULL_STRINGS, item) >= 0) {
                    ints = (int[]) data[column + 1];
                    ints[row - dataBegin] = GeogCSVReader_old.NULL_INT;
                } else {
                    ints = (int[]) data[column + 1];
                    try {
                        ints[row - dataBegin] = Integer.parseInt(item);
                    } catch (NumberFormatException nfe) {
                        logger.warning("could not parse " + item + " in column " + column);
                        // nfe.printStackTrace();
                        ints[row - dataBegin] = GeogCSVReader_old.NULL_INT;
                    }
                }
            } else if (dataTypes[column] == GeogCSVReader_old.DATA_TYPE_DOUBLE) {
                if (Arrays.binarySearch(GeogCSVReader_old.NULL_STRINGS, item) >= 0) {
                    doubles = (double[]) data[column + 1];
                    doubles[row - dataBegin] = GeogCSVReader_old.NULL_DOUBLE;
                } else {
                    doubles = (double[]) data[column + 1];
                    doubles[row - dataBegin] = parseDouble(item);
                }
            } else if (dataTypes[column] == GeogCSVReader_old.DATA_TYPE_STRING) {
                strings = (String[]) data[column + 1];
                strings[row - dataBegin] = item;
            } else {
                throw new IllegalArgumentException("GeogCSVReader.readFile, unknown type = " + types[row]);
            } // end if

        } // next column
    } // next row
    return data;

}

From source file:com.puppycrawl.tools.checkstyle.AllChecksTest.java

/**
 * Checks that an array is a subset of other array.
 * @param array to check whether it is a subset.
 * @param arrayToCheckIn array to check in.
 *///from  w w  w . jav  a 2 s. c  o  m
private static boolean isSubset(int[] array, int... arrayToCheckIn) {
    Arrays.sort(arrayToCheckIn);
    for (final int element : array) {
        if (Arrays.binarySearch(arrayToCheckIn, element) < 0) {
            return false;
        }
    }
    return true;
}

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

private void testStringDictionary(ImmutableDictionaryReader stringDictionary) {
    for (int i = 0; i < NUM_VALUES; i++) {
        Assert.assertEquals(stringDictionary.get(i), _stringValues[i]);
        Assert.assertEquals(stringDictionary.getStringValue(i), _stringValues[i]);

        Assert.assertEquals(stringDictionary.indexOf(_stringValues[i]), i);

        // Test String longer than MAX_STRING_LENGTH
        String randomString = RandomStringUtils.random(RANDOM.nextInt(2 * MAX_STRING_LENGTH)).replace('\0',
                ' ');
        Assert.assertEquals(stringDictionary.insertionIndexOf(randomString),
                Arrays.binarySearch(_stringValues, randomString));
    }//from   w ww . jav  a 2  s.co m
}

From source file:com.opengamma.analytics.financial.model.interestrate.definition.LiborMarketModelDisplacedDiffusionParameters.java

/**
 * Return the index in the Ibor time list of a given time. The match does not need to be exact (to allow rounding effects and 1 day discrepancy).
 * The allowed difference is set in the TIME_TOLERANCE variable.
 * @param time The time./*from  w  w  w.  j ava  2s.  c o  m*/
 * @return The index.
 */
public int getTimeIndex(final double time) {
    int index = Arrays.binarySearch(_iborTime, time);
    if (index < 0) {
        if (_iborTime[-index - 1] - time < TIME_TOLERANCE) {
            index = -index - 1;
        } else {
            if (time - _iborTime[-index - 2] < TIME_TOLERANCE) {
                index = -index - 2;
            } else {
                Validate.isTrue(true, "Instrument time incompatible with LMM");
            }
        }
    }
    return index;
}