Java Code Examples for org.apache.commons.lang3.ArrayUtils.subarray()

The following are Jave code examples for showing how to use subarray() of the org.apache.commons.lang3.ArrayUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: gamecraft   File: GameCommandExecutor.java   View Source Code Vote up 5 votes
private String[] trimArgs(GameCommand child, String[] args) {
    for (int x = 0; x < args.length; x++) {
        if (args[x].equalsIgnoreCase(child.getName())) {
            return ArrayUtils.subarray(args, x + 1, args.length);
        }

        for (String alias : child.getAliases()) {
            if (args[x].equalsIgnoreCase(alias)) {
                return ArrayUtils.subarray(args, x + 1, args.length);
            }
        }
    }

    return args;
}
 
Example 2
Project: sumo   File: MathUtil.java   View Source Code Vote up 5 votes
/**
 * Convolution U(m)=Sum( H(m)X(n-m) )    0<=m=<(size(H)-1) n=size(H)
 * 
 * This function reproduce the matlab conv function with shape='valid'
 * 
 * @param a
 * @param b
 * @return
 */
public static double[] linearConvolutionMatlabValid(double a[],double b[]){
	//size of the array result without zero padd values
	int sizeResult=a.length+b.length-1;
	int matlabSizeResult=a.length-b.length+1;
	
	b=ArrayUtils.add(b,0);
	
	double[] u=new double[sizeResult];
	int idU=0;
	for(int n=0;n<sizeResult;n++){
		double val=0;

		for(int m=0;m<=n;m++){
			int idx1=m;
			int idx2=n-m;
			
			if(idx2>=0&&idx1>=0&&idx2<b.length-1&&idx1<a.length){
				val=val+a[idx1]*b[idx2];
			}	
		}
		u[idU]=val;
		idU++;
	}
	int diff=(sizeResult-matlabSizeResult);
	int idxStart=diff/2+diff%2;
	int idxEnd=u.length-diff/2;
	u=ArrayUtils.subarray(u, idxStart, idxEnd);
	
	
	return u; 
}
 
Example 3
Project: sumo   File: TestJavaConvolution.java   View Source Code Vote up 5 votes
/**
 * Convolution U(m)=Sum( H(m)X(n-m) )    0<=m=<(size(H)-1) n=size(H)
 * 
 * This function reproduce the matlab conv function with shape='valid'
 * 
 * @param a
 * @param b
 * @return
 */
public static double[] linearConvolutionMatlabValid(double a[],double b[]){
	//size of the array result without zero padd values
	int sizeResult=a.length+b.length-1;
	int matlabSizeResult=a.length-b.length+1;
	
	b=ArrayUtils.add(b,0);
	List<Integer> idxPadded=new ArrayList<Integer>();
	
	double[] u=new double[sizeResult];
	int idU=0;
	for(int n=0;n<sizeResult;n++){
		double val=0;
		
		
		for(int m=0;m<=n;m++){
			
			int idx1=m;
			int idx2=n-m;
			
			if(idx2>=0&&idx1>=0&&idx2<b.length-1&&idx1<a.length){
				val=val+a[idx1]*b[idx2];
			}	
		}

		u[idU]=val;
		idU++;
	}
	int diff=(sizeResult-matlabSizeResult);
	int idxStart=diff/2+diff%2;
	int idxEnd=u.length-diff/2;
	u=ArrayUtils.subarray(u, idxStart, idxEnd);
	
	
	return u; 
}
 
Example 4
Project: DecompiledMinecraft   File: CrashReport.java   View Source Code Vote up 5 votes
/**
 * Gets the various sections of the crash report into the given StringBuilder
 */
public void getSectionsInStringBuilder(StringBuilder builder)
{
    if ((this.stacktrace == null || this.stacktrace.length <= 0) && this.crashReportSections.size() > 0)
    {
        this.stacktrace = (StackTraceElement[])ArrayUtils.subarray(((CrashReportCategory)this.crashReportSections.get(0)).getStackTrace(), 0, 1);
    }

    if (this.stacktrace != null && this.stacktrace.length > 0)
    {
        builder.append("-- Head --\n");
        builder.append("Stacktrace:\n");

        for (StackTraceElement stacktraceelement : this.stacktrace)
        {
            builder.append("\t").append("at ").append(stacktraceelement.toString());
            builder.append("\n");
        }

        builder.append("\n");
    }

    for (CrashReportCategory crashreportcategory : this.crashReportSections)
    {
        crashreportcategory.appendToStringBuilder(builder);
        builder.append("\n\n");
    }

    this.theReportCategory.appendToStringBuilder(builder);
}
 
