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:com.valygard.aohruthless.command.CommandHandler.java

/**
 * Trims the first argument, which eventually becomes the command name.
 * //from w ww .java2s .c  o  m
 * @param args
 *            the arguments to trim.
 * @return the new String array.
 */
private String[] trimFirstArg(String[] args) {
    return Arrays.copyOfRange(args, 1, args.length);
}

From source file:cc.arduino.plugins.wifi101.flashers.java.NinaFlasher.java

@Override
public void uploadCertificates(String port, List<String> websites) throws Exception {
    FlasherSerialClient client = null;/*from w  ww. java  2s .c om*/
    try {
        file = openFirmwareFile();
        progress(10, "Connecting to programmer...");
        client = new FlasherSerialClient();
        client.open(port, this.baudrate);
        client.hello();
        int maxPayload = client.getMaximumPayload();
        int count = websites.size();
        String pem = "";

        for (String website : websites) {
            URL url;
            try {
                url = new URL(website);
            } catch (MalformedURLException e1) {
                url = new URL("https://" + website);
            }

            progress(30 + 20 * count / websites.size(), "Downloading certificate from " + website + "...");
            Certificate[] certificates = SSLCertDownloader.retrieveFromURL(url);

            // Pick the latest certificate (that should be the root cert)
            X509Certificate x509 = (X509Certificate) certificates[certificates.length - 1];
            pem = convertToPem(x509) + "\n" + pem;
        }

        byte[] pemArray = pem.getBytes();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        output.write(pemArray);
        while (output.size() % maxPayload != 0) {
            output.write(0);
        }
        byte[] fwData = output.toByteArray();

        int size = fwData.length;
        int address = 0x10000;
        int written = 0;

        if (size > 0x20000) {
            throw new Exception("Too many certificates!");
        }

        progress(20, "Erasing target...");

        client.eraseFlash(address, size);

        while (written < size) {
            progress(20 + written * 40 / size, "Programming " + size + " bytes ...");
            int len = maxPayload;
            if (written + len > size) {
                len = size - written;
            }
            client.writeFlash(address, Arrays.copyOfRange(fwData, written, written + len));
            written += len;
            address += len;
        }
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:org.zkoss.zk.grails.composer.GrailsComposer.java

@Override
public void doAfterCompose(Component comp) throws Exception {
    try {//ww  w.j  a  v  a2 s  .c om
        super.doAfterCompose(comp);
        this.root = comp;
        //
        // Issue #328 - check if the desktop is null to prevent NPE
        //
        // if(comp.getDesktop() == null) {
        //     this.params = new HashMap();
        // } else {
        //    this.params = (Map)(comp.getDesktop().removeAttribute("$JQ_REQUEST_PARAMS$"));
        // }
        // this should be working with Issue #328 as well
        Desktop desktop = Executions.getCurrent().getDesktop();
        if (desktop == null) {
            this.params = new HashMap();
        } else {
            this.params = (Map) desktop.removeAttribute("$JQ_REQUEST_PARAMS$");
        }

        if (this.params == null) {
            this.params = new HashMap();
        }

        injectComet();

        handleRoutingClosure(comp);

        // work only on <window/> component
        comp.addEventListener("onBookmarkChange", new org.zkoss.zk.ui.event.EventListener<Event>() {
            public void onEvent(Event event) throws Exception {
                BookmarkEvent be = (BookmarkEvent) event;
                String hashTag = be.getBookmark();
                if (hashTag.startsWith("!")) {
                    hashTag = hashTag.substring(1);
                }

                String[] parsedHashTag = hashTag.split("\\/");
                String[] args = Arrays.copyOfRange(parsedHashTag, 1, parsedHashTag.length);
                MetaClass mc = InvokerHelper.getMetaClass(GrailsComposer.this);
                if (mc.respondsTo(GrailsComposer.this, parsedHashTag[0]).size() > 0) {
                    InvokerHelper.invokeMethod(GrailsComposer.this, parsedHashTag[0], args);
                }

            }
        });

        handleAfterComposeClosure(comp);
        handleScaffold(comp);

        Selectors.wireVariables(comp, this, null);
        Selectors.wireEventListeners(comp, this);

        //
        // See JQuery#redirect()
        //
        // comp.getDesktop().setAttribute("$JQ_REQUESTING_COMPOSER$", GrailsComposer.this);
        if (InvokerHelper.getMetaClass(GrailsComposer.this).respondsTo(GrailsComposer.this, "index")
                .size() > 0) {
            InvokerHelper.invokeMethod(GrailsComposer.this, "index", new Object[] {});
            // comp.getDesktop().setAttribute("$JQ_REQUESTING_COMPOSER$", null);
        }

    } catch (Exception e) {
        // grails.util.GrailsUtil.printSanitizedStackTrace(e);
        throw e;
    }
}

From source file:morphy.timeseal.TimesealCoder.java

public static byte[][] splitBytes(byte[] bytes, byte splitByte) {
    byte[] bytesToProcess = bytes;

    ArrayList<Byte[]> bytesList = new ArrayList<Byte[]>();
    int idx;/*w w  w.  j  a  v  a2  s .  c om*/
    while ((idx = ArrayUtils.indexOf(bytesToProcess, splitByte)) != -1) {
        bytesList.add(ArrayUtils.toObject(Arrays.copyOfRange(bytesToProcess, 0, idx)));
        if (idx + 1 < bytesToProcess.length) {
            bytesToProcess = Arrays.copyOfRange(bytesToProcess, idx + 1, bytesToProcess.length);
        }
    }
    bytesList.add(ArrayUtils.toObject(bytesToProcess));

    byte[][] newBytes = new byte[bytesList.size()][];
    Byte[][] objBytesArray = bytesList.toArray(new Byte[bytesList.size()][0]);
    for (int i = 0; i < objBytesArray.length; i++) {
        newBytes[i] = ArrayUtils.toPrimitive(objBytesArray[i]);
    }
    return newBytes;
}

From source file:ca.appbox.monitoring.jmx.jmxbox.commons.context.parser.JmxContextParserImpl.java

private void addReadAttributeCommands(JmxContext context, CommandLine commandLine) throws JmxException {

    String[] readAttributeCommands = commandLine.getOptionValues(CommandLineOptions.READ_ATTRIBUTE);

    if (readAttributeCommands != null) {

        for (String readCommandParameter : Arrays.asList(readAttributeCommands)) {

            String[] splittedReadCommand = readCommandParameter.split(";");

            // Has to be at least mBean;attribute
            if (splittedReadCommand.length < 2) {
                throw new JmxException("MBean read attribute has to specify at least one attribute name.");
            } else {

                List<String> mBeanAttributes = Arrays
                        .asList(Arrays.copyOfRange(splittedReadCommand, 1, splittedReadCommand.length));

                for (String commandAttribute : mBeanAttributes) {
                    context.addCommand(/*from  ww w .ja v a 2s  . co m*/
                            new JmxReadAttributeCommandImpl(splittedReadCommand[0], commandAttribute));
                }
            }
        }
    }
}

From source file:morphy.timeseal.TimesealCoder.java

public TimesealParseResult decode(byte[] bytes) {
    byte[] key = timesealKey;
    byte[] tmp = ArrayUtils.clone(bytes);

    int n;// w ww.j  av a 2 s  .com
    byte offset;
    int l = tmp.length;
    if (l % 12 != 1) {
        // malformed?
        //System.out.println("malformed");
    }
    offset = tmp[l - 1];
    for (n = 0; n < l; n++) {
        // n+offset+0x80 differs slightly from original C version, it was previously n+offset-0x80
        // but since offset is -128, -128 - 0x80 (128) = -256, so it was not working properly.
        tmp[n] = (byte) ((tmp[n] + 32) ^ key[(n + offset + 0x80) % key.length]);
        if ((tmp[n] & 0x80) == 0) {
            // malformed?
            //System.out.println("malformed");
        }
        tmp[n] ^= 0x80;
    }

    for (n = 0; n + 11 < l; n += 12) {
        SC(tmp, n, n + 11);
        SC(tmp, n + 2, n + 9);
        SC(tmp, n + 4, n + 7);
    }

    for (n = 0; n < tmp.length; n++) {
        if ((tmp[n] >> 5) == 0) {
            // malformed?
            //System.out.println("malformed");
        }
    }

    // \x18 = \u0024
    // \x19 = \u0025
    int timeStartIdx = indexOfByte(tmp, (byte) 24);
    int timeEndIdx = indexOfByte(tmp, (byte) 25);

    String timestamp = new String(Arrays.copyOfRange(tmp, timeStartIdx + 1, timeEndIdx));
    String message = new String(Arrays.copyOfRange(tmp, 0, timeStartIdx));

    TimesealParseResult result = new TimesealParseResult(Long.parseLong(timestamp), message);
    return result;
}

From source file:org.powertac.logtool.common.DomainObjectReader.java

/**
 * Converts a line from the log to an object.
 * Each line is of the form<br>//w ww  .  j  av a2s .c o m
 * &nbsp;&nbsp;<code>ms:class::id::method{::arg}*</code>
 * 
 * Note that some objects cannot be resolved in the order they appear
 * in a logfile, because they have forward dependencies. This means
 * that a failure to resolve an object does not necessarily mean it's bogus,
 * but could mean that it could be resolved at a later time, typically
 * within one or a very few input lines. 
 * @throws MissingDomainObject 
 */
public Object readObject(String line) throws MissingDomainObject {
    log.debug("readObject(" + line + ")");
    String body = line.substring(line.indexOf(':') + 1);
    String[] tokens = body.split("::");
    Class<?> clazz;
    if (ignores.contains(tokens[0])) {
        //log.info("ignoring " + tokens[0]);
        return null;
    }
    try {
        clazz = Class.forName(tokens[0]);
    } catch (ClassNotFoundException e) {
        Class<?> subst = substitutes.get(tokens[0]);
        if (null == subst) {
            log.warn("class " + tokens[0] + " not found");
            return null;
        } else {
            clazz = subst;
            //log.info("substituting " + clazz.getName() + " for " + tokens[0]);
        }
    }

    long id = -1;
    try {
        id = Long.parseLong(tokens[1]);
    } catch (NumberFormatException nfe) {
        if (clazz == TimeService.class) {
            // normal case - timeService does not have an id
            updateTime(tokens[3]);
            return null;
        } else if (noIdTypes.contains(clazz)) {
            id = 0;
        } else {
            log.debug("Number format exception reading id");
            return null;
        }
    }
    String methodName = tokens[2];
    log.debug("methodName=" + methodName);
    if (methodName.equals("new")) {
        // constructor
        Object newInst = constructInstance(clazz, Arrays.copyOfRange(tokens, 3, tokens.length));
        if (null != newInst) {
            if (!noIdTypes.contains(clazz)) {
                setId(newInst, id);
                idMap.put(id, newInst);
            }
            log.debug("Created new instance " + id + " of class " + tokens[0]);
            fireNewObjectEvent(newInst);
        }
        return newInst;
    } else if (methodName.equals("-rr")) {
        // readResolve
        Object newInst = restoreInstance(clazz, Arrays.copyOfRange(tokens, 3, tokens.length));
        if (null != newInst) {
            setId(newInst, id);
            idMap.put(id, newInst);
            log.debug("Restored instance " + id + " of class " + tokens[0]);
            fireNewObjectEvent(newInst);
        }
        return newInst;
    } else {
        // other method calls -- object should already exist
        Object inst = idMap.get(id);
        if (null == inst) {
            log.warn("Cannot find instance for id " + id + " of type " + clazz.getCanonicalName());
            return null;
        }
        Method[] methods = clazz.getMethods();
        ArrayList<Method> candidates = new ArrayList<Method>();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                candidates.add(method);
            }
        }
        // We now have a list of candidate methods.
        if (0 == candidates.size()) {
            log.error("Cannot find method " + methodName + " for class " + clazz.getName());
            return null;
        }
        if (1 == candidates.size()) {
            // there's one candidate, probably it is the correct one
            if (!tryMethodCall(inst, candidates.get(0), Arrays.copyOfRange(tokens, 3, tokens.length))) {
                log.error("Failed to invoke method " + methodName + " on instance of " + clazz.getName());
            }
        } else {
            // multiple candidates -- try them until we get success
            boolean success = false;
            for (Method candidate : candidates) {
                success = tryMethodCall(inst, candidate, Arrays.copyOfRange(tokens, 3, tokens.length));
                if (success)
                    break;
            }
            if (!success) {
                log.error("Failed to find viable candidate for " + methodName + " on instance of "
                        + clazz.getName());
            }
        }
    }
    return null;
}

