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:ditl.cli.DeleteTraces.java

@Override
protected void parseArgs(CommandLine cli, String[] args) throws ParseException, HelpException {
    store_file = new File(args[0]);
    traceNames = Arrays.copyOfRange(args, 1, args.length);
}

From source file:com.titankingdoms.dev.titanchat.command.defaults.KickCommand.java

@Override
public void execute(CommandSender sender, Channel channel, String[] args) {
    Participant participant = plugin.getParticipantManager().getParticipant(args[0]);

    if (!channel.isLinked(plugin.getParticipantManager().getParticipant(sender))) {
        sendMessage(sender, participant.getDisplayName() + " &4is not on the channel");
        return;/*from  w  w  w.  j a va  2 s. c om*/
    }

    String reason = StringUtils.join(Arrays.copyOfRange(args, 1, args.length));

    channel.unlink(participant);
    participant.notice("&4You have been kicked from " + channel.getName() + ": " + reason);

    if (!channel.isLinked(plugin.getParticipantManager().getParticipant(sender)))
        sendMessage(sender, participant.getDisplayName() + " &6has been kicked");

    channel.notice(participant.getDisplayName() + " &6has been kicked");
}

From source file:com.github.cbismuth.random.FastRandom.java

/**
 * Extracts random values from a source array the noob way:
 * remove unwanted elements from source array with a split & join.
 *
 * @param src the source array//  w  ww.  j  a  v  a2 s.co m
 * @param p the length of the random array to return
 * @param <T> the type of elements from the source array
 *
 * @return an array with random elements from the source array without duplicates
 *
 * @throws IllegalAccessException if p == 0 or p > src.length
 */
public static <T> T[] noobRandomOfLength(T[] src, final int p) throws IllegalAccessException {
    checkPreconditions(src, p);

    @SuppressWarnings("unchecked")
    final T[] dest = (T[]) new Object[p];
    int indexOfCurrentDestValueToSet = 0;

    // while destination array is not filled
    while (indexOfCurrentDestValueToSet != p && src.length > 0) {
        final int pickedIndex = convertRandomValueToIndex(src);

        final T pickedElement = src[pickedIndex];

        final boolean isDuplicate = isDuplicate_withoutHash(dest, indexOfCurrentDestValueToSet, pickedElement);

        // add to destination array if not a duplicate
        if (!isDuplicate) {
            dest[indexOfCurrentDestValueToSet] = pickedElement;
            indexOfCurrentDestValueToSet++;
        }

        // NOOB part - remove processed element from source element with a split & join
        final T[] left = Arrays.copyOfRange(src, 0, pickedIndex);
        final T[] right = Arrays.copyOfRange(src, pickedIndex + 1, src.length);
        src = ArrayUtils.addAll(left, right);
    }

    if (indexOfCurrentDestValueToSet != p) {
        throw new TooMuchDuplicatesException("Not enough distinct values in source array!");
    }

    return dest;
}

From source file:ditl.cli.CopyTraces.java

@Override
protected void parseArgs(CommandLine cli, String[] args) throws ParseException, HelpException {
    inStoreFile = new File(args[0]);
    outStoreFile = new File(args[1]);
    traceNames = Arrays.copyOfRange(args, 2, args.length);
    if (traceNames.length == 0)
        throw new HelpException();
}

From source file:com.hviper.codec.uodecode.PeakSignalNoiseRatioTest.java

