Example usage for java.util Arrays copyOfRange

List of usage examples for java.util Arrays copyOfRange

Introduction

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

Prototype

public static boolean[] copyOfRange(boolean[] original, int from, int to) 

Source Link

Document

Copies the specified range of the specified array into a new array.

Usage

From source file:bb.mcmc.analysis.ConvergeStatUtils.java

protected static int[][][] create3WaysContingencyTable(boolean[] testres, int newDim) {

    final boolean[] b1 = Arrays.copyOfRange(testres, 0, newDim - 2);
    final boolean[] b2 = Arrays.copyOfRange(testres, 1, newDim - 1);
    final boolean[] b3 = Arrays.copyOfRange(testres, 2, newDim);

    final int table[][][] = new int[][][] { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } };

    for (int i = 0; i < b1.length; i++) {
        if (b1[i] && b2[i] && b3[i]) {
            table[1][1][1] += 1;/*w  ww.ja  v a  2  s.  co  m*/
        } else if (!b1[i] && b2[i] && b3[i]) {
            table[0][1][1] += 1;
        } else if (b1[i] && !b2[i] && b3[i]) {
            table[1][0][1] += 1;
        } else if (b1[i] && b2[i] && !b3[i]) {
            table[1][1][0] += 1;
        } else if (b1[i] && !b2[i] && !b3[i]) {
            table[1][0][0] += 1;
        } else if (!b1[i] && b2[i] && !b3[i]) {
            table[0][1][0] += 1;
        } else if (!b1[i] && !b2[i] && b3[i]) {
            table[0][0][1] += 1;
        } else if (!b1[i] && !b2[i] && !b3[i]) {
            table[0][0][0] += 1;
        }
    }

    return table;

}

From source file:com.metawiring.load.generator.GeneratorInstanceFactory.java

private Object[] parseGeneratorArgs(String generatorType) {
    String[] parts = generatorType.split(":");
    generatorArgs = Arrays.copyOfRange(parts, 1, parts.length);
    return generatorArgs;
}

From source file:gobblin.runtime.cli.CliEmbeddedGobblin.java

@Override
public void run(String[] args) {

    int startOptions = 1;

    Class<? extends EmbeddedGobblinCliFactory> factoryClass;
    String alias = "";
    if (args.length >= 2 && !args[1].startsWith("-")) {
        alias = args[1];//w w w.ja  va  2  s .  c o m
        startOptions = 2;
    }

    if (alias.equals(LIST_QUICK_APPS)) {
        listQuickApps();
        return;
    }

    EmbeddedGobblinCliFactory factory;
    if (!Strings.isNullOrEmpty(alias)) {
        try {
            ClassAliasResolver<EmbeddedGobblinCliFactory> resolver = new ClassAliasResolver<>(
                    EmbeddedGobblinCliFactory.class);
            factoryClass = resolver.resolveClass(alias);
            factory = factoryClass.newInstance();
        } catch (ReflectiveOperationException roe) {
            System.out.println("Error: Could not find job with alias " + alias);
            System.out.println("For a list of jobs available: \"gobblin run " + LIST_QUICK_APPS + "\"");
            return;
        }
    } else {
        factory = new EmbeddedGobblin.CliFactory();
    }

    Options options = new Options();
    options.addOption(HELP);
    options.addOption(USE_LOG);
    for (Option opt : factory.getOptions().getOptions()) {
        options.addOption(opt);
    }

    CommandLine cli;
    try {
        CommandLineParser parser = new DefaultParser();
        cli = parser.parse(options, Arrays.copyOfRange(args, startOptions, args.length));
    } catch (ParseException pe) {
        System.out.println("Command line parse exception: " + pe.getMessage());
        printUsage(alias, options, factory);
        return;
    }

    if (cli.hasOption(HELP.getOpt())) {
        printUsage(alias, options, factory);
        return;
    }

    EmbeddedGobblin embeddedGobblin;
    try {
        embeddedGobblin = factory.buildEmbeddedGobblin(cli);
    } catch (Exception exc) {
        if (cli.hasOption(USE_LOG.getOpt())) {
            log.error("Failed to instantiate " + EmbeddedGobblin.class.getName(), exc);
        } else {
            System.out.println("Error: " + exc.getMessage());
        }
        printUsage(alias, options, factory);
        return;
    }

    try {
        embeddedGobblin.run();
    } catch (InterruptedException | TimeoutException | ExecutionException exc) {
        throw new RuntimeException("Failed to run Gobblin job.", exc);
    }
}

