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.cyberway.issue.net.UURIFactory.java

/**
 * Do heritrix fix-up on passed uri string.
 *
 * Does heritrix escaping; usually escaping done to make our behavior align
 * with IEs.  This method codifies our experience pulling URIs from the
 * wilds.  Its does all the escaping we want; its output can always be
 * assumed to be 'escaped' (though perhaps to a laxer standard than the 
 * vanilla HttpClient URI class or official specs might suggest). 
 *
 * @param uri URI as string./*from  w  ww .j  av  a  2s.  co  m*/
 * @param base May be null.
 * @param e True if the uri is already escaped.
 * @return A fixed up URI string.
 * @throws URIException
 */
private String fixup(String uri, final URI base, final String charset) throws URIException {
    if (uri == null) {
        throw new NullPointerException();
    } else if (uri.length() == 0 && base == null) {
        throw new URIException("URI length is zero (and not relative).");
    }

    if (uri.length() > UURI.MAX_URL_LENGTH) {
        // We check length here and again later after all convertions.
        throw new URIException("URI length > " + UURI.MAX_URL_LENGTH + ": " + uri);
    }

    // Replace nbsp with normal spaces (so that they get stripped if at
    // ends, or encoded if in middle)
    if (uri.indexOf(NBSP) >= 0) {
        uri = TextUtils.replaceAll(NBSP, uri, SPACE);
    }

    // Get rid of any trailing spaces or new-lines. 
    uri = uri.trim();

    // IE actually converts backslashes to slashes rather than to %5C.
    // Since URIs that have backslashes usually work only with IE, we will
    // convert backslashes to slashes as well.
    // TODO: Maybe we can first convert backslashes by specs and than by IE
    // so that we fetch both versions.
    if (uri.indexOf(BACKSLASH) >= 0) {
        uri = TextUtils.replaceAll(BACKSLASH_PATTERN, uri, SLASH);
    }

    // Remove stray TAB/CR/LF
    uri = TextUtils.replaceAll(STRAY_SPACING, uri, EMPTY_STRING);

    // Test for the case of more than two slashes after the http(s) scheme.
    // Replace with two slashes as mozilla does if found.
    // See [ 788219 ] URI Syntax Errors stop page parsing.
    Matcher matcher = HTTP_SCHEME_SLASHES.matcher(uri);
    if (matcher.matches()) {
        uri = matcher.group(1) + matcher.group(2);
    }

    // now, minimally escape any whitespace
    uri = escapeWhitespace(uri);

    // For further processing, get uri elements.  See the RFC2396REGEX
    // comment above for explaination of group indices used in the below.
    matcher = RFC2396REGEX.matcher(uri);
    if (!matcher.matches()) {
        throw new URIException("Failed parse of " + uri);
    }
    String uriScheme = checkUriElementAndLowerCase(matcher.group(2));
    String uriSchemeSpecificPart = checkUriElement(matcher.group(3));
    String uriAuthority = checkUriElement(matcher.group(5));
    String uriPath = checkUriElement(matcher.group(6));
    String uriQuery = checkUriElement(matcher.group(8));
    // UNUSED String uriFragment = checkUriElement(matcher.group(10));

    // If a scheme, is it a supported scheme?
    if (uriScheme != null && uriScheme.length() > 0 && this.schemes != null) {
        if (!(Arrays.binarySearch(schemes, uriScheme) >= 0)) {
            // unsupported; see if silently ignored
            if ((Arrays.binarySearch(ignoredSchemes, uriScheme) >= 0)) {
                throw new URIException(IGNORED_SCHEME, "Ignored scheme: " + uriScheme);
            } else {
                throw new URIException("Unsupported scheme: " + uriScheme);
            }
        }
    }

    // Test if relative URI. If so, need a base to resolve against.
    if (uriScheme == null || uriScheme.length() <= 0) {
        if (base == null) {
            throw new URIException("Relative URI but no base: " + uri);
        }
    } else {
        checkHttpSchemeSpecificPartSlashPrefix(base, uriScheme, uriSchemeSpecificPart);
    }

    // fixup authority portion: lowercase/IDN-punycode any domain; 
    // remove stray trailing spaces
    uriAuthority = fixupAuthority(uriAuthority);

    // Do some checks if absolute path.
    if (uriSchemeSpecificPart != null && uriSchemeSpecificPart.startsWith(SLASH)) {
        if (uriPath != null) {
            // Eliminate '..' if its first thing in the path.  IE does this.
            uriPath = TextUtils.replaceFirst(SLASHDOTDOTSLASH, uriPath, SLASH);
        }
        // Ensure root URLs end with '/': browsers always send "/"
        // on the request-line, so we should consider "http://host"
        // to be "http://host/".
        if (uriPath == null || EMPTY_STRING.equals(uriPath)) {
            uriPath = SLASH;
        }
    }

    if (uriAuthority != null) {
        if (uriScheme != null && uriScheme.length() > 0 && uriScheme.equals(HTTP)) {
            uriAuthority = checkPort(uriAuthority);
            uriAuthority = stripTail(uriAuthority, HTTP_PORT);
        } else if (uriScheme != null && uriScheme.length() > 0 && uriScheme.equals(HTTPS)) {
            uriAuthority = checkPort(uriAuthority);
            uriAuthority = stripTail(uriAuthority, HTTPS_PORT);
        }
        // Strip any prefix dot or tail dots from the authority.
        uriAuthority = stripTail(uriAuthority, DOT);
        uriAuthority = stripPrefix(uriAuthority, DOT);
    } else {
        // no authority; may be relative. consider stripping scheme
        // to work-around org.apache.commons.httpclient.URI bug
        // ( http://issues.apache.org/jira/browse/HTTPCLIENT-587 )
        if (uriScheme != null && base != null && uriScheme.equals(base.getScheme())) {
            // uriScheme redundant and will only confound httpclient.URI
            uriScheme = null;
        }
    }

    // Ensure minimal escaping. Use of 'lax' URI and URLCodec 
    // means minimal escaping isn't necessarily complete/consistent.
    // There is a chance such lax encoding will throw exceptions
    // later at inconvenient times. 
    //
    // One reason for these bad escapings -- though not the only --
    // is that the page is using an encoding other than the ASCII or the
    // UTF-8 that is our default URI encoding.  In this case the parent
    // class is burping on the passed URL encoding.  If the page encoding
    // was passed into this factory, the encoding seems to be parsed
    // correctly (See the testEscapedEncoding unit test).
    //
    // This fixup may cause us to miss content.  There is the charset case
    // noted above.  TODO: Look out for cases where we fail other than for
    // the above given reason which will be fixed when we address
    // '[ 913687 ] Make extractors interrogate for charset'.

    uriPath = ensureMinimalEscaping(uriPath, charset);
    uriQuery = ensureMinimalEscaping(uriQuery, charset, LaxURLCodec.QUERY_SAFE);

    // Preallocate.  The '1's and '2's in below are space for ':',
    // '//', etc. URI characters.
    MutableString s = new MutableString(((uriScheme != null) ? uriScheme.length() : 0) + 1 // ';' 
            + ((uriAuthority != null) ? uriAuthority.length() : 0) + 2 // '//'
            + ((uriPath != null) ? uriPath.length() : 0) + 1 // '?'
            + ((uriQuery != null) ? uriQuery.length() : 0));
    appendNonNull(s, uriScheme, ":", true);
    appendNonNull(s, uriAuthority, "//", false);
    appendNonNull(s, uriPath, "", false);
    appendNonNull(s, uriQuery, "?", false);
    return s.toString();
}

