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:org.apache.james.jdkim.tagvalue.SignatureRecordImpl.java

public static String dkimQuotedPrintableDecode(CharSequence input) throws IllegalArgumentException {
    StringBuilder sb = new StringBuilder(input.length());
    // TODO should we fail on WSP that is not part of FWS?
    // the specification in 2.6 DKIM-Quoted-Printable is not
    // clear//from  www.  j  a va  2s. c om
    int state = 0;
    int start = 0;
    int d = 0;
    boolean lastWasNL = false;
    for (int i = 0; i < input.length(); i++) {
        if (lastWasNL && input.charAt(i) != ' ' && input.charAt(i) != '\t') {
            throw new IllegalArgumentException("Unexpected LF not part of an FWS");
        }
        lastWasNL = false;
        switch (state) {
        case 0:
            switch (input.charAt(i)) {
            case ' ':
            case '\t':
            case '\r':
            case '\n':
                if ('\n' == input.charAt(i))
                    lastWasNL = true;
                sb.append(input.subSequence(start, i));
                start = i + 1;
                // ignoring whitespace by now.
                break;
            case '=':
                sb.append(input.subSequence(start, i));
                state = 1;
                break;
            }
            break;
        case 1:
        case 2:
            if (input.charAt(i) >= '0' && input.charAt(i) <= '9'
                    || input.charAt(i) >= 'A' && input.charAt(i) <= 'F') {
                int v = Arrays.binarySearch("0123456789ABCDEF".getBytes(), (byte) input.charAt(i));
                if (state == 1) {
                    state = 2;
                    d = v;
                } else {
                    d = d * 16 + v;
                    sb.append((char) d);
                    state = 0;
                    start = i + 1;
                }
            } else {
                throw new IllegalArgumentException("Invalid input sequence at " + i);
            }
        }
    }
    if (state != 0) {
        throw new IllegalArgumentException("Invalid quoted printable termination");
    }
    sb.append(input.subSequence(start, input.length()));
    return sb.toString();
}

From source file:master.utilities.PopulationFunctionFromJSON.java

@Override
public double getIntensity(double t) {

    double tforward = convertTime(t);

    if (tforward > times[times.length - 1]) {
        if (popSizeEndInput.get() > 0.0) {
            return intensities[times.length - 1] + (times[times.length - 1] - tforward) / popSizeEndInput.get();
        } else/* w w  w  .ja  v a 2s  . c om*/
            return Double.NEGATIVE_INFINITY;
    }

    if (tforward < 0.0) {
        if (popSizeStartInput.get() > 0.0) {
            return intensities[0] + (-tforward) / popSizeStartInput.get();
        } else
            return Double.POSITIVE_INFINITY;
    }

    int tidx = Arrays.binarySearch(times, tforward);
    if (tidx < 0) {
        tidx = -(tidx + 1); // index of first element greater than key

        // Integrate from different sides depending on location wrt peakIdx
        if (tidx <= peakIdx) {
            return (times[tidx] - tforward) / (popSizes[tidx - 1]) + intensities[tidx];
        } else {
            return intensities[tidx - 1] - (tforward - times[tidx - 1]) / popSizes[tidx - 1];
        }
    } else
        return intensities[tidx]; // Exact match can happen at boundaries.

}

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

License:asdf

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

    assertEquals(2, movies.size());/*w  w  w  .  ja va  2  s.c o  m*/

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

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

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

/**
 * The discount factor or survival probability
 * @param t Time//www.jav a  2s .c o  m
 * @return value
 */
public double getDiscountFactor(final double t) {
    ArgumentChecker.isTrue(t >= 0, "require t >= 0.0");
    if (t == 0.0) {
        return 1.0;
    }
    final int index = Arrays.binarySearch(_t, t);
    if (index >= 0) {
        return _df[index];
    }

    final int insertionPoint = -(1 + index);
    final double rt = getRT(t, insertionPoint);
    return Math.exp(-rt);
}

From source file:net.sf.taverna.t2.activities.wsdl.xmlsplitter.XMLSplitterConfigurationBeanBuilder.java