From source file:com.serotonin.modbus4j.ip.tcp.TcpMaster.java

@Override
synchronized public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException {
    try {//from  ww  w  . j av  a2s  .  c  om
        // Check if we need to open the connection.
        if (!keepAlive)
            openConnection();

        if (conn == null) {
            LOG.debug("Connection null: " + ipParameters.getPort());
        }

    } catch (Exception e) {
        closeConnection();
        throw new ModbusTransportException(e, request.getSlaveId());
    }

    // Wrap the modbus request in a ip request.
    OutgoingRequestMessage ipRequest;
    if (ipParameters.isEncapsulated())
        ipRequest = new EncapMessageRequest(request);
    else
        ipRequest = new XaMessageRequest(request, getNextTransactionId());

    if (LOG.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder();
        for (byte b : Arrays.copyOfRange(ipRequest.getMessageData(), 0, ipRequest.getMessageData().length)) {
            sb.append(String.format("%02X ", b));
        }
        LOG.debug("Encap Request: " + sb.toString());
    }

    // Send the request to get the response.
    IpMessageResponse ipResponse;
    LOG.debug("Sending on port: " + ipParameters.getPort());
    try {
        if (conn == null) {
            LOG.debug("Connection null: " + ipParameters.getPort());
        }
        ipResponse = (IpMessageResponse) conn.send(ipRequest);
        if (ipResponse == null)
            return null;

        if (LOG.isDebugEnabled()) {
            StringBuilder sb = new StringBuilder();
            for (byte b : Arrays.copyOfRange(ipResponse.getMessageData(), 0,
                    ipResponse.getMessageData().length)) {
                sb.append(String.format("%02X ", b));
            }
            LOG.debug("Response: " + sb.toString());
        }
        return ipResponse.getModbusResponse();
    } catch (Exception e) {
        LOG.debug("Exception: " + e.getMessage() + " " + e.getLocalizedMessage());
        if (keepAlive) {
            LOG.debug("KeepAlive - reconnect!");
            // The connection may have been reset, so try to reopen it and attempt the message again.
            try {
                LOG.debug("Modbus4J: Keep-alive connection may have been reset. Attempting to re-open.");
                openConnection();
                ipResponse = (IpMessageResponse) conn.send(ipRequest);
                if (ipResponse == null)
                    return null;
                if (LOG.isDebugEnabled()) {
                    StringBuilder sb = new StringBuilder();
                    for (byte b : Arrays.copyOfRange(ipResponse.getMessageData(), 0,
                            ipResponse.getMessageData().length)) {
                        sb.append(String.format("%02X ", b));
                    }
                    LOG.debug("Response: " + sb.toString());
                }
                return ipResponse.getModbusResponse();
            } catch (Exception e2) {
                LOG.debug("Exception: " + e2.getMessage() + " " + e2.getLocalizedMessage());
                throw new ModbusTransportException(e2, request.getSlaveId());
            }
        }

        throw new ModbusTransportException(e, request.getSlaveId());
    } finally {
        // Check if we should close the connection.
        if (!keepAlive)
            closeConnection();
    }
}

From source file:com.blockwithme.longdb.leveldb.Util.java

/** Split row.
 * //from  w w  w. j a  va 2  s  .  co  m
 * @param theRowColumnPair
 *        the combined row and column pair
 * @return the long row ID */
public static long splitRow(final byte[] theRowColumnPair) {
    return toLong(Arrays.copyOfRange(theRowColumnPair, 0, LONG_BYTES));
}

From source file:com.digitalpebble.storm.crawler.bolt.SiteMapParserBolt.java

