Example usage for org.apache.commons.lang ArrayUtils reverse

List of usage examples for org.apache.commons.lang ArrayUtils reverse

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils reverse.

Prototype

public static void reverse(boolean[] array) 

Source Link

Document

Reverses the order of the given array.

Usage

From source file:Main.java

public static void main(String[] args) {
    String[] colors = { "Red", "Green", "Blue", "Cyan", "Yellow", "Magenta" };
    System.out.println(ArrayUtils.toString(colors));

    ArrayUtils.reverse(colors);
    System.out.println(ArrayUtils.toString(colors));
}

From source file:ArrayUtilsExampleV1.java

public static void main(String args[]) {

    long[] longArray = new long[] { 10000, 30, 99 };
    String[] stringArray = new String[] { "abc", "def", "fgh" };

    long[] clonedArray = ArrayUtils.clone(longArray);
    System.err.println(ArrayUtils.toString((ArrayUtils.toObject(clonedArray))));

    System.err.println(ArrayUtils.indexOf(stringArray, "def"));

    ArrayUtils.reverse(stringArray);
    System.err.println(ArrayUtils.toString(stringArray));
}

From source file:examples.cnn.ImagesClassification.java

public static void main(String[] args) {

    SparkConf conf = new SparkConf();
    conf.setAppName("Images CNN Classification");
    conf.setMaster(String.format("local[%d]", NUM_CORES));
    conf.set(SparkDl4jMultiLayer.AVERAGE_EACH_ITERATION, String.valueOf(true));

    try (JavaSparkContext sc = new JavaSparkContext(conf)) {

        JavaRDD<String> raw = sc.textFile("data/images-data-rgb.csv");
        String first = raw.first();

        JavaPairRDD<String, String> labelData = raw.filter(f -> f.equals(first) == false).mapToPair(r -> {
            String[] tab = r.split(";");
            return new Tuple2<>(tab[0], tab[1]);
        });/*from  w ww .j  a  v  a  2s .  c o m*/

        Map<String, Long> labels = labelData.map(t -> t._1).distinct().zipWithIndex()
                .mapToPair(t -> new Tuple2<>(t._1, t._2)).collectAsMap();

        log.info("Number of labels {}", labels.size());
        labels.forEach((a, b) -> log.info("{}: {}", a, b));

        NetworkTrainer trainer = new NetworkTrainer.Builder().model(ModelLibrary.net1)
                .networkToSparkNetwork(net -> new SparkDl4jMultiLayer(sc, net)).numLabels(labels.size())
                .cores(NUM_CORES).build();

        JavaRDD<Tuple2<INDArray, double[]>> labelsWithData = labelData.map(t -> {
            INDArray label = FeatureUtil.toOutcomeVector(labels.get(t._1).intValue(), labels.size());
            double[] arr = Arrays.stream(t._2.split(" ")).map(normalize1).mapToDouble(Double::doubleValue)
                    .toArray();
            return new Tuple2<>(label, arr);
        });

        JavaRDD<Tuple2<INDArray, double[]>>[] splited = labelsWithData.randomSplit(new double[] { .8, .2 },
                seed);

        JavaRDD<DataSet> testDataset = splited[1].map(t -> {
            INDArray features = Nd4j.create(t._2, new int[] { 1, t._2.length });
            return new DataSet(features, t._1);
        }).cache();
        log.info("Number of test images {}", testDataset.count());

        JavaRDD<DataSet> plain = splited[0].map(t -> {
            INDArray features = Nd4j.create(t._2, new int[] { 1, t._2.length });
            return new DataSet(features, t._1);
        });

        /*
         * JavaRDD<DataSet> flipped = splited[0].randomSplit(new double[] { .5, .5 }, seed)[0].
         */
        JavaRDD<DataSet> flipped = splited[0].map(t -> {
            double[] arr = t._2;
            int idx = 0;
            double[] farr = new double[arr.length];
            for (int i = 0; i < arr.length; i += trainer.width) {
                double[] temp = Arrays.copyOfRange(arr, i, i + trainer.width);
                ArrayUtils.reverse(temp);
                for (int j = 0; j < trainer.height; ++j) {
                    farr[idx++] = temp[j];
                }
            }
            INDArray features = Nd4j.create(farr, new int[] { 1, farr.length });
            return new DataSet(features, t._1);
        });

        JavaRDD<DataSet> trainDataset = plain.union(flipped).cache();
        log.info("Number of train images {}", trainDataset.count());

        trainer.train(trainDataset, testDataset);
    }
}

From source file:examples.cnn.cifar.Cifar10Classification.java

