List of usage examples for org.apache.commons.lang3 ArrayUtils toPrimitive
public static boolean[] toPrimitive(final Boolean[] array)
Converts an array of object Booleans to primitives.
This method returns null for a null input array.
From source file:at.tuwien.mnsa.smssender.SMS.java
/** * Get the PDU representation of a single SMS message (<= 160 chars) * @return //from w w w. j a va 2s.c om */ public SMSRepresentation getMessage() { //https://en.wikipedia.org/wiki/GSM_03.40 //https://stackoverflow.com/questions/12298558/how-to-build-concatenated-sms-pdu-getting-junk-chars //http://mobiletidings.com/2009/02/18/combining-sms-messages/ List<Byte> bytes = new ArrayList<>(); bytes.add((byte) 0x00); //SMSC Information bytes.add((byte) 0x11); //First octed of the SMS-Submit message bytes.add((byte) 0x00); //TP-Message-Reference (0: phone default) int lenRec = this.recipient.length(); bytes.add((byte) lenRec); bytes.add((byte) 0x91); bytes.addAll(Arrays.asList(ArrayUtils.toObject(getSemiOctet(this.recipient)))); bytes.add((byte) 0x00); //TP-PID Protocol Identifier bytes.add((byte) 0x00); //7 bit encoding bytes.add((byte) 0xAA); //validity (4 days) - @TODO: optional? SMSPDUConverter.SMSPDUConversionResult result = SMSPDUConverter.getInstance().getContent(this.text); int lenContent = result.len; //count of septets bytes.add((byte) lenContent); byte[] message = result.message; bytes.addAll(Arrays.asList(ArrayUtils.toObject(message))); String sMessage = DatatypeConverter .printHexBinary(ArrayUtils.toPrimitive(bytes.toArray(new Byte[bytes.size()]))); int smsLen = (sMessage.length() / 2) - 1; SMSRepresentation r = new SMSRepresentation(sMessage, smsLen); return r; }
From source file:com.rockhoppertech.music.midi.js.xml.ModeFactoryXMLHelper.java
/** * Read modes.xml and create {@code Scale instances} from those definitions. *///from w w w . j a v a2 s. c om public static void init() { List<Integer> intervals = null; Scale currentMode = null; String tagContent = null; XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = null; try { reader = factory.createXMLStreamReader(ClassLoader.getSystemResourceAsStream("modes.xml")); } catch (XMLStreamException e) { e.printStackTrace(); return; } try { while (reader.hasNext()) { int event = reader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: String el = reader.getLocalName(); logger.debug("start element '{}'", el); if ("mode".equals(el)) { currentMode = new Scale(); intervals = new ArrayList<>(); } if ("modes".equals(el)) { modeList = new ArrayList<>(); } break; case XMLStreamConstants.CHARACTERS: tagContent = reader.getText().trim(); logger.debug("tagcontent '{}'", tagContent); break; case XMLStreamConstants.END_ELEMENT: switch (reader.getLocalName()) { case "mode": // wow. both guava and commmons to get an int[] array Integer[] array = FluentIterable.from(intervals).toArray(Integer.class); // same as Integer[] array = intervals.toArray(new // Integer[intervals.size()]); int[] a = ArrayUtils.toPrimitive(array); currentMode.setIntervals(a); modeList.add(currentMode); ScaleFactory.registerScale(currentMode); break; case "interval": logger.debug("interval '{}'", tagContent); logger.debug("intervals '{}'", intervals); intervals.add(Integer.parseInt(tagContent)); break; case "name": currentMode.setName(tagContent); break; } break; case XMLStreamConstants.START_DOCUMENT: modeList = new ArrayList<>(); intervals = new ArrayList<>(); break; } } } catch (XMLStreamException e) { logger.error(e.getLocalizedMessage(), e); e.printStackTrace(); } logger.debug("mode list \n{}", modeList); }
From source file:com.spotify.annoy.jni.base.AnnoyIndexImpl.java
private static float[] boxedToPrimitive(List<Float> vector) { return ArrayUtils.toPrimitive(vector.toArray(new Float[0])); }
From source file:bide.core.par.Spot.java
private double[] formatSpot(double[] spot) { int express = 0; ArrayList<Double> expressSpot = new ArrayList<Double>(); for (int i = 0; i < spot.length; i++) { if (!Double.isNaN(spot[i])) { express++;/*w ww. ja v a 2 s .co m*/ expressSpot.add(spot[i]); } } double[] expSpot = ArrayUtils.toPrimitive(expressSpot.toArray(new Double[express])); return expSpot; }
From source file:imperial.modaclouds.monitoring.sda.weka.CreateArff.java
/** * Create arff file given the data//from w w w .ja va2s . c om * * @param timestamps_str the timestamps data * @param data the values of the metrics * @param metricName the metric name * @param fileName the file name to keep the arff file */ public static void create(ArrayList<ArrayList<String>> timestamps_str, ArrayList<ArrayList<String>> data, ArrayList<String> metricName, String fileName) { System.out.println("data: " + data.get(0)); long min_timestamp = Long.valueOf(Collections.min(timestamps_str.get(0))); long max_timestamp = Long.valueOf(Collections.max(timestamps_str.get(0))); for (int i = 1; i < timestamps_str.size(); i++) { long min_temp = Long.valueOf(Collections.min(timestamps_str.get(i))); long max_temp = Long.valueOf(Collections.max(timestamps_str.get(i))); if (max_temp < max_timestamp) { max_timestamp = max_temp; } if (min_temp > min_timestamp) { min_timestamp = min_temp; } } for (int i = 0; i < timestamps_str.size(); i++) { Iterator<String> iter_time = timestamps_str.get(i).iterator(); Iterator<String> iter_data = data.get(i).iterator(); while (iter_time.hasNext()) { long temp_timestamps = Long.valueOf(iter_time.next()); if (temp_timestamps < min_timestamp || temp_timestamps > max_timestamp) { iter_time.remove(); iter_data.next(); iter_data.remove(); } } } double[] timestamps = convertDoubles(timestamps_str.get(0)); double[] targetData = convertDoubles(data.get(0)); double[][] otherData = new double[data.size() - 1][timestamps.length]; for (int i = 0; i < data.size() - 1; i++) { double[] timestamps_temp = convertDoubles(timestamps_str.get(i)); double[] targetData_temp = convertDoubles(data.get(i)); SplineInterpolator spline = new SplineInterpolator(); Map<Double, Integer> map = new TreeMap<Double, Integer>(); for (int j = 0; j < timestamps_temp.length; j++) { map.put(timestamps_temp[j], j); } Collection<Integer> indices = map.values(); int[] indices_int = ArrayUtils.toPrimitive(indices.toArray(new Integer[indices.size()])); double[] timestamps_temp_new = new double[indices_int.length]; double[] targetData_temp_new = new double[indices_int.length]; for (int j = 0; j < indices_int.length; j++) { timestamps_temp_new[j] = timestamps_temp[indices_int[j]]; targetData_temp_new[j] = targetData_temp[indices_int[j]]; } PolynomialSplineFunction polynomical = spline.interpolate(timestamps_temp_new, targetData_temp_new); for (int j = 0; j < timestamps.length; j++) { try { otherData[i][j] = polynomical.value(timestamps[j]); } catch (Exception ex) { otherData[i][j] = targetData_temp_new[j]; } } } ArrayList<Attribute> attributes; Instances dataSet; attributes = new ArrayList<Attribute>(); for (String metric : metricName) { attributes.add(new Attribute(metric)); } dataSet = new Instances("data", attributes, 0); for (int i = 0; i < timestamps.length; i++) { double[] instanceValue1 = new double[dataSet.numAttributes()]; instanceValue1[0] = timestamps[i]; instanceValue1[1] = targetData[i]; for (int j = 0; j < data.size() - 1; j++) { instanceValue1[2 + j] = otherData[j][i]; } DenseInstance denseInstance1 = new DenseInstance(1.0, instanceValue1); dataSet.add(denseInstance1); } ArffSaver saver = new ArffSaver(); saver.setInstances(dataSet); try { String workingDir = System.getProperty("user.dir"); System.out.println("workingDir: " + workingDir); saver.setFile(new File(workingDir + "/" + fileName)); saver.writeBatch(); } catch (IOException e) { e.printStackTrace(); } }
From source file:edu.washington.gs.skyline.model.quantification.FoldChangeDataSet.java
/** * Construct a new FoldChangeDataSet. The first four collections must all have the same number of elements. * The "subjectControls" must have the same number of elements as the number of unique values of "subjects". * @param abundances log2 intensity// ww w .j a v a 2 s .co m * @param features identifiers of the transition that the abundance was measured for. Note that Skyline always sums * the transition intensities before coming in here, the feature values should all be zero. * @param runs integers representing which replicate the value came from * @param subjects identifiers used for combining biological replicates. * @param subjectControls specifies which subject values belong to the control group. */ public FoldChangeDataSet(Collection<Double> abundances, Collection<Integer> features, Collection<Integer> runs, Collection<Integer> subjects, Collection<Boolean> subjectControls) { if (abundances.size() != features.size() || abundances.size() != subjects.size() || abundances.size() != runs.size()) { throw new IllegalArgumentException("Wrong number of rows"); } this.abundances = abundances.stream().mapToDouble(Double::doubleValue).toArray(); this.features = features.stream().mapToInt(Integer::intValue).toArray(); this.runs = runs.stream().mapToInt(Integer::intValue).toArray(); this.subjects = subjects.stream().mapToInt(Integer::intValue).toArray(); this.subjectControls = ArrayUtils.toPrimitive(subjectControls.toArray(new Boolean[subjectControls.size()])); if (this.abundances.length == 0) { featureCount = 0; subjectCount = 0; runCount = 0; } else { if (Arrays.stream(this.features).min().getAsInt() < 0 || Arrays.stream(this.runs).min().getAsInt() < 0 || Arrays.stream(this.subjects).min().getAsInt() < 0) { throw new IllegalArgumentException("Cannot be negative"); } featureCount = Arrays.stream(this.features).max().getAsInt() + 1; subjectCount = Arrays.stream(this.subjects).max().getAsInt() + 1; runCount = Arrays.stream(this.runs).max().getAsInt() + 1; } if (this.subjectControls.length != subjectCount) { throw new IllegalArgumentException("Wrong number of subjects"); } }
From source file:net.sf.sessionAnalysis.SessionVisitorSessionLengthNumActionsStatistics.java
/** * Transforms the aggregated length information in {@link #sessionLengthHistogram} * into a vector. // w w w .j a v a2 s.c o m */ public double[] computeLengthVector() { List<Double> lengths = new LinkedList<Double>(); for (Entry<Integer, AtomicInteger> entry : this.sessionLengthHistogram.entrySet()) { for (int i = 0; i < entry.getValue().get(); i++) { lengths.add((double) entry.getKey()); } } return ArrayUtils.toPrimitive(lengths.toArray(new Double[] {})); }
From source file:net.sf.sessionAnalysis.SessionVisitorSessionLengthNanosStatistics.java
/** * Transforms the aggregated length information in {@link #sessionLengthHistogram} * into a vector. //from w w w . j a v a 2 s . co m */ public double[] computeLengthVector() { List<Double> lengths = new LinkedList<Double>(); for (Entry<Long, AtomicInteger> entry : this.sessionLengthHistogram.entrySet()) { for (int i = 0; i < entry.getValue().get(); i++) { lengths.add((double) entry.getKey()); } } return ArrayUtils.toPrimitive(lengths.toArray(new Double[] {})); }
From source file:edu.stanford.slac.archiverappliance.PB.data.LargePBLineTest.java
@Test public void testLargeLines() throws Exception { // We create vector doubles with a large number of elements; write it out and then test the read. String pvName = ConfigServiceForTests.ARCH_UNIT_TEST_PVNAME_PREFIX + "LargeLineTest" + largeLineTest.getPartitionGranularity(); ArchDBRTypes type = ArchDBRTypes.DBR_WAVEFORM_DOUBLE; short year = TimeUtils.getCurrentYear(); for (int i = 1; i < 7200; i++) { try (BasicContext context = new BasicContext()) { ArrayListEventStream strm = new ArrayListEventStream(1024, new RemotableEventStreamDesc(type, pvName, year)); DBR_TIME_Double retvd = new DBR_TIME_Double(ArrayUtils .toPrimitive(Collections.nCopies(i, Math.sin(i * Math.PI / 3600)).toArray(new Double[0]))); retvd.setTimeStamp(new gov.aps.jca.dbr.TimeStamp(TimeUtils.getStartOfCurrentYearInSeconds() + i)); retvd.setSeverity(1);/*from w w w. ja v a2 s .c o m*/ retvd.setStatus(0); strm.add(new PBVectorDouble(retvd)); largeLineTest.appendData(context, pvName, strm); } catch (Exception ex) { logger.error("Exception appending data " + i, ex); fail(ex.getMessage()); } } Path[] allPaths = PlainPBPathNameUtility.getAllPathsForPV(new ArchPaths(), largeLineTest.getRootFolder(), pvName, ".pb", largeLineTest.getPartitionGranularity(), CompressionMode.NONE, configService.getPVNameToKeyConverter()); assertTrue("testLargeLines returns null for getAllFilesForPV for " + pvName, allPaths != null); assertTrue("testLargeLines returns empty array for getAllFilesForPV for " + pvName, allPaths.length > 0); for (Path destPath : allPaths) { try { PBFileInfo info = new PBFileInfo(destPath); info.getLastEventEpochSeconds(); assertTrue("File validation failed for " + destPath.toAbsolutePath().toString(), ValidatePBFile.validatePBFile(destPath, false)); } catch (Exception ex) { logger.error("Exception parsing file" + destPath.toAbsolutePath().toString(), ex); fail(ex.getMessage()); } } }
From source file:net.sf.gazpachoquest.questionnaire.support.AnswersPopulatorImpl.java
private void populateAnswers(AbstractQuestionDTO question, Map<String, Object> answers) { if (question.getType().hasSubquestions()) { QuestionDTO questionDTO = (QuestionDTO) question; for (SubquestionDTO subquestion : questionDTO.getSubquestions()) { populateAnswers(subquestion, answers); }/*from www . ja v a 2 s. c o m*/ } else { AbstractAnswer answer = null; QuestionType type = question.getType(); String questionCode = question.getCode(); if (!type.hasMultipleAnswers()) { if (QuestionType.S.equals(type) || QuestionType.L.equals(type)) { Object value = answers.get(questionCode); answer = value != null ? TextAnswer.fromValue((String) value) : NoAnswer.create(); } else if (QuestionType.N.equals(type)) { Object value = answers.get(questionCode); answer = value != null ? NumericAnswer.fromValue((Integer) value) : NoAnswer.create(); } else if (QuestionType.T.equals(type)) { Character[] value = (Character[]) answers.get(questionCode); answer = value != null ? new TextAnswer(new String(ArrayUtils.toPrimitive(value))) : NoAnswer.create(); } else { throw new IllegalStateException(type + " not supported"); } } else { List<QuestionOptionDTO> questionOptions = question.getQuestionOptions(); answer = new MultipleAnswer(); for (QuestionOptionDTO questionOptionDTO : questionOptions) { String optionCode = questionOptionDTO.getCode(); String answerCode = new StringBuilder(questionCode).append("_").append(optionCode).toString(); Object value = answers.get(answerCode); // Only checkbox are supported if (type.getAnswerType().isAssignableFrom(Boolean.class)) { ((MultipleAnswer) answer).addAnswer(BooleanAnswer.valueOf(optionCode, (Boolean) value)); } else { throw new IllegalStateException(type + " not supported"); } } } question.setAnswer(answer); } }