Example 5
Project: DecompiledMinecraft   File: CrashReport.java   View Source Code Vote up 5 votes
/**
 * Gets the various sections of the crash report into the given StringBuilder
 */
public void getSectionsInStringBuilder(StringBuilder builder)
{
    if ((this.stacktrace == null || this.stacktrace.length <= 0) && this.crashReportSections.size() > 0)
    {
        this.stacktrace = (StackTraceElement[])ArrayUtils.subarray(((CrashReportCategory)this.crashReportSections.get(0)).getStackTrace(), 0, 1);
    }

    if (this.stacktrace != null && this.stacktrace.length > 0)
    {
        builder.append("-- Head --\n");
        builder.append("Stacktrace:\n");

        for (StackTraceElement stacktraceelement : this.stacktrace)
        {
            builder.append("\t").append("at ").append(stacktraceelement.toString());
            builder.append("\n");
        }

        builder.append("\n");
    }

    for (CrashReportCategory crashreportcategory : this.crashReportSections)
    {
        crashreportcategory.appendToStringBuilder(builder);
        builder.append("\n\n");
    }

    this.theReportCategory.appendToStringBuilder(builder);
}
 
Example 6
Project: BaseClient   File: CrashReport.java   View Source Code Vote up 5 votes
/**
 * Gets the various sections of the crash report into the given StringBuilder
 */
public void getSectionsInStringBuilder(StringBuilder builder)
{
    if ((this.stacktrace == null || this.stacktrace.length <= 0) && this.crashReportSections.size() > 0)
    {
        this.stacktrace = (StackTraceElement[])((StackTraceElement[])ArrayUtils.subarray(((CrashReportCategory)this.crashReportSections.get(0)).getStackTrace(), 0, 1));
    }

    if (this.stacktrace != null && this.stacktrace.length > 0)
    {
        builder.append("-- Head --\n");
        builder.append("Stacktrace:\n");

        for (StackTraceElement stacktraceelement : this.stacktrace)
        {
            builder.append("\t").append("at ").append(stacktraceelement.toString());
            builder.append("\n");
        }

        builder.append("\n");
    }

    for (Object crashreportcategory : this.crashReportSections)
    {
        ((CrashReportCategory)crashreportcategory).appendToStringBuilder(builder);
        builder.append("\n\n");
    }

    this.theReportCategory.appendToStringBuilder(builder);
}
 
Example 7
Project: BaseClient   File: CrashReport.java   View Source Code Vote up 5 votes
/**
 * Gets the various sections of the crash report into the given StringBuilder
 */
public void getSectionsInStringBuilder(StringBuilder builder)
{
    if ((this.stacktrace == null || this.stacktrace.length <= 0) && this.crashReportSections.size() > 0)
    {
        this.stacktrace = (StackTraceElement[])((StackTraceElement[])ArrayUtils.subarray(((CrashReportCategory)this.crashReportSections.get(0)).getStackTrace(), 0, 1));
    }

    if (this.stacktrace != null && this.stacktrace.length > 0)
    {
        builder.append("-- Head --\n");
        builder.append("Stacktrace:\n");

        for (StackTraceElement stacktraceelement : this.stacktrace)
        {
            builder.append("\t").append("at ").append(stacktraceelement.toString());
            builder.append("\n");
        }

        builder.append("\n");
    }

    for (Object crashreportcategory : this.crashReportSections)
    {
        ((CrashReportCategory) crashreportcategory).appendToStringBuilder(builder);
        builder.append("\n\n");
    }

    this.theReportCategory.appendToStringBuilder(builder);
}
 