From source file:bin.spider.frame.uri.UURIFactory.java

/**
 * Do heritrix fix-up on passed uri string.
 *
 * Does heritrix escaping; usually escaping done to make our behavior align
 * with IEs.  This method codifies our experience pulling URIs from the
 * wilds.  Its does all the escaping we want; its output can always be
 * assumed to be 'escaped' (though perhaps to a laxer standard than the 
 * vanilla HttpClient URI class or official specs might suggest). 
 *
 * @param uri URI as string.//from  w  w w. j av a 2  s  .  co m
 * @param base May be null.
 * @param e True if the uri is already escaped.
 * @return A fixed up URI string.
 * @throws URIException
 */
private String fixup(String uri, final URI base, final String charset) throws URIException {
    if (uri == null) {
        throw new NullPointerException();
    } else if (uri.length() == 0 && base == null) {
        throw new URIException("URI length is zero (and not relative).");
    }

    if (uri.length() > UURI.MAX_URL_LENGTH) {
        // We check length here and again later after all convertions.
        throw new URIException("URI length > " + UURI.MAX_URL_LENGTH + ": " + uri);
    }

    // Replace nbsp with normal spaces (so that they get stripped if at
    // ends, or encoded if in middle)
    if (uri.indexOf(NBSP) >= 0) {
        uri = TextUtils.replaceAll(NBSP, uri, SPACE);
    }

    // Get rid of any trailing spaces or new-lines. 
    uri = uri.trim();

    // IE actually converts backslashes to slashes rather than to %5C.
    // Since URIs that have backslashes usually work only with IE, we will
    // convert backslashes to slashes as well.
    // TODO: Maybe we can first convert backslashes by specs and than by IE
    // so that we fetch both versions.
    if (uri.indexOf(BACKSLASH) >= 0) {
        uri = TextUtils.replaceAll(BACKSLASH_PATTERN, uri, SLASH);
    }

    // Remove stray TAB/CR/LF
    uri = TextUtils.replaceAll(STRAY_SPACING, uri, EMPTY_STRING);

    // Test for the case of more than two slashes after the http(s) scheme.
    // Replace with two slashes as mozilla does if found.
    // See [ 788219 ] URI Syntax Errors stop page parsing.
    Matcher matcher = HTTP_SCHEME_SLASHES.matcher(uri);
    if (matcher.matches()) {
        uri = matcher.group(1) + matcher.group(2);
    }

    // now, minimally escape any whitespace
    uri = escapeWhitespace(uri);

    // For further processing, get uri elements.  See the RFC2396REGEX
    // comment above for explaination of group indices used in the below.
    matcher = RFC2396REGEX.matcher(uri);
    if (!matcher.matches()) {
        throw new URIException("Failed parse of " + uri);
    }
    String uriScheme = checkUriElementAndLowerCase(matcher.group(2));
    String uriSchemeSpecificPart = checkUriElement(matcher.group(3));
    String uriAuthority = checkUriElement(matcher.group(5));
    String uriPath = checkUriElement(matcher.group(6));
    String uriQuery = checkUriElement(matcher.group(8));
    // UNUSED String uriFragment = checkUriElement(matcher.group(10));

    // If a scheme, is it a supported scheme?
    if (uriScheme != null && uriScheme.length() > 0 && this.schemes != null) {
        if (!(Arrays.binarySearch(schemes, uriScheme) >= 0)) {
            // unsupported; see if silently ignored
            if ((Arrays.binarySearch(ignoredSchemes, uriScheme) >= 0)) {
                throw new URIException(IGNORED_SCHEME, "Ignored scheme: " + uriScheme);
            } else {
                throw new URIException("Unsupported scheme: " + uriScheme);
            }
        }
    }

    // Test if relative URI. If so, need a base to resolve against.
    if (uriScheme == null || uriScheme.length() <= 0) {
        if (base == null) {
            throw new URIException("Relative URI but no base: " + uri);
        }
    } else {
        checkHttpSchemeSpecificPartSlashPrefix(base, uriScheme, uriSchemeSpecificPart);
    }

    // fixup authority portion: lowercase/IDN-punycode any domain; 
    // remove stray trailing spaces
    uriAuthority = fixupAuthority(uriAuthority, charset);

    // Do some checks if absolute path.
    if (uriSchemeSpecificPart != null && uriSchemeSpecificPart.startsWith(SLASH)) {
        if (uriPath != null) {
            // Eliminate '..' if its first thing in the path.  IE does this.
            uriPath = TextUtils.replaceFirst(SLASHDOTDOTSLASH, uriPath, SLASH);
        }
        // Ensure root URLs end with '/': browsers always send "/"
        // on the request-line, so we should consider "http://host"
        // to be "http://host/".
        if (uriPath == null || EMPTY_STRING.equals(uriPath)) {
            uriPath = SLASH;
        }
    }

    if (uriAuthority != null) {
        if (uriScheme != null && uriScheme.length() > 0 && uriScheme.equals(HTTP)) {
            uriAuthority = checkPort(uriAuthority);
            uriAuthority = stripTail(uriAuthority, HTTP_PORT);
        } else if (uriScheme != null && uriScheme.length() > 0 && uriScheme.equals(HTTPS)) {
            uriAuthority = checkPort(uriAuthority);
            uriAuthority = stripTail(uriAuthority, HTTPS_PORT);
        }
        // Strip any prefix dot or tail dots from the authority.
        uriAuthority = stripTail(uriAuthority, DOT);
        uriAuthority = stripPrefix(uriAuthority, DOT);
    } else {
        // no authority; may be relative. consider stripping scheme
        // to work-around org.apache.commons.httpclient.URI bug
        // ( http://issues.apache.org/jira/browse/HTTPCLIENT-587 )
        if (uriScheme != null && base != null && uriScheme.equals(base.getScheme())) {
            // uriScheme redundant and will only confound httpclient.URI
            uriScheme = null;
        }
    }

    // Ensure minimal escaping. Use of 'lax' URI and URLCodec 
    // means minimal escaping isn't necessarily complete/consistent.
    // There is a chance such lax encoding will throw exceptions
    // later at inconvenient times. 
    //
    // One reason for these bad escapings -- though not the only --
    // is that the page is using an encoding other than the ASCII or the
    // UTF-8 that is our default URI encoding.  In this case the parent
    // class is burping on the passed URL encoding.  If the page encoding
    // was passed into this factory, the encoding seems to be parsed
    // correctly (See the testEscapedEncoding unit test).
    //
    // This fixup may cause us to miss content.  There is the charset case
    // noted above.  TODO: Look out for cases where we fail other than for
    // the above given reason which will be fixed when we address
    // '[ 913687 ] Make extractors interrogate for charset'.

    uriPath = ensureMinimalEscaping(uriPath, charset);
    uriQuery = ensureMinimalEscaping(uriQuery, charset, LaxURLCodec.QUERY_SAFE);

    // Preallocate.  The '1's and '2's in below are space for ':',
    // '//', etc. URI characters.
    MutableString s = new MutableString(((uriScheme != null) ? uriScheme.length() : 0) + 1 // ';' 
            + ((uriAuthority != null) ? uriAuthority.length() : 0) + 2 // '//'
            + ((uriPath != null) ? uriPath.length() : 0) + 1 // '?'
            + ((uriQuery != null) ? uriQuery.length() : 0));
    appendNonNull(s, uriScheme, ":", true);
    appendNonNull(s, uriAuthority, "//", false);
    appendNonNull(s, uriPath, "", false);
    appendNonNull(s, uriQuery, "?", false);
    return s.toString();
}

