org.apache.commons.lang3.ArrayUtils#reverse ( )源码实例Demo

下面列出了org.apache.commons.lang3.ArrayUtils#reverse ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Flink-CEPplus   文件: ExpressionKeysTest.java
@Test
public void testStandardTupleKeys() {
	TupleTypeInfo<Tuple7<String, String, String, String, String, String, String>> typeInfo = new TupleTypeInfo<>(
			BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,
			BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO);
	
	ExpressionKeys<Tuple7<String, String, String, String, String, String, String>> ek;
	
	for( int i = 1; i < 8; i++) {
		int[] ints = new int[i];
		for( int j = 0; j < i; j++) {
			ints[j] = j;
		}
		int[] inInts = Arrays.copyOf(ints, ints.length); // copy, just to make sure that the code is not cheating by changing the ints.
		ek = new ExpressionKeys<>(inInts, typeInfo);
		Assert.assertArrayEquals(ints, ek.computeLogicalKeyPositions());
		Assert.assertEquals(ints.length, ek.computeLogicalKeyPositions().length);
		
		ArrayUtils.reverse(ints);
		inInts = Arrays.copyOf(ints, ints.length);
		ek = new ExpressionKeys<>(inInts, typeInfo);
		Assert.assertArrayEquals(ints, ek.computeLogicalKeyPositions());
		Assert.assertEquals(ints.length, ek.computeLogicalKeyPositions().length);
	}
}
 
源代码2 项目: flink   文件: ExpressionKeysTest.java
@Test
public void testStandardTupleKeys() {
	TupleTypeInfo<Tuple7<String, String, String, String, String, String, String>> typeInfo = new TupleTypeInfo<>(
			BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO,
			BasicTypeInfo.STRING_TYPE_INFO,BasicTypeInfo.STRING_TYPE_INFO);
	
	ExpressionKeys<Tuple7<String, String, String, String, String, String, String>> ek;
	
	for( int i = 1; i < 8; i++) {
		int[] ints = new int[i];
		for( int j = 0; j < i; j++) {
			ints[j] = j;
		}
		int[] inInts = Arrays.copyOf(ints, ints.length); // copy, just to make sure that the code is not cheating by changing the ints.
		ek = new ExpressionKeys<>(inInts, typeInfo);
		Assert.assertArrayEquals(ints, ek.computeLogicalKeyPositions());
		Assert.assertEquals(ints.length, ek.computeLogicalKeyPositions().length);
		
		ArrayUtils.reverse(ints);
		inInts = Arrays.copyOf(ints, ints.length);
		ek = new ExpressionKeys<>(inInts, typeInfo);
		Assert.assertArrayEquals(ints, ek.computeLogicalKeyPositions());
		Assert.assertEquals(ints.length, ek.computeLogicalKeyPositions().length);
	}
}
 
源代码3 项目: PacketProxy   文件: StringUtils.java
public static byte[] intToByte(int v, boolean littleEndian) {
	byte[] bytes = new byte[4];
	for (int i = 0; i < 4; i++) {
		bytes[i] = (byte)(0xff & (v >> (i * 8)));
	}
	if (!littleEndian) {
		ArrayUtils.reverse(bytes);
	}
	return bytes;
}
 
源代码4 项目: ghidra   文件: ChecksumAlgorithm.java
/**
 * Converts a long to a little-endian array.
 * 
 * @param l The long to convert.
 * @param numBytes The desired size of the resulting array.  Result is truncated or padded if 
 *                 numBytes is smaller or larger than size of long.
 * @return The little-endian array.
 */
public static byte[] toArray(long l, int numBytes) {
	ByteBuffer buffy = ByteBuffer.allocate(Long.BYTES);
	buffy.putLong(l);
	byte[] checksumArray = new byte[numBytes];
	int n = Math.min(Long.BYTES, numBytes);
	System.arraycopy(buffy.array(), Long.BYTES - n, checksumArray, numBytes - n, n);
	ArrayUtils.reverse(checksumArray);
	return checksumArray;
}
 
源代码5 项目: public-suffix-list   文件: RuleMatcher.java
/**
 * Returns the matched public suffix.
 *
 * Matching is case insensitive.
 *
 * @param domain  the domain name, may be null
 * @return the matched public suffix or null
 */
String match(final String domain) {
    if (domain == null) {
        return null;

    }

    String[] reversedDomainLabels = DomainUtil.splitLabels(domain);
    ArrayUtils.reverse(reversedDomainLabels);
    if (reversedDomainLabels.length < reversedLabels.length) {
        return null;

    }

    String[] reversedMatchedLabels = new String[reversedLabels.length];
    for (int i = 0; i < reversedLabels.length; i++) {
        if (i > reversedDomainLabels.length) {
            return null;

        }
        String matchLabel = reversedLabels[i];
        String domainLabel = reversedDomainLabels[i];

        LabelMatcher matcher = new LabelMatcher(matchLabel);
        if (!matcher.isMatch(domainLabel)) {
            return null;

        }
        reversedMatchedLabels[i] = domainLabel;

    }
    ArrayUtils.reverse(reversedMatchedLabels);
    return DomainUtil.joinLabels(reversedMatchedLabels);
}
 
