code
stringlengths
73
34.1k
label
stringclasses
1 value
public FunctionInfo getFunction(String name) { if (functions == null || functions.length == 0) { System.err.println("No functions"); return null; } for (int i=0; i < functions.length; i++) { if (functions[i].getName().equals(name)) { return f...
java
protected int readSamples () throws IOException { int samples; while ((samples = _dsp.synthesis_pcmout(_pcm, _offsets)) <= 0) { if (samples == 0 && !readPacket()) { return 0; } if (_block.synthesis(_packet) == 0) { _dsp.synt...
java
protected boolean readPacket () throws IOException { int result; while ((result = _stream.packetout(_packet)) != 1) { if (result == 0 && !readPage()) { return false; } } return true; }
java
protected boolean readPage () throws IOException { int result; while ((result = _sync.pageout(_page)) != 1) { if (result == 0 && !readChunk()) { return false; } } _stream.pagein(_page); return true; }
java
protected boolean readChunk () throws IOException { int offset = _sync.buffer(BUFFER_SIZE); int bytes = _in.read(_sync.data, offset, BUFFER_SIZE); if (bytes > 0) { _sync.wrote(bytes); return true; } return false; }
java
public static TrimmedTileSet trimTileSet (TileSet source, OutputStream destImage) throws IOException { return trimTileSet(source, destImage, FastImageIO.FILE_SUFFIX); }
java
public boolean sourceIsReady () { // make a note of our source's last modification time _sourceLastMod = _source.lastModified(); // if we are unpacking files, the time to do so is now if (_unpacked != null && _unpacked.lastModified() != _sourceLastMod) { try { ...
java
public void wipeBundle (boolean deleteJar) { // clear out our cache directory if (_cache != null) { FileUtil.recursiveClean(_cache); } // delete our unpack stamp file if (_unpacked != null) { _unpacked.delete(); } // clear out any .ja...
java
public File getResourceFile (String path) throws IOException { if (resolveJarFile()) { return null; } // if we have been unpacked, return our unpacked file if (_cache != null) { File cfile = new File(_cache, path); if (cfile.exists()) { ...
java
public boolean containsResource (String path) { try { if (resolveJarFile()) { return false; } return (_jarSource.getJarEntry(path) != null); } catch (IOException ioe) { return false; } }
java
protected boolean resolveJarFile () throws IOException { // if we don't yet have our resource bundle's last mod time, we // have not yet been notified that it is ready if (_sourceLastMod == -1) { return true; } if (!_source.exists()) { throw n...
java
public static File getCacheDir () { if (_tmpdir == null) { String tmpdir = System.getProperty("java.io.tmpdir"); if (tmpdir == null) { log.info("No system defined temp directory. Faking it."); tmpdir = System.getProperty("user.home"); } ...
java
public static void setCacheDir (File tmpdir) { String rando = Long.toHexString((long)(Math.random() * Long.MAX_VALUE)); _tmpdir = new File(tmpdir, "narcache_" + rando); if (!_tmpdir.exists()) { if (_tmpdir.mkdirs()) { log.debug("Created narya temp cache directory ...
java
protected static String stripSuffix (String path) { if (path.endsWith(".jar")) { return path.substring(0, path.length()-4); } else { // we have to change the path somehow return path + "-cache"; } }
java
public static <T> CloseableIterator<T> distinct(final CloseableIterator<T> iterator) { return wrap(Iterators2.distinct(iterator), iterator); }
java
public Stream<RangeWithCount> stream() { return buckets_.stream() .map(bucket -> new RangeWithCount(bucket.getRange(), bucket.getEvents())); }
java
public Optional<Double> avg() { if (isEmpty()) return Optional.empty(); return Optional.of(sum() / getEventCount()); }
java
public double sum() { return buckets_.stream() .mapToDouble(b -> b.getRange().getMidPoint() * b.getEvents()) .sum(); }
java
public double get(double index) { ListIterator<Bucket> b = buckets_.listIterator(0); ListIterator<Bucket> e = buckets_.listIterator(buckets_.size()); while (b.nextIndex() < e.previousIndex()) { final ListIterator<Bucket> mid = buckets_.listIterator(b.nextIndex() / 2 + e.nextIndex() ...
java
public Histogram modifyEventCounters(BiFunction<Range, Double, Double> fn) { return new Histogram(stream() .map(entry -> { entry.setCount(fn.apply(entry.getRange(), entry.getCount())); return entry; })); }
java
public static Histogram add(Histogram x, Histogram y) { return new Histogram(Stream.concat(x.stream(), y.stream())); }
java
public static Histogram subtract(Histogram x, Histogram y) { return new Histogram(Stream.concat( x.stream(), y.stream().map(rwc -> { rwc.setCount(-rwc.getCount()); return rwc; }))); }
java
public static Histogram multiply(Histogram x, double y) { return x.modifyEventCounters((r, d) -> d * y); }
java
public static Histogram divide(Histogram x, double y) { return x.modifyEventCounters((r, d) -> d / y); }
java
@Override public int compareTo(Histogram o) { int cmp = 0; final Iterator<Bucket> iter = buckets_.iterator(), o_iter = o.buckets_.iterator(); while (cmp == 0 && iter.hasNext() && o_iter.hasNext()) { final Bucket next = iter.next(), o_next = o_iter.next(); cmp = Double...
java
@Override protected final Object convertToObject(final String text) throws Exception { Map map = CollectionUtil.toMap(text, keyEditor, valueEditor); if (map == null) { return null; } return createMap(map); }
java
@Nullable @Override public NodeGraphicDefinition getGroupGraphics(Object group, Set<String> groupElements) { return null; }
java
public static final String name(SimpleGroupPath group, MetricName metric) { return name(Stream.concat(group.getPath().stream(), metric.getPath().stream()) .collect(Collectors.joining("."))); }
java
private static Optional<Map.Entry<String, String>> createTagEntry(Map.Entry<String, MetricValue> tag_entry) { final Optional<String> opt_tag_value = tag_entry.getValue().asString(); return opt_tag_value .map(tag_value -> SimpleMapEntry.create(name(tag_entry.getKey()), escapeTagValue(tag_...
java
private static Map.Entry<String, String> maybeTruncateTagEntry(Map.Entry<String, String> tag_entry) { String k = tag_entry.getKey(); String v = tag_entry.getValue(); if (k.length() + v.length() <= MAX_TAG_KEY_VAL_CHARS - 2) // 2 chars for the quotes around the value return tag_entry;...
java
public static Map<String, String> tags(Tags tags) { return tags.stream() .map(WavefrontStrings::createTagEntry) .flatMap(opt -> opt.map(Stream::of).orElseGet(Stream::empty)) .map(WavefrontStrings::maybeTruncateTagEntry) .collect(Collectors.toMap(Ma...
java
public static Optional<String> wavefrontValue(MetricValue mv) { // Omit NaN and Inf. if (mv.isInfiniteOrNaN()) return Optional.empty(); return mv.value().map(Number::toString); }
java
private static String extractTagSource(Map<String, String> tag_map) { return Optional.ofNullable(tag_map.remove("source")) .orElseGet(() -> { return Optional.ofNullable(tag_map.get("cluster")) .map(WavefrontStrings::escapeTagValue) ...
java
private static String wavefrontLine(DateTime ts, SimpleGroupPath group, MetricName metric, String value, String source, Map<String, String> tag_map) { return new StringBuilder() .append(name(group, metric)) .append(' ') .append(value) .append(' ') ...
java
public static Optional<String> wavefrontLine(DateTime ts, GroupName group, MetricName metric, MetricValue metric_value) { return wavefrontValue(metric_value) .map(value -> { final Map<String, String> tag_map = tags(group.getTags()); final String source = e...
java
public static Stream<String> wavefrontLine(DateTime ts, TimeSeriesValue tsv) { final GroupName group = tsv.getGroup(); return tsv.getMetrics().entrySet().stream() .flatMap(metricEntry -> wavefrontLineForMetric(ts, group, metricEntry)); }
java
public Point getEndPos () { return new Point( (int)(_center.x + Math.round(Math.cos(_sangle + _delta) * _xradius)), (int)(_center.y + Math.round(Math.sin(_sangle + _delta) * _yradius))); }
java
public static Serializable loadConfig (InputStream source) throws IOException { try { ObjectInputStream oin = new ObjectInputStream(source); return (Serializable)oin.readObject(); } catch (ClassNotFoundException cnfe) { String errmsg = "Unknown config clas...
java
public static void saveConfig (File target, Serializable config) throws IOException { FileOutputStream fout = new FileOutputStream(target); ObjectOutputStream oout = new ObjectOutputStream(fout); oout.writeObject(config); oout.close(); }
java
public void historyUpdated (int adjustment) { if (adjustment != 0) { for (int ii = 0, nn = _showingHistory.size(); ii < nn; ii++) { ChatGlyph cg = _showingHistory.get(ii); cg.histIndex -= adjustment; } // some history entries were deleted, ...
java
public boolean displayMessage (ChatMessage message, boolean alreadyDisplayed) { // nothing doing if we've not been laid out if (!isLaidOut()) { return false; } // possibly display it now Graphics2D gfx = getTargetGraphics(); if (gfx != null) { ...
java
protected void updateDimmed (List<? extends ChatGlyph> glyphs) { for (ChatGlyph glyph : glyphs) { glyph.setDim(_dimmed); } }
java
protected void setHistoryEnabled (boolean historyEnabled) { if (historyEnabled && _historyModel == null) { _historyModel = _scrollbar.getModel(); _historyModel.addChangeListener(this); resetHistoryOffset(); // out with the subtitles, we'll be displaying histo...
java
protected void viewDidScroll (List<? extends ChatGlyph> glyphs, int dx, int dy) { for (ChatGlyph glyph : glyphs) { glyph.viewDidScroll(dx, dy); } }
java
protected void updateHistBar (int val) { // we may need to figure out the new history offset amount.. if (!_histOffsetFinal && _history.size() > _histOffset) { Graphics2D gfx = getTargetGraphics(); if (gfx != null) { figureHistoryOffset(gfx); g...
java
protected void figureHistoryOffset (Graphics2D gfx) { if (!isLaidOut()) { return; } int hei = _subtitleYSpacing; int hsize = _history.size(); for (int ii = 0; ii < hsize; ii++) { ChatGlyph rec = getHistorySubtitle(ii, gfx); Rectangle r = r...
java
protected void figureCurrentHistory () { int first = _historyModel.getValue(); int count = 0; Graphics2D gfx = null; if (isLaidOut() && !_history.isEmpty()) { gfx = getTargetGraphics(); if (gfx == null) { log.warning("Can't figure current hist...
java
protected ChatGlyph getHistorySubtitle (int index, Graphics2D layoutGfx) { // do a brute search (over a small set) for an already-created subtitle for (int ii = 0, nn = _showingHistory.size(); ii < nn; ii++) { ChatGlyph cg = _showingHistory.get(ii); if (cg.histIndex == index)...
java
protected ChatGlyph createHistorySubtitle (int index, Graphics2D layoutGfx) { ChatMessage message = _history.get(index); int type = getType(message, true); return createSubtitle(message, type, layoutGfx, false); }
java
protected int getHistorySubtitleSpacing (int index) { ChatMessage message = _history.get(index); return _logic.getSubtitleSpacing(getType(message, true)); }
java
protected void clearGlyphs (List<ChatGlyph> glyphs) { if (_target != null) { for (int ii = 0, nn = glyphs.size(); ii < nn; ii++) { ChatGlyph rec = glyphs.get(ii); _target.abortAnimation(rec); } } else if (!glyphs.isEmpty()) { log.w...
java
protected void displayMessage (ChatMessage message, Graphics2D gfx) { // get the non-history message type... int type = getType(message, false); if (type != ChatLogic.IGNORECHAT) { // display it now displayMessage(message, type, gfx); } }
java
protected void displayMessage (ChatMessage message, int type, Graphics2D layoutGfx) { // if we're in history mode, this will show up in the history and we'll rebuild our // subtitle list if and when history goes away if (isHistoryMode()) { return; } addSubtitle(cr...
java
protected void addSubtitle (ChatGlyph rec) { // scroll up the old subtitles Rectangle r = rec.getBounds(); scrollUpSubtitles(-r.height - _logic.getSubtitleSpacing(rec.getType())); // put this one in place Rectangle vbounds = _target.getViewBounds(); rec.setLocation(v...
java
protected ChatGlyph createSubtitle (ChatMessage message, int type, Graphics2D layoutGfx, boolean expires) { // we might need to modify the textual part with translations, but we can't do that to the // message object, since other chatdisplays also get it. ...
java
protected ChatGlyph createSubtitle (Graphics2D gfx, int type, long timestamp, Icon icon, int indent, String text, boolean expires) { Dimension is = new Dimension(); if (icon != null) { is.setSize(icon.getIconWidth(), icon.getIconHeight()); ...
java
protected long getChatExpire (long timestamp, String text) { long[] durations = _logic.getDisplayDurations(getDisplayDurationOffset()); // start the computation from the maximum of the timestamp or our last expire time long start = Math.max(timestamp, _lastExpire); // set the next ex...
java
protected void scrollUpSubtitles (int dy) { // dirty and move all the old glyphs Rectangle vbounds = _target.getViewBounds(); int miny = vbounds.y + vbounds.height - _subtitleHeight; for (Iterator<ChatGlyph> iter = _subtitles.iterator(); iter.hasNext();) { ChatGlyph sub =...
java
private static ParsedLine extractCommandArguments(final ParsedLine line) { // copy the list, so we can mutate and pop the first item off LinkedList<String> words = Lists.newLinkedList(line.words()); String remove = words.pop(); String rawLine = line.line(); // rebuild that list sans the first argum...
java
protected void convert () { if (_image == null) { return; } // obtain the target color and offset try { BufferedImage image; if (_tabs.getSelectedIndex() == 0) { // All recolorings from file. image = getAllRecolors(...
java
public BufferedImage getAllRecolors (boolean label) { if (_colRepo == null) { return null; } ColorPository.ClassRecord colClass = _colRepo.getClassRecord((String)_classList.getSelectedItem()); int classId = colClass.classId; BufferedImage img = new B...
java
public void setColorizeFile (File path) { try { if (path.getName().endsWith("xml")) { ColorPositoryParser parser = new ColorPositoryParser(); _colRepo = (ColorPository)(parser.parseConfig(path)); } else { _colRepo = ColorPository.loadCo...
java
public static String stripControlCharacters(String rawValue) { if (rawValue == null) { return null; } String value = replaceEntities(rawValue); boolean hasControlChars = false; for (int i = value.length() - 1; i >= 0; i--) { if (Character.isISOControl(va...
java
public static void write (BufferedImage image, OutputStream out) throws IOException { DataOutputStream dout = new DataOutputStream(out); // write the image dimensions int width = image.getWidth(), height = image.getHeight(); dout.writeInt(width); dout.writeInt(height...
java
public List<AmqpTableEntry> getEntries(String key) { if ((key == null) || (tableEntryArray == null)) { return null; } List<AmqpTableEntry> entries = new ArrayList<AmqpTableEntry>(); for (AmqpTableEntry entry : tableEntryArray) { if (entry.key.equals(key))...
java
public void update(long numProcessedDuringStep) { if (this.closed) { throw new ETAPrinterException("You cannot update a closed ETAPrinter!"); } DateTime now = DateTime.now(); ItemsDuration itemsDuration = null; if (numProcessedDuringStep > 0) { long stepDu...
java
public static TagAttributeInfo getIdAttribute(TagAttributeInfo a[]) { for (int i=0; i<a.length; i++) { if (a[i].getName().equals(ID)) { return a[i]; } } return null; // no such attribute }
java
protected static <T> Class<T> firstKnownType(T... objects) { for (T obj : objects) if (obj != null) return (Class<T>) obj.getClass(); return null; }
java
public ColorRecord[] enumerateColors (String className) { // make sure the class exists ClassRecord record = getClassRecord(className); if (record == null) { return null; } // create the array ColorRecord[] crecs = new ColorRecord[record.colors.size()]; ...
java
public int[] enumerateColorIds (String className) { // make sure the class exists ClassRecord record = getClassRecord(className); if (record == null) { return null; } int[] cids = new int[record.colors.size()]; Iterator<ColorRecord> crecs = record.colors....
java
public ColorRecord getRandomStartingColor (String className, Random rand) { // make sure the class exists ClassRecord record = getClassRecord(className); return (record == null) ? null : record.randomStartingColor(rand); }
java
public Colorization getColorization (int classId, int colorId) { ColorRecord color = getColorRecord(classId, colorId); return (color == null) ? null : color.getColorization(); }
java
public Colorization getColorization (String className, int colorId) { ClassRecord crec = getClassRecord(className); if (crec != null) { ColorRecord color = crec.colors.get(colorId); if (color != null) { return color.getColorization(); } } ...
java
public Colorization getColorization (String className, String colorName) { ClassRecord crec = getClassRecord(className); if (crec != null) { int colorId = 0; try { colorId = crec.getColorId(colorName); } catch (ParseException pe) { ...
java
public ClassRecord getClassRecord (String className) { Iterator<ClassRecord> iter = _classes.values().iterator(); while (iter.hasNext()) { ClassRecord crec = iter.next(); if (crec.name.equals(className)) { return crec; } } log.warni...
java
public ColorRecord getColorRecord (int classId, int colorId) { ClassRecord record = getClassRecord(classId); if (record == null) { // if they request color class zero, we assume they're just // decoding a blank colorprint, otherwise we complain if (classId != 0) {...
java
public ColorRecord getColorRecord (String className, String colorName) { ClassRecord record = getClassRecord(className); if (record == null) { log.warning("Requested unknown color class", "className", className, "colorName", colorName, new Exception()); return...
java
public void addClass (ClassRecord record) { // validate the class id if (record.classId > 255) { log.warning("Refusing to add class; classId > 255 " + record + "."); } else { _classes.put(record.classId, record); } }
java
public static void saveColorPository (ColorPository posit, File root) { File path = new File(root, CONFIG_PATH); try { CompiledConfig.saveConfig(path, posit); } catch (IOException ioe) { log.warning("Failure saving color pository", "path", path, "error", ioe); ...
java
public void init (CharacterDescriptor descrip, CharacterManager charmgr) { // keep track of this stuff _descrip = descrip; _charmgr = charmgr; // sanity check our values sanityCheckDescrip(); // assign an arbitrary starting orientation _orient = SOUTHWEST; ...
java
public void setActionSequence (String action) { // sanity check if (action == null) { log.warning("Refusing to set null action sequence " + this + ".", new Exception()); return; } // no need to noop if (action.equals(_action)) { return; ...
java
protected void updateActionFrames () { // get a reference to the action sequence so that we can obtain // our animation frames and configure our frames per second ActionSequence actseq = _charmgr.getActionSequence(_action); if (actseq == null) { String errmsg = "No such a...
java
protected void sanityCheckDescrip () { if (_descrip.getComponentIds() == null || _descrip.getComponentIds().length == 0) { log.warning("Invalid character descriptor [sprite=" + this + ", descrip=" + _descrip + "].", new Exception()); } }
java
protected void halt () { // only do something if we're actually animating if (_animMode != NO_ANIMATION) { // disable animation setAnimationMode(NO_ANIMATION); // come to a halt looking settled and at peace String rest = getRestingAction(); ...
java
public static void unmask(WrappedByteBuffer buf, int mask) { byte b; int remainder = buf.remaining() % 4; int remaining = buf.remaining() - remainder; int end = remaining + buf.position(); // xor a 32bit word at a time as long as possible while (buf.position() < end) { ...
java
private static stream_response newTscStream(Stream<TimeSeriesCollection> tsc, int fetch) { final BufferedIterator<TimeSeriesCollection> iter = new BufferedIterator(tsc.iterator(), TSC_QUEUE_SIZE); final long idx = TSC_ITERS_ALLOC.getAndIncrement(); final IteratorAndCookie<TimeSeriesCollection> i...
java
private static evaluate_response newEvalStream(Stream<Collection<CollectHistory.NamedEvaluation>> tsc, int fetch) { final BufferedIterator<Collection<CollectHistory.NamedEvaluation>> iter = new BufferedIterator(tsc.iterator(), EVAL_QUEUE_SIZE); final long idx = EVAL_ITERS_ALLOC.getAndIncrement(); ...
java
private static group_stream_response newGroupStream(Stream<Map.Entry<DateTime, TimeSeriesValue>> tsc, int fetch) { final BufferedIterator<Map.Entry<DateTime, TimeSeriesValue>> iter = new BufferedIterator<>(tsc.iterator(), GROUP_STREAM_QUEUE_SIZE); final long idx = GROUP_STREAM_ITERS_ALLOC.getAndIncremen...
java
private static <T> List<T> fetchFromIter(BufferedIterator<T> iter, int fetch, int max_fetch) { final long t0 = System.currentTimeMillis(); assert (max_fetch >= 1); if (fetch < 0 || fetch > max_fetch) fetch = max_fetch; final List<T> result = new ArrayList<>(fetch); for (int i = ...
java
public static Object loadObject (ResourceBundle bundle, String path, boolean wipeOnFailure) throws IOException, ClassNotFoundException { InputStream bin = null; try { bin = bundle.getResource(path); if (bin == null) { return null; } ...
java
protected String getTargetPath (File fromDir, String path) { return path.substring(0, path.length()-4) + ".jar"; }
java
public void updateBounds () { // invalidate the old... invalidate(); // size the bounds to fit our label Dimension size = _label.getSize(); _bounds.width = size.width + PADDING*2 + (_style == ROUNDED ? _arcWidth : 0); _bounds.height = size.height + PADDIN...
java
public static int getClosest (int direction, int[] possible, boolean preferCW) { // rotate a tick at a time, looking for matches int first = direction; int second = direction; for (int ii = 0; ii <= FINE_DIRECTION_COUNT / 2; ii++) { if (IntListUtil.contains(po...
java
public static void moveDirection (Point p, int direction, int dx, int dy) { if (direction >= DIRECTION_COUNT) { throw new IllegalArgumentException("Fine coordinates not supported."); } switch (direction) { case NORTH: case NORTHWEST: case NORTHEAST: p.y -= dy; ...
java
protected Component getRoot (Component comp) { for (Component c = comp; c != null; c = c.getParent()) { boolean hidden = !c.isDisplayable(); // on the mac, the JRootPane is invalidated before it is visible and is never again // invalidated or repainted, so we punt and all...
java
public void validateComponents () { // swap out our invalid array Object[] invalid = null; synchronized (this) { invalid = _invalid; _invalid = null; } // if there's nothing to validate, we're home free if (invalid == null) { retur...
java
protected static void dumpHierarchy (Component comp) { for (String indent = ""; comp != null; indent += " ") { log.info(indent + toString(comp)); comp = comp.getParent(); } }
java
public void addNode (int x, int y, int dir) { _nodes.add(new PathNode(x, y, dir)); }
java
public void setDuration (long millis) { // if we have only zero or one nodes, we don't have enough // information to compute our velocity int ncount = _nodes.size(); if (ncount < 2) { log.warning("Requested to set duration of bogus path", "path", this, "du...
java
protected boolean headToNextNode (Pathable pable, long startstamp, long now) { if (_niter == null) { throw new IllegalStateException("headToNextNode() called before init()"); } // check to see if we've completed our path if (!_niter.hasNext()) { // move the p...
java