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

The following examples show how to use org.apache.commons.lang.ArrayUtils#subarray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SpectralMethods.java    From egads with GNU General Public License v3.0 6 votes vote down vote up
public static RealMatrix createHankelMatrix(RealMatrix data, int windowSize) {

        int n = data.getRowDimension();
        int m = data.getColumnDimension();
        int k = n - windowSize + 1;

        RealMatrix res = MatrixUtils.createRealMatrix(k, m * windowSize);
        double[] buffer = {};

        for (int i = 0; i < n; ++i) {
            double[] row = data.getRow(i);
            buffer = ArrayUtils.addAll(buffer, row);

            if (i >= windowSize - 1) {
                RealMatrix mat = MatrixUtils.createRowRealMatrix(buffer);
                res.setRowMatrix(i - windowSize + 1, mat);
                buffer = ArrayUtils.subarray(buffer, m, buffer.length);
            }
        }

        return res;
    }
 
Example 2
Source File: SerialMessage.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Constructor. Creates a new instance of the SerialMessage class from a
 * specified buffer, and subsequently sets the node ID.
 *
 * @param nodeId the node the message is destined for
 * @param buffer the buffer to create the SerialMessage from.
 */
public SerialMessage(int nodeId, byte[] buffer) {
    logger.trace("NODE {}: Creating new SerialMessage from buffer = {}", nodeId, SerialMessage.bb2hex(buffer));
    messageLength = buffer.length - 2; // buffer[1];
    byte messageCheckSumm = calculateChecksum(buffer);
    byte messageCheckSummReceived = buffer[messageLength + 1];
    if (messageCheckSumm == messageCheckSummReceived) {
        logger.trace("NODE {}: Checksum matched", nodeId);
        isValid = true;
    } else {
        logger.trace("NODE {}: Checksum error. Calculated = 0x%02X, Received = 0x%02X", nodeId, messageCheckSumm,
                messageCheckSummReceived);
        isValid = false;
        return;
    }
    this.priority = SerialMessagePriority.High;
    this.messageType = buffer[2] == 0x00 ? SerialMessageType.Request : SerialMessageType.Response;
    this.messageClass = SerialMessageClass.getMessageClass(buffer[3] & 0xFF);
    this.messagePayload = ArrayUtils.subarray(buffer, 4, messageLength + 1);
    this.messageNode = nodeId;
    logger.trace("NODE {}: Message payload = {}", getMessageNode(), SerialMessage.bb2hex(messagePayload));
}
 
Example 3
Source File: LengthCodedStringReader.java    From canal with Apache License 2.0 6 votes vote down vote up
public String readLengthCodedString(byte[] data) throws IOException {
    byte[] lengthBytes = ByteHelper.readBinaryCodedLengthBytes(data, getIndex());
    long length = ByteHelper.readLengthCodedBinary(data, getIndex());
    setIndex(getIndex() + lengthBytes.length);
    if (ByteHelper.NULL_LENGTH == length) {
        return null;
    }

    try {
        return new String(ArrayUtils.subarray(data, getIndex(), (int) (getIndex() + length)),
            encoding == null ? CODE_PAGE_1252 : encoding);
    } finally {
        setIndex((int) (getIndex() + length));
    }

}
 
Example 4
Source File: SerialMessage.java    From fuchsia with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor. Creates a new instance of the SerialMessage class from a
 * specified buffer, and subsequently sets the node ID.
 * @param nodeId the node the message is destined for
 * @param buffer the buffer to create the SerialMessage from.
 */