源代码6 项目: jhdf   文件: Utils.java
/**
 * This method is used when the length required is awkward i.e. no support
 * directly from {@link ByteBuffer}
 *
 * @param buffer to read from
 * @param length the number of bytes to read
 * @return the long value read from the buffer
 * @throws ArithmeticException if the data cannot be safely converted to an
 *                             unsigned long
 */
private static int readArbitraryLengthBytesAsUnsignedInt(ByteBuffer buffer, int length) {
	// Here we will use BigInteger to convert a byte array
	byte[] bytes = new byte[length];
	buffer.get(bytes);
	// BigInteger needs big endian so flip the order if needed
	if (buffer.order() == LITTLE_ENDIAN) {
		ArrayUtils.reverse(bytes);
	}
	// Convert to a unsigned long throws if it overflows
	return new BigInteger(1, bytes).intValueExact();
}
 
源代码7 项目: jhdf   文件: Utils.java
/**
 * This method is used when the length required is awkward i.e. no support
 * directly from {@link ByteBuffer}
 *
 * @param buffer to read from
 * @param length the number of bytes to read
 * @return the long value read from the buffer
 * @throws ArithmeticException if the data cannot be safely converted to an
 *                             unsigned long
 */
private static long readArbitraryLengthBytesAsUnsignedLong(ByteBuffer buffer, int length) {
	// Here we will use BigInteger to convert a byte array
	byte[] bytes = new byte[length];
	buffer.get(bytes);
	// BigInteger needs big endian so flip the order if needed
	if (buffer.order() == LITTLE_ENDIAN) {
		ArrayUtils.reverse(bytes);
	}
	// Convert to a unsigned long throws if it overflows
	return new BigInteger(1, bytes).longValueExact();
}
 
源代码8 项目: tutorials   文件: ArrayUtilsUnitTest.java
@Test
public void givenArray_whenReversingAllElements_thenCorrect() {
    int[] originalArray = { 1, 2, 3, 4, 5 };
    ArrayUtils.reverse(originalArray);
    int[] expectedArray = { 5, 4, 3, 2, 1 };
    assertArrayEquals(expectedArray, originalArray);
}
 
public byte[] getHMAC() throws NoSuchAlgorithmException {
    String shortSerial = this.stickSerial.replaceAll("\\d+-", "");
    byte[] message = (shortSerial + HMAC_PADDING).getBytes();
    byte[] numArray;

    MessageDigest instance = MessageDigest.getInstance("SHA-256");
    instance.update(message);

    numArray = instance.digest();
    ArrayUtils.reverse(numArray);

    return numArray;
}
 
源代码10 项目: pyramid   文件: NDCG.java
private static double idcg(double[] gradesInRankedList, int truncation){
    //should not sort the original one
    double[] sortedGrades = Arrays.copyOf(gradesInRankedList, gradesInRankedList.length);
    Arrays.sort(sortedGrades);
    ArrayUtils.reverse(sortedGrades);
    return dcg(sortedGrades,truncation);
}
 
源代码11 项目: cuba   文件: AbstractMessages.java
@Nullable
protected String searchIncludes(Properties properties, String key, Locale locale, Locale truncatedLocale,
                                Set<String> passedPacks) {
    String includesProperty = properties.getProperty("@include");
    if (includesProperty != null) {
        // multiple includes separated by comma
        String[] includes = StringUtils.split(includesProperty, " ,");
        if (includes != null && includes.length > 0) {
            ArrayUtils.reverse(includes);
            for (String includePath : includes) {
                includePath = StringUtils.trimToNull(includePath);
                if (includePath != null) {
                    String message;
                    if (truncatedLocale == null) {
                        message = searchMessage(includePath, key, locale, messageTools.getDefaultLocale(), passedPacks);
                    } else {
                        message = searchMessage(includePath, key, locale, truncatedLocale, passedPacks);
                    }
                    if (message != null) {
                        return message;
                    }
                }
            }
        }
    }
    return null;
}
 