Example 8
Project: QDrill   File: FooterGatherer.java   View Source Code Vote up 5 votes
private static void checkMagicBytes(FileStatus status, byte[] data, int offset) throws IOException {
  for(int i =0, v = offset; i < MAGIC_LENGTH; i++, v++){
    if(ParquetFileWriter.MAGIC[i] != data[v]){
      byte[] magic = ArrayUtils.subarray(data, offset, offset + MAGIC_LENGTH);
      throw new IOException(status.getPath() + " is not a Parquet file. expected magic number at tail " + Arrays.toString(ParquetFileWriter.MAGIC) + " but found " + Arrays.toString(magic));
    }
  }
}
 
Example 9
Project: QDrill   File: FooterGatherer.java   View Source Code Vote up 5 votes
/**
 * An updated footer reader that tries to read the entire footer without knowing the length.
 * This should reduce the amount of seek/read roundtrips in most workloads.
 * @param fs
 * @param status
 * @return
 * @throws IOException
 */
public static Footer readFooter(final Configuration config, final FileStatus status) throws IOException {
  final FileSystem fs = status.getPath().getFileSystem(config);
  try(FSDataInputStream file = fs.open(status.getPath())) {

    final long fileLength = status.getLen();
    Preconditions.checkArgument(fileLength >= MIN_FILE_SIZE, "%s is not a Parquet file (too small)", status.getPath());

    int len = (int) Math.min( fileLength, (long) DEFAULT_READ_SIZE);
    byte[] footerBytes = new byte[len];
    readFully(file, fileLength - len, footerBytes, 0, len);

    checkMagicBytes(status, footerBytes, footerBytes.length - ParquetFileWriter.MAGIC.length);
    final int size = BytesUtils.readIntLittleEndian(footerBytes, footerBytes.length - FOOTER_METADATA_SIZE);

    if(size > footerBytes.length - FOOTER_METADATA_SIZE){
      // if the footer is larger than our initial read, we need to read the rest.
      byte[] origFooterBytes = footerBytes;
      int origFooterRead = origFooterBytes.length - FOOTER_METADATA_SIZE;

      footerBytes = new byte[size];

      readFully(file, fileLength - size - FOOTER_METADATA_SIZE, footerBytes, 0, size - origFooterRead);
      System.arraycopy(origFooterBytes, 0, footerBytes, size - origFooterRead, origFooterRead);
    }else{
      int start = footerBytes.length - (size + FOOTER_METADATA_SIZE);
      footerBytes = ArrayUtils.subarray(footerBytes, start, start + size);
    }

    ParquetMetadata metadata = ParquetFormatPlugin.parquetMetadataConverter.readParquetMetadata(new ByteArrayInputStream(footerBytes));
    Footer footer = new Footer(status.getPath(), metadata);
    return footer;
  }
}
 
Example 10
Project: Backmemed   File: CrashReport.java   View Source Code Vote up 5 votes
/**
 * Gets the various sections of the crash report into the given StringBuilder
 */
public void getSectionsInStringBuilder(StringBuilder builder)
{
    if ((this.stacktrace == null || this.stacktrace.length <= 0) && !this.crashReportSections.isEmpty())
    {
        this.stacktrace = (StackTraceElement[])((StackTraceElement[])ArrayUtils.subarray(((CrashReportCategory)this.crashReportSections.get(0)).getStackTrace(), 0, 1));
    }

    if (this.stacktrace != null && this.stacktrace.length > 0)
    {
        builder.append("-- Head --\n");
        builder.append("Thread: ").append(Thread.currentThread().getName()).append("\n");
        builder.append("Stacktrace:\n");

        for (StackTraceElement stacktraceelement : this.stacktrace)
        {
            builder.append("\t").append("at ").append((Object)stacktraceelement);
            builder.append("\n");
        }

        builder.append("\n");
    }

    for (CrashReportCategory crashreportcategory : this.crashReportSections)
    {
        crashreportcategory.appendToStringBuilder(builder);
        builder.append("\n\n");
    }

    this.theReportCategory.appendToStringBuilder(builder);
}
 
