List of usage examples for java.util Arrays fill
public static void fill(Object[] a, Object val)
From source file:edu.jhuapl.bsp.detector.EWMASagesDetector.java
private void calculate(double omega) { UCL_R = new double[degFreedomRange]; UCL_Y = new double[degFreedomRange]; sigmaCoeff = new double[degFreedomRange]; deltaSigma = new double[degFreedomRange]; minSigma = new double[degFreedomRange]; int[] degFreedom = new int[data.length]; ////from w w w .j av a 2 s. c o m double term1 = omega / (2.0 - omega), term2, term3; for (int i = 0; i < degFreedomRange; i++) { TDistribution tdist = new TDistribution(i + 1); UCL_R[i] = tdist.inverseCumulativeProbability(1 - threshPValueR); UCL_Y[i] = tdist.inverseCumulativeProbability(1 - threshPValueY); int numBaseline = NUM_FIT_PARAMS + i; term2 = 1.0 / numBaseline; term3 = -2.0 * Math.pow((1 - omega), (numGuardBand + 1.0)) * (1.0 - Math.pow((1 - omega), numBaseline)) / numBaseline; sigmaCoeff[i] = Math.sqrt(term1 + term2 + term3); deltaSigma[i] = (omega / UCL_Y[i]) * (0.1289 - (0.2414 - 0.1826 * Math.pow((1 - omega), 4)) * Math.log(10.0 * threshPValueY)); minSigma[i] = (omega / UCL_Y[i]) * (1.0 + 0.5 * Math.pow((1 - omega), 2)); } // levels = new double[data.length]; Arrays.fill(levels, 0.5); pvalues = new double[data.length]; Arrays.fill(pvalues, 0.5); expectedData = new double[data.length]; Arrays.fill(expectedData, 0); colors = new double[data.length]; r2Levels = new double[data.length]; Arrays.fill(r2Levels, 0); switchFlags = new double[data.length]; Arrays.fill(switchFlags, 0); test_stat = new double[data.length]; Arrays.fill(test_stat, 0); // FilterBaselineZeros3 zf = new FilterBaselineZeros3(); // double smoothedData, sigma, testBase[], baselineData[]; ArrayList<Integer> ndxBaseline = new ArrayList<Integer>(); // initialize the smoothed data smoothedData = 0; for (int i = 1; i < minBaseline + numGuardBand && i < data.length; i++) { smoothedData = omega * data[i] + (1 - omega) * smoothedData; } // initialize the indices of the baseline period for (int i = 0; i < minBaseline - 1; i++) { ndxBaseline.add(new Integer(i)); } // loop through the days on which to make predictions for (int i = minBaseline + numGuardBand; i < data.length; i++) { // smooth the data using an exponentially weighted moving average (EWMA) smoothedData = omega * data[i] + (1 - omega) * smoothedData; // lengthen and advance the baseline period if (ndxBaseline.isEmpty() || ndxBaseline.get(ndxBaseline.size() - 1) + 1 < maxBaseline) { ndxBaseline.add(0, -1); } // advance the indices of the baseline period arrayAdd(ndxBaseline, 1); // remove excess consecutive zeros from the baseline data testBase = dataInd(data, ndxBaseline); if (removeZeros && FilterBaselineZeros3.filterBaselineZerosTest(testBase)) { int[] ndxOK = zf.filterBaselineZeros(testBase); baselineData = dataInd(testBase, ndxOK); } else { baselineData = testBase; } // check the baseline period is filled with zeros; no prediction can be if (!any(baselineData)) { continue; } // the number of degrees of freedom degFreedom[i] = baselineData.length - NUM_FIT_PARAMS; // there are not enough data points in the baseline period; no prediction can be made if (degFreedom[i] < MIN_DEG_FREEDOM) { continue; } // the predicted current value of the data expectedData[i] = mean(baselineData); // calculate the test statistic // the adjusted standard deviation of the baseline data sigma = sigmaCoeff[degFreedom[i] - 1] * std(baselineData) + deltaSigma[degFreedom[i] - 1]; // don't allow values smaller than MinSigma sigma = Math.max(sigma, minSigma[degFreedom[i] - 1]); // the test statistic test_stat[i] = (smoothedData - expectedData[i]) / sigma; if (Math.abs(test_stat[i]) > UCL_R[degFreedom[i] - 1]) { // the current value of the smoothed data is too extreme; adjust this value for the next iteration smoothedData = expectedData[i] + Math.signum(test_stat[i]) * UCL_R[degFreedom[i] - 1] * sigma; } } for (int i = 0; i < data.length; i++) { if (Math.abs(test_stat[i]) > 0.0) { TDistribution tdist = new TDistribution(degFreedom[i]); pvalues[i] = 1 - tdist.cumulativeProbability(test_stat[i]); levels[i] = pvalues[i]; } } }
From source file:com.neophob.sematrix.core.generator.Textwriter.java
/** * create image./*from w w w. ja v a 2 s . c om*/ * * @param text the text */ public void createTextImage(String text) { //only load if needed if (StringUtils.equals(text, this.text)) { return; } this.text = text; BufferedImage img = new BufferedImage(TEXT_BUFFER_X_SIZE, internalBufferYSize, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = img.createGraphics(); FontRenderContext frc = g2.getFontRenderContext(); TextLayout layout = new TextLayout(text, font, frc); Rectangle2D rect = layout.getBounds(); int h = (int) (0.5f + rect.getHeight()); //head and tailing space maxXPos = (int) (0.5f + rect.getWidth()) + 2 * internalBufferXSize; int ypos = internalBufferYSize - (internalBufferYSize - h) / 2; img = new BufferedImage(maxXPos, internalBufferYSize, BufferedImage.TYPE_BYTE_GRAY); g2 = img.createGraphics(); g2.setColor(new Color(128)); g2.setFont(font); g2.setClip(0, 0, maxXPos, internalBufferYSize); g2.drawString(text, internalBufferXSize, ypos); DataBufferByte dbi = (DataBufferByte) img.getRaster().getDataBuffer(); byte[] textBuffer = dbi.getData(); g2.dispose(); xofs = 0; textAsImage = new int[maxXPos * internalBufferYSize]; for (int i = 0; i < textAsImage.length; i++) { if (textBuffer[i] > 10) { textAsImage[i] = 127; } else { textAsImage[i] = 0; } } //clear internalbuffer Arrays.fill(this.internalBuffer, 0); }
From source file:com.webcohesion.ofx4j.io.TestBaseOFXReader.java
/** * tests using sax to parse an OFX doc.// w w w. j a v a 2 s. c o m */ public void testVersion2() throws Exception { BaseOFXReader reader = new BaseOFXReader() { protected void parseV1FromFirstElement(Reader reader) throws IOException, OFXParseException { fail(); } }; final Map<String, String> headers = new HashMap<String, String>(); final Stack<Map<String, Object>> aggregateStack = new Stack<Map<String, Object>>(); TreeMap<String, Object> root = new TreeMap<String, Object>(); aggregateStack.push(root); reader.setContentHandler(new DefaultHandler() { @Override public void onHeader(String name, String value) { LOG.debug(name + ":" + value); headers.put(name, value); } @Override public void onElement(String name, String value) { char[] tabs = new char[aggregateStack.size() * 2]; Arrays.fill(tabs, ' '); LOG.debug(new String(tabs) + name + "=" + value); aggregateStack.peek().put(name, value); } @Override public void startAggregate(String aggregateName) { char[] tabs = new char[aggregateStack.size() * 2]; Arrays.fill(tabs, ' '); LOG.debug(new String(tabs) + aggregateName + " {"); TreeMap<String, Object> aggregate = new TreeMap<String, Object>(); aggregateStack.peek().put(aggregateName, aggregate); aggregateStack.push(aggregate); } @Override public void endAggregate(String aggregateName) { aggregateStack.pop(); char[] tabs = new char[aggregateStack.size() * 2]; Arrays.fill(tabs, ' '); LOG.debug(new String(tabs) + "}"); } }); reader.parse(BaseOFXReader.class.getResourceAsStream("example-response.ofx2")); assertEquals(5, headers.size()); assertEquals(1, aggregateStack.size()); assertSame(root, aggregateStack.pop()); }
From source file:egat.cli.strategyregret.StrategyRegretCommandHandler.java
protected void processStrategicGame(MutableStrategicGame game) throws CommandProcessingException { try {//from ww w.ja v a 2 s.c o m Profile profile = null; if (uniform) { Player[] players = game.players().toArray(new Player[0]); Strategy[] strategies = new Strategy[players.length]; for (int i = 0; i < players.length; i++) { Action[] actions = ((Set<Action>) game.getActions(players[i])).toArray(new Action[0]); Number[] distribution = new Number[actions.length]; Arrays.fill(distribution, 1.0 / distribution.length); strategies[i] = Games.createStrategy(actions, distribution); } profile = Games.createProfile(players, strategies); } else { InputStream inputStream = null; inputStream = new FileInputStream(profilePath); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); ProfileHandler handler = new ProfileHandler(); parser.parse(inputStream, handler); profile = handler.getProfile(); } findRegret(profile, game); } catch (NonexistentPayoffException e) { System.err.println(String.format("Could not calculate regret. %s", e.getMessage())); } catch (FileNotFoundException e) { throw new CommandProcessingException(e); } catch (ParserConfigurationException e) { throw new CommandProcessingException(e); } catch (SAXException e) { throw new CommandProcessingException(e); } catch (IOException e) { throw new CommandProcessingException(e); } }
From source file:de.csdev.ebus.command.datatypes.EBusAbstractType.java
/** * Returns the replace value or <code>null</code> * * @return/*from w w w. j a v a2 s. c om*/ */ public byte[] getReplaceValue() { int length = getTypeLength(); if (replaceValue == null || replaceValue.length == 0) { replaceValue = new byte[length]; Arrays.fill(replaceValue, (byte) 0xFF); } return replaceValue; }
From source file:com.quest.orahive.HiveJdbcClient.java
private static void showWelcomeMessage() { String msg1 = String.format("Using %s %s", Constants.ORAHIVE_PRODUCT_NAME, Utilities.getOraHiveVersion()); String msg2 = "Copyright 2011 Quest Software, Inc."; String msg3 = "ALL RIGHTS RESERVED."; int longestMessage = Math.max(msg1.length(), msg2.length()); msg1 = Utilities.padRight(msg1, longestMessage); msg2 = Utilities.padRight(msg2, longestMessage); msg3 = Utilities.padRight(msg3, longestMessage); char[] asterisks = new char[longestMessage + 8]; Arrays.fill(asterisks, '*'); String msg = String.format( "\n" + "%1$s\n" + "*** %2$s ***\n" + "*** %3$s ***\n" + "*** %4$s ***\n" + "%1$s", new String(asterisks), msg1, msg2, msg3); LOG.info(msg);// www. j a v a 2 s . c o m }
From source file:edu.uci.ics.hivesterix.serde.lazy.LazyStruct.java
/** * Parse the byte[] and fill fieldStart, fieldLength, fieldInited and * fieldIsNull./*from w w w. j a v a 2s. c om*/ */ private void parse() { List<? extends StructField> fieldRefs = ((StructObjectInspector) oi).getAllStructFieldRefs(); if (fields == null) { fields = new LazyObject[fieldRefs.size()]; for (int i = 0; i < fields.length; i++) { ObjectInspector insp = fieldRefs.get(i).getFieldObjectInspector(); fields[i] = insp == null ? null : LazyFactory.createLazyObject(insp); } fieldInited = new boolean[fields.length]; fieldIsNull = new boolean[fields.length]; fieldStart = new int[fields.length]; fieldLength = new int[fields.length]; } /** * Please note that one null byte is followed by eight fields, then more * null byte and fields. */ int fieldId = 0; int structByteEnd = start + length; byte nullByte = bytes[start]; int lastFieldByteEnd = start + 1; // Go through all bytes in the byte[] for (int i = 0; i < fields.length; i++) { fieldIsNull[i] = true; if ((nullByte & (1 << (i % 8))) != 0) { fieldIsNull[i] = false; LazyUtils.checkObjectByteInfo(fieldRefs.get(i).getFieldObjectInspector(), bytes, lastFieldByteEnd, recordInfo); fieldStart[i] = lastFieldByteEnd + recordInfo.elementOffset; fieldLength[i] = recordInfo.elementSize; lastFieldByteEnd = fieldStart[i] + fieldLength[i]; } // count how many fields are there if (lastFieldByteEnd <= structByteEnd) { fieldId++; } // next byte is a null byte if there are more bytes to go if (7 == (i % 8)) { if (lastFieldByteEnd < structByteEnd) { nullByte = bytes[lastFieldByteEnd]; lastFieldByteEnd++; } else { // otherwise all null afterwards nullByte = 0; lastFieldByteEnd++; } } } // Extra bytes at the end? if (!extraFieldWarned && lastFieldByteEnd < structByteEnd) { extraFieldWarned = true; LOG.warn("Extra bytes detected at the end of the row! Ignoring similar " + "problems."); } // Missing fields? if (!missingFieldWarned && lastFieldByteEnd > structByteEnd) { missingFieldWarned = true; LOG.warn("Missing fields! Expected " + fields.length + " fields but " + "only got " + fieldId + "! Ignoring similar problems."); } Arrays.fill(fieldInited, false); parsed = true; }
From source file:com.google.uzaygezen.core.hbase.HBaseQueryTest.java
/** * With more than 62 bits (using {@link BigInteger} rather than plain * {@link Long}) and without any caching rollup version of the data * {@link BoundedRollup}, this way of building the queries is likely to be * quite slow, but it shows off the capability of perform queries of * non-cached arbitrary-precision data./*from w w w. jav a 2s . c o m*/ */ @Test public void queryHBase() throws IOException, InterruptedException { MockHTable table = MockHTable.create(); final byte[] family = "FAMILY".getBytes(Charsets.ISO_8859_1); /* * We choose not to store the coordinates themselves, since storing the * Hilbert index is sufficient to recover the coordinate values. So let's * use a dummy column. */ final byte[][] qualifiers = { "NICE".getBytes(Charsets.ISO_8859_1), }; MultiDimensionalSpec spec = new MultiDimensionalSpec(Ints.asList(30, 10, 25)); // Add some data. Random rnd = new Random(TestUtils.SEED); int[][] data = generateData(spec, 1 << 16, rnd); SpaceFillingCurve sfc = new CompactHilbertCurve(spec); logger.log(Level.INFO, "Populating table with up to {0} rows.", data.length); populateTable(family, qualifiers, spec, data, sfc, table); int cacheSize = 1 << 8; logger.log(Level.INFO, "Building cache of size {0}.", cacheSize); // The cache is optional. Map<Pow2LengthBitSetRange, NodeValue<BigIntegerContent>> rolledupMap = createRolledupCache(table, spec, sfc, cacheSize); logger.log(Level.INFO, "Constructed cache of actual size {0}.", rolledupMap.size()); for (int trial = 0; trial < 1; ++trial) { logger.log(Level.INFO, "trial={0}", trial); int[] maxLengthPerDimension = new int[spec.getBitsPerDimension().size()]; for (boolean useCache : new boolean[] { false, true }) { int m = useCache ? 256 : 32; /* * For testing purposes limit the range size to m values for each * dimension to speed up query computation. In practice, query volume * should be enforced to be small, and when a certain query volume is * exceeded, a full table scan will probably be faster anyway. */ Arrays.fill(maxLengthPerDimension, m); int[][] ranges = generateRanges(spec, maxLengthPerDimension, rnd); logger.log(Level.INFO, "ranges={0}", Arrays.deepToString(ranges)); // Limit the maximum number of ranges. int maxRanges = 1 + rnd.nextInt(32); List<int[]> actual = queryAndFilter(table, spec, sfc, ranges, maxRanges, useCache ? rolledupMap : null); List<int[]> expected = uniq(fullScanQuery(data, sfc, ranges)); logger.log(Level.INFO, "expected.size()={0}", expected.size()); Assert.assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); ++i) { Assert.assertArrayEquals(expected.get(i), actual.get(i)); } } } }
From source file:com.breadwallet.tools.security.RequestHandler.java
public static boolean tryBitIdUri(final Activity app, String uri, JSONObject jsonBody) { if (uri == null) return false; boolean isBitUri = false; URI bitIdUri = null;//from www . j ava2 s . com try { bitIdUri = new URI(uri); if ("bitid".equals(bitIdUri.getScheme())) isBitUri = true; } catch (URISyntaxException e) { e.printStackTrace(); } _bitUri = uri; if (jsonBody != null) { try { _authString = jsonBody.getString("prompt_string"); _bitCallback = jsonBody.getString("bitid_url"); _index = jsonBody.getInt("bitid_index"); _strToSign = jsonBody.getString("string_to_sign"); } catch (JSONException e) { e.printStackTrace(); } } else if (bitIdUri != null && "bitid".equals(bitIdUri.getScheme())) { if (app == null) { Log.e(TAG, "tryBitIdUri: app is null, returning true still"); return isBitUri; } //ask for phrase, will system auth if needed _authString = "BitID Authentication Request"; } // Log.e(TAG, "tryBitIdUri: _bitUri: " + _bitUri); // Log.e(TAG, "tryBitIdUri: _strToSign: " + _strToSign); // Log.e(TAG, "tryBitIdUri: _index: " + _index); new Thread(new Runnable() { @Override public void run() { byte[] phrase = null; try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } Uri tmpUri = Uri.parse(_bitUri); try { phrase = KeyStoreManager.getKeyStorePhrase(app, REQUEST_PHRASE_BITID); ((BreadWalletApp) app.getApplicationContext()).promptForAuthentication(app, AUTH_FOR_BIT_ID, null, tmpUri.getHost(), _authString, null, false); } catch (BRKeystoreErrorException e) { //asked the system, no need for local auth e.printStackTrace(); } finally { //free the phrase if (phrase != null) Arrays.fill(phrase, (byte) 0); } } }).start(); return isBitUri; }