源代码12 项目: vertexium   文件: GeoUtils.java
private static LinearRing toJtsLinearRing(List<GeoPoint> geoPoints, boolean counterClockwise, boolean lenient) {
    if (geoPoints.size() < 4) {
        throw new VertexiumInvalidShapeException("A polygon must specify at least 4 points for each boundary and hole.");
    }

    Coordinate[] shellCoordinates = geoPoints.stream()
        .map(geoPoint -> new Coordinate(geoPoint.getLongitude(), geoPoint.getLatitude()))
        .toArray(Coordinate[]::new);

    if (!shellCoordinates[0].equals(shellCoordinates[shellCoordinates.length - 1])) {
        if (lenient) {
            LOGGER.info("Closing an unclosed GeoShape by appending the beginning coordinate");
            shellCoordinates = org.apache.commons.lang3.ArrayUtils.add(shellCoordinates, shellCoordinates[0].copy());
        } else {
            throw new VertexiumInvalidShapeException("All polygon boundaries and holes must begin and end at the same point.");
        }
    }
    if (Orientation.isCCW(shellCoordinates) != counterClockwise) {
        if (lenient) {
            LOGGER.info("Reversing the coordinates of a ring that has a backwards orientation");
            ArrayUtils.reverse(shellCoordinates);
        } else {
            throw new VertexiumInvalidShapeException("The outer shell of a polygon must be specified in counter-clockwise " +
                "orientation and all holes must be specified in the clockwise direction.");
        }
    }
    return GEOMETRY_FACTORY.createLinearRing(shellCoordinates);
}
 
源代码13 项目: tutorials   文件: ArrayUtilsUnitTest.java
@Test
public void givenArray_whenReversingElementsWithinARange_thenCorrect() {
    int[] originalArray = { 1, 2, 3, 4, 5 };
    ArrayUtils.reverse(originalArray, 1, 4);
    int[] expectedArray = { 1, 4, 3, 2, 5 };
    assertArrayEquals(expectedArray, originalArray);
}
 
源代码14 项目: tutorials   文件: ArrayUtilsUnitTest.java
@Test
public void givenArrayUtilsClass_whenCalledreverse_thenCorrect() {
    int[] array1 = {1, 2, 3};
    int[] array2 = {3, 2, 1};
    ArrayUtils.reverse(array1);
    assertThat(array1).isEqualTo(array2);
}
 
源代码15 项目: sejda   文件: PageRangeSetAdapterTest.java
@Test
public void insertionOrder() {
    PageRange[] inputRanges = { new PageRange(4), new PageRange(6, 9), new PageRange(1, 2) };
    doTestInsertionOrder(inputRanges);
    ArrayUtils.reverse(inputRanges);
    doTestInsertionOrder(inputRanges);
}
 
源代码16 项目: api   文件: Utils.java
public static byte[] toByteArrayLittleEndianUnsigned(BigInteger bi) {
    byte[] extractedBytes = toByteArrayUnsigned(bi);
    ArrayUtils.reverse(extractedBytes);
    //byte[] reversed = ByteUtils.reverseArray(extractedBytes);
    return extractedBytes;
}
 
源代码17 项目: public-suffix-list   文件: RuleMatcher.java
/**
 * Returns the rule pattern.
 *
 * @return the rule pattern, not null
 */
String getPattern() {
    String[] labels = reversedLabels.clone();
    ArrayUtils.reverse(labels);
    return DomainUtil.joinLabels(labels);
}
 
源代码18 项目: phoenix   文件: PhoenixResultSet.java
/**
 * Separate the actual cell data from the serialized list of dynamic column PColumns and
 * return the deserialized list of dynamic column PColumns for the current row
 * @return Deserialized list of dynamic column PColumns or null if there are no dynamic columns
 */
private List<PColumn> getDynColsListAndSeparateFromActualData() {
    Cell base = this.currentRow.getValue(0);
    final byte[] valueArray = CellUtil.cloneValue(base);
    // We inserted the known byte array before appending the serialized list of dynamic columns
    final byte[] anchor = Arrays.copyOf(DYN_COLS_METADATA_CELL_QUALIFIER,
            DYN_COLS_METADATA_CELL_QUALIFIER.length);
    // Reverse the arrays to find the last occurrence of the sub-array in the value array
    ArrayUtils.reverse(valueArray);
    ArrayUtils.reverse(anchor);
    final int pos = valueArray.length - Bytes.indexOf(valueArray, anchor);
    // There are no dynamic columns to process so return immediately
    if (pos >= valueArray.length) {
        return null;
    }
    ArrayUtils.reverse(valueArray);

    // Separate the serialized list of dynamic column PColumns from the actual cell data
    byte[] actualCellDataBytes = Arrays.copyOfRange(valueArray, 0,
            pos - DYN_COLS_METADATA_CELL_QUALIFIER.length);
    ImmutableBytesWritable actualCellData = new ImmutableBytesWritable(actualCellDataBytes);
    ImmutableBytesWritable key = new ImmutableBytesWritable();
    currentRow.getKey(key);
    // Store only the actual cell data as part of the current row
    this.currentRow = new TupleProjector.ProjectedValueTuple(key.get(), key.getOffset(),
            key.getLength(), base.getTimestamp(),
            actualCellData.get(), actualCellData.getOffset(), actualCellData.getLength(), 0);

    byte[] dynColsListBytes = Arrays.copyOfRange(valueArray, pos, valueArray.length);
    List<PColumn> dynCols = new ArrayList<>();
    try {
        List<PTableProtos.PColumn> dynColsProtos = DynamicColumnMetaDataProtos
                .DynamicColumnMetaData.parseFrom(dynColsListBytes).getDynamicColumnsList();
        for (PTableProtos.PColumn colProto : dynColsProtos) {
            dynCols.add(PColumnImpl.createFromProto(colProto));
        }
    } catch (InvalidProtocolBufferException e) {
        return null;
    }
    return dynCols;
}
 