Example 11
Project: dremio-oss   File: SingletonParquetFooterCache.java   View Source Code Vote up 5 votes
private static void checkMagicBytes(FileStatus status, byte[] data, int offset) throws IOException {
  for(int i =0, v = offset; i < MAGIC_LENGTH; i++, v++){
    if(ParquetFileWriter.MAGIC[i] != data[v]){
      byte[] magic = ArrayUtils.subarray(data, offset, offset + MAGIC_LENGTH);
      throw new IOException(status.getPath() + " is not a Parquet file. expected magic number at tail " + Arrays.toString(ParquetFileWriter.MAGIC) + " but found " + Arrays.toString(magic));
    }
  }
}
 
Example 12
Project: dremio-oss   File: SingletonParquetFooterCache.java   View Source Code Vote up 5 votes
/**
 * An updated footer reader that tries to read the entire footer without knowing the length.
 * This should reduce the amount of seek/read roundtrips in most workloads.
 * @param fs
 * @param status
 * @return
 * @throws IOException
 */
public static ParquetMetadata readFooter(
  final FileSystem fs,
  final FileStatus status,
  ParquetMetadataConverter.MetadataFilter filter) throws IOException {
  try(FSDataInputStream file = fs.open(status.getPath())) {
    final long fileLength = status.getLen();
    Preconditions.checkArgument(fileLength >= MIN_FILE_SIZE, "%s is not a Parquet file (too small)", status.getPath());

    int len = (int) Math.min( fileLength, (long) DEFAULT_READ_SIZE);
    byte[] footerBytes = new byte[len];
    readFully(file, fileLength - len, footerBytes, 0, len);

    checkMagicBytes(status, footerBytes, footerBytes.length - ParquetFileWriter.MAGIC.length);
    final int size = BytesUtils.readIntLittleEndian(footerBytes, footerBytes.length - FOOTER_METADATA_SIZE);

    if(size > footerBytes.length - FOOTER_METADATA_SIZE){
      // if the footer is larger than our initial read, we need to read the rest.
      byte[] origFooterBytes = footerBytes;
      int origFooterRead = origFooterBytes.length - FOOTER_METADATA_SIZE;

      footerBytes = new byte[size];

      readFully(file, fileLength - size - FOOTER_METADATA_SIZE, footerBytes, 0, size - origFooterRead);
      System.arraycopy(origFooterBytes, 0, footerBytes, size - origFooterRead, origFooterRead);
    }else{
      int start = footerBytes.length - (size + FOOTER_METADATA_SIZE);
      footerBytes = ArrayUtils.subarray(footerBytes, start, start + size);
    }

    return ParquetFormatPlugin.parquetMetadataConverter.readParquetMetadata(new ByteArrayInputStream(footerBytes), filter);
  }
}
 
Example 13
Project: CustomWorldGen   File: CrashReport.java   View Source Code Vote up 5 votes
/**
 * Gets the various sections of the crash report into the given StringBuilder
 */
public void getSectionsInStringBuilder(StringBuilder builder)
{
    if ((this.stacktrace == null || this.stacktrace.length <= 0) && !this.crashReportSections.isEmpty())
    {
        this.stacktrace = (StackTraceElement[])ArrayUtils.subarray(((CrashReportCategory)this.crashReportSections.get(0)).getStackTrace(), 0, 1);
    }

    if (this.stacktrace != null && this.stacktrace.length > 0)
    {
        builder.append("-- Head --\n");
        builder.append("Thread: ").append(Thread.currentThread().getName()).append("\n");
        builder.append("Stacktrace:\n");

        for (StackTraceElement stacktraceelement : this.stacktrace)
        {
            builder.append("\t").append("at ").append((Object)stacktraceelement);
            builder.append("\n");
        }

        builder.append("\n");
    }

    for (CrashReportCategory crashreportcategory : this.crashReportSections)
    {
        crashreportcategory.appendToStringBuilder(builder);
        builder.append("\n\n");
    }

    this.theReportCategory.appendToStringBuilder(builder);
}
 
Example 14
Project: jigsaw-payment   File: TProtobufProcessor.java   View Source Code Vote up 4 votes
private byte[] getValidBytes(ByteBuffer byteBuffer) {
	return ArrayUtils.subarray(byteBuffer.array(), byteBuffer.position(),
			byteBuffer.limit());
}
 