From source file:dk.netarkivet.wayback.batch.copycode.NetarchiveSuiteUURIFactory.java

/**
 * Do heritrix fix-up on passed uri string.
 *
 * Does heritrix escaping; usually escaping done to make our behavior align
 * with IEs.  This method codifies our experience pulling URIs from the
 * wilds.  Its does all the escaping we want; its output can always be
 * assumed to be 'escaped' (though perhaps to a laxer standard than the
 * vanilla HttpClient URI class or official specs might suggest).
 *
 * @param uri URI as string./*www  . jav  a 2 s  .  com*/
 * @param base May be null.
 * @param e True if the uri is already escaped.
 * @return A fixed up URI string.
 * @throws URIException
 */
private String fixup(String uri, final URI base, final String charset) throws URIException {
    if (uri == null) {
        throw new NullPointerException();
    } else if (uri.length() == 0 && base == null) {
        throw new URIException("URI length is zero (and not relative).");
    }

    if (uri.length() > UURI.MAX_URL_LENGTH) {
        // We check length here and again later after all convertions.
        throw new URIException("URI length > " + UURI.MAX_URL_LENGTH + ": " + uri);
    }

    // Replace nbsp with normal spaces (so that they get stripped if at
    // ends, or encoded if in middle)
    if (uri.indexOf(NBSP) >= 0) {
        uri = TextUtils.replaceAll(NBSP, uri, SPACE);
    }

    // Get rid of any trailing spaces or new-lines.
    uri = uri.trim();

    // IE actually converts backslashes to slashes rather than to %5C.
    // Since URIs that have backslashes usually work only with IE, we will
    // convert backslashes to slashes as well.
    // TODO Maybe we can first convert backslashes by specs and than by IE
    // so that we fetch both versions.
    if (uri.indexOf(BACKSLASH) >= 0) {
        uri = TextUtils.replaceAll(BACKSLASH_PATTERN, uri, SLASH);
    }

    // Remove stray TAB/CR/LF
    uri = TextUtils.replaceAll(STRAY_SPACING, uri, EMPTY_STRING);

    // Test for the case of more than two slashes after the http(s) scheme.
    // Replace with two slashes as mozilla does if found.
    // See [ 788219 ] URI Syntax Errors stop page parsing.
    Matcher matcher = HTTP_SCHEME_SLASHES.matcher(uri);
    if (matcher.matches()) {
        uri = matcher.group(1) + matcher.group(2);
    }

    // now, minimally escape any whitespace
    uri = escapeWhitespace(uri);

    // For further processing, get uri elements.  See the RFC2396REGEX
    // comment above for explaination of group indices used in the below.
    matcher = RFC2396REGEX.matcher(uri);
    if (!matcher.matches()) {
        throw new URIException("Failed parse of " + uri);
    }
    String uriScheme = checkUriElementAndLowerCase(matcher.group(2));
    String uriSchemeSpecificPart = checkUriElement(matcher.group(3));
    String uriAuthority = checkUriElement(matcher.group(5));
    String uriPath = checkUriElement(matcher.group(6));
    String uriQuery = checkUriElement(matcher.group(8));
    // UNUSED String uriFragment = checkUriElement(matcher.group(10));

    // If a scheme, is it a supported scheme?
    if (uriScheme != null && uriScheme.length() > 0 && this.schemes != null) {
        if (!(Arrays.binarySearch(schemes, uriScheme) >= 0)) {
            // unsupported; see if silently ignored
            if ((Arrays.binarySearch(ignoredSchemes, uriScheme) >= 0)) {
                throw new URIException(IGNORED_SCHEME, "Ignored scheme: " + uriScheme);
            } else {
                throw new URIException("Unsupported scheme: " + uriScheme);
            }
        }
    }

    // Test if relative URI. If so, need a base to resolve against.
    if (uriScheme == null || uriScheme.length() <= 0) {
        if (base == null) {
            throw new URIException("Relative URI but no base: " + uri);
        }
    } else {
        checkHttpSchemeSpecificPartSlashPrefix(base, uriScheme, uriSchemeSpecificPart);
    }

    // fixup authority portion: lowercase/IDN-punycode any domain;
    // remove stray trailing spaces
    uriAuthority = fixupAuthority(uriAuthority);

    // Do some checks if absolute path.
    if (uriSchemeSpecificPart != null && uriSchemeSpecificPart.startsWith(SLASH)) {
        if (uriPath != null) {
            // Eliminate '..' if its first thing in the path.  IE does this.
            uriPath = TextUtils.replaceFirst(SLASHDOTDOTSLASH, uriPath, SLASH);
        }
        // Ensure root URLs end with '/': browsers always send "/"
        // on the request-line, so we should consider "http://host"
        // to be "http://host/".
        if (uriPath == null || EMPTY_STRING.equals(uriPath)) {
            uriPath = SLASH;
        }
    }

    if (uriAuthority != null) {
        if (uriScheme != null && uriScheme.length() > 0 && uriScheme.equals(HTTP)) {
            uriAuthority = checkPort(uriAuthority);
            uriAuthority = stripTail(uriAuthority, HTTP_PORT);
        } else if (uriScheme != null && uriScheme.length() > 0 && uriScheme.equals(HTTPS)) {
            uriAuthority = checkPort(uriAuthority);
            uriAuthority = stripTail(uriAuthority, HTTPS_PORT);
        }
        // Strip any prefix dot or tail dots from the authority.
        uriAuthority = stripTail(uriAuthority, DOT);
        uriAuthority = stripPrefix(uriAuthority, DOT);
    } else {
        // no authority; may be relative. consider stripping scheme
        // to work-around org.apache.commons.httpclient.URI bug
        // ( http://issues.apache.org/jira/browse/HTTPCLIENT-587 )
        if (uriScheme != null && base != null && uriScheme.equals(base.getScheme())) {
            // uriScheme redundant and will only confound httpclient.URI
            uriScheme = null;
        }
    }

    // Ensure minimal escaping. Use of 'lax' URI and URLCodec
    // means minimal escaping isn't necessarily complete/consistent.
    // There is a chance such lax encoding will throw exceptions
    // later at inconvenient times.
    //
    // One reason for these bad escapings -- though not the only --
    // is that the page is using an encoding other than the ASCII or the
    // UTF-8 that is our default URI encoding.  In this case the parent
    // class is burping on the passed URL encoding.  If the page encoding
    // was passed into this factory, the encoding seems to be parsed
    // correctly (See the testEscapedEncoding unit test).
    //
    // This fixup may cause us to miss content.  There is the charset case
    // noted above.  TODO Look out for cases where we fail other than for
    // the above given reason which will be fixed when we address
    // '[ 913687 ] Make extractors interrogate for charset'.

    uriPath = ensureMinimalEscaping(uriPath, charset);
    uriQuery = ensureMinimalEscaping(uriQuery, charset, LaxURLCodec.QUERY_SAFE);

    // Preallocate.  The '1's and '2's in below are space for ':',
    // '//', etc. URI characters.
    MutableString s = new MutableString(((uriScheme != null) ? uriScheme.length() : 0) + 1 // ';'
            + ((uriAuthority != null) ? uriAuthority.length() : 0) + 2 // '//'
            + ((uriPath != null) ? uriPath.length() : 0) + 1 // '?'
            + ((uriQuery != null) ? uriQuery.length() : 0));
    appendNonNull(s, uriScheme, ":", true);
    appendNonNull(s, uriAuthority, "//", false);
    appendNonNull(s, uriPath, "", false);
    appendNonNull(s, uriQuery, "?", false);
    return s.toString();
}