From source file:com.yahoo.egads.utilities.SpectralMethods.java

public static RealMatrix mFilter(RealMatrix data, int windowSize, FilteringMethod method,
        double methodParameter) {

    int n = data.getRowDimension();
    int m = data.getColumnDimension();
    int k = n - windowSize + 1;
    int i = 0, ind = 0;
    double[] temp;
    double sum = 0;

    RealMatrix hankelMat = SpectralMethods.createHankelMatrix(data, windowSize);
    SingularValueDecomposition svd = new SingularValueDecomposition(hankelMat);

    double[] singularValues = svd.getSingularValues();

    switch (method) {
    case VARIANCE:
        temp = new double[singularValues.length - 1];

        for (i = 1; i < singularValues.length; ++i) {
            sum += (singularValues[i] * singularValues[i]);
        }//from   w  w  w.  j a v  a 2  s .co  m

        for (i = 0; i < temp.length; ++i) {
            temp[i] = (singularValues[i + 1] * singularValues[i + 1]) / sum;
        }

        sum = 0;
        for (i = temp.length - 1; i >= 0; --i) {
            sum += temp[i];
            if (sum >= 1 - methodParameter) {
                ind = i;
                break;
            }
        }

        break;

    case EXPLICIT:
        ind = (int) Math.max(Math.min(methodParameter - 1, singularValues.length - 1), 0);
        break;

    case K_GAP:
        final double[] eigenGaps = new double[singularValues.length - 1];
        Integer[] index = new Integer[singularValues.length - 1];
        for (i = 0; i < eigenGaps.length; ++i) {
            eigenGaps[i] = singularValues[i] - singularValues[i + 1];
            index[i] = i;
        }

        Arrays.sort(index, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Double.compare(eigenGaps[o1], eigenGaps[o2]);
            }
        });

        int maxIndex = 0;
        for (i = index.length - (int) methodParameter; i < index.length; ++i) {
            if (index[i] > maxIndex) {
                maxIndex = index[i];
            }
        }

        ind = Math.min(maxIndex, singularValues.length / 3);
        break;

    case SMOOTHNESS:
        double[] variances = new double[singularValues.length];

        for (i = 1; i < singularValues.length; ++i) {
            variances[i] = (singularValues[i] * singularValues[i]);
        }
        variances[0] = variances[1];

        double smoothness = SpectralMethods
                .computeSmoothness(Arrays.copyOfRange(variances, 1, variances.length));

        if (methodParameter - smoothness < 0.01) {
            methodParameter += 0.01;
        }

        double invalidS = smoothness;
        int validIndex = 1, invalidIndex = singularValues.length;

        while (true) {
            if (invalidS >= methodParameter) {
                ind = invalidIndex - 1;
                break;
            } else if (invalidIndex - validIndex <= 1) {
                ind = validIndex - 1;
                break;
            }

            int ii = (validIndex + invalidIndex) / 2;

            double[] tempVariances = Arrays.copyOf(Arrays.copyOfRange(variances, 0, ii + 1),
                    singularValues.length);
            double s = SpectralMethods.computeSmoothness(tempVariances);

            if (s >= methodParameter) {
                validIndex = ii;
            } else {
                invalidIndex = ii;
                invalidS = s;
            }
        }

        break;

    case EIGEN_RATIO:
        int startIndex = 0, endIndex = singularValues.length - 1;

        if (singularValues[endIndex] / singularValues[0] >= methodParameter) {
            ind = endIndex;
        } else {
            while (true) {
                int midIndex = (startIndex + endIndex) / 2;
                if (singularValues[midIndex] / singularValues[0] >= methodParameter) {
                    if (singularValues[midIndex + 1] / singularValues[0] < methodParameter) {
                        ind = midIndex;
                        break;
                    } else {
                        startIndex = midIndex;
                    }
                } else {
                    endIndex = midIndex;
                }
            }
        }

        break;

    case GAP_RATIO:
        double[] gaps = new double[singularValues.length - 1];
        for (i = 0; i < gaps.length; ++i) {
            gaps[i] = singularValues[i] - singularValues[i + 1];
        }

        ind = 0;
        for (i = gaps.length - 1; i >= 0; --i) {
            if (gaps[i] / singularValues[0] >= methodParameter) {
                ind = i;
                break;
            }
        }

        break;

    default:
        ind = singularValues.length - 1;
        break;
    }

    ind = Math.max(0, Math.min(ind, singularValues.length - 1));
    RealMatrix truncatedHankelMatrix = MatrixUtils.createRealMatrix(k, m * windowSize);
    RealMatrix mU = svd.getU();
    RealMatrix mVT = svd.getVT();

    for (i = 0; i <= ind; ++i) {
        truncatedHankelMatrix = truncatedHankelMatrix
                .add(mU.getColumnMatrix(i).multiply(mVT.getRowMatrix(i)).scalarMultiply(singularValues[i]));
    }

    return SpectralMethods.averageHankelMatrix(truncatedHankelMatrix, windowSize);
}