public SerialMessage(int nodeId, byte[] buffer) {
	logger.debug("Creating new SerialMessage from buffer = " + SerialMessage.bb2hex(buffer));
	messageLength = buffer.length - 2; // buffer[1];
	byte messageCheckSumm = calculateChecksum(buffer);
	byte messageCheckSummReceived = buffer[messageLength+1];
	logger.debug(String.format("Message checksum calculated = 0x%02X, received = 0x%02X", messageCheckSumm, messageCheckSummReceived));
	if (messageCheckSumm == messageCheckSummReceived) {
		logger.trace("Checksum matched");
		isValid = true;
	} else {
		logger.trace("Checksum error");
		isValid = false;
		return;
	}
	this.messageType = buffer[2] == 0x00 ? SerialMessageType.Request : SerialMessageType.Response;;
	this.messageClass = SerialMessageClass.getMessageClass(buffer[3] & 0xFF);
	this.messagePayload = ArrayUtils.subarray(buffer, 4, messageLength + 1);
	this.messageNode = nodeId;
	logger.debug("Message Node ID = " + getMessageNode());
	logger.debug("Message payload = " + SerialMessage.bb2hex(messagePayload));
}
 
Example 5
Source File: GetVersionMessageClass.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean handleResponse(ZWaveController zController, SerialMessage lastSentMessage,
        SerialMessage incomingMessage) {
    ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);
    zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));
    logger.debug(String.format("Got MessageGetVersion response. Version = %s, Library Type = 0x%02X", zWaveVersion,
            ZWaveLibraryType));

    checkTransactionComplete(lastSentMessage, incomingMessage);

    return true;
}
 
Example 6
Source File: AbstractEndToEndCrypto.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void dumpMessage(byte[] paramArrayOfByte, String msg) {
   if (config.getBooleanProperty("be.ehealth.technicalconnector.service.etee.cryptoimpl.dump_messages", Boolean.FALSE).booleanValue()) {
      int maxNumberOfBytesToLog = config.getIntegerProperty("be.ehealth.technicalconnector.service.etee.cryptoimpl.dump_first_chars", Integer.valueOf(50)).intValue();
      String stringToLog;
      if (paramArrayOfByte.length < maxNumberOfBytesToLog) {
         stringToLog = new String(paramArrayOfByte);
      } else {
         stringToLog = new String(ArrayUtils.subarray(paramArrayOfByte, 0, maxNumberOfBytesToLog - 1));
      }

      LOG.debug(msg + ": " + stringToLog);
   }

}
 
Example 7
Source File: AbstractEndToEndCrypto.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void dumpMessage(byte[] paramArrayOfByte, String msg) {
   if (config.getBooleanProperty("org.taktik.connector.technical.service.etee.cryptoimpl.dump_messages", Boolean.FALSE)) {
      int maxNumberOfBytesToLog = config.getIntegerProperty("org.taktik.connector.technical.service.etee.cryptoimpl.dump_first_chars", Integer.valueOf(50));
      String stringToLog;
      if (paramArrayOfByte.length < maxNumberOfBytesToLog) {
         stringToLog = new String(paramArrayOfByte);
      } else {
         stringToLog = new String(ArrayUtils.subarray(paramArrayOfByte, 0, maxNumberOfBytesToLog - 1));
      }

      LOG.debug(msg + ": " + stringToLog);
   }

}
 
Example 8
Source File: TimelineMetricMetadataManager.java    From ambari-metrics with Apache License 2.0 5 votes vote down vote up
public String getMetricNameFromUuid(byte[] uuid) {

    byte[] metricUuid = uuid;
    if (uuid.length == TIMELINE_METRIC_UUID_LENGTH + HOSTNAME_UUID_LENGTH) {
      metricUuid = ArrayUtils.subarray(uuid, 0, TIMELINE_METRIC_UUID_LENGTH);
    }

    TimelineMetricMetadataKey key = uuidKeyMap.get(new TimelineMetricUuid(metricUuid));
    return key != null ? key.getMetricName() : null;
  }
 