public static void main(String[] args) {

    CifarReader.downloadAndExtract();//from   w w  w  . j  a  v  a  2s. co m

    int numLabels = 10;

    SparkConf conf = new SparkConf();
    conf.setMaster(String.format("local[%d]", NUM_CORES));
    conf.setAppName("Cifar-10 CNN Classification");
    conf.set(SparkDl4jMultiLayer.AVERAGE_EACH_ITERATION, String.valueOf(true));

    try (JavaSparkContext sc = new JavaSparkContext(conf)) {

        NetworkTrainer trainer = new NetworkTrainer.Builder().model(ModelLibrary.net2)
                .networkToSparkNetwork(net -> new SparkDl4jMultiLayer(sc, net)).numLabels(numLabels)
                .cores(NUM_CORES).build();

        JavaPairRDD<String, PortableDataStream> files = sc.binaryFiles("data/cifar-10-batches-bin");

        JavaRDD<double[]> imagesTrain = files
                .filter(f -> ArrayUtils.contains(CifarReader.TRAIN_DATA_FILES, extractFileName.apply(f._1)))
                .flatMap(f -> CifarReader.rawDouble(f._2.open()));

        JavaRDD<double[]> imagesTest = files
                .filter(f -> CifarReader.TEST_DATA_FILE.equals(extractFileName.apply(f._1)))
                .flatMap(f -> CifarReader.rawDouble(f._2.open()));

        JavaRDD<DataSet> testDataset = imagesTest.map(i -> {
            INDArray label = FeatureUtil.toOutcomeVector(Double.valueOf(i[0]).intValue(), numLabels);
            double[] arr = Arrays.stream(ArrayUtils.remove(i, 0)).boxed().map(normalize2)
                    .mapToDouble(Double::doubleValue).toArray();
            INDArray features = Nd4j.create(arr, new int[] { 1, arr.length });
            return new DataSet(features, label);
        }).cache();
        log.info("Number of test images {}", testDataset.count());

        JavaPairRDD<INDArray, double[]> labelsWithDataTrain = imagesTrain.mapToPair(i -> {
            INDArray label = FeatureUtil.toOutcomeVector(Double.valueOf(i[0]).intValue(), numLabels);
            double[] arr = Arrays.stream(ArrayUtils.remove(i, 0)).boxed().map(normalize2)
                    .mapToDouble(Double::doubleValue).toArray();
            return new Tuple2<>(label, arr);
        });

        JavaRDD<DataSet> flipped = labelsWithDataTrain.map(t -> {
            double[] arr = t._2;
            int idx = 0;
            double[] farr = new double[arr.length];
            for (int i = 0; i < arr.length; i += trainer.getWidth()) {
                double[] temp = Arrays.copyOfRange(arr, i, i + trainer.getWidth());
                ArrayUtils.reverse(temp);
                for (int j = 0; j < trainer.getHeight(); ++j) {
                    farr[idx++] = temp[j];
                }
            }
            INDArray features = Nd4j.create(farr, new int[] { 1, farr.length });
            return new DataSet(features, t._1);
        });

        JavaRDD<DataSet> trainDataset = labelsWithDataTrain.map(t -> {
            INDArray features = Nd4j.create(t._2, new int[] { 1, t._2.length });
            return new DataSet(features, t._1);
        }).union(flipped).cache();
        log.info("Number of train images {}", trainDataset.count());

        trainer.train(trainDataset, testDataset);
    }
}

From source file:com.example.java.collections.ArrayExample.java