private double computePsnrPcm16(String uoResource, String referenceResource) throws Exception {
    // Read the UO file and the reference encoder's decode output into byte arrays
    byte uoFile[] = IOUtils.toByteArray(this.getClass().getResourceAsStream(uoResource));
    byte referenceWavFile[] = IOUtils.toByteArray(this.getClass().getResourceAsStream(referenceResource));

    // Decode the UO file ourselves into a byte array
    ByteArrayOutputStream decodedWavOutputStream = new ByteArrayOutputStream(referenceWavFile.length);
    UODecode.uoToPcm16Wav(uoFile, decodedWavOutputStream);
    byte decodedWavFile[] = decodedWavOutputStream.toByteArray();

    // Find the start of the sample data; this will be after a 'data' header and four bytes of
    // content length.
    int dataStart = -1;
    for (int i = 0; i < decodedWavFile.length - 4; ++i) {
        if ((decodedWavFile[i] == 'd') && (decodedWavFile[i + 1] == 'a') && (decodedWavFile[i + 2] == 't')
                && (decodedWavFile[i + 3] == 'a')) {
            dataStart = i + 8; // 8 = length of header + chunk length
            break;
        }//w w w. ja v  a2 s  .c  om
    }
    assertFalse("No 'data' header in decoded output", dataStart < 0);

    // Headers must be equal. Compare as hex strings for better assert failures here.
    String refHeaders = DatatypeConverter.printHexBinary(Arrays.copyOfRange(referenceWavFile, 0, dataStart));
    String ourHeaders = DatatypeConverter.printHexBinary(Arrays.copyOfRange(decodedWavFile, 0, dataStart));
    assertEquals("WAV headers do not match", refHeaders, ourHeaders);
    assertEquals("File lengths do not match", referenceWavFile.length, decodedWavFile.length);

    // Compute total squared error
    int cursor = dataStart;
    long totalSqError = 0;
    int sampleCount = 0;
    int worstSoFar = 0;
    for (; (cursor + 1) < referenceWavFile.length; cursor += 2) {
        short refSample = (short) ((referenceWavFile[cursor] & 0xff)
                | ((referenceWavFile[cursor + 1] & 0xff) << 8));
        short ourSample = (short) ((decodedWavFile[cursor] & 0xff)
                | ((decodedWavFile[cursor + 1] & 0xff) << 8));
        int absDiff = Math.abs(ourSample - refSample);

        long sqError = ((long) absDiff) * ((long) absDiff);
        totalSqError += sqError;
        ++sampleCount;
    }
    assertNotEquals("No samples read!", 0, sampleCount);

    // Compute the PSNR in decibels; higher the better
    double psnr;
    if (totalSqError > 0) {
        double sqrtMeanSquaredError = Math.sqrt((double) (totalSqError) / (double) (sampleCount));
        double maxValue = 65535.0;
        psnr = 20.0 * Math.log10(maxValue / sqrtMeanSquaredError);
    } else {
        // Identical! Pick a large PSNR result
        psnr = 1000.0;
    }

    return psnr;
}

From source file:com.naver.divideandconquer.closestpair.ClosestPair.java

private Pair getCenterClosestPair(Point[] points, double minDistance) {
    Point[] closestPairCandidatePoints = new Point[points.length];
    int count = 0;
    int mid = points.length / 2;
    Point standardPoint = points[mid];

    for (int i = 0; i < points.length; i++) {
        double distance = standardPoint.getX() > points[i].getX() ? standardPoint.getX() - points[i].getX()
                : points[i].getX() - standardPoint.getX();
        if (distance < minDistance) {
            closestPairCandidatePoints[count++] = points[i];
        }//from  w  ww.ja va 2s .com
    }

    closestPairCandidatePoints = Arrays.copyOfRange(closestPairCandidatePoints, 0, count);

    Arrays.sort(closestPairCandidatePoints, Comparator.comparing(Point::getY));

    Pair centerClosestPair = null;
    for (int i = 0; i < closestPairCandidatePoints.length - 5; i++) {
        for (int j = i + 1; j < i + 6 && j < closestPairCandidatePoints.length; j++) {
            double distance = calculateDistance(closestPairCandidatePoints[i], closestPairCandidatePoints[j]);
            if (distance < minDistance) {
                Pair pair = new Pair(closestPairCandidatePoints[i], closestPairCandidatePoints[j], distance);
                centerClosestPair = pair;
            }
        }
    }

    return centerClosestPair;
}

From source file:dev.maisentito.suca.commands.ToCommandHandler.java