Example 9
Source File: EmoService.java    From emodb with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {

        ArgumentParser parser = ArgumentParsers.newArgumentParser("emoparser");
        parser.addArgument("server").required(true).help("server");
        parser.addArgument("emo-config").required(true).help("config.yaml");
        parser.addArgument("config-ddl").required(true).help("config-ddl.yaml");

        // Get the path to config-ddl
        String[] first3Args = (String[]) ArrayUtils.subarray(args, 0, Math.min(args.length, 3));
        Namespace result = parser.parseArgs(first3Args);

        // Remove config-ddl arg
        new EmoService(result.getString("config-ddl"), new File(result.getString("emo-config")))
                .run((String[]) ArrayUtils.remove(args, 2));
    }
 
Example 10
Source File: RowKeyDesc.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private void initColumnsNeedIndex() {
    int[] tmp = new int[100];
    int x = 0;
    for (int i = 0, n = rowkeyColumns.length; i < n; i++) {
        if ("true".equalsIgnoreCase(rowkeyColumns[i].getIndex()) && rowkeyColumns[i].isUsingDictionary()) {
            tmp[x] = i;
            x++;
        }
    }

    columnsNeedIndex = ArrayUtils.subarray(tmp, 0, x);
}
 
Example 11
Source File: RowKeyDesc.java    From kylin with Apache License 2.0 5 votes vote down vote up
private void initColumnsNeedIndex() {
    int[] tmp = new int[100];
    int x = 0;
    for (int i = 0, n = rowkeyColumns.length; i < n; i++) {
        if ("true".equalsIgnoreCase(rowkeyColumns[i].getIndex()) && rowkeyColumns[i].isUsingDictionary()) {
            tmp[x] = i;
            x++;
        }
    }

    columnsNeedIndex = ArrayUtils.subarray(tmp, 0, x);
}
 
Example 12
Source File: SelectionModel.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
public int[] getFullySelectedRows(int rowWidth) {
	final Set<Range> selectedRows = getSelectedRows();
	int[] fullySelectedRows = new int[getSelectedRowCount()];
	int index = 0;

	for (Range rowRange : selectedRows) {
		for (int i = rowRange.start; i < rowRange.end; i++) {
			if (isRowFullySelected(i, rowWidth)) {
				fullySelectedRows[index++] = i;
			}
		}
	}

	return index > 0 ? ArrayUtils.subarray(fullySelectedRows, 0, index) : new int[0];
}
 
Example 13
Source File: SelectionModel.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the positions of all fully selected columns.
 * @param fullySelectedColumnRowCount the number of rows in a fully selected column
 * @return
 */
public int[] getFullySelectedColumns(int fullySelectedColumnRowCount) {
	final int[] selectedColumns = getSelectedColumns();
	int[] columnsToHide = new int[selectedColumns.length];
	int index = 0;
	for (int columnPosition : selectedColumns) {
		if (isColumnFullySelected(columnPosition, fullySelectedColumnRowCount)) {
			columnsToHide[index++] = columnPosition;
		}
	}

	return index > 0  ? ArrayUtils.subarray(columnsToHide, 0, index) : new int[0];
}
 
Example 14
Source File: DcCoreUtils.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * @param uriInfo UriInfo
 * @param baseLevelsAbove 何階層上のパスをルートとするか
 * @param add 追加パス情報
 */
public DcUriInfo(final UriInfo uriInfo, final int baseLevelsAbove, final String add) {
    this.core = uriInfo;
    String reqUrl = uriInfo.getRequestUri().toASCIIString();
    if (reqUrl.endsWith("/")) {
        reqUrl = reqUrl.substring(0, reqUrl.length() - 1);
    }
    String[] urlSplitted = reqUrl.split("/");
    urlSplitted = (String[]) ArrayUtils.subarray(urlSplitted, 0, urlSplitted.length - baseLevelsAbove);
    reqUrl = StringUtils.join(urlSplitted, "/") + "/";
    if (add != null && add.length() != 0) {
        reqUrl = reqUrl + add + "/";
    }
    this.baseUriBuilder = UriBuilder.fromUri(reqUrl);
}
 