From source file:com.palantir.atlasdb.ptobject.EncodingUtils.java

public static byte[] decodeSizedBytes(byte[] bytes, int offset) {
    int len = (int) decodeVarLong(bytes, offset);
    offset += sizeOfVarLong(len);//w  ww  .  ja v  a 2s .  com
    return Arrays.copyOfRange(bytes, offset, offset + len);
}

From source file:com.netflix.imfutility.ttmltostl.stl.StlTtiTest.java

@Test
public void testEbnBlocksForLongSubtitle() throws Exception {
    // prepare long subtitles, so that one subtitles is stored in two tti blocks
    TimedTextObject tto = StlTestUtil.buildTto("10:00:00:00", "10:00:05:00", StringUtils.rightPad("", 200, '1'), // in 2 tti
            "10:00:10:00", "10:01:10:00", StringUtils.rightPad("", 400, '2') // in 4 tti
    );/*  w  ww  . java 2 s. c  o m*/
    byte[][] stl = StlTestUtil.build(tto, StlTestUtil.getMetadataXml());
    byte[] tti = stl[1];

    // 1st subtitle 1st block
    int offset = 128; // zero subtitle;
    assertArrayEquals(new byte[] { 0x01, 0x00, // subtitle number - 1
            (byte) 0x00, // extension block - 1st
            0x00, // cumulative status - 00 (no cumulative)
            0x0a, 0x00, 0x00, 0x00, // code in: 10:00:00:00
            0x0a, 0x00, 0x05, 0x00, // code out: 10:00:05:00
            0x16 // vertical position
    }, Arrays.copyOfRange(tti, offset + 1, offset + 14));

    // 1st subtitle 2d block
    offset += 128;
    assertArrayEquals(new byte[] { 0x01, 0x00, // subtitle number - 1
            (byte) 0xff, // extension block - last
            0x00, // cumulative status - 00 (no cumulative)
            0x0a, 0x00, 0x00, 0x00, // code in: 10:00:00:00
            0x0a, 0x00, 0x05, 0x00, // code out: 10:00:05:00
            0x16 // vertical position
    }, Arrays.copyOfRange(tti, offset + 1, offset + 14));

    // 2d subtitle 1st block
    offset += 128;
    assertArrayEquals(new byte[] { 0x02, 0x00, // subtitle number - 2
            (byte) 0x00, // extension block - 1st
            0x00, // cumulative status - 00 (no cumulative)
            0x0a, 0x00, 0x0a, 0x00, // code in: 10:00:10:00
            0x0a, 0x01, 0x0a, 0x00, // code out: 10:01:10:00
            0x16 // vertical position
    }, Arrays.copyOfRange(tti, offset + 1, offset + 14));

    // 2d subtitle 2d block
    offset += 128;
    assertArrayEquals(new byte[] { 0x02, 0x00, // subtitle number - 2
            (byte) 0x01, // extension block - 2d
            0x00, // cumulative status - 00 (no cumulative)
            0x0a, 0x00, 0x0a, 0x00, // code in: 10:00:10:00
            0x0a, 0x01, 0x0a, 0x00, // code out: 10:01:10:00
            0x16 // vertical position
    }, Arrays.copyOfRange(tti, offset + 1, offset + 14));

    // 2d subtitle 3d block
    offset += 128;
    assertArrayEquals(new byte[] { 0x02, 0x00, // subtitle number - 2
            (byte) 0x02, // extension block - 3d
            0x00, // cumulative status - 00 (no cumulative)
            0x0a, 0x00, 0x0a, 0x00, // code in: 10:00:10:00
            0x0a, 0x01, 0x0a, 0x00, // code out: 10:01:10:00
            0x16 // vertical position
    }, Arrays.copyOfRange(tti, offset + 1, offset + 14));

    // 2d subtitle 4th block
    offset += 128;
    assertArrayEquals(new byte[] { 0x02, 0x00, // subtitle number - 2
            (byte) 0xff, // extension block - last
            0x00, // cumulative status - 00 (no cumulative)
            0x0a, 0x00, 0x0a, 0x00, // code in: 10:00:10:00
            0x0a, 0x01, 0x0a, 0x00, // code out: 10:01:10:00
            0x16 // vertical position
    }, Arrays.copyOfRange(tti, offset + 1, offset + 14));
}