源代码19 项目: picard   文件: LiftoverUtils.java
/**
 * method to swap the reference and alt alleles of a bi-allelic, SNP
 *
 * @param vc                   the {@link VariantContext} (bi-allelic SNP) that needs to have it's REF and ALT alleles swapped.
 * @param annotationsToReverse INFO field annotations (of double value) that will be reversed (x->1-x)
 * @param annotationsToDrop    INFO field annotations that will be dropped from the result since they are invalid when REF and ALT are swapped
 * @return a new {@link VariantContext} with alleles swapped, INFO fields modified and in the genotypes, GT, AD and PL corrected appropriately
 */
public static VariantContext swapRefAlt(final VariantContext vc, final Collection<String> annotationsToReverse, final Collection<String> annotationsToDrop) {

    if (!vc.isBiallelic() || !vc.isSNP()) {
        throw new IllegalArgumentException("swapRefAlt can only process biallelic, SNPS, found " + vc.toString());
    }

    final VariantContextBuilder swappedBuilder = new VariantContextBuilder(vc);

    swappedBuilder.attribute(SWAPPED_ALLELES, true);

    // Use getBaseString() (rather than the Allele itself) in order to create new Alleles with swapped
    // reference and non-variant attributes
    swappedBuilder.alleles(Arrays.asList(vc.getAlleles().get(1).getBaseString(), vc.getAlleles().get(0).getBaseString()));

    final Map<Allele, Allele> alleleMap = new HashMap<>();

    // A mapping from the old allele to the new allele, to be used when fixing the genotypes
    alleleMap.put(vc.getAlleles().get(0), swappedBuilder.getAlleles().get(1));
    alleleMap.put(vc.getAlleles().get(1), swappedBuilder.getAlleles().get(0));

    final GenotypesContext swappedGenotypes = GenotypesContext.create(vc.getGenotypes().size());
    for (final Genotype genotype : vc.getGenotypes()) {
        final List<Allele> swappedAlleles = new ArrayList<>();
        for (final Allele allele : genotype.getAlleles()) {
            if (allele.isNoCall()) {
                swappedAlleles.add(allele);
            } else {
                swappedAlleles.add(alleleMap.get(allele));
            }
        }
        // Flip AD
        final GenotypeBuilder builder = new GenotypeBuilder(genotype).alleles(swappedAlleles);
        if (genotype.hasAD() && genotype.getAD().length == 2) {
            final int[] ad = ArrayUtils.clone(genotype.getAD());
            ArrayUtils.reverse(ad);
            builder.AD(ad);
        } else {
            builder.noAD();
        }

        //Flip PL
        if (genotype.hasPL() && genotype.getPL().length == 3) {
            final int[] pl = ArrayUtils.clone(genotype.getPL());
            ArrayUtils.reverse(pl);
            builder.PL(pl);
        } else {
            builder.noPL();
        }
        swappedGenotypes.add(builder.make());
    }
    swappedBuilder.genotypes(swappedGenotypes);

    for (final String key : vc.getAttributes().keySet()) {
        if (annotationsToDrop.contains(key)) {
            swappedBuilder.rmAttribute(key);
        } else if (annotationsToReverse.contains(key) && !vc.getAttributeAsString(key, "").equals(VCFConstants.MISSING_VALUE_v4)) {
            final double attributeToReverse = vc.getAttributeAsDouble(key, -1);

            if (attributeToReverse < 0 || attributeToReverse > 1) {
                log.warn("Trying to reverse attribute " + key +
                        " but found value that isn't between 0 and 1: (" + attributeToReverse + ") in variant " + vc + ". Results might be wrong.");
            }
            swappedBuilder.attribute(key, 1 - attributeToReverse);
        }
    }

    return swappedBuilder.make();
}
 
源代码20 项目: public-suffix-list   文件: RuleMatcher.java
/**
 * Sets the rule labels.
 *
 * The labels are stored as a reversed copy in {@link #reversedLabels}.
 *
 * @param labels  the rule labels, not null
 */
RuleMatcher(final String[] labels) {
    this.reversedLabels = labels.clone();
    ArrayUtils.reverse(reversedLabels);
}