Example 15
Source File: BandPassActivityProfileUnitTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private double[] bandPassInOnePass(final BandPassActivityProfile profile, final double[] activeProbArray) {
    final double[] bandPassProbArray = new double[activeProbArray.length];

    // apply the band pass filter for activeProbArray into filteredProbArray
    final double[] GaussianKernel = profile.getKernel();
    for( int iii = 0; iii < activeProbArray.length; iii++ ) {
        final double[] kernel = ArrayUtils.subarray(GaussianKernel, Math.max(profile.getFilteredSize() - iii, 0), Math.min(GaussianKernel.length, profile.getFilteredSize() + activeProbArray.length - iii));
        final double[] activeProbSubArray = ArrayUtils.subarray(activeProbArray, Math.max(0,iii - profile.getFilteredSize()), Math.min(activeProbArray.length,iii + profile.getFilteredSize() + 1));
        bandPassProbArray[iii] = MathUtils.dotProduct(activeProbSubArray, kernel);
    }

    return bandPassProbArray;
}
 
Example 16
Source File: AbstractEndToEndCrypto.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void dumpMessage(byte[] paramArrayOfByte, String msg) {
   if (config.getBooleanProperty("be.ehealth.technicalconnector.service.etee.cryptoimpl.dump_messages", Boolean.FALSE)) {
      int maxNumberOfBytesToLog = config.getIntegerProperty("be.ehealth.technicalconnector.service.etee.cryptoimpl.dump_first_chars", 50);
      String stringToLog;
      if (paramArrayOfByte.length < maxNumberOfBytesToLog) {
         stringToLog = new String(paramArrayOfByte);
      } else {
         stringToLog = new String(ArrayUtils.subarray(paramArrayOfByte, 0, maxNumberOfBytesToLog - 1));
      }

      LOG.debug(msg + ": " + stringToLog);
   }

}
 
Example 17
Source File: SelectionModel.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the positions of all fully selected columns.
 * @param fullySelectedColumnRowCount the number of rows in a fully selected column
 * @return
 */
public int[] getFullySelectedColumns(int fullySelectedColumnRowCount) {
	final int[] selectedColumns = getSelectedColumns();
	int[] columnsToHide = new int[selectedColumns.length];
	int index = 0;
	for (int columnPosition : selectedColumns) {
		if (isColumnFullySelected(columnPosition, fullySelectedColumnRowCount)) {
			columnsToHide[index++] = columnPosition;
		}
	}

	return index > 0  ? ArrayUtils.subarray(columnsToHide, 0, index) : new int[0];
}
 
Example 18
Source File: AbstractEndToEndCrypto.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void dumpMessage(byte[] paramArrayOfByte, String msg) {
   if (config.getBooleanProperty("be.ehealth.technicalconnector.service.etee.cryptoimpl.dump_messages", Boolean.FALSE)) {
      int maxNumberOfBytesToLog = config.getIntegerProperty("be.ehealth.technicalconnector.service.etee.cryptoimpl.dump_first_chars", 50);
      String stringToLog;
      if (paramArrayOfByte.length < maxNumberOfBytesToLog) {
         stringToLog = new String(paramArrayOfByte);
      } else {
         stringToLog = new String(ArrayUtils.subarray(paramArrayOfByte, 0, maxNumberOfBytesToLog - 1));
      }

      LOG.debug(msg + ": " + stringToLog);
   }

}
 
Example 19
Source File: HashBasedUuidGenStrategy.java    From ambari-metrics with Apache License 2.0 4 votes vote down vote up
/**
 * Computes the UUID for a timelineClusterMetric.
 * @param timelineClusterMetric
 * @param maxLength
 * @return byte array of length 'maxlength'
 */