@Override
public void execute(Tuple tuple) {
    Metadata metadata = (Metadata) tuple.getValueByField("metadata");

    // TODO check that we have the right number of fields?
    byte[] content = tuple.getBinaryByField("content");
    String url = tuple.getStringByField("url");

    String isSitemap = metadata.getFirstValue(isSitemapKey);
    // doesn't have the metadata expected
    if (!Boolean.valueOf(isSitemap)) {
        int found = -1;

        if (sniffWhenNoSMKey) {
            // try based on the first bytes?
            // works for XML and non-compressed documents
            byte[] clue = "http://www.sitemaps.org/schemas/sitemap/0.9".getBytes();
            byte[] beginning = content;
            final int maxOffsetGuess = 200;
            if (content.length > maxOffsetGuess) {
                beginning = Arrays.copyOfRange(content, 0, maxOffsetGuess);
            }// w  w  w. j  a v a 2 s  . c om
            found = Bytes.indexOf(beginning, clue);
            if (found != -1) {
                LOG.info("{} detected as sitemap based on content", url);
            }
        }

        // not a sitemap file
        if (found == -1) {
            // just pass it on
            this.collector.emit(tuple, tuple.getValues());
            this.collector.ack(tuple);
            return;
        }
    }

    // it is a sitemap
    String ct = metadata.getFirstValue(HttpHeaders.CONTENT_TYPE);

    List<Outlink> outlinks = Collections.emptyList();
    try {
        outlinks = parseSiteMap(url, content, ct, metadata);
    } catch (Exception e) {
        // exception while parsing the sitemap
        String errorMessage = "Exception while parsing " + url + ": " + e;
        LOG.error(errorMessage);
        // send to status stream in case another component wants to update
        // its status
        metadata.setValue(Constants.STATUS_ERROR_SOURCE, "sitemap parsing");
        metadata.setValue(Constants.STATUS_ERROR_MESSAGE, errorMessage);
        collector.emit(Constants.StatusStreamName, tuple, new Values(url, metadata, Status.ERROR));
        this.collector.ack(tuple);
        return;
    }

    // apply the parse filters if any to the current document
    try {
        ParseResult parse = new ParseResult();
        parse.setOutlinks(outlinks);
        ParseData parseData = parse.get(url);
        parseData.setMetadata(metadata);

        parseFilters.filter(url, content, null, parse);
    } catch (RuntimeException e) {
        String errorMessage = "Exception while running parse filters on " + url + ": " + e;
        LOG.error(errorMessage);
        metadata.setValue(Constants.STATUS_ERROR_SOURCE, "content filtering");
        metadata.setValue(Constants.STATUS_ERROR_MESSAGE, errorMessage);
        collector.emit(StatusStreamName, tuple, new Values(url, metadata, Status.ERROR));
        collector.ack(tuple);
        return;
    }

    // send to status stream
    for (Outlink ol : outlinks) {
        Values v = new Values(ol.getTargetURL(), ol.getMetadata(), Status.DISCOVERED);
        collector.emit(Constants.StatusStreamName, tuple, v);
    }

    // marking the main URL as successfully fetched
    // regardless of whether we got a parse exception or not
    collector.emit(Constants.StatusStreamName, tuple, new Values(url, metadata, Status.FETCHED));
    this.collector.ack(tuple);
}

From source file:io.mycat.util.ByteBufferUtil.java

/**
 * You should almost never use this.  Instead, use the write* methods to avoid copies.
 *//*w  ww  .j  a v  a  2  s. c  om*/
public static byte[] getArray(ByteBuffer buffer) {
    int length = buffer.remaining();

    if (buffer.hasArray()) {
        int boff = buffer.arrayOffset() + buffer.position();
        return Arrays.copyOfRange(buffer.array(), boff, boff + length);
    }
    // else, DirectByteBuffer.get() is the fastest route
    byte[] bytes = new byte[length];
    buffer.duplicate().get(bytes);

    return bytes;
}

From source file:edu.iu.daal_subgraph.Graph.java

/**
 * @brief get adj array from relative v id
 *
 * @param v/*from w  ww  .jav a 2 s . c  o m*/
 *
 * @return 
 */
int[] adjacent_vertices(int v) {
    //return (&adjacency_array[degree_list[v]]);
    //this doesn't return original array.
    //Be aware of the difference
    return Arrays.copyOfRange(adjacency_array, degree_list[v], degree_list[v + 1]);

}

From source file:au.org.ala.delta.translation.TypeSetterTest.java