Example 15
Project: QDrill   File: EasyFormatPlugin.java   View Source Code Vote up 4 votes
CloseableRecordBatch getReaderBatch(FragmentContext context, EasySubScan scan) throws ExecutionSetupException {
  String partitionDesignator = context.getOptions()
    .getOption(ExecConstants.FILESYSTEM_PARTITION_COLUMN_LABEL).string_val;
  List<SchemaPath> columns = scan.getColumns();
  List<RecordReader> readers = Lists.newArrayList();
  List<String[]> partitionColumns = Lists.newArrayList();
  List<Integer> selectedPartitionColumns = Lists.newArrayList();
  boolean selectAllColumns = false;

  if (columns == null || columns.size() == 0 || AbstractRecordReader.isStarQuery(columns)) {
    selectAllColumns = true;
  } else {
    List<SchemaPath> newColumns = Lists.newArrayList();
    Pattern pattern = Pattern.compile(String.format("%s[0-9]+", partitionDesignator));
    for (SchemaPath column : columns) {
      Matcher m = pattern.matcher(column.getAsUnescapedPath());
      if (m.matches()) {
        selectedPartitionColumns.add(Integer.parseInt(column.getAsUnescapedPath().toString().substring(partitionDesignator.length())));
      } else {
        newColumns.add(column);
      }
    }

    // We must make sure to pass a table column(not to be confused with partition column) to the underlying record
    // reader.
    if (newColumns.size()==0) {
      newColumns.add(AbstractRecordReader.STAR_COLUMN);
    }
    // Create a new sub scan object with the new set of columns;
    EasySubScan newScan = new EasySubScan(scan.getUserName(), scan.getWorkUnits(), scan.getFormatPlugin(),
        newColumns, scan.getSelectionRoot());
    newScan.setOperatorId(scan.getOperatorId());
    scan = newScan;
  }

  int numParts = 0;
  OperatorContext oContext = context.newOperatorContext(scan, false /*
                                                                     * ScanBatch is not subject to fragment memory
                                                                     * limit
                                                                     */);
  final DrillFileSystem dfs;
  try {
    dfs = oContext.newFileSystem(fsConf);
  } catch (IOException e) {
    throw new ExecutionSetupException(String.format("Failed to create FileSystem: %s", e.getMessage()), e);
  }

  for(FileWork work : scan.getWorkUnits()){
    readers.add(getRecordReader(context, dfs, work, scan.getColumns()));
    if (scan.getSelectionRoot() != null) {
      String[] r = Path.getPathWithoutSchemeAndAuthority(new Path(scan.getSelectionRoot())).toString().split("/");
      String[] p = Path.getPathWithoutSchemeAndAuthority(new Path(work.getPath())).toString().split("/");
      if (p.length > r.length) {
        String[] q = ArrayUtils.subarray(p, r.length, p.length - 1);
        partitionColumns.add(q);
        numParts = Math.max(numParts, q.length);
      } else {
        partitionColumns.add(new String[] {});
      }
    } else {
      partitionColumns.add(new String[] {});
    }
  }

  if (selectAllColumns) {
    for (int i = 0; i < numParts; i++) {
      selectedPartitionColumns.add(i);
    }
  }

  return new ScanBatch(scan, context, oContext, readers.iterator(), partitionColumns, selectedPartitionColumns);
}
 
Example 16
Project: ECFileCache   File: ECFileCacheTest.java   View Source Code Vote up 4 votes
private void putChunk(String fileCacheKey, byte[] buffer, int chunkPos, int endPos) throws ECFileCacheException {
  byte[] chunk = ArrayUtils.subarray(buffer, chunkPos, endPos);
  InputStream inputStream = new ByteArrayInputStream(chunk);
  client.putFile(fileCacheKey, chunkPos, inputStream, 0);
  IOUtils.closeQuietly(inputStream);
}
 