From source file:com.github.michalbednarski.intentslab.editor.IntentGeneralFragment.java

private void setupActionSpinnerOrField() {
    IntentFilter[] intentFilters = getIntentEditor().getAttachedIntentFilters();
    if (intentFilters != null) {
        // Build action set
        Set<String> actionSet = new HashSet<String>();
        for (IntentFilter filter : intentFilters) {
            for (int i = 0, j = filter.countActions(); i < j; i++) {
                actionSet.add(filter.getAction(i));
            }//from  ww w.j  av a  2 s. co  m
        }

        // Check if we have any action and if not (invalid intent-filter)
        // switch to textfield
        if (actionSet.isEmpty()) {
            setupActionField();
            return;
        }

        // Convert action set to array
        mAvailbleActions = actionSet.toArray(new String[actionSet.size()]);
        Arrays.sort(mAvailbleActions);

        // Select current action
        String action = mEditedIntent.getAction();
        if (action == null) {
            action = Intent.ACTION_VIEW;
        }
        int position = Arrays.binarySearch(mAvailbleActions, action);
        mActionsSpinner.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,
                mAvailbleActions));
        if (position < 0) {
            position = 0;
        }
        mActionsSpinner.setSelection(position);

        // Show spinner and hide textfield
        mActionText.setVisibility(View.GONE);
        mActionsSpinner.setVisibility(View.VISIBLE);

        // Set listener for action change to refresh intent filter
        mActionsSpinner.setOnItemSelectedListener(this);
    } else {
        setupActionField();
    }
}