public static void main(String[] args) {

    /* ########################################################### */
    // Initializing an Array
    String[] creatures = { "goldfish", "oscar", "guppy", "minnow" };
    int[] numbers = new int[10];
    int counter = 0;
    while (counter < numbers.length) {
        numbers[counter] = counter;/*from  w w  w  .j  a v a2  s.c  om*/
        System.out.println("number[" + counter + "]: " + counter);
        counter++;
    }
    for (int theInt : numbers) {
        System.out.println(theInt);
    }
    //System.out.println(numbers[numbers.length]);
    /* ########################################################### */

    /* ########################################################### */
    // Using Charecter Array
    String name = "Michael";
    // Charecter Array
    char[] charName = name.toCharArray();
    System.out.println(charName);

    // Array Fuctions
    char[] html = new char[] { 'M', 'i', 'c', 'h', 'a', 'e', 'l' };
    char[] lastFour = new char[4];
    System.arraycopy(html, 3, lastFour, 0, lastFour.length);
    System.out.println(lastFour);
    /* ########################################################### */

    /* ########################################################### */
    // Using Arrays of Other Types
    Object[] person = new Object[] { "Michael", new Integer(94), new Integer(1), new Date() };

    String fname = (String) person[0]; //ok
    Integer age = (Integer) person[1]; //ok
    Date start = (Date) person[2]; //oops!
    /* ########################################################### */

    /* ########################################################### */
    // Muti Dimestional Array
    String[][] bits = { { "Michael", "Ernest", "MFE" }, { "Ernest", "Friedman-Hill", "EFH" },
            { "Kathi", "Duggan", "KD" }, { "Jeff", "Kellum", "JK" } };

    bits[0] = new String[] { "Rudy", "Polanski", "RP" };
    bits[1] = new String[] { "Rudy", "Washington", "RW" };
    bits[2] = new String[] { "Rudy", "O'Reilly", "RO" };
    /* ########################################################### */

    /* ########################################################### */
    //Create ArrayList from array
    String[] stringArray = { "a", "b", "c", "d", "e" };
    ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
    System.out.println(arrayList);
    // [a, b, c, d, e]
    /* ########################################################### */

    /* ########################################################### */
    //Check if an array contains a certain value
    String[] stringArray1 = { "a", "b", "c", "d", "e" };
    boolean b = Arrays.asList(stringArray).contains("a");
    System.out.println(b);
    // true
    /* ########################################################### */

    /* ########################################################### */
    //Concatenate two arrays
    int[] intArray = { 1, 2, 3, 4, 5 };
    int[] intArray2 = { 6, 7, 8, 9, 10 };
    // Apache Commons Lang library
    int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
    /* ########################################################### */

    /* ########################################################### */
    //Joins the elements of the provided array into a single String
    // Apache common lang
    String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");
    System.out.println(j);
    // a, b, c
    /* ########################################################### */

    /* ########################################################### */
    //Covnert ArrayList to Array
    String[] stringArray3 = { "a", "b", "c", "d", "e" };
    ArrayList<String> arrayList1 = new ArrayList<String>(Arrays.asList(stringArray));
    String[] stringArr = new String[arrayList.size()];
    arrayList.toArray(stringArr);
    for (String s : stringArr) {
        System.out.println(s);
    }
    /* ########################################################### */

    /* ########################################################### */
    //Convert Array to Set
    Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
    System.out.println(set);
    //[d, e, b, c, a]
    /* ########################################################### */

    /* ########################################################### */
    //Reverse an array
    int[] intArray1 = { 1, 2, 3, 4, 5 };
    ArrayUtils.reverse(intArray1);
    System.out.println(Arrays.toString(intArray1));
    //[5, 4, 3, 2, 1]
    /* ########################################################### */

    /* ########################################################### */
    // Remove element of an array
    int[] intArray3 = { 1, 2, 3, 4, 5 };
    int[] removed = ArrayUtils.removeElement(intArray3, 3);//create a new array
    System.out.println(Arrays.toString(removed));
    /* ########################################################### */

    /* ########################################################### */
    byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();
    for (byte t : bytes) {
        System.out.format("0x%x ", t);
    }
    /* ########################################################### */

}

From source file:de.csdev.ebus.command.datatypes.std.AbstractEBusTypeUnsignedNumber.java

@Override
public BigDecimal decodeInt(byte[] data) throws EBusTypeException {

    byte[] clone = ArrayUtils.clone(data);
    ArrayUtils.reverse(clone);

    return new BigDecimal(new BigInteger(1, clone));
}

From source file:lu.lippmann.cdb.datasetview.tasks.HierarchizeReverseTask.java

/**
 * {@inheritDoc}/*  ww w.  j a  v  a 2s.  com*/
 */
@Override
Instances process0(final Instances dataSet) throws Exception {
    if (dataSet.classIndex() == -1)
        throw new Exception("Need a selected class!");
    final int[] idx = WekaMachineLearningUtil.computeRankedAttributes(dataSet);
    ArrayUtils.reverse(idx);
    return WekaDataProcessingUtil.buildFilteredByAttributesDataSet(dataSet, idx);
}

From source file:cz.zeno.miner.Utils.java

public static byte[] swapEndian(byte[] data) {
    //reverse each four bytes
    for (int i = 0; i < data.length / 4; i++) {
        byte[] msub = ArrayUtils.subarray(data, i * 4, i * 4 + 4);
        ArrayUtils.reverse(msub);
        System.arraycopy(msub, 0, data, i * 4, 4);
    }//from w w w .  j  av  a 2 s  . c o m
    return data;
}

From source file:de.berlin.magun.nfcmime.core.RfidDAO.java

/** 
 * @param tag Tag/*from  ww w. j  a  v a  2  s.c  om*/
 * @return a hexadecimal String representation of a Tag's ID or UID
 */
public String getTagId(Tag tag) {

    // get the ID byte array
    byte[] id = tag.getId();

    if (NfcV.get(tag) != null) {
        ArrayUtils.reverse(id);
    }

    return new String(Hex.encodeHex(id));
}

From source file:de.csdev.ebus.command.datatypes.EBusAbstractType.java

/**
 * Create a clone of the input array and reverse the byte order if set
 *
 * @param data/*from   ww w. ja v a  2  s.co m*/
 * @return
 */
protected byte[] applyByteOrder(byte[] data) {

    data = ArrayUtils.clone(data);

    // reverse the byte order immutable
    if (reverseByteOrder) {
        ArrayUtils.reverse(data);
    }

    return data;
}