Example 17
Project: CodeCompilerApp   File: MainActivity.java   View Source Code Vote up 4 votes
private void refreshList(@Nullable GreatUri thisUri, boolean add, boolean delete) {
    int max_recent_files = 15;
    if(add)
        max_recent_files--;

    // File paths saved in preferences
    String[] savedPaths = PreferenceHelper.getSavedPaths(this);
    int first_index_of_array = savedPaths.length > max_recent_files ? savedPaths.length - max_recent_files : 0;
    savedPaths = ArrayUtils.subarray(savedPaths, first_index_of_array, savedPaths.length);
    // File names for the list
    greatUris.clear();
    // StringBuilder that will contain the file paths
    StringBuilder sb = new StringBuilder();

    // for cycle to convert paths to names
    for(int i = 0; i < savedPaths.length; i++){
        Uri particularUri = Uri.parse(savedPaths[i]);
        String name = AccessStorageApi.getName(this, particularUri);
        // Check that the file exist
        // if is null or empty the particular url we dont use it
        if (particularUri != null && !particularUri.equals(Uri.EMPTY) && !TextUtils.isEmpty(name)) {
            // if the particular uri is good
            boolean good = false;
            if (thisUri == null || thisUri.getUri() == null || thisUri.getUri() == Uri.EMPTY)
                good = true;
            else {
                if (delete == false)
                    good = true;
                else if (!thisUri.getUri().equals(particularUri))
                    good = true;
                else
                    good = false;
            }
            if (good) {
                greatUris.addFirst(new GreatUri(particularUri, AccessStorageApi.getPath(this, particularUri), name));
                sb.append(savedPaths[i]).append(",");
            }
        }
        //}
    }
    // if is not null, empty, we have to add something and we dont already have this uri
    if(thisUri != null && !thisUri.getUri().equals(Uri.EMPTY) && add && !ArrayUtils.contains(savedPaths, thisUri.getUri().toString())) {
        sb.append(thisUri.getUri().toString()).append(",");
        greatUris.addFirst(thisUri);
    }
    // save list without empty or non existed files
    PreferenceHelper.setSavedPaths(this, sb);
    // Set adapter
    arrayAdapter.notifyDataSetChanged();
}
 
Example 18
Project: cassandra-client   File: DataFilter.java   View Source Code Vote up 4 votes
public static Predicate<DataObject> parsePredicate(String filter) {
    if (filter.startsWith("(")) {
        int closingBracketIndex = findClosingBracketIndex(filter);
        Predicate<DataObject> predicate = parsePredicate(filter.substring(1, closingBracketIndex));

        if (closingBracketIndex != filter.length() - 1) {
            String secondFilterPart = filter.substring(closingBracketIndex + 1).trim();
            if (startsWithIgnoreCase(secondFilterPart, AND.name())) {
                return predicate.and(parsePredicate(secondFilterPart.substring(3).trim()));
            } else if (startsWithIgnoreCase(secondFilterPart, OR.name())) {
                return predicate.or(parsePredicate(secondFilterPart.substring(2).trim()));
            } else {
                throw new IllegalArgumentException("Illegal combiner : " + secondFilterPart);
            }
        } else {
            return predicate;
        }
    }
    String[] words = parseWords(filter);

    if (words.length < 3) {
        throw new IllegalArgumentException("Incomplete filter : " + filter);
    }
    String firstWord = wordAtPosition(words, 0)
            .orElseThrow(() -> new IllegalArgumentException("Should not be called with empty string"));
    String secondWord = wordAtPosition(words, 1)
            .orElseThrow(() -> new IllegalArgumentException("Should not be called with empty string"));
    String thirdWord = wordAtPosition(words, 2)
            .orElseThrow(() -> new IllegalArgumentException("Should not be called with empty string"));

    Operator operator = Operator.fromValue(secondWord);
    Predicate<DataObject> operatorPredicate = predicateFactories.get(operator).build(firstWord, thirdWord);

    Optional<String> fourthWord = wordAtPosition(words, 3);
    if (fourthWord.isPresent()) {
        Combiner combiner = Combiner.valueOf(fourthWord.get());
        String[] remainingWords = ArrayUtils.subarray(words, 4, words.length);
        String remainingFilterString = StringUtils.join(remainingWords, " ");
        switch (combiner) {
            case AND:
                return operatorPredicate.and(parsePredicate(remainingFilterString));
            case OR:
                return operatorPredicate.or(parsePredicate(remainingFilterString));
        }
    }

    return operatorPredicate;
}