From source file:au.gov.ga.conn4d.utils.BicubicSplineInterpolatingFunction.java

/**
 * @param c Coordinate.//from  w  w w  .ja v  a  2 s.  c o m
 * @param val Coordinate samples.
 * @return the index in {@code val} corresponding to the interval
 * containing {@code c}.
 * @throws OutOfRangeException if {@code c} is out of the
 * range defined by the boundary values of {@code val}.
 */
private int searchIndex(double c, double[] val) {
    final int r = Arrays.binarySearch(val, c);

    if (r == -1 || r == -val.length - 1) {
        throw new OutOfRangeException(c, val[0], val[val.length - 1]);
    }

    if (r < 0) {
        // "c" in within an interpolation sub-interval: Return the
        // index of the sample at the lower end of the sub-interval.
        return -r - 2;
    }
    final int last = val.length - 1;
    if (r == last) {
        // "c" is the last sample of the range: Return the index
        // of the sample at the lower end of the last sub-interval.
        return last - 1;
    }

    // "c" is another sample point.
    return r;
}

From source file:org.apache.fop.complexscripts.scripts.ArabicScriptProcessor.java

private static boolean hasIsolateFinal(int ch) {
    return Arrays.binarySearch(isolatedFinals, ch) >= 0;
}

From source file:com.koda.integ.hbase.test.TestHFileBlockIndexer.java