public static JsonNode buildBeanForOutput(Element element) throws JDOMException, IOException {
    ObjectNode bean = JSON_NODE_FACTORY.objectNode();
    ArrayNode inputDefinitions = bean.arrayNode();
    bean.put("inputPorts", inputDefinitions);
    ArrayNode outputDefinitions = bean.arrayNode();
    bean.put("outputPorts", outputDefinitions);

    TypeDescriptor descriptor = XMLSplitterSerialisationHelper.extensionXMLToTypeDescriptor(element);

    ObjectNode inBean = inputDefinitions.addObject();
    inBean.put("name", "input");
    inBean.put("mimeType", "'text/xml'");
    inBean.put("depth", 0);

    if (descriptor instanceof ComplexTypeDescriptor) {
        List<TypeDescriptor> elements = ((ComplexTypeDescriptor) descriptor).getElements();
        String[] names = new String[elements.size()];
        Class<?>[] types = new Class<?>[elements.size()];
        TypeDescriptor.retrieveSignature(elements, names, types);
        for (int i = 0; i < names.length; i++) {
            ObjectNode portBean = outputDefinitions.addObject();
            portBean.put("name", names[i]);
            portBean.put("mimeType", TypeDescriptor.translateJavaType(types[i]));
            int depth = depthForDescriptor(elements.get(i));
            portBean.put("depth", depth);
            portBean.put("granularDepth", depth);
        }/*from   w  w  w .ja v  a 2  s.co  m*/

        List<TypeDescriptor> attributes = ((ComplexTypeDescriptor) descriptor).getAttributes();
        String[] elementNames = Arrays.copyOf(names, names.length);
        Arrays.sort(elementNames);
        String[] attributeNames = new String[attributes.size()];
        Class<?>[] attributeTypes = new Class<?>[attributes.size()];
        TypeDescriptor.retrieveSignature(attributes, attributeNames, attributeTypes);
        for (int i = 0; i < attributeNames.length; i++) {
            ObjectNode portBean = outputDefinitions.addObject();
            if (Arrays.binarySearch(elementNames, attributeNames[i]) < 0) {
                portBean.put("name", attributeNames[i]);
            } else {
                portBean.put("name", "1" + attributeNames[i]);
            }
            portBean.put("mimeType", TypeDescriptor.translateJavaType(attributeTypes[i]));
            int depth = depthForDescriptor(attributes.get(i));
            portBean.put("depth", depth);
            portBean.put("granularDepth", depth);
        }

    } else if (descriptor instanceof ArrayTypeDescriptor) {
        ObjectNode portBean = outputDefinitions.addObject();
        String name = descriptor.getName();
        portBean.put("name", name);
        portBean.put("depth", 1);
        portBean.put("granularDepth", 1);
        if (((ArrayTypeDescriptor) descriptor).getElementType() instanceof BaseTypeDescriptor) {
            portBean.put("mimeType", "l('text/plain')");
        } else {
            portBean.put("mimeType", "l('text/xml')");
        }
    }

    String wrappedType = new XMLOutputter().outputString(element);
    bean.put("wrappedType", wrappedType);

    return bean;
}

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

@Test
public void testListTables() throws IOException {
    SqoopOptions options = new SqoopOptions(new Configuration());
    options.setConnectString(CubridTestUtils.getConnectString());
    options.setUsername(CubridTestUtils.getCurrentUser());
    options.setPassword(CubridTestUtils.getPassword());

    ConnManager mgr = new CubridManager(options);
    String[] tables = mgr.listTables();
    Arrays.sort(tables);/*  www  . ja  va2 s  .c o m*/
    assertTrue(TABLE_NAME + " is not found!", Arrays.binarySearch(tables, TABLE_NAME) >= 0);
}

From source file:OogieDocumentConverter.java