@Override
public byte[] computeUuid(TimelineClusterMetric timelineClusterMetric, int maxLength) {

  int metricNameUuidLength = 12;
  String instanceId = timelineClusterMetric.getInstanceId();

  if ((StringUtils.isEmpty(instanceId))) {
    metricNameUuidLength = 14;
  }

  String metricName = timelineClusterMetric.getMetricName();

  //Compute the individual splits.
  String[] splits = getIndidivualSplits(metricName);

  /*
  Compute the weighted ascii sum of every split in the metric name. (asciiSum += (int) splits[s].charAt(i))
  These weighted sums are 'appended' to get the unique ID for metric name.
   */
  StringBuilder splitSums = new StringBuilder();
  long totalAsciiSum = 0l;
  if (splits.length > 0) {
    for (String split : splits) {
      int asciiSum = 0;
      for (int i = 0; i < split.length(); i++) {
        asciiSum += ((i + 1) * (int) split.charAt(i)); //weighted sum for split.
      }
      splitSums.append(asciiSum); //Append the sum to the array of sums.
      totalAsciiSum += asciiSum; //Parity Sum
    }
  }

  String splitSumString = totalAsciiSum + splitSums.reverse().toString(); //Reverse and attach parity sum.
  int splitLength = splitSumString.length();

  //Compute a unique metric seed for the stemmed metric name
  String stemmedMetric = stem(metricName);
  long metricSeed = 100123456789L;
  metricSeed += computeWeightedNumericalAsciiSum(stemmedMetric);
  //Reverse the computed seed to get a metric UUID portion which is used optionally.
  byte[] metricSeedBytes = StringUtils.reverse(String.valueOf(metricSeed)).getBytes();

  int seedLength = (int)(0.25 * metricNameUuidLength);
  int sumLength = metricNameUuidLength - seedLength;
  if (splitLength < sumLength) {
    sumLength = splitLength;
    seedLength = metricNameUuidLength - sumLength;
  }

  byte[] metricUuidPortion = ArrayUtils.addAll(
    ArrayUtils.subarray(splitSumString.getBytes(), 0, sumLength)
    , ArrayUtils.subarray(metricSeedBytes, 0, seedLength));

  /*
    For appId and instanceId the logic is similar. Use a seed integer to start with and compute ascii sum.
    Based on required length, use a suffix of the computed uuid.
   */
  String appId = timelineClusterMetric.getAppId();
  int appidSeed = 11;
  for (int i = 0; i < appId.length(); i++) {
    appidSeed += appId.charAt(i);
  }
  String appIdSeedStr = String.valueOf(appidSeed);
  byte[] appUuidPortion = ArrayUtils.subarray(appIdSeedStr.getBytes(), appIdSeedStr.length() - 2, appIdSeedStr.length());

  if (StringUtils.isNotEmpty(instanceId)) {
    byte[] instanceUuidPortion = new byte[2];
    ByteBuffer buffer = ByteBuffer.allocate(4);
    int instanceIdSeed = 1489;
    for (int i = 0; i < appId.length(); i++) {
      instanceIdSeed += ((i+1) * appId.charAt(i));
    }
    buffer.putInt(instanceIdSeed);
    ArrayUtils.subarray(buffer.array(), 2, 4);
    // Concatenate all UUIDs together (metric uuid + appId uuid + instanceId uuid)
    return ArrayUtils.addAll(ArrayUtils.addAll(metricUuidPortion, appUuidPortion), instanceUuidPortion);
  }

  return ArrayUtils.addAll(metricUuidPortion, appUuidPortion);
}
 
Example 20
Source File: ZWaveController.java    From fuchsia with Apache License 2.0 4 votes vote down vote up
/**
 * Handles the response of the getVersion request.
 * @param incomingMessage the response message to process.
 */
private void handleGetVersionResponse(SerialMessage incomingMessage) {
	this.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);
	this.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));
	logger.debug(String.format("Got MessageGetVersion response. Version = %s, Library Type = 0x%02X", zWaveVersion, ZWaveLibraryType));
}