@Test
public void testSeekNonExactAbsoluteBefore() {
    LOG.info("Test seek non exact absolute Before starts");
    int limit = buffer.limit();
    Random r = new Random();
    for (int i = 0; i < 100; i++) {
        buffer.position(0);// ww w . j  a  v  a 2 s  . co  m
        buffer.limit(limit);
        int index = N + r.nextInt(N);
        byte[] row = getRow(index);
        KeyValue kv = new KeyValue(row, CF, CQ, Integer.toString(index).getBytes());
        //LOG.info("Looking for: "+kv);
        int offset = HFileBlockIndexer.seekBefore(buffer, kv.getBuffer(), kv.getKeyOffset(), kv.getKeyLength(),
                indexData, true, comparator);
        if (offset < 0) {
            // Verify that the largest KV in array is less than 'kv'
            assertTrue(KeyValue.COMPARATOR.compareRows(array[0], kv) > 0);
            //LOG.info("Not found.");
        } else {
            // else
            // we found offset of a KV which is strictly less than 'kv'
            // find index
            int k = Arrays.binarySearch(indexData, offset);
            assertTrue(k >= 0);
            assertTrue(KeyValue.COMPARATOR.compare(array[k], kv) < 0);
            if (k < array.length - 1) {
                assertTrue(KeyValue.COMPARATOR.compare(array[k + 1], kv) >= 0);
            }
            //LOG.info("Found      : "+array[k]);
        }
        offset = HFileBlockIndexer.seekBefore(buffer, kv.getBuffer(), kv.getKeyOffset(), kv.getKeyLength(),
                indexData, false, comparator);
        if (offset < 0) {
            // Verify that the largest KV in array is less than 'kv'
            assertTrue(KeyValue.COMPARATOR.compare(array[0], kv) > 0);
            //LOG.info("Not found.");
        } else {
            // else
            // we found offset of a KV which is strictly less than 'kv'
            // find index
            int k = Arrays.binarySearch(indexData, offset);
            assertTrue(k >= 0);
            assertTrue(KeyValue.COMPARATOR.compare(array[k], kv) <= 0);
            if (k < array.length - 1) {
                assertTrue(KeyValue.COMPARATOR.compare(array[k + 1], kv) >= 0);
            }
            //LOG.info("Found      : "+array[k]);
        }

    }

    LOG.info("Test seek non-exact absolute Before finished");
}

