code
stringlengths
73
34.1k
label
stringclasses
1 value
public void performCompletion(String s) { int selStart = getSelectionStart(); int selEnd = getSelectionEnd(); if (selStart != selEnd) return; Editable text = getText(); HintSpan[] spans = text.getSpans(0, length(), HintSpan.class); if (spans.length > 1) ...
java
public Iterator iterator() { // remove garbage collected elements processQueue(); // get an iterator of the superclass WeakHashSet final Iterator i = super.iterator(); return new Iterator() { public boolean hasNext() { return i.hasNext(); ...
java
public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme) throws XmlPullParserException, IOException { }
java
public void getBounds(Rect bounds) { final int outerX = (int) mTargetX; final int outerY = (int) mTargetY; final int r = (int) mTargetRadius + 1; bounds.set(outerX - r, outerY - r, outerX + r, outerY + r); }
java
private void computeBoundedTargetValues() { mTargetX = (mClampedStartingX - mBounds.exactCenterX()) * .7f; mTargetY = (mClampedStartingY - mBounds.exactCenterY()) * .7f; mTargetRadius = mBoundedRadius; }
java
private void clampStartingPosition() { final float cX = mBounds.exactCenterX(); final float cY = mBounds.exactCenterY(); final float dX = mStartingX - cX; final float dY = mStartingY - cY; final float r = mTargetRadius; if (dX * dX + dY * dY > r * r) { // Poin...
java
public void setAllCorners(CornerTreatment cornerTreatment) { topLeftCorner = cornerTreatment.clone(); topRightCorner = cornerTreatment.clone(); bottomRightCorner = cornerTreatment.clone(); bottomLeftCorner = cornerTreatment.clone(); }
java
public void setAllEdges(EdgeTreatment edgeTreatment) { leftEdge = edgeTreatment.clone(); topEdge = edgeTreatment.clone(); rightEdge = edgeTreatment.clone(); bottomEdge = edgeTreatment.clone(); }
java
public void setCornerTreatments( CornerTreatment topLeftCorner, CornerTreatment topRightCorner, CornerTreatment bottomRightCorner, CornerTreatment bottomLeftCorner) { this.topLeftCorner = topLeftCorner; this.topRightCorner = topRightCorner; this.bo...
java
public void setEdgeTreatments( EdgeTreatment leftEdge, EdgeTreatment topEdge, EdgeTreatment rightEdge, EdgeTreatment bottomEdge) { this.leftEdge = leftEdge; this.topEdge = topEdge; this.rightEdge = rightEdge; this.bottomEdge = bottomEdge; ...
java
boolean scrollIfNecessary() { if (mSelected == null) { mDragScrollStartTimeInMs = Long.MIN_VALUE; return false; } final long now = System.currentTimeMillis(); final long scrollDuration = mDragScrollStartTimeInMs == Long.MIN_VALUE ? 0 : now - mDragS...
java
int endRecoverAnimation(ViewHolder viewHolder, boolean override) { final int recoverAnimSize = mRecoverAnimations.size(); for (int i = recoverAnimSize - 1; i >= 0; i--) { final RecoverAnimation anim = mRecoverAnimations.get(i); if (anim.mViewHolder == viewHolder) { ...
java
boolean checkSelectForSwipe(int action, MotionEvent motionEvent, int pointerIndex) { if (mSelected != null || action != MotionEvent.ACTION_MOVE || mActionState == ACTION_STATE_DRAG || !mCallback.isItemViewSwipeEnabled()) { return false; } if (mRecyclerView.getScrollSt...
java
private void inflateLayers(Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme) throws XmlPullParserException, IOException { final LayerState state = mLayerState; final int innerDepth = parser.getDepth() + 1; int type; int depth; while ((type...
java
int addLayer(ChildDrawable layer) { final LayerState st = mLayerState; final int N = st.mChildren != null ? st.mChildren.length : 0; final int i = st.mNum; if (i >= N) { final ChildDrawable[] nu = new ChildDrawable[N + 10]; if (i > 0) { System.arra...
java
ChildDrawable addLayer(Drawable dr, int[] themeAttrs, int id, int left, int top, int right, int bottom) { final ChildDrawable childDrawable = createLayer(dr); childDrawable.mId = id; childDrawable.mThemeAttrs = themeAttrs; if (Build.VERSION.SDK_INT >= Build.VER...
java
public int getId(int index) { if (index >= mLayerState.mNum) { throw new IndexOutOfBoundsException(); } return mLayerState.mChildren[index].mId; }
java
public void setDrawable(int index, Drawable drawable) { if (index >= mLayerState.mNum) { throw new IndexOutOfBoundsException(); } final ChildDrawable[] layers = mLayerState.mChildren; final ChildDrawable childDrawable = layers[index]; if (childDrawable.mDrawable != n...
java
public Drawable getDrawable(int index) { if (index >= mLayerState.mNum) { throw new IndexOutOfBoundsException(); } return mLayerState.mChildren[index].mDrawable; }
java
public void setLayerInset(int index, int l, int t, int r, int b) { setLayerInsetInternal(index, l, t, r, b, UNDEFINED_INSET, UNDEFINED_INSET); }
java
public void setLayerInsetRelative(int index, int s, int t, int e, int b) { setLayerInsetInternal(index, 0, t, 0, b, s, e); }
java
private boolean refreshChildPadding(int i, ChildDrawable r) { if (r.mDrawable != null) { final Rect rect = mTmpRect; r.mDrawable.getPadding(rect); if (rect.left != mPaddingL[i] || rect.top != mPaddingT[i] || rect.right != mPaddingR[i] || rect.bottom != mPa...
java
void ensurePadding() { final int N = mLayerState.mNum; if (mPaddingL != null && mPaddingL.length >= N) { return; } mPaddingL = new int[N]; mPaddingT = new int[N]; mPaddingR = new int[N]; mPaddingB = new int[N]; }
java
public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException { Properties props = new Properties(); InputStream in = null; String propfile = resource; in = getResourceAsStream(loader, propfile); props.load(in); in.close(); ...
java
public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException { return new InputStreamReader(getResourceAsStream(loader, resource)); }
java
public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException { return new File(getResourceURL(loader, resource).getFile()); }
java
public synchronized String generateId() { final StringBuilder sb = new StringBuilder(this.length); sb.append(this.seed); sb.append(this.sequence.getAndIncrement()); return sb.toString(); }
java
public String generateSanitizedId() { String result = this.generateId(); result = result.replace(':', '-'); result = result.replace('_', '-'); result = result.replace('.', '-'); return result; }
java
protected void doResponseHeaders(final HttpServletResponse response, final String mimeType) { if (mimeType != null) { response.setContentType(mimeType); } }
java
public MessageProducer getOrCreateProducer(final String topic) { if (!this.shareProducer) { FutureTask<MessageProducer> task = this.producers.get(topic); if (task == null) { task = new FutureTask<MessageProducer>(new Callable<MessageProducer>() { @Ove...
java
public SendResult send(MessageBuilder builder, long timeout, TimeUnit unit) throws InterruptedException { Message msg = builder.build(this.messageBodyConverter); final String topic = msg.getTopic(); MessageProducer producer = this.getOrCreateProducer(topic); try { return prod...
java
public void send(MessageBuilder builder, SendMessageCallback cb, long timeout, TimeUnit unit) { Message msg = builder.build(this.messageBodyConverter); final String topic = msg.getTopic(); MessageProducer producer = this.getOrCreateProducer(topic); producer.sendMessage(msg, cb, timeout, ...
java
public <T> Message build(MessageBodyConverter<T> converter) { if (StringUtils.isBlank(this.topic)) { throw new IllegalArgumentException("Blank topic"); } if (this.body == null && this.payload == null) { throw new IllegalArgumentException("Empty payload"); } ...
java
public boolean acquireProcessLock() throws MongobeeConnectionException, MongobeeLockException { verifyDbConnection(); boolean acquired = lockDao.acquireLock(getMongoDatabase()); if (!acquired && waitForLock) { long timeToGiveUp = new Date().getTime() + (changeLogLockWaitTime * 1000 * 60); while...
java
public boolean waitForCompletion(long duration, TimeUnit timeUnit) throws InterruptedException { synchronized (lock) { if (!isCompleted()) { lock.wait(timeUnit.toMillis(duration)); } return isCompleted(); } }
java
@SuppressWarnings("unchecked") public static <TResult> Task<TResult> forResult(TResult value) { if (value == null) { return (Task<TResult>) TASK_NULL; } if (value instanceof Boolean) { return (Task<TResult>) ((Boolean) value ? TASK_TRUE : TASK_FALSE); } bolts.TaskCompletionSource<TResu...
java
public static <TResult> Task<TResult> forError(Exception error) { bolts.TaskCompletionSource<TResult> tcs = new bolts.TaskCompletionSource<>(); tcs.setError(error); return tcs.getTask(); }
java
public static Task<Void> delay(long delay, CancellationToken cancellationToken) { return delay(delay, BoltsExecutors.scheduled(), cancellationToken); }
java
public <TOut> Task<TOut> cast() { @SuppressWarnings("unchecked") Task<TOut> task = (Task<TOut>) this; return task; }
java
public <TContinuationResult> Task<TContinuationResult> continueWith( Continuation<TResult, TContinuationResult> continuation) { return continueWith(continuation, IMMEDIATE_EXECUTOR, null); }
java
public <TContinuationResult> Task<TContinuationResult> continueWithTask( final Continuation<TResult, Task<TContinuationResult>> continuation, final Executor executor, final CancellationToken ct) { boolean completed; final bolts.TaskCompletionSource<TContinuationResult> tcs = new bolts.TaskCompletion...
java
public <TContinuationResult> Task<TContinuationResult> continueWithTask( Continuation<TResult, Task<TContinuationResult>> continuation) { return continueWithTask(continuation, IMMEDIATE_EXECUTOR, null); }
java
private static Map<String, Object> parseAlData(JSONArray dataArray) throws JSONException { HashMap<String, Object> al = new HashMap<String, Object>(); for (int i = 0; i < dataArray.length(); i++) { JSONObject tag = dataArray.getJSONObject(i); String name = tag.getString("property"); String[] n...
java
public void cancel() { List<CancellationTokenRegistration> registrations; synchronized (lock) { throwIfClosed(); if (cancellationRequested) { return; } cancelScheduledCancellation(); cancellationRequested = true; registrations = new ArrayList<>(this.registrations); ...
java
@Override public void close() { synchronized (lock) { if (closed) { return; } closed = true; tokenSource.unregister(this); tokenSource = null; action = null; } }
java
public static ExecutorService newCachedThreadPool() { ThreadPoolExecutor executor = new ThreadPoolExecutor( CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); allowCoreThreadTimeout(executor, true); return executor; }
java
public static Bundle getAppLinkExtras(Intent intent) { Bundle appLinkData = getAppLinkData(intent); if (appLinkData == null) { return null; } return appLinkData.getBundle(KEY_NAME_EXTRAS); }
java
public static Uri getTargetUrl(Intent intent) { Bundle appLinkData = getAppLinkData(intent); if (appLinkData != null) { String targetString = appLinkData.getString(KEY_NAME_TARGET); if (targetString != null) { return Uri.parse(targetString); } } return intent.getData(); }
java
public static Uri getTargetUrlFromInboundIntent(Context context, Intent intent) { Bundle appLinkData = getAppLinkData(intent); if (appLinkData != null) { String targetString = appLinkData.getString(KEY_NAME_TARGET); if (targetString != null) { MeasurementEvent.sendBroadcastEvent(context, Mea...
java
private Bundle buildAppLinkDataForNavigation(Context context) { Bundle data = new Bundle(); Bundle refererAppLinkData = new Bundle(); if (context != null) { String refererAppPackage = context.getPackageName(); if (refererAppPackage != null) { refererAppLinkData.putString(KEY_NAME_REFERER...
java
private JSONObject getJSONForBundle(Bundle bundle) throws JSONException { JSONObject root = new JSONObject(); for (String key : bundle.keySet()) { root.put(key, getJSONValue(bundle.get(key))); } return root; }
java
public NavigationResult navigate(Context context) { PackageManager pm = context.getPackageManager(); Bundle finalAppLinkData = buildAppLinkDataForNavigation(context); Intent eligibleTargetIntent = null; for (AppLink.Target target : getAppLink().getTargets()) { Intent targetIntent = new Intent(Int...
java
public static void setRegistry(Registry registry) { SpectatorContext.registry = registry; if (registry instanceof NoopRegistry) { initStacktrace = null; } else { Exception cause = initStacktrace; Exception e = new IllegalStateException( "called SpectatorContext.setRegistry(" + re...
java
public static LazyGauge gauge(MonitorConfig config) { return new LazyGauge(Registry::gauge, registry, createId(config)); }
java
public static LazyGauge maxGauge(MonitorConfig config) { return new LazyGauge(Registry::maxGauge, registry, createId(config)); }
java
public static Id createId(MonitorConfig config) { // Need to ensure that Servo type tag is removed to avoid incorrectly reprocessing the // data in later transforms Map<String, String> tags = new HashMap<>(config.getTags().asMap()); tags.remove("type"); return registry .createId(config.getNa...
java
public static PolledMeter.Builder polledGauge(MonitorConfig config) { long delayMillis = Math.max(Pollers.getPollingIntervals().get(0) - 1000, 5000); Id id = createId(config); PolledMeter.remove(registry, id); return PolledMeter.using(registry) .withId(id) .withDelay(Duration.ofMillis(de...
java
public static void register(Monitor<?> monitor) { if (monitor instanceof SpectatorMonitor) { ((SpectatorMonitor) monitor).initializeSpectator(BasicTagList.EMPTY); } else if (!isEmptyComposite(monitor)) { ServoMeter m = new ServoMeter(monitor); PolledMeter.remove(registry, m.id()); Polled...
java
public static AmazonCloudWatch cloudWatch(AWSCredentialsProvider credentials) { AmazonCloudWatch client = new AmazonCloudWatchClient(credentials); client.setEndpoint(System.getProperty(AwsPropertyKeys.AWS_CLOUD_WATCH_END_POINT.getBundle(), "monitoring.amazonaws.com")); return client; }
java
public static AmazonAutoScaling autoScaling(AWSCredentials credentials) { AmazonAutoScaling client = new AmazonAutoScalingClient(credentials); client.setEndpoint(System.getProperty( AwsPropertyKeys.AWS_AUTO_SCALING_END_POINT.getBundle(), "autoscaling.amazonaws.com")); return client; }
java
public static Stopwatch start(MonitorConfig config, TimeUnit unit) { return INSTANCE.get(config, unit).start(); }
java
public static Stopwatch start(MonitorConfig config) { return INSTANCE.get(config, TimeUnit.MILLISECONDS).start(); }
java
public static void record(MonitorConfig config, long duration) { INSTANCE.get(config, TimeUnit.MILLISECONDS).record(duration, TimeUnit.MILLISECONDS); }
java
public static void record(MonitorConfig config, long duration, TimeUnit unit) { INSTANCE.get(config, unit).record(duration, unit); }
java
public static Stopwatch start(String name, TagList list, TimeUnit unit) { final MonitorConfig config = new MonitorConfig.Builder(name).withTags(list).build(); return INSTANCE.get(config, unit).start(); }
java
@Override public long getDuration() { final long end = running.get() ? System.nanoTime() : endTime.get(); return end - startTime.get(); }
java
public static <T> Memoizer<T> create(Callable<T> getter, long duration, TimeUnit unit) { return new Memoizer<>(getter, duration, unit); }
java
public T get() { long expiration = whenItExpires; long now = System.nanoTime(); // if uninitialized or expired update value if (expiration == 0 || now >= expiration) { synchronized (this) { // ensure a different thread didn't update it if (whenItExpires == expiration) { ...
java
public void push(List<Metric> rawMetrics) { List<Metric> validMetrics = ValidCharacters.toValidValues(filter(rawMetrics)); List<Metric> metrics = transformMetrics(validMetrics); LOGGER.debug("Scheduling push of {} metrics", metrics.size()); final UpdateTasks tasks = getUpdateTasks(BasicTagList.EMPTY, ...
java
protected Func1<HttpClientResponse<ByteBuf>, Integer> withBookkeeping(final int batchSize) { return response -> { boolean ok = response.getStatus().code() == 200; if (ok) { numMetricsSent.increment(batchSize); } else { LOGGER.info("Status code: {} - Lost {} metrics", re...
java
public static ServoAtlasConfig getAtlasConfig() { return new ServoAtlasConfig() { @Override public String getAtlasUri() { return getAtlasObserverUri(); } @Override public int getPushQueueSize() { return 1000; } @Override public boolean shouldSendMetr...
java
public static Set<Field> getAllFields(Class<?> classs) { Set<Field> set = new HashSet<>(); Class<?> c = classs; while (c != null) { set.addAll(Arrays.asList(c.getDeclaredFields())); c = c.getSuperclass(); } return set; }
java
public static Set<Method> getAllMethods(Class<?> classs) { Set<Method> set = new HashSet<>(); Class<?> c = classs; while (c != null) { set.addAll(Arrays.asList(c.getDeclaredMethods())); c = c.getSuperclass(); } return set; }
java
public static Set<Field> getFieldsAnnotatedBy(Class<?> classs, Class<? extends Annotation> ann) { Set<Field> set = new HashSet<>(); for (Field field : getAllFields(classs)) { if (field.isAnnotationPresent(ann)) { set.add(field); } } return set; }
java
public static Set<Method> getMethodsAnnotatedBy( Class<?> classs, Class<? extends Annotation> ann) { Set<Method> set = new HashSet<>(); for (Method method : getAllMethods(classs)) { if (method.isAnnotationPresent(ann)) { set.add(method); } } return set; }
java
protected M getMonitorForCurrentContext() { MonitorConfig contextConfig = getConfig(); M monitor = monitors.get(contextConfig); if (monitor == null) { M newMon = newMonitor.apply(contextConfig); if (newMon instanceof SpectatorMonitor) { ((SpectatorMonitor) newMon).initializeSpectator(spe...
java
static Tag internCustom(Tag t) { return (t instanceof BasicTag) ? t : newTag(t.getKey(), t.getValue()); }
java
public static Tag newTag(String key, String value) { Tag newTag = new BasicTag(intern(key), intern(value)); return intern(newTag); }
java
public String getTimeUnitAbbreviation() { switch (timeUnit) { case DAYS: return "day"; case HOURS: return "hr"; case MICROSECONDS: return "\u00B5s"; case MILLISECONDS: return "ms"; case MINUTES: return "min"; case NANOSECONDS: retur...
java
public synchronized void start() { if (!running) { running = true; Thread t = new Thread(new CpuStatRunnable(), "ThreadCpuStatsCollector"); t.setDaemon(true); t.start(); } }
java
public static String toDuration(long inputTime) { final long second = 1000000000L; final long minute = 60 * second; final long hour = 60 * minute; final long day = 24 * hour; final long week = 7 * day; long time = inputTime; final StringBuilder buf = new StringBuilder(); buf.append('P')...
java
public void printThreadCpuUsages(OutputStream out, CpuUsageComparator cmp) { final PrintWriter writer = getPrintWriter(out); final Map<String, Object> threadCpuUsages = getThreadCpuUsages(cmp); writer.printf("Time: %s%n%n", new Date((Long) threadCpuUsages.get(CURRENT_TIME))); final long uptimeMillis = ...
java
private void updateStats() { final ThreadMXBean bean = ManagementFactory.getThreadMXBean(); if (bean.isThreadCpuTimeEnabled()) { // Update stats for all current threads final long[] ids = bean.getAllThreadIds(); Arrays.sort(ids); long totalCpuTime = 0L; for (long id : ids) { ...
java
public <T> T callWithTimeout(Callable<T> callable, long duration, TimeUnit unit) throws Exception { Future<T> future = executor.submit(callable); try { return future.get(duration, unit); } catch (InterruptedException e) { future.cancel(true); throw e; } catch (ExecutionException ...
java
public static Timer newTimer(String name, TimeUnit unit) { return new BasicTimer(MonitorConfig.builder(name).build(), unit); }
java
public static Counter newCounter(String name, TaggingContext context) { final MonitorConfig config = MonitorConfig.builder(name).build(); return new ContextualCounter(config, context, COUNTER_FUNCTION); }
java
public static CompositeMonitor<?> newObjectMonitor(String id, Object obj) { final TagList tags = getMonitorTags(obj); List<Monitor<?>> monitors = new ArrayList<>(); addMonitors(monitors, id, tags, obj); final Class<?> c = obj.getClass(); final String objectId = (id == null) ? DEFAULT_ID : id; ...
java
public static CompositeMonitor<?> newThreadPoolMonitor(String id, ThreadPoolExecutor pool) { return newObjectMonitor(id, new MonitoredThreadPool(pool)); }
java
public static CompositeMonitor<?> newCacheMonitor(String id, Cache<?, ?> cache) { return newObjectMonitor(id, new MonitoredCache(cache)); }
java
public static boolean isObjectRegistered(String id, Object obj) { return DefaultMonitorRegistry.getInstance().isRegistered(newObjectMonitor(id, obj)); }
java
@SuppressWarnings("unchecked") static <T> Monitor<T> wrap(TagList tags, Monitor<T> monitor) { Monitor<T> m; if (monitor instanceof CompositeMonitor<?>) { m = new CompositeMonitorWrapper<>(tags, (CompositeMonitor<T>) monitor); } else { m = MonitorWrapper.create(tags, monitor); } return ...
java
static void addMonitors(List<Monitor<?>> monitors, String id, TagList tags, Object obj) { addMonitorFields(monitors, id, tags, obj); addAnnotatedFields(monitors, id, tags, obj); }
java
private static TagList getMonitorTags(Object obj) { try { Set<Field> fields = getFieldsAnnotatedBy(obj.getClass(), MonitorTags.class); for (Field field : fields) { field.setAccessible(true); return (TagList) field.get(obj); } Set<Method> methods = getMethodsAnnotatedBy(obj.g...
java
private static void checkType( com.netflix.servo.annotations.Monitor anno, Class<?> type, Class<?> container) { if (!isNumericType(type)) { final String msg = "annotation of type " + anno.type().name() + " can only be used" + " with numeric values, " + anno.name() + " in class " + container.ge...
java
private static MonitorConfig newObjectConfig(Class<?> c, String id, TagList tags) { final MonitorConfig.Builder builder = MonitorConfig.builder(id); final String className = className(c); if (!className.isEmpty()) { builder.withTag("class", className); } if (tags != null) { builder.with...
java
private static MonitorConfig newConfig( Class<?> c, String defaultName, String id, com.netflix.servo.annotations.Monitor anno, TagList tags) { String name = anno.name(); if (name.isEmpty()) { name = defaultName; } MonitorConfig.Builder builder = MonitorConfig.builder(...
java
public void stop() { try { if (socket != null) { socket.close(); socket = null; LOGGER.info("Disconnected from graphite server: {}", graphiteServerURI); } } catch (IOException e) { LOGGER.warn("Error Stopping", e); } }
java
public Tag get(String key) { int idx = binarySearch(tagArray, key); if (idx < 0) { return null; } else { return tagArray[idx]; } }
java
public void record(long n) { values[Integer.remainderUnsigned(pos++, size)] = n; if (curSize < size) { ++curSize; } }
java
public void computeStats() { if (statsComputed.getAndSet(true)) { return; } if (curSize == 0) { return; } Arrays.sort(values, 0, curSize); // to compute percentileValues min = values[0]; max = values[curSize - 1]; total = 0L; double sumSquares = 0.0; for (int i = 0...
java