@Override
public void handleCommand(MessageEvent event, String[] args) throws Throwable {
    String userHost = formatUserHost(event.getUser());

    if (!messages.containsKey(args[0].toLowerCase())) {
        messages.put(args[0].toLowerCase(), new HashMap<String, String>());
    }//from  w  w  w  . ja v  a2 s  .  co m

    messages.get(args[0].toLowerCase()).put(userHost,
            StringUtils.join(Arrays.copyOfRange(args, 1, args.length), ' '));

    event.respond("message added to queue");
}

From source file:com.baidu.oped.apm.common.buffer.AutomaticBufferTest.java

@Test
public void testPadBytes() throws Exception {
    int TOTAL_LENGTH = 20;
    int TEST_SIZE = 10;
    Buffer buffer = new AutomaticBuffer(10);
    byte[] test = new byte[10];

    random.nextBytes(test);/* w  ww . j  a v  a2s.com*/

    buffer.putPadBytes(test, TOTAL_LENGTH);

    byte[] result = buffer.getBuffer();
    Assert.assertEquals(result.length, TOTAL_LENGTH);
    Assert.assertTrue("check data",
            Arrays.equals(Arrays.copyOfRange(test, 0, TEST_SIZE), Arrays.copyOfRange(result, 0, TEST_SIZE)));
    byte[] padBytes = new byte[TOTAL_LENGTH - TEST_SIZE];
    Assert.assertTrue("check pad", Arrays.equals(Arrays.copyOfRange(padBytes, 0, TEST_SIZE),
            Arrays.copyOfRange(result, TEST_SIZE, TOTAL_LENGTH)));

}

From source file:geneticalgorithm.GeneticAlgorithm.java

public double calcFitness(Individual individual, Rule rule) {
    // number of fitter genes
    //        individual = resetFitness(individual);
    int fitGenes = 0;
    int[] condition = rule.getCondition();
    int action = rule.getAction();
    int chunk = 7; // chunk size to divide
    boolean isMatch = false;
    while (isMatch == false) {
        for (int i = 0; i < individual.getChromosome().length; i += chunk) { //loop though indiduals in rule chunks
            int[] chunks = Arrays.copyOfRange(individual.getChromosome(), i,
                    Math.min(individual.getChromosome().length, i + chunk)); //split small array

            int match = 0;
            //check if the condition matches
            for (int j = 0; j < chunks.length - 1; j++) {
                if (chunks[j] == condition[j] || chunks[j] == 2) {
                    match += 1;/*from  w  ww  . j  a  v a  2 s  . c o m*/
                }

            }
            if (match == 6) {
                //if the condition matches check if action matches
                if (chunks[chunks.length - 1] == action) {
                    //if both match increase fitness
                    double indFitness = individual.getFitness();
                    indFitness += 1;
                    individual.setFitness(indFitness);
                    //                        fitGenes += 1;
                    isMatch = true;
                    break;

                }
                if (isMatch == true) {
                    break;
                }
            }
            if (isMatch == true) {
                break;
            }
        }
        isMatch = true;
    }

    // calculate fitness
    double fitness = (double) fitGenes / individual.getChromosomeLength();
    return fitGenes;
}

From source file:com.opengamma.analytics.math.interpolation.data.Interpolator1DDataBundleBuilderFunction.java

@Override
public LinkedHashMap<String, Interpolator1DDataBundle> evaluate(final DoubleMatrix1D x) {
    Validate.notNull(x, "null data x");
    Validate.isTrue(_nNodes == x.getNumberOfElements(), "x wrong length");

    final LinkedHashMap<String, Interpolator1DDataBundle> res = new LinkedHashMap<String, Interpolator1DDataBundle>();
    int index = 0;

    for (final String name : _interpolators.keySet()) {
        final Interpolator1D interpolator = _interpolators.get(name);
        final double[] nodes = _knotPoints.get(name);
        final double[] values = Arrays.copyOfRange(x.getData(), index, index + nodes.length);
        index += nodes.length;//from   w  w w.j  a va2s.  c  o  m
        final Interpolator1DDataBundle db = interpolator.getDataBundleFromSortedArrays(nodes, values);
        res.put(name, db);
    }

    return res;
}