From source file:com.opengamma.util.timeseries.fast.integer.FastArrayIntDoubleTimeSeries.java

@Override
public double getValueFast(final int time) {
    final int binarySearch = Arrays.binarySearch(_times, time);
    if (binarySearch >= 0 && _times[binarySearch] == time) {
        return _values[binarySearch];
    } else {//from w  w  w .  j a  v  a 2  s  .c o  m
        throw new NoSuchElementException();
    }
}

From source file:org.dspace.app.rest.utils.MultipartFileSender.java

private static boolean accepts(String acceptHeader, String toAccept) {
    String[] acceptValues = acceptHeader.split("\\s*(,|;)\\s*");
    Arrays.sort(acceptValues);/*from   ww  w .ja  v a  2s.  c  o  m*/

    return Arrays.binarySearch(acceptValues, toAccept) > -1
            || Arrays.binarySearch(acceptValues, toAccept.replaceAll("/.*$", "/*")) > -1
            || Arrays.binarySearch(acceptValues, "*/*") > -1;
}

From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java

/**
 * Constructs an aggregate quad tree out of a two-dimensional array of values.
 * //from   w  ww. ja  v  a2  s .  com
 * @param values
 * @param out
 *          - the output stream to write the constructed quad tree to
 * @throws IOException
 */