public void testLineWrapWithSpaceAtWrapPosition() {
    char[] input = new char[_lineWidth * 2];
    Arrays.fill(input, 'a');
    input[_lineWidth - 1] = ' ';

    _typeSetter.writeJustifiedText(new String(input), -1);
    _typeSetter.printBufferLine(false);//  w w  w  .  ja v  a  2 s .  com

    String[] lines = output().split(SystemUtils.LINE_SEPARATOR);
    char[] expectedLine1Chars = Arrays.copyOfRange(input, 0, _lineWidth - 1);
    char[] expectedLine2Chars = Arrays.copyOfRange(input, _lineWidth, input.length);

    String expectedLine1 = new String(expectedLine1Chars);
    String expectedLine2 = new String(expectedLine2Chars);
    assertEquals(expectedLine1, lines[0]);
    assertEquals(expectedLine2, lines[1]);

    // Now do it again as two separate writes
    _typeSetter.writeJustifiedText(expectedLine1, -1);
    _typeSetter.writeJustifiedText(expectedLine2, -1);
    _typeSetter.printBufferLine(false);

    lines = output().split(SystemUtils.LINE_SEPARATOR);
    assertEquals(expectedLine1, lines[0]);
    assertEquals(expectedLine2, lines[1]);
}

From source file:com.digitalpebble.stormcrawler.bolt.SiteMapParserBolt.java

@Override
public void execute(Tuple tuple) {
    Metadata metadata = (Metadata) tuple.getValueByField("metadata");

    // TODO check that we have the right number of fields?
    byte[] content = tuple.getBinaryByField("content");
    String url = tuple.getStringByField("url");

    String isSitemap = metadata.getFirstValue(isSitemapKey);
    // doesn't have the metadata expected
    if (!Boolean.valueOf(isSitemap)) {
        int found = -1;

        if (sniffWhenNoSMKey) {
            // try based on the first bytes?
            // works for XML and non-compressed documents
            byte[] clue = "http://www.sitemaps.org/schemas/sitemap/0.9".getBytes();
            byte[] beginning = content;
            final int maxOffsetGuess = 200;
            if (content.length > maxOffsetGuess) {
                beginning = Arrays.copyOfRange(content, 0, maxOffsetGuess);
            }//from ww  w  .  j a  v  a2 s.c o m
            found = Bytes.indexOf(beginning, clue);
            if (found != -1) {
                LOG.info("{} detected as sitemap based on content", url);
            }
        }

        // not a sitemap file
        if (found == -1) {
            // just pass it on
            this.collector.emit(tuple, tuple.getValues());
            this.collector.ack(tuple);
            return;
        }
    }

    // it is a sitemap
    String ct = metadata.getFirstValue(HttpHeaders.CONTENT_TYPE);

    List<Outlink> outlinks;
    try {
        outlinks = parseSiteMap(url, content, ct, metadata);
    } catch (Exception e) {
        // exception while parsing the sitemap
        String errorMessage = "Exception while parsing " + url + ": " + e;
        LOG.error(errorMessage);
        // send to status stream in case another component wants to update
        // its status
        metadata.setValue(Constants.STATUS_ERROR_SOURCE, "sitemap parsing");
        metadata.setValue(Constants.STATUS_ERROR_MESSAGE, errorMessage);
        collector.emit(Constants.StatusStreamName, tuple, new Values(url, metadata, Status.ERROR));
        this.collector.ack(tuple);
        return;
    }

    // apply the parse filters if any to the current document
    try {
        ParseResult parse = new ParseResult();
        parse.setOutlinks(outlinks);
        ParseData parseData = parse.get(url);
        parseData.setMetadata(metadata);

        parseFilters.filter(url, content, null, parse);
    } catch (RuntimeException e) {
        String errorMessage = "Exception while running parse filters on " + url + ": " + e;
        LOG.error(errorMessage);
        metadata.setValue(Constants.STATUS_ERROR_SOURCE, "content filtering");
        metadata.setValue(Constants.STATUS_ERROR_MESSAGE, errorMessage);
        collector.emit(StatusStreamName, tuple, new Values(url, metadata, Status.ERROR));
        collector.ack(tuple);
        return;
    }

    // send to status stream
    for (Outlink ol : outlinks) {
        Values v = new Values(ol.getTargetURL(), ol.getMetadata(), Status.DISCOVERED);
        collector.emit(Constants.StatusStreamName, tuple, v);
    }

    // marking the main URL as successfully fetched
    // regardless of whether we got a parse exception or not
    collector.emit(Constants.StatusStreamName, tuple, new Values(url, metadata, Status.FETCHED));
    this.collector.ack(tuple);
}