code
stringlengths
73
34.1k
label
stringclasses
1 value
public MethodHandle branch(MethodHandle test, MethodHandle truePath, MethodHandle falsePath) { return invoke(MethodHandles.guardWithTest(test, truePath, falsePath)); }
java
public String toJava(MethodType incoming) { StringBuilder builder = new StringBuilder(); boolean second = false; for (Transform transform : transforms) { if (second) builder.append('\n'); second = true; builder.append(transform.toJava(incoming)); } ...
java
@Override public HttpResponse execute() throws IOException { if (this.method == HttpMethod.GET) { String url = this.toString(); if (url.length() > this.cutoff) { if (log.isLoggable(Level.FINER)) log.finer("URL length " + url.length() + " too long, converting GET to POST: " + url); Str...
java
private <T> GraphRequest<T> graph(String object, JavaType type, Param... params) { this.checkForBatchExecution(); // The data is transformed through a chain of wrappers GraphRequest<T> req = new GraphRequest<T>(object, params, this.mapper, this.<T>createMappingChain(type)); this.graphRequests.ad...
java
private <T> QueryRequest<T> query(String fql, JavaType type) { this.checkForBatchExecution(); if (this.multiqueryRequest == null) { this.multiqueryRequest = new MultiqueryRequest(mapper, this.createUnmappedChain()); this.graphRequests.add(this.multiqueryRequest); } // There is a circular ref...
java
private <T> MapperWrapper<T> createMappingChain(JavaType type) { return new MapperWrapper<T>(type, this.mapper, this.createUnmappedChain()); }
java
private ErrorDetectingWrapper createUnmappedChain() { int nextIndex = this.graphRequests.size(); return new ErrorDetectingWrapper( new GraphNodeExtractor(nextIndex, this.mapper, new ErrorDetectingWrapper(this))); }
java
private Later<JsonNode> getRawBatchResult() { if (this.rawBatchResult == null) { // Use LaterWrapper to cache the result so we don't fetch over and over this.rawBatchResult = new LaterWrapper<JsonNode, JsonNode>(this.createFetcher()); // Also let the master know it's time to kick off any other batch...
java
private Later<JsonNode> createFetcher() { final RequestBuilder call = new GraphRequestBuilder(getGraphEndpoint(), HttpMethod.POST, this.timeout, this.retries); // This actually creates the correct JSON structure as an array String batchValue = JSONUtils.toJSON(this.graphRequests, this.mapper); if (log.i...
java
private void throwPageMigratedException(String msg, int code, int subcode, String userTitle, String userMsg) { // This SUCKS ASS. Messages look like: // (#21) Page ID 114267748588304 was migrated to page ID 111013272313096. Please update your API calls to the new ID Matcher matcher = ID_PATTERN.matcher(msg...
java
private long extractNextId(Matcher matcher, String msg) { if (!matcher.find()) throw new IllegalStateException("Facebook changed the error msg for page migration to something unfamiliar. The new msg is: " + msg); String idStr = matcher.group().substring("ID ".length()); return Long.parseLong(idStr); }
java
protected void throwCodeAndMessage(int code, String msg) { switch (code) { case 0: case 101: case 102: case 190: throw new OAuthException(msg, "OAuthException", code, null, null, null); default: throw new ErrorFacebookException(msg + " (code " + code +")", null, code, null, null, null); }...
java
protected ListSetItem<T> newItem(IModel<T> itemModel) { ListSetItem<T> item = new ListSetItem<T>(Integer.toString(counter++), itemModel); populateItem(item); return item; }
java
public DateTextField getDateTextField(){ DateTextField component = visitChildren(DateTextField.class, new IVisitor<DateTextField, DateTextField>() { @Override public void component(DateTextField arg0, IVisit<DateTextField> arg1) { arg1.stop(arg0); } }); if (component == null) throw new WicketRunt...
java
private boolean typesAreCompatible(Class<?>[] paramTypes, Class<?>[] constructorParamTypes) { boolean matches = true; for (int i = 0; i < paramTypes.length; i++) { Class<?> paramType = paramTypes[i]; if (paramType != null) { Class<?> inputParamType = translateFro...
java
public V action(Callable<V> callable) throws Exception { Exception re; RetryState retryState = retryStrategy.getRetryState(); do { try { return callable.call(); } catch (Exception e) { re = e; if (Thread.interrupted() || isI...
java
private boolean isInterruptTransitively(Throwable e) { do { if (e instanceof InterruptedException) { return true; } e = e.getCause(); } while (e != null); return false; }
java
public Object getSet(String key, Object value, Integer expiration) throws Exception { Jedis jedis = null; try { jedis = this.jedisPool.getResource(); long begin = System.currentTimeMillis(); // 操作expire成功返回1,失败返回0,仅当均返回1时,实际操作成功 byte[] val = jedis.getSet...
java
public boolean add(String key, Object value, Integer expiration) throws Exception { Jedis jedis = null; try { jedis = this.jedisPool.getResource(); long begin = System.currentTimeMillis(); // 操作setnx与expire成功返回1,失败返回0,仅当均返回1时,实际操作成功 Long result = jedis.s...
java
public boolean exists(String key) throws Exception { boolean isExist = false; Jedis jedis = null; try { jedis = this.jedisPool.getResource(); isExist = jedis.exists(SafeEncoder.encode(key)); } catch (Exception e) { logger.error(e.getMessage(), e); ...
java
public boolean delete(String key) { Jedis jedis = null; try { jedis = this.jedisPool.getResource(); jedis.del(SafeEncoder.encode(key)); logger.info("delete key:" + key); return true; } catch (Exception e) { logger.error(e.getMessage(),...
java
public boolean flushall() { String result = ""; Jedis jedis = null; try { jedis = this.jedisPool.getResource(); result = jedis.flushAll(); logger.info("redis client name: " + this.getCacheName() + " flushall."); } catch (Exception e) { log...
java
public Object get(Object obj) throws ReflectionException { try { if (isPublic(readMethod)) { return readMethod.invoke(obj); } else { throw new ReflectionException("Cannot get the value of " + this + ", as it is write-only."); } } catch ...
java
public void set(Object obj, Object value) throws ReflectionException { try { if (isPublic(writeMethod)) { writeMethod.invoke(obj, value); } else { throw new ReflectionException("Cannot set the value of " + this + ", as it is read-only."); } ...
java
@SuppressWarnings("unchecked") @Override public <C> IConverter<C> getConverter(final Class<C> type) { if (Temporal.class.isAssignableFrom(type)) { return (IConverter<C>)converter; } else { return super.getConverter(type); } }
java
public static boolean isSqlStateDuplicateValueInUniqueIndex(SQLException se) { String sqlState = se.getSQLState(); return sqlState != null && (sqlState.equals("23505") || se.getMessage().contains("duplicate value in unique index")); }
java
public static boolean isSqlStateConnectionException(SQLException se) { String sqlState = se.getSQLState(); return sqlState != null && sqlState.startsWith("08"); }
java
public static boolean isSqlStateRollbackException(SQLException se) { String sqlState = se.getSQLState(); return sqlState != null && sqlState.startsWith("40"); }
java
public static Date getPreviousDay(Date dt) { if (dt == null) { return dt; } Calendar cal = Calendar.getInstance(); cal.setTime(dt); cal.add(Calendar.DAY_OF_YEAR, -1); return cal.getTime(); }
java
public static synchronized void cancel(TimerTask task) { if (task == null) { return; } task.cancel(); usageCount.decrementAndGet(); if (usageCount.get() == 0) { timer.cancel(); timer = null; } }
java
public void push(AbstractDrawer drawer, AjaxRequestTarget target, String cssClass) { ListItem item = new ListItem("next", drawer, this, cssClass); drawers.push(item); if (first == null) { first = item; addOrReplace(first); } else { ListItem iter = first; while (iter.next != null) { iter = iter....
java
public void replaceLast(AbstractDrawer newDrawer, AjaxRequestTarget target) { if (!drawers.isEmpty()) { ListItem last = drawers.getFirst(); last.drawer.replaceWith(newDrawer); last.drawer = newDrawer; newDrawer.setManager(this); target.add(newDrawer); } }
java
@Override public void renderHead(IHeaderResponse response) { super.renderHead(response); response.render(JavaScriptHeaderItem.forReference(DRAWER_JAVASCRIPT)); response.render(JavaScriptHeaderItem.forReference(MANAGER_JAVASCRIPT)); response.render(CssHeaderItem.forReference(DRAWER_CSS)); Iterator<ListItem>...
java
public void setWrappedObject(Object obj) { if (obj == null) { throw new IllegalArgumentException("Cannot warp a 'null' object."); } this.object = obj; this.bean = Bean.forClass(obj.getClass()); }
java
public Object getIndexedValue(String propertyName, int index) { return getIndexedValue(object, getPropertyOrThrow(bean, propertyName), index, this); }
java
public void setSimpleValue(String propertyName, Object value) { setSimpleValue(object, getPropertyOrThrow(bean, propertyName), value); }
java
public static Class<?> translateFromPrimitive(Class<?> paramType) { if (paramType == int.class) { return Integer.class; } else if (paramType == char.class) { return Character.class; } else if (paramType == byte.class) { return Byte.class; } else if (p...
java
@Override protected final void onRender() { Iterator<? extends Component> it = renderIterator(); while (it.hasNext()) { Component child = it.next(); if (child == null) { throw new IllegalStateException( "The render iterator returned null for a child. Container: " + this.toString() + "; I...
java
private static int metadata_end_cmp_(MetaData x, MetaData y) { return x.getEnd().compareTo(y.getEnd()); }
java
private static List<Path> file_listing_(Path dir) throws IOException { try (Stream<Path> files = Files.list(dir)) { return files.collect(Collectors.toList()); } }
java
public TSDataScanDir filterUpgradable() { return new TSDataScanDir(getDir(), getFiles().stream().filter(MetaData::isUpgradable).collect(Collectors.toList())); }
java
protected void init (ExplodeInfo info, int x, int y, int width, int height) { _info = info; _ox = x; _oy = y; _owid = width; _ohei = height; _info.rvel = (float)((2.0f * Math.PI) * _info.rvel); _chunkcount = (_info.xchunk * _info.ychunk); _cxpos = new...
java
public static MetricValue fromNumberValue(Number number) { if (number == null) { return EMPTY; } else if (number instanceof Float || number instanceof Double) { return fromDblValue(number.doubleValue()); } else if (number instanceof Byte || number instanceof Short || numb...
java
public void positionAvoidAnimation (Animation anim, Rectangle viewBounds) { Rectangle abounds = new Rectangle(anim.getBounds()); @SuppressWarnings("unchecked") ArrayList<Animation> avoidables = (ArrayList<Animation>) _avoidAnims.clone(); // if we are able to place it somewhere, d...
java
public void invalidateRegion (int x, int y, int width, int height) { if (isValidSize(width, height)) { addDirtyRegion(new Rectangle(x, y, width, height)); } }
java
protected final boolean isValidSize (int width, int height) { if (width < 0 || height < 0) { log.warning("Attempt to add invalid dirty region?!", "size", (width + "x" + height), new Exception()); return false; } else if (width == 0 || height == 0) { ...
java
public Rectangle[] getDirtyRegions () { List<Rectangle> merged = Lists.newArrayList(); for (int ii = _dirty.size() - 1; ii >= 0; ii--) { // pop the next rectangle from the dirty list Rectangle mr = _dirty.remove(ii); // merge in any overlapping rectangles ...
java
public List<Any2<Integer, String>> getArguments() { final List<Any2<Integer, String>> result = new ArrayList<>(); elements_.forEach(elem -> elem.keys(result::add)); return result; }
java
public boolean hasConstraint (int tileIdx, String constraint) { return (_bits == null || _bits[tileIdx].constraints == null) ? false : ListUtil.contains(_bits[tileIdx].constraints, constraint); }
java
public static TrimmedObjectTileSet trimObjectTileSet ( ObjectTileSet source, OutputStream destImage) throws IOException { return trimObjectTileSet(source, destImage, FastImageIO.FILE_SUFFIX); }
java
public int renderCompareTo (AbstractMedia other) { int result = Ints.compare(_renderOrder, other._renderOrder); return (result != 0) ? result : naturalCompareTo(other); }
java
public void queueNotification (ObserverList.ObserverOp<Object> amop) { if (_observers != null) { if (_mgr != null) { _mgr.queueNotification(_observers, amop); } else { log.warning("Have no manager, dropping notification", "media", this, "op", amop); ...
java
protected void addObserver (Object obs) { if (_observers == null) { _observers = ObserverList.newFastUnsafe(); } _observers.add(obs); }
java
private void dispatchEvent(XoaEvent event) { LOG.entering(CLASS_NAME, "dispatchEvent", event); try { Integer handlerId = event.getHandlerId(); XoaEventKind eventKind = event.getEvent(); if (LOG.isLoggable(Level.FINEST)) { LOG.fine...
java
public void setVariance (int dx, int dy) { if ((dx < 0) || (dy < 0) || ((dx == 0) && (dy == 0))) { throw new IllegalArgumentException( "Variance values must be positive, and at least one must be non-zero."); } else { _dx = dx; _dy = dy; } ...
java
protected boolean updatePositionTo (Pathable pable, int x, int y) { if ((pable.getX() == x) && (pable.getY() == y)) { return false; } else { pable.setLocation(x, y); return true; } }
java
public static DisplayMode getDisplayMode ( GraphicsDevice gd, int width, int height, int desiredDepth, int minimumDepth) { DisplayMode[] modes = gd.getDisplayModes(); final int ddepth = desiredDepth; // we sort modes in order of desirability Comparator<DisplayMode> mcomp = n...
java
public static CharacterDescriptor getRandomDescriptor ( ComponentRepository crepo, String gender, String[] COMP_CLASSES, ColorPository cpos, String[] COLOR_CLASSES) { // get all available classes ArrayList<ComponentClass> classes = Lists.newArrayList(); for (String element : ...
java
public CompletableFuture<NewFile> run() { LOG.log(Level.FINE, "starting optimized file creation for {0} files", files.size()); CompletableFuture<NewFile> fileCreation = new CompletableFuture<>(); final List<TSData> fjpFiles = this.files; // We clear out files below, which makes createTmpFile se...
java
private static void createTmpFile(CompletableFuture<NewFile> fileCreation, Path destDir, List<TSData> files, Compression compression) { LOG.log(Level.FINE, "starting temporary file creation..."); try { Collections.sort(files, Comparator.comparing(TSData::getBegin)); final FileC...
java
private static void install(CompletableFuture<NewFile> fileCreation, Path destDir, FileChannel tmpFile, DateTime begin) { try { try { synchronized (OUTSTANDING) { OUTSTANDING.remove(fileCreation); } if (fileCreation.isCancelled()) ...
java
private static String prefixForTimestamp(DateTime timestamp) { return String.format("monsoon-%04d%02d%02d-%02d%02d", timestamp.getYear(), timestamp.getMonthOfYear(), timestamp.getDayOfMonth(), timestamp.getHourOfDay(), timestamp.getMinuteOfHour()); }
java
public ErrorData getErrorData() { return new ErrorData( (Throwable)getRequest().getAttribute( "javax.servlet.error.exception" ), ((Integer)getRequest().getAttribute( "javax.servlet.error.status_code" )).intValue(), (String)getRequest().getAttribute( "javax.servlet.error.request_uri" ), (String)...
java
public static void storeLogs(String sourceLogFileName, String destLogFileName) throws Exception { // assumes eventmanager is running // store logs String tmpdir = System.getProperty("java.io.tmpdir"); if (tmpdir == null || tmpdir == "null") { tmpdir = "/tmp"; } F...
java
protected void setSelectedComponent (int idx) { int cid = _components.get(idx).intValue(); _model.setSelectedComponent(_cclass, cid); }
java
public boolean isFlowActive() { Object val = this.getArgument("active"); if (val instanceof Integer) { return ((Integer)val).intValue() == 1; } else { throw new IllegalStateException("ChannelEvent does not contain the 'active' argument"); } }
java
static void writeTracker(JSONWriter writer, Tracker tracker) throws JSONException { writer.key("id"); writer.value(tracker.getId()); writer.key("name"); writer.value(tracker.getName()); }
java
public static void addFull(JSONWriter writer, String field, Date value) throws JSONException { final SimpleDateFormat format = RedmineDateUtils.FULL_DATE_FORMAT.get(); JsonOutput.add(writer, field, value, format); }
java
private Optional<Data<Input, Output>> match_(Input input) { return Optional.ofNullable(recent_.get()) .filter((Data<Input, Output> data) -> equality_.test(data.getInput(), input)); }
java
private Data<Input, Output> derive_(Input input) { Data<Input, Output> result = new Data<>(input, fn_.apply(input)); recent_.set(result); return result; }
java
@Override public Output apply(Input input) { if (input == null) return fn_.apply(input); return match_(input) .orElseGet(() -> derive_(input)) .getOutput(); }
java
public void setWarning (float warnPercent, ResultListener<TimerView> warner) { // This warning hasn't triggered yet _warned = false; // Here are the details _warnPercent = warnPercent; _warner = warner; }
java
public void start (float startPercent, long duration, ResultListener<TimerView> finisher) { // Sanity check input arguments if (startPercent < 0.0f || startPercent >= 1.0f) { throw new IllegalArgumentException( "Invalid starting percent " + startPercent); } ...
java
public void unpause () { // Don't unpause the timer if it wasn't paused to begin with if (_lastUpdate == Long.MIN_VALUE || _start == Long.MIN_VALUE) { return; } // Adjust the starting time when the timer next ticks _processUnpause = true; // Start things...
java
public void changeComplete (float complete) { // Store the new state _complete = complete; // Determine the percentage difference between the "actual" // completion state and the completion amount to render during // the smooth interpolation _renderOffset = _renderCo...
java
protected void invalidate () { // Schedule the timer's location on screen to get repainted _invalidated = true; _host.repaint(_bounds.x, _bounds.y, _bounds.width, _bounds.height); }
java
public void checkFrameParticipation () { // Determine whether or not the timer should participate in // media ticks boolean participate = _host.isShowing(); // Start participating if necessary if (participate && !_participating) { _fmgr.registerFrameParti...
java
public static int getTileHash (int x, int y) { long seed = (((x << 2) ^ y) ^ MULTIPLIER) & MASK; long hash = (seed * MULTIPLIER + ADDEND) & MASK; return (int) (hash >>> 30); }
java
public static ObjectSequence<TimeSeriesCollection> fixSequence(ObjectSequence<TimeSeriesCollection> seq) { seq = seq.sort(); // Does nothing if already sorted. if (!seq.isDistinct() && !seq.isEmpty()) { List<ObjectSequence<TimeSeriesCollection>> toConcat = new ArrayList<>(); in...
java
public static ObjectSequence<TimeSeriesCollection> mergeSequences(ObjectSequence<TimeSeriesCollection>... tsSeq) { if (tsSeq.length == 0) return ObjectSequence.empty(); if (tsSeq.length == 1) return tsSeq[0]; // Sort sequences and remove any that are empty. final...
java
public void queueResource (String bundle, String resource, boolean loop) { try { queueURL(new URL("resource://" + bundle + "/" + resource), loop); } catch (MalformedURLException e) { log.warning("Invalid resource url.", "resource", resource, e); } }
java
public static boolean isMappedIPv4Address(Inet6Address ip) { byte bytes[] = ip.getAddress(); return ((bytes[0] == 0x00) && (bytes[1] == 0x00) && (bytes[2] == 0x00) && (bytes[3] == 0x00) && (bytes[4] == 0x00) && (bytes[5] == 0x00) && (bytes[6] == 0x00) && (...
java
public static Inet4Address getMappedIPv4Address(Inet6Address ip) { if (!isMappedIPv4Address(ip)) throw new IllegalArgumentException(String.format("Address '%s' is not IPv4-mapped.", toAddrString(ip))); return getInet4Address(copyOfRange(ip.getAddress(), 12, 16)); }
java
protected void checkIdle () { long now = getTimeStamp(); switch (_state) { case ACTIVE: // check whether they've idled out if (now >= (_lastEvent + _toIdleTime)) { log.info("User idle for " + (now-_lastEvent) + "ms."); _state = IDLE; ...
java
private void run_implementation_(PushProcessor p) throws Exception { final Map<GroupName, Alert> alerts = registry_.getCollectionAlerts(); final TimeSeriesCollection tsdata = registry_.getCollectionData(); p.accept(tsdata, unmodifiableMap(alerts), registry_.getFailedCollections()); }
java
@Override public final void run() { try { registry_.updateCollection(); final long t0 = System.nanoTime(); processors_.forEach(p -> { try { run_implementation_(p); } catch (Exception ex) { logger.lo...
java
public void resolveBlock (SceneBlock block, boolean hipri) { log.debug("Queueing block for resolution", "block", block, "hipri", hipri); if (hipri) { _queue.prepend(block); } else { _queue.append(block); } }
java
public static boolean openNotification() throws Exception { boolean success = false; // get API level int apiLevel = Client.getInstance().mapField("android.os.Build$VERSION", "SDK_INT").getInt(0); if (apiLevel >= 18) { success = Client.getInstance().map(Constants.UIAUTOMATO...
java
public static boolean click(int x, int y) throws Exception { return Client.getInstance().map(Constants.UIAUTOMATOR_UIDEVICE, "click", x, y).getBoolean(0); }
java
public void moveAndFadeIn (Path path, long pathDuration, float fadePortion) { move(path); setAlpha(0.0f); _fadeInDuration = (long)(pathDuration * fadePortion); }
java
public void moveAndFadeOut (Path path, long pathDuration, float fadePortion) { move(path); setAlpha(1.0f); _fadeStamp = 0; _pathDuration = pathDuration; _fadeOutDuration = (long)(pathDuration * fadePortion); _fadeDelay = _pathDuration - _fadeOutDuration; }
java
public void moveAndFadeInAndOut (Path path, long pathDuration, float fadePortion) { move(path); setAlpha(0.0f); _pathDuration = pathDuration; _fadeInDuration = _fadeOutDuration = (long)(pathDuration * fadePortion); }
java
public void setAlpha (float alpha) { if (alpha < 0.0f) { alpha = 0.0f; } else if (alpha > 1.0f) { alpha = 1.0f; } if (alpha != _alphaComposite.getAlpha()) { _alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha); ...
java
public static void register (PerformanceObserver obs, String name, long delta) { // get the observer's action hashtable Map<String, PerformanceAction> actions = _observers.get(obs); if (actions == null) { // create it if it didn't exist _observers.put(obs, actions = M...
java
public static void unregister (PerformanceObserver obs, String name) { // get the observer's action hashtable Map<String, PerformanceAction> actions = _observers.get(obs); if (actions == null) { log.warning("Attempt to unregister by unknown observer " + "[...
java
public static void tick (PerformanceObserver obs, String name) { // get the observer's action hashtable Map<String, PerformanceAction> actions = _observers.get(obs); if (actions == null) { log.warning("Attempt to tick by unknown observer " + "[observer=" +...
java
private URI _getSpecURI(String spec) { URI specURI = URI.create(spec); if (_scheme.indexOf(':') == -1) { return specURI; } String schemeSpecificPart = specURI.getSchemeSpecificPart(); return URI.create(schemeSpecificPart); }
java
protected boolean checkTileIndex (int tileIndex) { int tcount = getTileCount(); if (tileIndex >= 0 && tileIndex < tcount) { return true; } else { log.warning("Requested invalid tile [tset=" + this + ", index=" + tileIndex + "].", new Exception(...
java
public TagInfo getTag(String shortname) { TagInfo tags[] = getTags(); if (tags == null || tags.length == 0) { return null; } for (int i=0; i < tags.length; i++) { if (tags[i].getTagName().equals(shortname)) { return tags[i]; } ...
java
public TagFileInfo getTagFile(String shortname) { TagFileInfo tagFiles[] = getTagFiles(); if (tagFiles == null || tagFiles.length == 0) { return null; } for (int i=0; i < tagFiles.length; i++) { if (tagFiles[i].getName().equals(shortname)) { retu...
java