protected void loadAndExport(String inputUrl, Map/*<String,Object>*/ loadProperties, String outputUrl,
        Map/*<String,Object>*/ storeProperties) throws Exception {
    XComponentLoader desktop = openOfficeConnection.getDesktop();
    XComponent document = desktop.loadComponentFromURL(inputUrl, "_blank", 0, toPropertyValues(loadProperties));
    if (document == null) {
        throw new OpenOfficeException("conversion failed: input document is null after loading");
    }//from  ww  w . ja v a2  s.co m

    refreshDocument(document);

    try {

        outputUrl = FilenameUtils.getFullPath(outputUrl) + FilenameUtils.getBaseName(outputUrl);

        //          filter
        PropertyValue[] loadProps = new PropertyValue[4];

        // type of image
        loadProps[0] = new PropertyValue();
        loadProps[0].Name = "MediaType";
        loadProps[0].Value = "image/png";

        // Height and width
        PropertyValue[] filterDatas = new PropertyValue[4];
        for (int i = 0; i < 4; i++) {
            filterDatas[i] = new PropertyValue();
        }

        filterDatas[0].Name = "PixelWidth";
        filterDatas[0].Value = new Integer(this.width);
        filterDatas[1].Name = "PixelHeight";
        filterDatas[1].Value = new Integer(this.height);
        filterDatas[2].Name = "LogicalWidth";

        filterDatas[2].Value = new Integer(2000);
        filterDatas[3].Name = "LogicalHeight";
        filterDatas[3].Value = new Integer(2000);

        XDrawPagesSupplier pagesSupplier = (XDrawPagesSupplier) UnoRuntime
                .queryInterface(XDrawPagesSupplier.class, document);
        //System.out.println(pagesSupplier.toString());            
        XDrawPages pages = pagesSupplier.getDrawPages();
        int nbPages = pages.getCount();
        String[] slidenames = new String[nbPages];
        Arrays.fill(slidenames, "");

        for (int i = 0; i < nbPages; i++) {

            XDrawPage page = (XDrawPage) UnoRuntime.queryInterface(com.sun.star.drawing.XDrawPage.class,
                    pages.getByIndex(i));
            XShapes xShapes = (XShapes) UnoRuntime.queryInterface(XShapes.class, page);
            int top = 0;
            String slidename = "";
            for (int j = 0; j < xShapes.getCount(); j++) {
                XShape firstXshape = (XShape) UnoRuntime.queryInterface(XShape.class, xShapes.getByIndex(j));
                Point pos = firstXshape.getPosition();
                if (pos.Y < top || top == 0) {
                    XText xText = (XText) UnoRuntime.queryInterface(XText.class, firstXshape);
                    if (xText != null && xText.getString().length() > 0) {
                        top = pos.Y;
                        slidename = xText.getString();
                    }
                }
            }

            String slidenameDisplayed = "";
            if (slidename.trim().length() == 0) {
                slidename = "slide" + (i + 1);
            } else {
                int nbSpaces = 0;
                String formatedSlidename = "";
                slidename = slidename.replaceAll(" ", "_");
                slidename = slidename.replaceAll("\n", "_");
                slidename = slidename.replaceAll("__", "_");

                for (int j = 0; j < slidename.length(); j++) {
                    char currentChar = slidename.charAt(j);
                    if (currentChar == '_') {
                        nbSpaces++;
                    }
                    if (nbSpaces == 5) {
                        break;
                    }
                    formatedSlidename += slidename.charAt(j);
                }

                slidenameDisplayed = formatedSlidename;

                slidename = formatedSlidename.toLowerCase();
                slidename = slidename.replaceAll("\\W", "_");
                slidename = slidename.replaceAll("__", "_");
                slidename = StringOperation.sansAccent(slidename);

            }
            int j = 1;
            String slidenamebackup = slidename;
            Arrays.sort(slidenames);
            while (Arrays.binarySearch(slidenames, slidename) >= 0) {
                j++;
                slidename = slidenamebackup + j;
            }
            slidenames[nbPages - (i + 1)] = slidename;

            XNamed xPageName = (XNamed) UnoRuntime.queryInterface(XNamed.class, page);

            xPageName.setName(slidename);

            XMultiComponentFactory localServiceManager = ((DokeosSocketOfficeConnection) this.openOfficeConnection)
                    .getServiceManager();
            Object GraphicExportFilter = localServiceManager.createInstanceWithContext(
                    "com.sun.star.drawing.GraphicExportFilter",
                    ((DokeosSocketOfficeConnection) this.openOfficeConnection).getComponentContext());

            XExporter xExporter = (XExporter) UnoRuntime.queryInterface(XExporter.class, GraphicExportFilter);

            XComponent xComp = (XComponent) UnoRuntime.queryInterface(XComponent.class, page);

            xExporter.setSourceDocument(xComp);
            loadProps[1] = new PropertyValue();
            loadProps[1].Name = "URL";

            loadProps[1].Value = outputUrl + "/" + xPageName.getName() + ".png";
            loadProps[2] = new PropertyValue();
            loadProps[2].Name = "FilterData";
            loadProps[2].Value = filterDatas;
            loadProps[3] = new PropertyValue();
            loadProps[3].Name = "Quality";
            loadProps[3].Value = new Integer(100);

            XFilter xFilter = (XFilter) UnoRuntime.queryInterface(XFilter.class, GraphicExportFilter);

            xFilter.filter(loadProps);
            if (slidenameDisplayed == "")
                slidenameDisplayed = xPageName.getName();
            System.out.println(slidenameDisplayed + "||" + xPageName.getName() + ".png");

        }

    } finally {
        document.dispose();
    }
}

From source file:CharMap.java

/**
 * Adds the mapping from the provided key to the value.
 *
 * @param key/*  w  w  w  .j  av a  2 s .c o  m*/
 * @param value
 *
 * @throws NullPointerException if the key is {@code null}
 * @throws IllegalArgumentException if the key is not an instance of {@link
 *         Integer}
 */
@SuppressWarnings("unchecked")
public V put(char key, V value) {
    char k = key;
    int index = Arrays.binarySearch(keyIndices, k);

    if (index >= 0) {
        V old = (V) (values[index]);
        values[index] = value;
        return old;
    } else {
        int newIndex = 0 - (index + 1);
        Object[] newValues = Arrays.copyOf(values, values.length + 1);
        char[] newIndices = Arrays.copyOf(keyIndices, values.length + 1);

        // shift the elements down to make room for the new value
        for (int i = newIndex; i < values.length; ++i) {
            newValues[i + 1] = values[i];
            newIndices[i + 1] = keyIndices[i];
        }

        // insert the new value
        newValues[newIndex] = value;
        newIndices[newIndex] = k;

        // switch the arrays with the lengthed versions
        values = newValues;
        keyIndices = newIndices;

        return null;
    }
}

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

public double getDataPointFast(final int time) {
    final int index = Arrays.binarySearch(_times, time);
    if (index >= 0) {
        return _values[index];
    } else {//from w  w w  . j  a va  2  s.  com
        throw new NoSuchElementException();
    }
}

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

License:asdf

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

    assertEquals(1, movies.size());// w  ww .j  a va2  s.  c  om

    String[] moviesCategory4 = { "Movie 2" };

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