public static void build(NASADataset metadata, short[] values, short fillValue, DataOutputStream out)
        throws IOException {
    int length = Array.getLength(values);
    int resolution = (int) Math.round(Math.sqrt(length));

    // Write tree header
    out.writeInt(resolution); // resolution
    out.writeShort(fillValue);
    out.writeInt(1); // cardinality
    out.writeLong(metadata.time); // Timestamp

    // Fetch the stock quad tree of the associated resolution
    StockQuadTree stockQuadTree = getOrCreateStockQuadTree(resolution);
    // Sort values by their respective Z-Order values in linear time
    short[] sortedValues = new short[length];
    for (int i = 0; i < length; i++)
        sortedValues[i] = values[stockQuadTree.r[i]];

    // Write all sorted values
    for (short v : sortedValues)
        out.writeShort(v);

    // Compute aggregate values for all nodes in the tree
    // Go in reverse ID order to ensure children are computed before parents
    Node[] nodes = new Node[stockQuadTree.nodesID.length];
    for (int iNode = stockQuadTree.nodesID.length - 1; iNode >= 0; iNode--) {
        // Initialize all aggregate values
        nodes[iNode] = new Node();

        int firstChildId = stockQuadTree.nodesID[iNode] * 4;
        int firstChildPos = Arrays.binarySearch(stockQuadTree.nodesID, firstChildId);
        boolean isLeaf = firstChildPos < 0;

        if (isLeaf) {
            for (int iVal = stockQuadTree.nodesStartPosition[iNode]; iVal < stockQuadTree.nodesEndPosition[iNode]; iVal++) {
                short value;
                Object val = Array.get(sortedValues, iVal);
                if (val instanceof Short) {
                    value = (Short) val;
                } else {
                    throw new RuntimeException("Cannot handle values of type " + val.getClass());
                }
                if (value != fillValue)
                    nodes[iNode].accumulate(value);
            }
        } else {
            // Compute from the four children
            for (int iChild = 0; iChild < 4; iChild++) {
                int childPos = firstChildPos + iChild;
                nodes[iNode].accumulate(nodes[childPos]);
            }
        }
    }

    // Write nodes to file in sorted order
    for (int iNode = 0; iNode < nodes.length; iNode++)
        nodes[iNode].write(out);
}