before
stringlengths
12
3.21M
after
stringlengths
41
3.21M
repo
stringlengths
1
56
type
stringclasses
1 value
__index_level_0__
int64
0
442k
@Override public boolean bindService(final Intent intent, final ServiceConnection conn, final int flags) { final boolean result = mCondom.proceed(OutboundType.BIND_SERVICE, intent, Boolean.FALSE, () -> CondomContext.super.bindService(intent, conn, flags)); if (result) mCondom.logIfOutboundPass(TAG, intent, CondomCore.getTargetPackage(intent), CondomCore.CondomEvent.BIND_PASS); return result; }
@Override public boolean bindService(final Intent intent, final ServiceConnection conn, final int flags) { <DeepExtract> final boolean result = mCondom.proceed(OutboundType.BIND_SERVICE, intent, Boolean.FALSE, () -> CondomContext.super.bindService(intent, conn, flags)); if (result) mCondom.logIfOutboundPass(TAG, intent, CondomCore.getTargetPackage(intent), CondomCore.CondomEvent.BIND_PASS); return result; </DeepExtract> }
condom
positive
3,940
public void hide(boolean animate) { mIsHidden = true; if (animate) { animateOffset(this.getHeight()); } else { if (mTranslationAnimator != null) { mTranslationAnimator.cancel(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { this.setTranslationY(this.getHeight()); } } }
public void hide(boolean animate) { mIsHidden = true; <DeepExtract> if (animate) { animateOffset(this.getHeight()); } else { if (mTranslationAnimator != null) { mTranslationAnimator.cancel(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { this.setTranslationY(this.getHeight()); } } </DeepExtract> }
JD-Mall-Master
positive
3,941
@Override public String get(final Pokemon p) { final int number = (int) Math.round((double) PokeColumn.GYM_OFFENSE.get(p) * Utilities.PERCENTAGE_FACTOR); return pad(number, 2); }
@Override public String get(final Pokemon p) { <DeepExtract> final int number = (int) Math.round((double) PokeColumn.GYM_OFFENSE.get(p) * Utilities.PERCENTAGE_FACTOR); return pad(number, 2); </DeepExtract> }
BlossomsPokemonGoManager
positive
3,942
public static int[] sort(int[] numbers) { if (0 < numbers.length - 1) { int middle = (0 + numbers.length - 1) / 2; numbers = mergesort(numbers, 0, middle); numbers = mergesort(numbers, middle + 1, numbers.length - 1); numbers = merge(numbers, 0, middle, numbers.length - 1); } return numbers; }
public static int[] sort(int[] numbers) { <DeepExtract> if (0 < numbers.length - 1) { int middle = (0 + numbers.length - 1) / 2; numbers = mergesort(numbers, 0, middle); numbers = mergesort(numbers, middle + 1, numbers.length - 1); numbers = merge(numbers, 0, middle, numbers.length - 1); } return numbers; </DeepExtract> }
JavaTutorialForBeginners
positive
3,943
@RequestMapping(value = "/{configType}_configs/{configName}/matchers/{matcherName}", params = "form", produces = "text/html") public String updateForm(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("matcherName") String matcherName, Model uiModel) { Matcher matcher = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getMatcherForName(matcherName); uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); List<Matcher> matchers = config.getMatchers(); matchers.remove(matcher); uiModel.addAttribute("matcher", matcher); uiModel.addAttribute("matchers", matchers); uiModel.addAttribute("configType", configType); uiModel.addAttribute("configName", configName); return "config_matchers/update"; }
@RequestMapping(value = "/{configType}_configs/{configName}/matchers/{matcherName}", params = "form", produces = "text/html") public String updateForm(@PathVariable("configType") String configType, @PathVariable("configName") String configName, @PathVariable("matcherName") String matcherName, Model uiModel) { Matcher matcher = Configuration.findConfigurationsByNameEquals(configName).getSingleResult().getMatcherForName(matcherName); <DeepExtract> uiModel.addAttribute("availableItems", LibraryScanner.availableItems()); Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); List<Matcher> matchers = config.getMatchers(); matchers.remove(matcher); uiModel.addAttribute("matcher", matcher); uiModel.addAttribute("matchers", matchers); uiModel.addAttribute("configType", configType); uiModel.addAttribute("configName", configName); </DeepExtract> return "config_matchers/update"; }
Reconciliation-and-Matching-Framework
positive
3,944
private void initializeBitmap() { if (mDisableCircularTransformation) { mBitmap = null; } else { mBitmap = getBitmapFromDrawable(getDrawable()); } if (!mReady) { mSetupPending = true; return; } if (getWidth() == 0 && getHeight() == 0) { return; } if (mBitmap == null) { invalidate(); return; } mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mBitmapPaint.setAntiAlias(true); mBitmapPaint.setShader(mBitmapShader); mBorderPaint.setStyle(Paint.Style.STROKE); mBorderPaint.setAntiAlias(true); mBorderPaint.setColor(mBorderColor); mBorderPaint.setStrokeWidth(mBorderWidth); mCircleBackgroundPaint.setStyle(Paint.Style.FILL); mCircleBackgroundPaint.setAntiAlias(true); mCircleBackgroundPaint.setColor(mCircleBackgroundColor); mBitmapHeight = mBitmap.getHeight(); mBitmapWidth = mBitmap.getWidth(); mBorderRect.set(calculateBounds()); mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2.0f, (mBorderRect.width() - mBorderWidth) / 2.0f); mDrawableRect.set(mBorderRect); if (!mBorderOverlay && mBorderWidth > 0) { mDrawableRect.inset(mBorderWidth - 1.0f, mBorderWidth - 1.0f); } mDrawableRadius = Math.min(mDrawableRect.height() / 2.0f, mDrawableRect.width() / 2.0f); applyColorFilter(); updateShaderMatrix(); invalidate(); }
private void initializeBitmap() { if (mDisableCircularTransformation) { mBitmap = null; } else { mBitmap = getBitmapFromDrawable(getDrawable()); } <DeepExtract> if (!mReady) { mSetupPending = true; return; } if (getWidth() == 0 && getHeight() == 0) { return; } if (mBitmap == null) { invalidate(); return; } mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mBitmapPaint.setAntiAlias(true); mBitmapPaint.setShader(mBitmapShader); mBorderPaint.setStyle(Paint.Style.STROKE); mBorderPaint.setAntiAlias(true); mBorderPaint.setColor(mBorderColor); mBorderPaint.setStrokeWidth(mBorderWidth); mCircleBackgroundPaint.setStyle(Paint.Style.FILL); mCircleBackgroundPaint.setAntiAlias(true); mCircleBackgroundPaint.setColor(mCircleBackgroundColor); mBitmapHeight = mBitmap.getHeight(); mBitmapWidth = mBitmap.getWidth(); mBorderRect.set(calculateBounds()); mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2.0f, (mBorderRect.width() - mBorderWidth) / 2.0f); mDrawableRect.set(mBorderRect); if (!mBorderOverlay && mBorderWidth > 0) { mDrawableRect.inset(mBorderWidth - 1.0f, mBorderWidth - 1.0f); } mDrawableRadius = Math.min(mDrawableRect.height() / 2.0f, mDrawableRect.width() / 2.0f); applyColorFilter(); updateShaderMatrix(); invalidate(); </DeepExtract> }
Kirby-Assistant
positive
3,945
@Override public void configDeveloperInfo(Hashtable<String, String> cpInfo) { if (bDebug) { Log.d(LOG_TAG, "initDeveloperInfo invoked " + cpInfo.toString()); } final Hashtable<String, String> curCPInfo = cpInfo; PluginWrapper.runOnMainThread(new Runnable() { @Override public void run() { try { String appId = curCPInfo.get("Nd91AppId"); String appKey = curCPInfo.get("Nd91AppKey"); int id = Integer.parseInt(appId); String orientation = curCPInfo.get("Nd91Orientation"); Nd91Wrapper.initSDK(mContext, id, appKey, orientation); } catch (Exception e) { LogE("Developer info is wrong!", e); } } }); }
@Override public void configDeveloperInfo(Hashtable<String, String> cpInfo) { <DeepExtract> if (bDebug) { Log.d(LOG_TAG, "initDeveloperInfo invoked " + cpInfo.toString()); } </DeepExtract> final Hashtable<String, String> curCPInfo = cpInfo; PluginWrapper.runOnMainThread(new Runnable() { @Override public void run() { try { String appId = curCPInfo.get("Nd91AppId"); String appKey = curCPInfo.get("Nd91AppKey"); int id = Integer.parseInt(appId); String orientation = curCPInfo.get("Nd91Orientation"); Nd91Wrapper.initSDK(mContext, id, appKey, orientation); } catch (Exception e) { LogE("Developer info is wrong!", e); } } }); }
Cocos2d-x-Guessing-Game
positive
3,946
public SwipeBackPage setSwipeBackEnable(boolean enable) { mEnable = enable; mSwipeBackLayout.setEnableGesture(enable); if (mEnable || mRelativeEnable) { mSwipeBackLayout.attachToActivity(mActivity); } else { mSwipeBackLayout.removeFromActivity(mActivity); } return this; }
public SwipeBackPage setSwipeBackEnable(boolean enable) { mEnable = enable; mSwipeBackLayout.setEnableGesture(enable); <DeepExtract> if (mEnable || mRelativeEnable) { mSwipeBackLayout.attachToActivity(mActivity); } else { mSwipeBackLayout.removeFromActivity(mActivity); } </DeepExtract> return this; }
MainUiFrame
positive
3,949
public void setXmppOauthRefreshToken(String token) { final SharedPreferences.Editor editor = mPreferences.edit(); editor.putString(XMPP_OAUTH_REFRESH_TOKEN, token); editor.apply(); final SharedPreferences.Editor editor = mPreferences.edit(); editor.putString(DATE_LAST_TOKEN_UPDATE, XmppDateTime.formatXEP0082Date(new Date())); editor.apply(); }
public void setXmppOauthRefreshToken(String token) { final SharedPreferences.Editor editor = mPreferences.edit(); editor.putString(XMPP_OAUTH_REFRESH_TOKEN, token); editor.apply(); <DeepExtract> final SharedPreferences.Editor editor = mPreferences.edit(); editor.putString(DATE_LAST_TOKEN_UPDATE, XmppDateTime.formatXEP0082Date(new Date())); editor.apply(); </DeepExtract> }
mangosta-android
positive
3,950
@Override public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) { int port = event.getEmbeddedServletContainer().getPort(); String host; try { host = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); host = "127.0.0.1"; } Address.getInstance().setHost(host).setPort(port).setDomain(String.join(":", host, String.valueOf(port))); }
@Override public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) { int port = event.getEmbeddedServletContainer().getPort(); <DeepExtract> String host; try { host = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); host = "127.0.0.1"; } </DeepExtract> Address.getInstance().setHost(host).setPort(port).setDomain(String.join(":", host, String.valueOf(port))); }
Lottor
positive
3,951
Node rightLeftRotate(Node x) { Node y = x.right.left; Node T = y.right; y.right = x.right; x.right.left = T; x.right.height = max(height(x.right.left), height(x.right.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; return y; Node y = x.right; Node T = y.left; y.left = x; x.right = T; x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; return y; }
Node rightLeftRotate(Node x) { Node y = x.right.left; Node T = y.right; y.right = x.right; x.right.left = T; x.right.height = max(height(x.right.left), height(x.right.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; return y; <DeepExtract> Node y = x.right; Node T = y.left; y.left = x; x.right = T; x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; return y; </DeepExtract> }
Problem-Solving-in-Data-Structures-Algorithms-using-Java
positive
3,952
public void run() { background = new ColorDrawable(DIM_COLOR); if (tmpBgView != null) { try { Bitmap bgBm = captureView(tmpBgView, tmpBgView.getWidth(), tmpBgView.getHeight()); bgBm = blur(bgBm, 20, 8); BitmapDrawable blurBm = new BitmapDrawable(activity.getResources(), bgBm); background = new LayerDrawable(new Drawable[] { blurBm, background }); } catch (Throwable e) { e.printStackTrace(); } } rlPage.setBackgroundDrawable(background); }
public void run() { <DeepExtract> background = new ColorDrawable(DIM_COLOR); if (tmpBgView != null) { try { Bitmap bgBm = captureView(tmpBgView, tmpBgView.getWidth(), tmpBgView.getHeight()); bgBm = blur(bgBm, 20, 8); BitmapDrawable blurBm = new BitmapDrawable(activity.getResources(), bgBm); background = new LayerDrawable(new Drawable[] { blurBm, background }); } catch (Throwable e) { e.printStackTrace(); } } </DeepExtract> rlPage.setBackgroundDrawable(background); }
WeCenterMobile-Android
positive
3,953
@PreAuthorize("hasPermission(#consumer, 'CREATE')") public Optional<Consumer> create(Consumer consumer) throws ValidationException { if (consumerView.get(consumer.getKey()).isPresent()) { throw new ValidationException("Can't create " + consumer.getKey() + " because it already exists"); } consumerValidator.validateForCreate(consumer); consumer.setSpecification(handlerService.handleInsert(consumer)); return Optional.ofNullable(consumerRepository.save(consumer)); }
@PreAuthorize("hasPermission(#consumer, 'CREATE')") public Optional<Consumer> create(Consumer consumer) throws ValidationException { if (consumerView.get(consumer.getKey()).isPresent()) { throw new ValidationException("Can't create " + consumer.getKey() + " because it already exists"); } consumerValidator.validateForCreate(consumer); consumer.setSpecification(handlerService.handleInsert(consumer)); <DeepExtract> return Optional.ofNullable(consumerRepository.save(consumer)); </DeepExtract> }
stream-registry
positive
3,955
@Override public LogicalEdge clone() { try { res = (LogicalEdge) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } this.u = null; this.v = null; return res; }
@Override public LogicalEdge clone() { try { res = (LogicalEdge) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } this.u = null; <DeepExtract> this.v = null; </DeepExtract> return res; }
dapper
positive
3,956
public boolean onKeyUp(int keyCode, KeyEvent event) { Integer res = androidToMIDP.get(keyCode); if (res != null) { keyCode = res; } else { keyCode = -(keyCode << 8); } if (overlay == null || !overlay.keyReleased(keyCode)) { postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.KEY_RELEASED, keyCode)); } return super.onKeyUp(keyCode, event); }
public boolean onKeyUp(int keyCode, KeyEvent event) { <DeepExtract> Integer res = androidToMIDP.get(keyCode); if (res != null) { keyCode = res; } else { keyCode = -(keyCode << 8); } </DeepExtract> if (overlay == null || !overlay.keyReleased(keyCode)) { postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.KEY_RELEASED, keyCode)); } return super.onKeyUp(keyCode, event); }
J2meLoader
positive
3,957
public static void main(String[] args) { Thread t = new Thread(() -> { while (true) { updateBalance(); } }); t.start(); Thread t = new Thread(() -> { while (true) { monitorBalance(); } }); t.start(); }
public static void main(String[] args) { Thread t = new Thread(() -> { while (true) { updateBalance(); } }); t.start(); <DeepExtract> Thread t = new Thread(() -> { while (true) { monitorBalance(); } }); t.start(); </DeepExtract> }
java-language-features
positive
3,958
private static void branch1() { }
private static void branch1() { <DeepExtract> </DeepExtract> }
jsonde
positive
3,959
@Override public void onClick(PopupWindow popup, int position, String item) { if (mEdgeType == position) { return; } mEdgeType = position; mListType = ListType.PULLRECYCLERLAYOUT_PULLRECYCLERVIEW; super.replace(mType, mListType, mEdgeType); final String title = EdgeType.getTypeTitle(mEdgeType); tl_title.setText(R.id.tv_title_title, title); }
@Override public void onClick(PopupWindow popup, int position, String item) { if (mEdgeType == position) { return; } mEdgeType = position; <DeepExtract> mListType = ListType.PULLRECYCLERLAYOUT_PULLRECYCLERVIEW; super.replace(mType, mListType, mEdgeType); final String title = EdgeType.getTypeTitle(mEdgeType); tl_title.setText(R.id.tv_title_title, title); </DeepExtract> }
PullLayout
positive
3,960
@Test public void queueRejectionWithSynchronousQueue() throws Exception { new SleepCommand(DependencyKey.EXAMPLE).getCumulativeCommandEventCounterStream().startCachingStreamValuesIfUnstarted(); final ImmutableCollection.Builder<Future<Optional<String>>> futures = ImmutableList.builder(); for (int i = 0; i < 50; i++) { futures.add(new SleepCommand(DependencyKey.EXAMPLE).queue()); } for (Future<Optional<String>> future : futures.build()) { assertFalse(future.isCancelled()); final Optional<String> result = future.get(); if (result.isPresent()) { assertThat(result).contains("sleep"); } else { assertThat(result).isEmpty(); } } Thread.sleep(500); final HystrixCommandMetrics sleepCommandMetrics = new SleepCommand(DependencyKey.EXAMPLE).getCommandMetrics(); assertThat(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)).isGreaterThan(15L); assertThat(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.TIMEOUT)).isEqualTo(0L); assertThat(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)).isGreaterThanOrEqualTo(40L); assertThat(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)).isEqualTo(0L); assertThat(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)).isEqualTo(0L); assertThat(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)).isEqualTo(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS) - sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); final HystrixThreadPoolProperties threadPoolProperties = new SleepCommand(DependencyKey.EXAMPLE).getThreadpoolProperties(); assertEquals(threadPoolProperties.maxQueueSize().get().intValue(), -1); assertEquals(TenacityPropertyStore.getTenacityConfiguration(DependencyKey.EXAMPLE), new TenacityConfiguration(new ThreadPoolConfiguration(), new CircuitBreakerConfiguration(), new SemaphoreConfiguration(), 1000, HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)); }
@Test public void queueRejectionWithSynchronousQueue() throws Exception { new SleepCommand(DependencyKey.EXAMPLE).getCumulativeCommandEventCounterStream().startCachingStreamValuesIfUnstarted(); final ImmutableCollection.Builder<Future<Optional<String>>> futures = ImmutableList.builder(); for (int i = 0; i < 50; i++) { futures.add(new SleepCommand(DependencyKey.EXAMPLE).queue()); } <DeepExtract> for (Future<Optional<String>> future : futures.build()) { assertFalse(future.isCancelled()); final Optional<String> result = future.get(); if (result.isPresent()) { assertThat(result).contains("sleep"); } else { assertThat(result).isEmpty(); } } </DeepExtract> Thread.sleep(500); final HystrixCommandMetrics sleepCommandMetrics = new SleepCommand(DependencyKey.EXAMPLE).getCommandMetrics(); assertThat(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)).isGreaterThan(15L); assertThat(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.TIMEOUT)).isEqualTo(0L); assertThat(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)).isGreaterThanOrEqualTo(40L); assertThat(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)).isEqualTo(0L); assertThat(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)).isEqualTo(0L); assertThat(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)).isEqualTo(sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS) - sleepCommandMetrics.getCumulativeCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); final HystrixThreadPoolProperties threadPoolProperties = new SleepCommand(DependencyKey.EXAMPLE).getThreadpoolProperties(); assertEquals(threadPoolProperties.maxQueueSize().get().intValue(), -1); assertEquals(TenacityPropertyStore.getTenacityConfiguration(DependencyKey.EXAMPLE), new TenacityConfiguration(new ThreadPoolConfiguration(), new CircuitBreakerConfiguration(), new SemaphoreConfiguration(), 1000, HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)); }
tenacity
positive
3,961
private void refreshSettings() { SharedPreferences preferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE); mCameraEnable = preferences.getBoolean(CommonUtils.CAMERA_ENABLE, CommonUtils.CAMERA_ON); mMicEnable = preferences.getBoolean(CommonUtils.MIC_ENABLE, CommonUtils.MIC_ON); mScreenEnable = preferences.getBoolean(CommonUtils.SCREEN_ENABLE, CommonUtils.SCREEN_OFF); int classType = preferences.getInt(CommonUtils.SDK_CLASS_TYPE, UCloudRtcSdkRoomType.UCLOUD_RTC_SDK_ROOM_SMALL.ordinal()); mClass = UCloudRtcSdkRoomType.valueOf(classType); mPublishMode = preferences.getInt(CommonUtils.PUBLISH_MODE, CommonUtils.AUTO_MODE); mScribeMode = preferences.getInt(CommonUtils.SUBSCRIBE_MODE, CommonUtils.AUTO_MODE); mExtendCameraCapture = preferences.getBoolean(CommonUtils.CAMERA_CAPTURE_MODE, false); mExtendVideoFormat = preferences.getInt(CommonUtils.EXTEND_CAMERA_VIDEO_FORMAT, CommonUtils.i420_format); switch(mExtendVideoFormat) { case CommonUtils.nv21_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_NV21; mURTCVideoFormat = UCloudRTCDataProvider.NV21; break; case CommonUtils.nv12_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_YUV420SP; mURTCVideoFormat = UCloudRTCDataProvider.NV12; break; case CommonUtils.i420_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_I420; mURTCVideoFormat = UCloudRTCDataProvider.I420; break; case CommonUtils.rgba_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_RGBX; mURTCVideoFormat = UCloudRTCDataProvider.RGBA_TO_I420; break; case CommonUtils.argb_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_ARGB; mURTCVideoFormat = UCloudRTCDataProvider.ARGB_TO_I420; break; case CommonUtils.rgb24_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_BGR888; mURTCVideoFormat = UCloudRTCDataProvider.RGB24_TO_I420; break; case CommonUtils.rgb565_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_RGB565; mURTCVideoFormat = UCloudRTCDataProvider.RGB565_TO_I420; break; } String[] resolutions = getResources().getStringArray(R.array.videoResolutions); mResolutionOption.addAll(Arrays.asList(resolutions)); Log.d(TAG, " Camera enable is: " + mCameraEnable + " Mic enable is: " + mMicEnable + " ScreenShare enable is: " + mScreenEnable); if (!mScreenEnable && !mCameraEnable && mMicEnable) { sdkEngine.setAudioOnlyMode(true); } else { sdkEngine.setAudioOnlyMode(false); } sdkEngine.configLocalCameraPublish(mCameraEnable); sdkEngine.configLocalAudioPublish(mMicEnable); if (isScreenCaptureSupport) { sdkEngine.configLocalScreenPublish(mScreenEnable); } else { sdkEngine.configLocalScreenPublish(false); } }
private void refreshSettings() { SharedPreferences preferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE); mCameraEnable = preferences.getBoolean(CommonUtils.CAMERA_ENABLE, CommonUtils.CAMERA_ON); mMicEnable = preferences.getBoolean(CommonUtils.MIC_ENABLE, CommonUtils.MIC_ON); mScreenEnable = preferences.getBoolean(CommonUtils.SCREEN_ENABLE, CommonUtils.SCREEN_OFF); int classType = preferences.getInt(CommonUtils.SDK_CLASS_TYPE, UCloudRtcSdkRoomType.UCLOUD_RTC_SDK_ROOM_SMALL.ordinal()); mClass = UCloudRtcSdkRoomType.valueOf(classType); mPublishMode = preferences.getInt(CommonUtils.PUBLISH_MODE, CommonUtils.AUTO_MODE); mScribeMode = preferences.getInt(CommonUtils.SUBSCRIBE_MODE, CommonUtils.AUTO_MODE); mExtendCameraCapture = preferences.getBoolean(CommonUtils.CAMERA_CAPTURE_MODE, false); mExtendVideoFormat = preferences.getInt(CommonUtils.EXTEND_CAMERA_VIDEO_FORMAT, CommonUtils.i420_format); <DeepExtract> switch(mExtendVideoFormat) { case CommonUtils.nv21_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_NV21; mURTCVideoFormat = UCloudRTCDataProvider.NV21; break; case CommonUtils.nv12_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_YUV420SP; mURTCVideoFormat = UCloudRTCDataProvider.NV12; break; case CommonUtils.i420_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_I420; mURTCVideoFormat = UCloudRTCDataProvider.I420; break; case CommonUtils.rgba_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_RGBX; mURTCVideoFormat = UCloudRTCDataProvider.RGBA_TO_I420; break; case CommonUtils.argb_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_ARGB; mURTCVideoFormat = UCloudRTCDataProvider.ARGB_TO_I420; break; case CommonUtils.rgb24_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_BGR888; mURTCVideoFormat = UCloudRTCDataProvider.RGB24_TO_I420; break; case CommonUtils.rgb565_format: mUVCCameraFormat = UVCCamera.PIXEL_FORMAT_RGB565; mURTCVideoFormat = UCloudRTCDataProvider.RGB565_TO_I420; break; } </DeepExtract> String[] resolutions = getResources().getStringArray(R.array.videoResolutions); mResolutionOption.addAll(Arrays.asList(resolutions)); Log.d(TAG, " Camera enable is: " + mCameraEnable + " Mic enable is: " + mMicEnable + " ScreenShare enable is: " + mScreenEnable); if (!mScreenEnable && !mCameraEnable && mMicEnable) { sdkEngine.setAudioOnlyMode(true); } else { sdkEngine.setAudioOnlyMode(false); } sdkEngine.configLocalCameraPublish(mCameraEnable); sdkEngine.configLocalAudioPublish(mMicEnable); if (isScreenCaptureSupport) { sdkEngine.configLocalScreenPublish(mScreenEnable); } else { sdkEngine.configLocalScreenPublish(false); } }
urtc-android-demo
positive
3,962
private void removeInternal(long hashEntryAdr, long prevEntryAdr, long hash) { long next = NonMemoryPoolHashEntries.getNext(hashEntryAdr); removeLinkInternal(hash, hashEntryAdr, prevEntryAdr, next); }
private void removeInternal(long hashEntryAdr, long prevEntryAdr, long hash) { <DeepExtract> long next = NonMemoryPoolHashEntries.getNext(hashEntryAdr); removeLinkInternal(hash, hashEntryAdr, prevEntryAdr, next); </DeepExtract> }
HaloDB
positive
3,963
public static Date getDateIgnoreTime(Date date) { return string2Date(date2String(date, DATE_PATTERN_DEFAULT), DATE_PATTERN_DEFAULT, true); }
public static Date getDateIgnoreTime(Date date) { <DeepExtract> return string2Date(date2String(date, DATE_PATTERN_DEFAULT), DATE_PATTERN_DEFAULT, true); </DeepExtract> }
DesignPatterns
positive
3,964
@Test public void testShouldReturnUnavailable() throws Exception { server.prime(when(query).then(unavailable(ConsistencyLevel.ALL, 5, 1))); thrown.expect(UnavailableException.class); thrown.expect(match((UnavailableException uae) -> uae.getAliveReplicas() == 1 && uae.getRequiredReplicas() == 5 && uae.getConsistencyLevel() == com.datastax.driver.core.ConsistencyLevel.ALL)); return query(new SimpleStatement(query)); }
@Test public void testShouldReturnUnavailable() throws Exception { server.prime(when(query).then(unavailable(ConsistencyLevel.ALL, 5, 1))); thrown.expect(UnavailableException.class); thrown.expect(match((UnavailableException uae) -> uae.getAliveReplicas() == 1 && uae.getRequiredReplicas() == 5 && uae.getConsistencyLevel() == com.datastax.driver.core.ConsistencyLevel.ALL)); <DeepExtract> return query(new SimpleStatement(query)); </DeepExtract> }
simulacron
positive
3,965
public void traceWarn(String format, Object... params) { this.tracer.trace(EventTracer.Level.WARN, format, params); }
public void traceWarn(String format, Object... params) { <DeepExtract> this.tracer.trace(EventTracer.Level.WARN, format, params); </DeepExtract> }
spokestack-android
positive
3,966
public void setBufferWriteHeader(DirectBuffer buffer, int offset) { this.initialOffset = offset; this.buffer = buffer; if (buffer instanceof UnsafeBuffer) { unsafeBuffer = (UnsafeBuffer) buffer; mutableBuffer = (MutableDirectBuffer) buffer; isUnsafe = true; isMutable = true; } else if (buffer instanceof MutableDirectBuffer) { mutableBuffer = (MutableDirectBuffer) buffer; isUnsafe = false; isMutable = true; } else { isUnsafe = false; isMutable = false; } buffer.checkLimit(initialOffset + BUFFER_LENGTH); if (!isMutable) throw new RuntimeException("cannot write to immutable buffer"); mutableBuffer.putShort(initialOffset + HEADER_OFFSET, EIDER_ID, java.nio.ByteOrder.LITTLE_ENDIAN); mutableBuffer.putShort(initialOffset + HEADER_GROUP_OFFSET, EIDER_GROUP_ID, java.nio.ByteOrder.LITTLE_ENDIAN); mutableBuffer.putInt(initialOffset + LENGTH_OFFSET, BUFFER_LENGTH, java.nio.ByteOrder.LITTLE_ENDIAN); }
public void setBufferWriteHeader(DirectBuffer buffer, int offset) { this.initialOffset = offset; this.buffer = buffer; if (buffer instanceof UnsafeBuffer) { unsafeBuffer = (UnsafeBuffer) buffer; mutableBuffer = (MutableDirectBuffer) buffer; isUnsafe = true; isMutable = true; } else if (buffer instanceof MutableDirectBuffer) { mutableBuffer = (MutableDirectBuffer) buffer; isUnsafe = false; isMutable = true; } else { isUnsafe = false; isMutable = false; } buffer.checkLimit(initialOffset + BUFFER_LENGTH); <DeepExtract> if (!isMutable) throw new RuntimeException("cannot write to immutable buffer"); mutableBuffer.putShort(initialOffset + HEADER_OFFSET, EIDER_ID, java.nio.ByteOrder.LITTLE_ENDIAN); mutableBuffer.putShort(initialOffset + HEADER_GROUP_OFFSET, EIDER_GROUP_ID, java.nio.ByteOrder.LITTLE_ENDIAN); mutableBuffer.putInt(initialOffset + LENGTH_OFFSET, BUFFER_LENGTH, java.nio.ByteOrder.LITTLE_ENDIAN); </DeepExtract> }
aeron-cookbook-code
positive
3,967
public void unlockToolbar(Node node) { m_stop.setEnabled(false); m_play.setEnabled(true); m_tomove.setEnabled(true); m_setup_black.setEnabled(true); m_setup_white.setEnabled(true); m_new.setEnabled(true); m_load.setEnabled(true); m_save.setEnabled(true); m_hint.setEnabled(true); m_solve.setEnabled(true); m_program_options.setEnabled(true); m_beginning.setEnabled(node.getParent() != null); m_back10.setEnabled(node.getParent() != null); m_back.setEnabled(node.getParent() != null); m_forward.setEnabled(node.getChild() != null); m_forward10.setEnabled(node.getChild() != null); m_end.setEnabled(node.getChild() != null); m_up.setEnabled(node.getNext() != null); m_down.setEnabled(node.getPrev() != null); m_swap.setEnabled(node.isSwapAllowed()); }
public void unlockToolbar(Node node) { m_stop.setEnabled(false); m_play.setEnabled(true); m_tomove.setEnabled(true); m_setup_black.setEnabled(true); m_setup_white.setEnabled(true); m_new.setEnabled(true); m_load.setEnabled(true); m_save.setEnabled(true); m_hint.setEnabled(true); m_solve.setEnabled(true); m_program_options.setEnabled(true); <DeepExtract> m_beginning.setEnabled(node.getParent() != null); m_back10.setEnabled(node.getParent() != null); m_back.setEnabled(node.getParent() != null); m_forward.setEnabled(node.getChild() != null); m_forward10.setEnabled(node.getChild() != null); m_end.setEnabled(node.getChild() != null); m_up.setEnabled(node.getNext() != null); m_down.setEnabled(node.getPrev() != null); m_swap.setEnabled(node.isSwapAllowed()); </DeepExtract> }
hexgui
positive
3,968
void refreshSetting() { if (maxEnergy >= 100000000) tier = 5; else if (maxEnergy >= 10000000) tier = 4; else if (maxEnergy >= 1000000) tier = 3; else if (maxEnergy >= 100000) tier = 2; else tier = 1; if (inv[5] != null) { if (inv[5].itemID == ic2.api.item.Items.getItem("transformerUpgrade").itemID && inv[5].getItemDamage() == ic2.api.item.Items.getItem("transformerUpgrade").getItemDamage()) { switch(inv[5].stackSize) { case 1: vOut = 128; break; case 2: vOut = 512; break; default: vOut = 2048; } } else if (inv[5].itemID == GregTech.GTComponent && inv[5].getItemDamage() == 27) { if (inv[5].stackSize == 1) vOut = 512; else vOut = 2048; } else vOut = 32; } else vOut = 32; chargingRate = vOut * 2; if (inv[7] == null) overClock = 0; if (ic2.api.item.Items.getItem("overclockerUpgrade").itemID != inv[7].itemID | ic2.api.item.Items.getItem("overclockerUpgrade").getItemDamage() != inv[7].getItemDamage()) overClock = 0; return inv[7].stackSize; if (overClock > 7) overClock = 7; tickMax = 150 - (overClock * 20); smeltingCost = (int) (390 * (overClock / 3.0) + 390); }
void refreshSetting() { if (maxEnergy >= 100000000) tier = 5; else if (maxEnergy >= 10000000) tier = 4; else if (maxEnergy >= 1000000) tier = 3; else if (maxEnergy >= 100000) tier = 2; else tier = 1; if (inv[5] != null) { if (inv[5].itemID == ic2.api.item.Items.getItem("transformerUpgrade").itemID && inv[5].getItemDamage() == ic2.api.item.Items.getItem("transformerUpgrade").getItemDamage()) { switch(inv[5].stackSize) { case 1: vOut = 128; break; case 2: vOut = 512; break; default: vOut = 2048; } } else if (inv[5].itemID == GregTech.GTComponent && inv[5].getItemDamage() == 27) { if (inv[5].stackSize == 1) vOut = 512; else vOut = 2048; } else vOut = 32; } else vOut = 32; chargingRate = vOut * 2; <DeepExtract> if (inv[7] == null) overClock = 0; if (ic2.api.item.Items.getItem("overclockerUpgrade").itemID != inv[7].itemID | ic2.api.item.Items.getItem("overclockerUpgrade").getItemDamage() != inv[7].getItemDamage()) overClock = 0; return inv[7].stackSize; </DeepExtract> if (overClock > 7) overClock = 7; tickMax = 150 - (overClock * 20); smeltingCost = (int) (390 * (overClock / 3.0) + 390); }
FrogCraft
positive
3,969
public Criteria andAvatarBetween(String value1, String value2) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "avatar" + " cannot be null"); } criteria.add(new Criterion("avatar between", value1, value2)); return (Criteria) this; }
public Criteria andAvatarBetween(String value1, String value2) { <DeepExtract> if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "avatar" + " cannot be null"); } criteria.add(new Criterion("avatar between", value1, value2)); </DeepExtract> return (Criteria) this; }
webim
positive
3,970
private void init() { mMountPaint.setAntiAlias(true); mMountPaint.setStyle(Paint.Style.FILL); mTrunkPaint.setAntiAlias(true); mBranchPaint.setAntiAlias(true); mBoarderPaint.setAntiAlias(true); mBoarderPaint.setStyle(Paint.Style.STROKE); mBoarderPaint.setStrokeWidth(2); mBoarderPaint.setStrokeJoin(Paint.Join.ROUND); mTransMatrix.reset(); mTransMatrix.setScale(mScaleX, mScaleY); int offset1 = (int) (10 * mMoveFactor); mMount1.reset(); mMount1.moveTo(0, 95 + offset1); mMount1.lineTo(55, 74 + offset1); mMount1.lineTo(146, 104 + offset1); mMount1.lineTo(227, 72 + offset1); mMount1.lineTo(WIDTH, 80 + offset1); mMount1.lineTo(WIDTH, HEIGHT); mMount1.lineTo(0, HEIGHT); mMount1.close(); mMount1.transform(mTransMatrix); int offset2 = (int) (20 * mMoveFactor); mMount2.reset(); mMount2.moveTo(0, 103 + offset2); mMount2.lineTo(67, 90 + offset2); mMount2.lineTo(165, 115 + offset2); mMount2.lineTo(221, 87 + offset2); mMount2.lineTo(WIDTH, 100 + offset2); mMount2.lineTo(WIDTH, HEIGHT); mMount2.lineTo(0, HEIGHT); mMount2.close(); mMount2.transform(mTransMatrix); int offset3 = (int) (30 * mMoveFactor); mMount3.reset(); mMount3.moveTo(0, 114 + offset3); mMount3.cubicTo(30, 106 + offset3, 196, 97 + offset3, WIDTH, 104 + offset3); mMount3.lineTo(WIDTH, HEIGHT); mMount3.lineTo(0, HEIGHT); mMount3.close(); mMount3.transform(mTransMatrix); if (mMoveFactor == mTreeBendFactor && !true) { return; } final Interpolator interpolator = PathInterpolatorCompat.create(0.8f, -0.5f * mMoveFactor); final float width = TREE_WIDTH; final float height = TREE_HEIGHT; final float maxMove = width * 0.3f * mMoveFactor; final float trunkSize = width * 0.05f; final float branchSize = width * 0.2f; final float x0 = width / 2; final float y0 = height; final int N = 25; final float dp = 1f / N; final float dy = -dp * height; float y = y0; float p = 0; float[] xx = new float[N + 1]; float[] yy = new float[N + 1]; for (int i = 0; i <= N; i++) { xx[i] = interpolator.getInterpolation(p) * maxMove + x0; yy[i] = y; y += dy; p += dp; } mTrunk.reset(); mTrunk.moveTo(x0 - trunkSize, y0); int max = (int) (N * 0.7f); int max1 = (int) (max * 0.5f); float diff = max - max1; for (int i = 0; i < max; i++) { if (i < max1) { mTrunk.lineTo(xx[i] - trunkSize, yy[i]); } else { mTrunk.lineTo(xx[i] - trunkSize * (max - i) / diff, yy[i]); } } for (int i = max - 1; i >= 0; i--) { if (i < max1) { mTrunk.lineTo(xx[i] + trunkSize, yy[i]); } else { mTrunk.lineTo(xx[i] + trunkSize * (max - i) / diff, yy[i]); } } mTrunk.close(); mBranch.reset(); int min = (int) (N * 0.4f); diff = N - min; mBranch.moveTo(xx[min] - branchSize, yy[min]); mBranch.addArc(new RectF(xx[min] - branchSize, yy[min] - branchSize, xx[min] + branchSize, yy[min] + branchSize), 0f, 180f); for (int i = min; i <= N; i++) { float f = (i - min) / diff; mBranch.lineTo(xx[i] - branchSize + f * f * branchSize, yy[i]); } for (int i = N; i >= min; i--) { float f = (i - min) / diff; mBranch.lineTo(xx[i] + branchSize - f * f * branchSize, yy[i]); } }
private void init() { mMountPaint.setAntiAlias(true); mMountPaint.setStyle(Paint.Style.FILL); mTrunkPaint.setAntiAlias(true); mBranchPaint.setAntiAlias(true); mBoarderPaint.setAntiAlias(true); mBoarderPaint.setStyle(Paint.Style.STROKE); mBoarderPaint.setStrokeWidth(2); mBoarderPaint.setStrokeJoin(Paint.Join.ROUND); mTransMatrix.reset(); mTransMatrix.setScale(mScaleX, mScaleY); int offset1 = (int) (10 * mMoveFactor); mMount1.reset(); mMount1.moveTo(0, 95 + offset1); mMount1.lineTo(55, 74 + offset1); mMount1.lineTo(146, 104 + offset1); mMount1.lineTo(227, 72 + offset1); mMount1.lineTo(WIDTH, 80 + offset1); mMount1.lineTo(WIDTH, HEIGHT); mMount1.lineTo(0, HEIGHT); mMount1.close(); mMount1.transform(mTransMatrix); int offset2 = (int) (20 * mMoveFactor); mMount2.reset(); mMount2.moveTo(0, 103 + offset2); mMount2.lineTo(67, 90 + offset2); mMount2.lineTo(165, 115 + offset2); mMount2.lineTo(221, 87 + offset2); mMount2.lineTo(WIDTH, 100 + offset2); mMount2.lineTo(WIDTH, HEIGHT); mMount2.lineTo(0, HEIGHT); mMount2.close(); mMount2.transform(mTransMatrix); int offset3 = (int) (30 * mMoveFactor); mMount3.reset(); mMount3.moveTo(0, 114 + offset3); mMount3.cubicTo(30, 106 + offset3, 196, 97 + offset3, WIDTH, 104 + offset3); mMount3.lineTo(WIDTH, HEIGHT); mMount3.lineTo(0, HEIGHT); mMount3.close(); mMount3.transform(mTransMatrix); <DeepExtract> if (mMoveFactor == mTreeBendFactor && !true) { return; } final Interpolator interpolator = PathInterpolatorCompat.create(0.8f, -0.5f * mMoveFactor); final float width = TREE_WIDTH; final float height = TREE_HEIGHT; final float maxMove = width * 0.3f * mMoveFactor; final float trunkSize = width * 0.05f; final float branchSize = width * 0.2f; final float x0 = width / 2; final float y0 = height; final int N = 25; final float dp = 1f / N; final float dy = -dp * height; float y = y0; float p = 0; float[] xx = new float[N + 1]; float[] yy = new float[N + 1]; for (int i = 0; i <= N; i++) { xx[i] = interpolator.getInterpolation(p) * maxMove + x0; yy[i] = y; y += dy; p += dp; } mTrunk.reset(); mTrunk.moveTo(x0 - trunkSize, y0); int max = (int) (N * 0.7f); int max1 = (int) (max * 0.5f); float diff = max - max1; for (int i = 0; i < max; i++) { if (i < max1) { mTrunk.lineTo(xx[i] - trunkSize, yy[i]); } else { mTrunk.lineTo(xx[i] - trunkSize * (max - i) / diff, yy[i]); } } for (int i = max - 1; i >= 0; i--) { if (i < max1) { mTrunk.lineTo(xx[i] + trunkSize, yy[i]); } else { mTrunk.lineTo(xx[i] + trunkSize * (max - i) / diff, yy[i]); } } mTrunk.close(); mBranch.reset(); int min = (int) (N * 0.4f); diff = N - min; mBranch.moveTo(xx[min] - branchSize, yy[min]); mBranch.addArc(new RectF(xx[min] - branchSize, yy[min] - branchSize, xx[min] + branchSize, yy[min] + branchSize), 0f, 180f); for (int i = min; i <= N; i++) { float f = (i - min) / diff; mBranch.lineTo(xx[i] - branchSize + f * f * branchSize, yy[i]); } for (int i = N; i >= min; i--) { float f = (i - min) / diff; mBranch.lineTo(xx[i] + branchSize - f * f * branchSize, yy[i]); } </DeepExtract> }
Android-Ptr-Comparison
positive
3,971
public static Filter eq(String propertyName, Object value) { Filter f = new Filter(); f.filterDto.setOperator(Op.EQ.name()); List<Object> values = new LinkedList<Object>(); values.add(propertyName); values.add(value); f.filterDto.setValues(values); return f; }
public static Filter eq(String propertyName, Object value) { <DeepExtract> Filter f = new Filter(); f.filterDto.setOperator(Op.EQ.name()); List<Object> values = new LinkedList<Object>(); values.add(propertyName); values.add(value); f.filterDto.setValues(values); return f; </DeepExtract> }
io2014-codelabs
positive
3,972
@Override public void onClick(View v) { if (puzzleType.equals("hexagon")) return; puzzleType = "hexagon"; PuzzleBase puzzleBase = null; if (puzzleType.equals("grid")) { puzzleBase = new GridPuzzle(palette, getWidth(), getHeight()); ((GridPuzzle) puzzleBase).addStartingPoint(0, 0); ((GridPuzzle) puzzleBase).addEndingPoint(getWidth(), getHeight()); } else if (puzzleType.equals("hexagon")) { puzzleBase = new HexagonPuzzle(palette); } else if (puzzleType.equals("jungle")) { puzzleBase = new JunglePuzzle(palette, getWidth()); } else if (puzzleType.equals("video_room")) { puzzleBase = new VideoRoomPuzzle(palette); } puzzleRenderer = new PuzzleRenderer(game, puzzleBase, false); game.setPuzzle(puzzleRenderer); game.update(); if (puzzleType.equals("grid")) { gridSizeView.setVisibility(View.VISIBLE); heightEditText.setVisibility(View.VISIBLE); } else if (puzzleType.equals("hexagon")) { gridSizeView.setVisibility(View.GONE); } else if (puzzleType.equals("jungle")) { gridSizeView.setVisibility(View.VISIBLE); heightEditText.setVisibility(View.GONE); } else if (puzzleType.equals("video_room")) { gridSizeView.setVisibility(View.GONE); } }
@Override public void onClick(View v) { if (puzzleType.equals("hexagon")) return; puzzleType = "hexagon"; PuzzleBase puzzleBase = null; if (puzzleType.equals("grid")) { puzzleBase = new GridPuzzle(palette, getWidth(), getHeight()); ((GridPuzzle) puzzleBase).addStartingPoint(0, 0); ((GridPuzzle) puzzleBase).addEndingPoint(getWidth(), getHeight()); } else if (puzzleType.equals("hexagon")) { puzzleBase = new HexagonPuzzle(palette); } else if (puzzleType.equals("jungle")) { puzzleBase = new JunglePuzzle(palette, getWidth()); } else if (puzzleType.equals("video_room")) { puzzleBase = new VideoRoomPuzzle(palette); } puzzleRenderer = new PuzzleRenderer(game, puzzleBase, false); game.setPuzzle(puzzleRenderer); game.update(); <DeepExtract> if (puzzleType.equals("grid")) { gridSizeView.setVisibility(View.VISIBLE); heightEditText.setVisibility(View.VISIBLE); } else if (puzzleType.equals("hexagon")) { gridSizeView.setVisibility(View.GONE); } else if (puzzleType.equals("jungle")) { gridSizeView.setVisibility(View.VISIBLE); heightEditText.setVisibility(View.GONE); } else if (puzzleType.equals("video_room")) { gridSizeView.setVisibility(View.GONE); } </DeepExtract> }
TheWitness-LockScreen
positive
3,973
public static CancelMessage parse(ByteBuffer buffer, TorrentInfo torrent) throws MessageValidationException { int piece = buffer.getInt(); int offset = buffer.getInt(); int length = buffer.getInt(); return this; }
public static CancelMessage parse(ByteBuffer buffer, TorrentInfo torrent) throws MessageValidationException { int piece = buffer.getInt(); int offset = buffer.getInt(); int length = buffer.getInt(); <DeepExtract> return this; </DeepExtract> }
ttorrent
positive
3,974
@Override protected void onDetachedFromWindow() { if (mAnimator != null) { mAnimator.end(); mAnimator.removeAllUpdateListeners(); mAnimator.cancel(); } mAnimator = null; mAnimationStarted = false; if (mGlobalLayoutListener != null) { getViewTreeObserver().removeGlobalOnLayoutListener(mGlobalLayoutListener); mGlobalLayoutListener = null; } super.onDetachedFromWindow(); }
@Override protected void onDetachedFromWindow() { <DeepExtract> if (mAnimator != null) { mAnimator.end(); mAnimator.removeAllUpdateListeners(); mAnimator.cancel(); } mAnimator = null; mAnimationStarted = false; </DeepExtract> if (mGlobalLayoutListener != null) { getViewTreeObserver().removeGlobalOnLayoutListener(mGlobalLayoutListener); mGlobalLayoutListener = null; } super.onDetachedFromWindow(); }
mylove
positive
3,976
public UserInfo getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new java.lang.IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); getTeacherById_result result = new getTeacherById_result(); receiveBase(result, "getTeacherById"); if (result.isSetSuccess()) { return result.success; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getTeacherById failed: unknown result"); }
public UserInfo getResult() throws org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new java.lang.IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); <DeepExtract> getTeacherById_result result = new getTeacherById_result(); receiveBase(result, "getTeacherById"); if (result.isSetSuccess()) { return result.success; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getTeacherById failed: unknown result"); </DeepExtract> }
imooc-Docker-Kubernetes-k8s
positive
3,977
public static Document getFormatDocument(String text, String charset) throws DocumentException, UnsupportedEncodingException { String formatText = new String(text.getBytes(Dom4JConstant.ENCODING_ISO_8859_1), Dom4JConstant.ENCODING_UTF_8); return DocumentHelper.parseText(formatText); }
public static Document getFormatDocument(String text, String charset) throws DocumentException, UnsupportedEncodingException { String formatText = new String(text.getBytes(Dom4JConstant.ENCODING_ISO_8859_1), Dom4JConstant.ENCODING_UTF_8); <DeepExtract> return DocumentHelper.parseText(formatText); </DeepExtract> }
Discovery-redis
positive
3,978
public List<String> binaryTreePaths(TreeNode root) { List<String> result = new ArrayList<String>(); if (root == null) { return result; } if (root == null) return; if (root.left == null && root.right == null) { result.add("" + root.val); return; } if (root.left != null) { pathHelper(root.left, "" + root.val + "->" + String.valueOf(root.left.val), result); } if (root.right != null) { pathHelper(root.right, "" + root.val + "->" + String.valueOf(root.right.val), result); } return result; }
public List<String> binaryTreePaths(TreeNode root) { List<String> result = new ArrayList<String>(); if (root == null) { return result; } <DeepExtract> if (root == null) return; if (root.left == null && root.right == null) { result.add("" + root.val); return; } if (root.left != null) { pathHelper(root.left, "" + root.val + "->" + String.valueOf(root.left.val), result); } if (root.right != null) { pathHelper(root.right, "" + root.val + "->" + String.valueOf(root.right.val), result); } </DeepExtract> return result; }
interviewprep
positive
3,979
public static void displayCriticalError(Throwable exception, boolean exitAfter) { Log.error(LogCategory.GENERAL, "A critical error occurred", exception); displayError(Localization.format("gui.error.header"), exception, tree -> { StringWriter error = new StringWriter(); error.append(Localization.format("gui.error.header")); if (exception != null) { error.append(System.lineSeparator()); exception.printStackTrace(new PrintWriter(error)); } tree.addButton(Localization.format("gui.button.copyError"), FabricBasicButtonType.CLICK_MANY).withClipboard(error.toString()); }, exitAfter); }
public static void displayCriticalError(Throwable exception, boolean exitAfter) { Log.error(LogCategory.GENERAL, "A critical error occurred", exception); <DeepExtract> displayError(Localization.format("gui.error.header"), exception, tree -> { StringWriter error = new StringWriter(); error.append(Localization.format("gui.error.header")); if (exception != null) { error.append(System.lineSeparator()); exception.printStackTrace(new PrintWriter(error)); } tree.addButton(Localization.format("gui.button.copyError"), FabricBasicButtonType.CLICK_MANY).withClipboard(error.toString()); }, exitAfter); </DeepExtract> }
fabric-loader
positive
3,980
private void init() { if (mInstance == null) { mInstance = new ConinDetailManager(MonitorApplication.getInstance()); } return mInstance; mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch(msg.what) { case MSG_REQUEST_DATA: requestBTCData(false); break; } } }; mBaseTimer = new BaseTimer(mContext); mBaseTimer.setHandler(mHandler, MSG_REQUEST_DATA); int interval = LocalConfigSharePreference.getDetailInterval(mContext); log.e("ConinDetailManager setTime = " + interval * 1000); mBaseTimer.setTimeInterval(interval * 1000 * 1000); }
private void init() { if (mInstance == null) { mInstance = new ConinDetailManager(MonitorApplication.getInstance()); } return mInstance; mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch(msg.what) { case MSG_REQUEST_DATA: requestBTCData(false); break; } } }; mBaseTimer = new BaseTimer(mContext); mBaseTimer.setHandler(mHandler, MSG_REQUEST_DATA); int interval = LocalConfigSharePreference.getDetailInterval(mContext); <DeepExtract> log.e("ConinDetailManager setTime = " + interval * 1000); mBaseTimer.setTimeInterval(interval * 1000 * 1000); </DeepExtract> }
BtcMonitor
positive
3,981
@Override public PublisherBuilder<T> peek(Consumer<? super T> consumer) { return new PublisherBuilderImpl<>(new Stages.Peek(consumer), this); }
@Override public PublisherBuilder<T> peek(Consumer<? super T> consumer) { <DeepExtract> return new PublisherBuilderImpl<>(new Stages.Peek(consumer), this); </DeepExtract> }
microprofile-reactive-streams-operators
positive
3,982
@Override public void removeUpdate(DocumentEvent e) { Document doc = e.getDocument(); String projectName = projectNameTextField.getText(); if (doc == txtPackage.getDocument()) { txtPackageCustom = txtPackage.getText().trim().length() != 0; } if (doc == projectNameTextField.getDocument() || doc == projectLocationTextField.getDocument()) { String projectFolder = projectLocationTextField.getText(); txtArtifactId.setText(projectName); createdFolderTextField.setText(projectFolder + File.separatorChar + projectName); } if (!txtPackageCustom && (doc == txtGroupId.getDocument() || doc == projectNameTextField.getDocument())) { txtPackage.getDocument().removeDocumentListener(this); txtPackage.setText(getPackageName(txtGroupId.getText() + "." + txtArtifactId.getText().replace("-", "."))); txtPackage.getDocument().addDocumentListener(this); } panel.fireChangeEvent(); if (this.projectNameTextField.getDocument() == e.getDocument()) { firePropertyChange(PROP_PROJECT_NAME, null, this.projectNameTextField.getText()); } if (this.txtGroupId.getDocument() == e.getDocument()) { firePropertyChange(PROP_GROUP_ID, null, this.txtGroupId.getText()); } }
@Override public void removeUpdate(DocumentEvent e) { <DeepExtract> Document doc = e.getDocument(); String projectName = projectNameTextField.getText(); if (doc == txtPackage.getDocument()) { txtPackageCustom = txtPackage.getText().trim().length() != 0; } if (doc == projectNameTextField.getDocument() || doc == projectLocationTextField.getDocument()) { String projectFolder = projectLocationTextField.getText(); txtArtifactId.setText(projectName); createdFolderTextField.setText(projectFolder + File.separatorChar + projectName); } if (!txtPackageCustom && (doc == txtGroupId.getDocument() || doc == projectNameTextField.getDocument())) { txtPackage.getDocument().removeDocumentListener(this); txtPackage.setText(getPackageName(txtGroupId.getText() + "." + txtArtifactId.getText().replace("-", "."))); txtPackage.getDocument().addDocumentListener(this); } panel.fireChangeEvent(); </DeepExtract> if (this.projectNameTextField.getDocument() == e.getDocument()) { firePropertyChange(PROP_PROJECT_NAME, null, this.projectNameTextField.getText()); } if (this.txtGroupId.getDocument() == e.getDocument()) { firePropertyChange(PROP_GROUP_ID, null, this.txtGroupId.getText()); } }
Aspose.BarCode-for-Java
positive
3,983
public void onClickShowFilters(View v) { setPanelVisibility(mFiltersList, true, false); mFiltersList.setAdapter(new FilterListAdapter(mShortVideoEditor.getBuiltinFilterList())); }
public void onClickShowFilters(View v) { <DeepExtract> setPanelVisibility(mFiltersList, true, false); </DeepExtract> mFiltersList.setAdapter(new FilterListAdapter(mShortVideoEditor.getBuiltinFilterList())); }
eden
positive
3,984
public HttpRequest authorization(final String authorization) { getConnection().setRequestProperty(HEADER_AUTHORIZATION, authorization); return this; }
public HttpRequest authorization(final String authorization) { <DeepExtract> getConnection().setRequestProperty(HEADER_AUTHORIZATION, authorization); return this; </DeepExtract> }
nanoleaf-aurora
positive
3,985
private void initButtons() { concentrateWrite = (Switch) findViewById(R.id.s_concentrate_write); concentrateWrite.setChecked(MyLitePrefs.getBoolean(MyLitePrefs.CONCENTRATE_WRITE)); concentrateWrite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { MyLitePrefs.putBoolean(MyLitePrefs.CONCENTRATE_WRITE, isChecked); } }); oneColumn = (CheckBox) findViewById(R.id.cb_one_column); oneColumn.setChecked(MyLitePrefs.getBoolean(MyLitePrefs.ONE_COLUMN)); oneColumn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { MyLitePrefs.putBoolean(MyLitePrefs.ONE_COLUMN, isChecked); refreshStartActivity(StartActivity.NEED_CONFIG_LAYOUT); } }); createOrder = (CheckBox) findViewById(R.id.cb_create_order); createOrder.setChecked(MyLitePrefs.getBoolean(MyLitePrefs.CREATE_ORDER)); createOrder.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { MyLitePrefs.putBoolean(MyLitePrefs.CREATE_ORDER, isChecked); refreshStartActivity(StartActivity.NEED_NOTIFY); } }); maxLengthRatio = (TextView) findViewById(R.id.tv_note_max_length); float ratio = MyLitePrefs.getFloat(MyLitePrefs.NOTE_MAX_LENGTH_RATIO); maxLengthRatio.setText(String.valueOf(ratio)); passwordGuard = (TextView) findViewById(R.id.tv_password_guard); if (MyLitePrefs.getBoolean(MyLitePrefs.PASSWORD_GUARD)) { passwordGuard.setText(R.string.password_guard_on); } else { passwordGuard.setText(R.string.password_guard_off); } passwordGuard.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!MyLitePrefs.getBoolean(MyLitePrefs.PASSWORD_GUARD)) { showCreatePasswordDialog(); } else { showCancelPasswordDialog(); } } }); if (MyLitePrefs.getBoolean(MyLitePrefs.SHOW_UNIVERSAL_SWITCH)) { findViewById(R.id.mr_universal_container).setVisibility(View.VISIBLE); findViewById(R.id.v_universal).setVisibility(View.VISIBLE); } universal = (CheckBox) findViewById(R.id.cb_universal); universal.setChecked(MyLitePrefs.getBoolean(MyLitePrefs.USE_UNIVERSAL_PASSWORD)); universal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { MyLitePrefs.putBoolean(MyLitePrefs.USE_UNIVERSAL_PASSWORD, b); } }); alwaysShow = (Switch) findViewById(R.id.s_notification_always_show); alwaysShow.setChecked(MyLitePrefs.getBoolean(MyLitePrefs.NOTIFICATION_ALWAYS_SHOW)); alwaysShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { MyLitePrefs.putBoolean(MyLitePrefs.NOTIFICATION_ALWAYS_SHOW, isChecked); AlarmService.showOrHide(mContext); } }); lightningExtract = (Switch) findViewById(R.id.s_lightning_extract); lightningExtract.setChecked(MyLitePrefs.getBoolean(MyLitePrefs.LIGHTNING_EXTRACT)); lightningExtract.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { MyLitePrefs.putBoolean(MyLitePrefs.LIGHTNING_EXTRACT, isChecked); if (isChecked) { if (Util.isServiceWork(mContext, "com.duanze.gasst.service.AlarmService")) { AlarmService.startExtractTask(mContext); } else { AlarmService.alarmTask(mContext); } } else { if (Util.isServiceWork(mContext, "com.duanze.gasst.service.AlarmService")) { AlarmService.stopExtractTask(mContext); } } } }); quickLocationSummary = (TextView) findViewById(R.id.tv_quick_location_summary); quickLocationSummary.setText(Util.readSaveLocation(MyLitePrefs.QUICK_WRITE_SAVE_LOCATION, mContext)); quickLocationSummary.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showSelectSaveLocationDialog(MyLitePrefs.QUICK_WRITE_SAVE_LOCATION, quickLocationSummary); } }); extractLocationSummary = (TextView) findViewById(R.id.tv_extract_location_summary); extractLocationSummary.setText(Util.readSaveLocation(MyLitePrefs.LIGHTNING_EXTRACT_SAVE_LOCATION, mContext)); extractLocationSummary.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showSelectSaveLocationDialog(MyLitePrefs.LIGHTNING_EXTRACT_SAVE_LOCATION, extractLocationSummary); } }); }
private void initButtons() { concentrateWrite = (Switch) findViewById(R.id.s_concentrate_write); concentrateWrite.setChecked(MyLitePrefs.getBoolean(MyLitePrefs.CONCENTRATE_WRITE)); concentrateWrite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { MyLitePrefs.putBoolean(MyLitePrefs.CONCENTRATE_WRITE, isChecked); } }); oneColumn = (CheckBox) findViewById(R.id.cb_one_column); oneColumn.setChecked(MyLitePrefs.getBoolean(MyLitePrefs.ONE_COLUMN)); oneColumn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { MyLitePrefs.putBoolean(MyLitePrefs.ONE_COLUMN, isChecked); refreshStartActivity(StartActivity.NEED_CONFIG_LAYOUT); } }); createOrder = (CheckBox) findViewById(R.id.cb_create_order); createOrder.setChecked(MyLitePrefs.getBoolean(MyLitePrefs.CREATE_ORDER)); createOrder.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { MyLitePrefs.putBoolean(MyLitePrefs.CREATE_ORDER, isChecked); refreshStartActivity(StartActivity.NEED_NOTIFY); } }); maxLengthRatio = (TextView) findViewById(R.id.tv_note_max_length); float ratio = MyLitePrefs.getFloat(MyLitePrefs.NOTE_MAX_LENGTH_RATIO); maxLengthRatio.setText(String.valueOf(ratio)); passwordGuard = (TextView) findViewById(R.id.tv_password_guard); <DeepExtract> if (MyLitePrefs.getBoolean(MyLitePrefs.PASSWORD_GUARD)) { passwordGuard.setText(R.string.password_guard_on); } else { passwordGuard.setText(R.string.password_guard_off); } </DeepExtract> passwordGuard.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!MyLitePrefs.getBoolean(MyLitePrefs.PASSWORD_GUARD)) { showCreatePasswordDialog(); } else { showCancelPasswordDialog(); } } }); if (MyLitePrefs.getBoolean(MyLitePrefs.SHOW_UNIVERSAL_SWITCH)) { findViewById(R.id.mr_universal_container).setVisibility(View.VISIBLE); findViewById(R.id.v_universal).setVisibility(View.VISIBLE); } universal = (CheckBox) findViewById(R.id.cb_universal); universal.setChecked(MyLitePrefs.getBoolean(MyLitePrefs.USE_UNIVERSAL_PASSWORD)); universal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { MyLitePrefs.putBoolean(MyLitePrefs.USE_UNIVERSAL_PASSWORD, b); } }); alwaysShow = (Switch) findViewById(R.id.s_notification_always_show); alwaysShow.setChecked(MyLitePrefs.getBoolean(MyLitePrefs.NOTIFICATION_ALWAYS_SHOW)); alwaysShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { MyLitePrefs.putBoolean(MyLitePrefs.NOTIFICATION_ALWAYS_SHOW, isChecked); AlarmService.showOrHide(mContext); } }); lightningExtract = (Switch) findViewById(R.id.s_lightning_extract); lightningExtract.setChecked(MyLitePrefs.getBoolean(MyLitePrefs.LIGHTNING_EXTRACT)); lightningExtract.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { MyLitePrefs.putBoolean(MyLitePrefs.LIGHTNING_EXTRACT, isChecked); if (isChecked) { if (Util.isServiceWork(mContext, "com.duanze.gasst.service.AlarmService")) { AlarmService.startExtractTask(mContext); } else { AlarmService.alarmTask(mContext); } } else { if (Util.isServiceWork(mContext, "com.duanze.gasst.service.AlarmService")) { AlarmService.stopExtractTask(mContext); } } } }); quickLocationSummary = (TextView) findViewById(R.id.tv_quick_location_summary); quickLocationSummary.setText(Util.readSaveLocation(MyLitePrefs.QUICK_WRITE_SAVE_LOCATION, mContext)); quickLocationSummary.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showSelectSaveLocationDialog(MyLitePrefs.QUICK_WRITE_SAVE_LOCATION, quickLocationSummary); } }); extractLocationSummary = (TextView) findViewById(R.id.tv_extract_location_summary); extractLocationSummary.setText(Util.readSaveLocation(MyLitePrefs.LIGHTNING_EXTRACT_SAVE_LOCATION, mContext)); extractLocationSummary.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showSelectSaveLocationDialog(MyLitePrefs.LIGHTNING_EXTRACT_SAVE_LOCATION, extractLocationSummary); } }); }
PureNote
positive
3,986
@Override public void onWriteAtPositionSuccess(String num) { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.cancel(); progressDialog = null; } mEdShowCard.setText(num); mTips.setText(R.string.m1_writing_success); }
@Override public void onWriteAtPositionSuccess(String num) { <DeepExtract> if (progressDialog != null && progressDialog.isShowing()) { progressDialog.cancel(); progressDialog = null; } </DeepExtract> mEdShowCard.setText(num); mTips.setText(R.string.m1_writing_success); }
CWDemo
positive
3,988
public void flingCapturedView(int minLeft, int minTop, int maxLeft, int maxTop) { if (!mReleaseInProgress) { throw new IllegalStateException("Cannot flingCapturedView outside of a call to " + "Callback#onViewReleased"); } mScroller.fling(mCapturedView.getLeft(), mCapturedView.getTop(), (int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId), (int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId), minLeft, maxLeft, minTop, maxTop); if (mDragState != STATE_SETTLING) { mDragState = STATE_SETTLING; mCallback.onViewDragStateChanged(STATE_SETTLING); if (STATE_SETTLING == STATE_IDLE) { mCapturedView = null; } } }
public void flingCapturedView(int minLeft, int minTop, int maxLeft, int maxTop) { if (!mReleaseInProgress) { throw new IllegalStateException("Cannot flingCapturedView outside of a call to " + "Callback#onViewReleased"); } mScroller.fling(mCapturedView.getLeft(), mCapturedView.getTop(), (int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId), (int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId), minLeft, maxLeft, minTop, maxTop); <DeepExtract> if (mDragState != STATE_SETTLING) { mDragState = STATE_SETTLING; mCallback.onViewDragStateChanged(STATE_SETTLING); if (STATE_SETTLING == STATE_IDLE) { mCapturedView = null; } } </DeepExtract> }
CustomProject
positive
3,989
private double errbd(double u, double[] cx) { count = count + 1; if (count > lim) { ifault = 4; throw new NonCovergeneceException(); } xconst = u * sigsq; sum1 = u * xconst; u = 2.0 * u; for (j = r - 1; j >= 0; j--) { nj = n[j]; lj = lb[j]; ncj = nc[j]; x = u * lj; y = 1.0 - x; xconst = xconst + lj * (ncj / y + nj) / y; sum1 = sum1 + ncj * square(x / y) + nj * (square(x) / y + log1(-x, false)); } cx[0] = xconst; return -0.5 * sum1 < -50.0 ? 0.0 : Math.exp(-0.5 * sum1); }
private double errbd(double u, double[] cx) { count = count + 1; if (count > lim) { ifault = 4; throw new NonCovergeneceException(); } xconst = u * sigsq; sum1 = u * xconst; u = 2.0 * u; for (j = r - 1; j >= 0; j--) { nj = n[j]; lj = lb[j]; ncj = nc[j]; x = u * lj; y = 1.0 - x; xconst = xconst + lj * (ncj / y + nj) / y; sum1 = sum1 + ncj * square(x / y) + nj * (square(x) / y + log1(-x, false)); } cx[0] = xconst; <DeepExtract> return -0.5 * sum1 < -50.0 ? 0.0 : Math.exp(-0.5 * sum1); </DeepExtract> }
Pascal
positive
3,990
private void consumeWithCheck() { int currentInputChar; if (buffer.length() > 0) { currentInputChar = buffer.getCharAt(0); } else { currentInputChar = getCharAt(position); } final int peekedNextInputChar = peekNextInputCharacter(1); final int previousInputChar = previousCharacter; boolean isCurrentCharHighSurrogate = Character.isHighSurrogate((char) currentInputChar); boolean isLowSurrogatePeekedNextInputChar = Character.isLowSurrogate((char) peekedNextInputChar); boolean isLowSurrogate = Character.isLowSurrogate((char) currentInputChar); boolean isHighSurrogatePeekendPreviousInputChar = Character.isHighSurrogate((char) previousInputChar); if (position > alreadyVisitedPosition && (invalidCharacters(currentInputChar) || (isLowSurrogate && !isHighSurrogatePeekendPreviousInputChar) || (isCurrentCharHighSurrogate && !isLowSurrogatePeekedNextInputChar) || (isCurrentCharHighSurrogate && isLowSurrogatePeekedNextInputChar && invalidCharacters(Character.toCodePoint((char) currentInputChar, (char) peekedNextInputChar))))) { tokenHandler.emitParseError(); } alreadyVisitedPosition = Math.max(position, alreadyVisitedPosition); }
private void consumeWithCheck() { <DeepExtract> int currentInputChar; if (buffer.length() > 0) { currentInputChar = buffer.getCharAt(0); } else { currentInputChar = getCharAt(position); } </DeepExtract> final int peekedNextInputChar = peekNextInputCharacter(1); final int previousInputChar = previousCharacter; boolean isCurrentCharHighSurrogate = Character.isHighSurrogate((char) currentInputChar); boolean isLowSurrogatePeekedNextInputChar = Character.isLowSurrogate((char) peekedNextInputChar); boolean isLowSurrogate = Character.isLowSurrogate((char) currentInputChar); boolean isHighSurrogatePeekendPreviousInputChar = Character.isHighSurrogate((char) previousInputChar); if (position > alreadyVisitedPosition && (invalidCharacters(currentInputChar) || (isLowSurrogate && !isHighSurrogatePeekendPreviousInputChar) || (isCurrentCharHighSurrogate && !isLowSurrogatePeekedNextInputChar) || (isCurrentCharHighSurrogate && isLowSurrogatePeekedNextInputChar && invalidCharacters(Character.toCodePoint((char) currentInputChar, (char) peekedNextInputChar))))) { tokenHandler.emitParseError(); } alreadyVisitedPosition = Math.max(position, alreadyVisitedPosition); }
jfiveparse
positive
3,991
@Override public void onPageFinishedLoading(String url) { LOG.d(TAG, "onPageFinished(" + url + ")"); loadUrlTimeout++; return pluginManager.postMessage("onPageFinished", url); if (engine.getView().getVisibility() != View.VISIBLE) { Thread t = new Thread(new Runnable() { public void run() { try { Thread.sleep(2000); cordova.getActivity().runOnUiThread(new Runnable() { public void run() { pluginManager.postMessage("spinner", "stop"); } }); } catch (InterruptedException e) { } } }); t.start(); } if (url.equals("about:blank")) { pluginManager.postMessage("exit", null); } }
@Override public void onPageFinishedLoading(String url) { LOG.d(TAG, "onPageFinished(" + url + ")"); loadUrlTimeout++; <DeepExtract> return pluginManager.postMessage("onPageFinished", url); </DeepExtract> if (engine.getView().getVisibility() != View.VISIBLE) { Thread t = new Thread(new Runnable() { public void run() { try { Thread.sleep(2000); cordova.getActivity().runOnUiThread(new Runnable() { public void run() { pluginManager.postMessage("spinner", "stop"); } }); } catch (InterruptedException e) { } } }); t.start(); } if (url.equals("about:blank")) { pluginManager.postMessage("exit", null); } }
cordova-plugin-app-update-demo
positive
3,992
public static byte getAsByteValue(final Object obj) { return getAsNumber(obj).byteValue(); }
public static byte getAsByteValue(final Object obj) { <DeepExtract> return getAsNumber(obj).byteValue(); </DeepExtract> }
database-all
positive
3,993
public void save() { List<ChunkPosition> modified = new ArrayList<>(this.modified); modified.forEach(c -> save(c, true)); this.modified.clear(); try { return backend.saveAll().get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); return null; } }
public void save() { List<ChunkPosition> modified = new ArrayList<>(this.modified); modified.forEach(c -> save(c, true)); this.modified.clear(); <DeepExtract> try { return backend.saveAll().get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); return null; } </DeepExtract> }
RedLib
positive
3,994
@Override public <W extends IBaseTabPageAdapter<T, V>> W addNoNotify(T bean) { addNoNotify(bean); notifyItemInserted(list_bean.size() - 1); return (W) this; return (W) this; }
@Override public <W extends IBaseTabPageAdapter<T, V>> W addNoNotify(T bean) { <DeepExtract> addNoNotify(bean); notifyItemInserted(list_bean.size() - 1); return (W) this; </DeepExtract> return (W) this; }
TabLayoutNiubility
positive
3,995
private void testMkdirs(@NonNull final Shell shell, @NonNull final Settings settings) { final CommandLineFile file3 = CommandLineFile.fromFile(shell, settings, test3); assertEquals(false, file3.exists()); assertEquals(false, file3.canRead()); assertEquals(false, file3.isSymlink()); assertEquals(false, file3.isDirectory()); assertEquals(0, file3.length()); assertTrue(file3.mkdirs()); assertEquals(true, file3.exists()); assertEquals(true, file3.canRead()); assertEquals(false, file3.isSymlink()); assertEquals(true, file3.isDirectory()); }
private void testMkdirs(@NonNull final Shell shell, @NonNull final Settings settings) { final CommandLineFile file3 = CommandLineFile.fromFile(shell, settings, test3); assertEquals(false, file3.exists()); assertEquals(false, file3.canRead()); assertEquals(false, file3.isSymlink()); assertEquals(false, file3.isDirectory()); assertEquals(0, file3.length()); assertTrue(file3.mkdirs()); <DeepExtract> assertEquals(true, file3.exists()); assertEquals(true, file3.canRead()); assertEquals(false, file3.isSymlink()); assertEquals(true, file3.isDirectory()); </DeepExtract> }
Pure-File-Manager
positive
3,996
@BeforeMethod public void prepareTest() { builder = PWAssociatedApp.builder(); builder.title(TITLE).idGooglePlay(ID_GOOGLE_PLAY).idAmazon(ID_AMAZON); }
@BeforeMethod public void prepareTest() { builder = PWAssociatedApp.builder(); <DeepExtract> builder.title(TITLE).idGooglePlay(ID_GOOGLE_PLAY).idAmazon(ID_AMAZON); </DeepExtract> }
jpasskit
positive
3,998
public Criteria andPhonecodeNotBetween(String value1, String value2) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "phonecode" + " cannot be null"); } criteria.add(new Criterion("phonecode not between", value1, value2)); return (Criteria) this; }
public Criteria andPhonecodeNotBetween(String value1, String value2) { <DeepExtract> if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "phonecode" + " cannot be null"); } criteria.add(new Criterion("phonecode not between", value1, value2)); </DeepExtract> return (Criteria) this; }
ssmBillBook
positive
3,999
public void terminate() { logger.debug("TERMINATE - START."); return this.disconnect(10, 10); if (disconnectReceiver != null) { org.ossie.corba.utils.deactivateObject(disconnectReceiver); } proxy = null; disconnectReceiver = null; logger.debug("TERMINATE - END."); }
public void terminate() { logger.debug("TERMINATE - START."); <DeepExtract> return this.disconnect(10, 10); </DeepExtract> if (disconnectReceiver != null) { org.ossie.corba.utils.deactivateObject(disconnectReceiver); } proxy = null; disconnectReceiver = null; logger.debug("TERMINATE - END."); }
framework-core
positive
4,000
public void actionPerformed(java.awt.event.ActionEvent evt) { new CodeWizard(this).setVisible(true); }
public void actionPerformed(java.awt.event.ActionEvent evt) { <DeepExtract> new CodeWizard(this).setVisible(true); </DeepExtract> }
8085simulator
positive
4,001
@Singleton @Provides @WanAndroidUrl Retrofit provideRetrofit(Retrofit.Builder builder, OkHttpClient client) { return builder.baseUrl(Constants.HOST).client(client).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build(); }
@Singleton @Provides @WanAndroidUrl Retrofit provideRetrofit(Retrofit.Builder builder, OkHttpClient client) { <DeepExtract> return builder.baseUrl(Constants.HOST).client(client).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build(); </DeepExtract> }
DavyWanAndroid
positive
4,002
public void testOverWriteRelease() throws MojoExecutionException, InterruptedException, IOException, MojoFailureException { Set<Artifact> artifacts = new HashSet<>(); Artifact release = stubFactory.getReleaseArtifact(); assertTrue(release.getFile().setLastModified(System.currentTimeMillis() - 2000)); artifacts.add(release); mojo.getProject().setArtifacts(artifacts); mojo.getProject().setDependencyArtifacts(artifacts); mojo.overWriteReleases = true; mojo.overWriteIfNewer = false; mojo.execute(); File unpackedFile = getUnpackedFile(release); Thread.sleep(100); long time = System.currentTimeMillis(); time = time - (time % 1000); assertTrue(unpackedFile.setLastModified(time)); Thread.sleep(1000); assertEquals(time, unpackedFile.lastModified()); mojo.execute(); if (true) { assertTrue(time != unpackedFile.lastModified()); } else { assertEquals(time, unpackedFile.lastModified()); } }
public void testOverWriteRelease() throws MojoExecutionException, InterruptedException, IOException, MojoFailureException { Set<Artifact> artifacts = new HashSet<>(); Artifact release = stubFactory.getReleaseArtifact(); assertTrue(release.getFile().setLastModified(System.currentTimeMillis() - 2000)); artifacts.add(release); mojo.getProject().setArtifacts(artifacts); mojo.getProject().setDependencyArtifacts(artifacts); mojo.overWriteReleases = true; mojo.overWriteIfNewer = false; mojo.execute(); <DeepExtract> File unpackedFile = getUnpackedFile(release); Thread.sleep(100); long time = System.currentTimeMillis(); time = time - (time % 1000); assertTrue(unpackedFile.setLastModified(time)); Thread.sleep(1000); assertEquals(time, unpackedFile.lastModified()); mojo.execute(); if (true) { assertTrue(time != unpackedFile.lastModified()); } else { assertEquals(time, unpackedFile.lastModified()); } </DeepExtract> }
maven-dependency-plugin
positive
4,003
public Criteria andIsmenuGreaterThan(String value) { if (value == null) { throw new RuntimeException("Value for " + "ismenu" + " cannot be null"); } criteria.add(new Criterion("ISMENU >", value)); return (Criteria) this; }
public Criteria andIsmenuGreaterThan(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "ismenu" + " cannot be null"); } criteria.add(new Criterion("ISMENU >", value)); </DeepExtract> return (Criteria) this; }
console
positive
4,004
private static boolean subNode_5(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "subNode_5")) return false; if (!recursion_guard_(b, l + 1, "subNodeDefault")) return false; if (!nextTokenIs(b, EQUAL)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, EQUAL); r = r && subNodeDefaultType(b, l + 1 + 1); exit_section_(b, m, null, r); return r; return true; }
private static boolean subNode_5(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "subNode_5")) return false; <DeepExtract> if (!recursion_guard_(b, l + 1, "subNodeDefault")) return false; if (!nextTokenIs(b, EQUAL)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, EQUAL); r = r && subNodeDefaultType(b, l + 1 + 1); exit_section_(b, m, null, r); return r; </DeepExtract> return true; }
IntelliJ_Jahia_plugin
positive
4,005
private List<Emoji> addQuantity(Emoji emoji, Pair pair, int quantity) { var list = new ArrayList<Emoji>(); var list = Arrays.asList(emoji); this.pairs.put(pair, list); return list; for (int i = 0; i < quantity; i++) list.add(emoji); return list; }
private List<Emoji> addQuantity(Emoji emoji, Pair pair, int quantity) { var list = new ArrayList<Emoji>(); <DeepExtract> var list = Arrays.asList(emoji); this.pairs.put(pair, list); return list; </DeepExtract> for (int i = 0; i < quantity; i++) list.add(emoji); return list; }
EmojIDE
positive
4,006
public static String get(String url, Map<String, String> header, Map<String, String> queries) { StringBuffer sb = new StringBuffer(url); if (queries != null && queries.keySet().size() > 0) { sb.append("?clientId=blade"); queries.forEach((k, v) -> sb.append("&").append(k).append("=").append(v)); } Request.Builder builder = new Request.Builder(); if (header != null && header.keySet().size() > 0) { header.forEach(builder::addHeader); } Request request = builder.url(sb.toString()).build(); String responseBody = ""; Response response = null; try { OkHttpClient okHttpClient = new OkHttpClient(); response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } } catch (Exception e) { log.error("okhttp3 post error >> ex = {}", e.getMessage()); } finally { if (response != null) { response.close(); } } return responseBody; }
public static String get(String url, Map<String, String> header, Map<String, String> queries) { StringBuffer sb = new StringBuffer(url); if (queries != null && queries.keySet().size() > 0) { sb.append("?clientId=blade"); queries.forEach((k, v) -> sb.append("&").append(k).append("=").append(v)); } Request.Builder builder = new Request.Builder(); if (header != null && header.keySet().size() > 0) { header.forEach(builder::addHeader); } Request request = builder.url(sb.toString()).build(); <DeepExtract> String responseBody = ""; Response response = null; try { OkHttpClient okHttpClient = new OkHttpClient(); response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } } catch (Exception e) { log.error("okhttp3 post error >> ex = {}", e.getMessage()); } finally { if (response != null) { response.close(); } } return responseBody; </DeepExtract> }
AIOPS
positive
4,007
@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Iconics.init(this); setContentView(R.layout.activity_main); unbinder = ButterKnife.bind(this); setSupportActionBar(toolbar); setupNavigationDrawer(); setupFAB(); pickMode = getIntent().getBooleanExtra(ARGS_PICK_MODE, false); if (savedInstanceState == null) { fragmentMode = FragmentMode.MODE_ALBUMS; initAlbumsFragment(); setContentFragment(); return; } fragmentMode = savedInstanceState.getInt(SAVE_FRAGMENT_MODE, FragmentMode.MODE_ALBUMS); switch(fragmentMode) { case FragmentMode.MODE_MEDIA: rvMediaFragment = (RvMediaFragment) getSupportFragmentManager().findFragmentByTag(RvMediaFragment.TAG); rvMediaFragment.setListener(this); break; case FragmentMode.MODE_ALBUMS: albumsFragment = (AlbumsFragment) getSupportFragmentManager().findFragmentByTag(AlbumsFragment.TAG); break; case FragmentMode.MODE_TIMELINE: setupUiForTimeline(); } }
@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Iconics.init(this); setContentView(R.layout.activity_main); unbinder = ButterKnife.bind(this); setSupportActionBar(toolbar); setupNavigationDrawer(); setupFAB(); pickMode = getIntent().getBooleanExtra(ARGS_PICK_MODE, false); if (savedInstanceState == null) { fragmentMode = FragmentMode.MODE_ALBUMS; initAlbumsFragment(); setContentFragment(); return; } <DeepExtract> fragmentMode = savedInstanceState.getInt(SAVE_FRAGMENT_MODE, FragmentMode.MODE_ALBUMS); </DeepExtract> switch(fragmentMode) { case FragmentMode.MODE_MEDIA: rvMediaFragment = (RvMediaFragment) getSupportFragmentManager().findFragmentByTag(RvMediaFragment.TAG); rvMediaFragment.setListener(this); break; case FragmentMode.MODE_ALBUMS: albumsFragment = (AlbumsFragment) getSupportFragmentManager().findFragmentByTag(AlbumsFragment.TAG); break; case FragmentMode.MODE_TIMELINE: setupUiForTimeline(); } }
leafpicrevived
positive
4,008
public StorageServer getFetchStorage(TrackerServer trackerServer, String groupName, String filename) throws IOException { ServerInfo[] servers; byte[] header; byte[] bFileName; byte[] bGroupName; byte[] bs; int len; String ip_addr; int port; boolean bNewConnection; Socket trackerSocket; if (trackerServer == null) { trackerServer = getConnection(); if (trackerServer == null) { servers = null; } bNewConnection = true; } else { bNewConnection = false; } trackerSocket = trackerServer.getSocket(); OutputStream out = trackerSocket.getOutputStream(); try { bs = groupName.getBytes(ClientGlobal.g_charset); bGroupName = new byte[ProtoCommon.FDFS_GROUP_NAME_MAX_LEN]; bFileName = filename.getBytes(ClientGlobal.g_charset); if (bs.length <= ProtoCommon.FDFS_GROUP_NAME_MAX_LEN) { len = bs.length; } else { len = ProtoCommon.FDFS_GROUP_NAME_MAX_LEN; } Arrays.fill(bGroupName, (byte) 0); System.arraycopy(bs, 0, bGroupName, 0, len); header = ProtoCommon.packHeader(ProtoCommon.TRACKER_PROTO_CMD_SERVICE_QUERY_FETCH_ONE, ProtoCommon.FDFS_GROUP_NAME_MAX_LEN + bFileName.length, (byte) 0); byte[] wholePkg = new byte[header.length + bGroupName.length + bFileName.length]; System.arraycopy(header, 0, wholePkg, 0, header.length); System.arraycopy(bGroupName, 0, wholePkg, header.length, bGroupName.length); System.arraycopy(bFileName, 0, wholePkg, header.length + bGroupName.length, bFileName.length); out.write(wholePkg); ProtoCommon.RecvPackageInfo pkgInfo = ProtoCommon.recvPackage(trackerSocket.getInputStream(), ProtoCommon.TRACKER_PROTO_CMD_RESP, -1); this.errno = pkgInfo.errno; if (pkgInfo.errno != 0) { servers = null; } if (pkgInfo.body.length < ProtoCommon.TRACKER_QUERY_STORAGE_FETCH_BODY_LEN) { throw new IOException("Invalid body length: " + pkgInfo.body.length); } if ((pkgInfo.body.length - ProtoCommon.TRACKER_QUERY_STORAGE_FETCH_BODY_LEN) % (ProtoCommon.FDFS_IPADDR_SIZE - 1) != 0) { throw new IOException("Invalid body length: " + pkgInfo.body.length); } int server_count = 1 + (pkgInfo.body.length - ProtoCommon.TRACKER_QUERY_STORAGE_FETCH_BODY_LEN) / (ProtoCommon.FDFS_IPADDR_SIZE - 1); ip_addr = new String(pkgInfo.body, ProtoCommon.FDFS_GROUP_NAME_MAX_LEN, ProtoCommon.FDFS_IPADDR_SIZE - 1).trim(); int offset = ProtoCommon.FDFS_GROUP_NAME_MAX_LEN + ProtoCommon.FDFS_IPADDR_SIZE - 1; port = (int) ProtoCommon.buff2long(pkgInfo.body, offset); offset += ProtoCommon.FDFS_PROTO_PKG_LEN_SIZE; ServerInfo[] servers = new ServerInfo[server_count]; servers[0] = new ServerInfo(ip_addr, port); for (int i = 1; i < server_count; i++) { servers[i] = new ServerInfo(new String(pkgInfo.body, offset, ProtoCommon.FDFS_IPADDR_SIZE - 1).trim(), port); offset += ProtoCommon.FDFS_IPADDR_SIZE - 1; } servers = servers; } catch (IOException ex) { if (!bNewConnection) { try { trackerServer.close(); } catch (IOException ex1) { ex1.printStackTrace(); } } throw ex; } finally { if (bNewConnection) { try { trackerServer.close(); } catch (IOException ex1) { ex1.printStackTrace(); } } } if (servers == null) { return null; } else { return new StorageServer(servers[0].getIpAddr(), servers[0].getPort(), 0); } }
public StorageServer getFetchStorage(TrackerServer trackerServer, String groupName, String filename) throws IOException { <DeepExtract> ServerInfo[] servers; byte[] header; byte[] bFileName; byte[] bGroupName; byte[] bs; int len; String ip_addr; int port; boolean bNewConnection; Socket trackerSocket; if (trackerServer == null) { trackerServer = getConnection(); if (trackerServer == null) { servers = null; } bNewConnection = true; } else { bNewConnection = false; } trackerSocket = trackerServer.getSocket(); OutputStream out = trackerSocket.getOutputStream(); try { bs = groupName.getBytes(ClientGlobal.g_charset); bGroupName = new byte[ProtoCommon.FDFS_GROUP_NAME_MAX_LEN]; bFileName = filename.getBytes(ClientGlobal.g_charset); if (bs.length <= ProtoCommon.FDFS_GROUP_NAME_MAX_LEN) { len = bs.length; } else { len = ProtoCommon.FDFS_GROUP_NAME_MAX_LEN; } Arrays.fill(bGroupName, (byte) 0); System.arraycopy(bs, 0, bGroupName, 0, len); header = ProtoCommon.packHeader(ProtoCommon.TRACKER_PROTO_CMD_SERVICE_QUERY_FETCH_ONE, ProtoCommon.FDFS_GROUP_NAME_MAX_LEN + bFileName.length, (byte) 0); byte[] wholePkg = new byte[header.length + bGroupName.length + bFileName.length]; System.arraycopy(header, 0, wholePkg, 0, header.length); System.arraycopy(bGroupName, 0, wholePkg, header.length, bGroupName.length); System.arraycopy(bFileName, 0, wholePkg, header.length + bGroupName.length, bFileName.length); out.write(wholePkg); ProtoCommon.RecvPackageInfo pkgInfo = ProtoCommon.recvPackage(trackerSocket.getInputStream(), ProtoCommon.TRACKER_PROTO_CMD_RESP, -1); this.errno = pkgInfo.errno; if (pkgInfo.errno != 0) { servers = null; } if (pkgInfo.body.length < ProtoCommon.TRACKER_QUERY_STORAGE_FETCH_BODY_LEN) { throw new IOException("Invalid body length: " + pkgInfo.body.length); } if ((pkgInfo.body.length - ProtoCommon.TRACKER_QUERY_STORAGE_FETCH_BODY_LEN) % (ProtoCommon.FDFS_IPADDR_SIZE - 1) != 0) { throw new IOException("Invalid body length: " + pkgInfo.body.length); } int server_count = 1 + (pkgInfo.body.length - ProtoCommon.TRACKER_QUERY_STORAGE_FETCH_BODY_LEN) / (ProtoCommon.FDFS_IPADDR_SIZE - 1); ip_addr = new String(pkgInfo.body, ProtoCommon.FDFS_GROUP_NAME_MAX_LEN, ProtoCommon.FDFS_IPADDR_SIZE - 1).trim(); int offset = ProtoCommon.FDFS_GROUP_NAME_MAX_LEN + ProtoCommon.FDFS_IPADDR_SIZE - 1; port = (int) ProtoCommon.buff2long(pkgInfo.body, offset); offset += ProtoCommon.FDFS_PROTO_PKG_LEN_SIZE; ServerInfo[] servers = new ServerInfo[server_count]; servers[0] = new ServerInfo(ip_addr, port); for (int i = 1; i < server_count; i++) { servers[i] = new ServerInfo(new String(pkgInfo.body, offset, ProtoCommon.FDFS_IPADDR_SIZE - 1).trim(), port); offset += ProtoCommon.FDFS_IPADDR_SIZE - 1; } servers = servers; } catch (IOException ex) { if (!bNewConnection) { try { trackerServer.close(); } catch (IOException ex1) { ex1.printStackTrace(); } } throw ex; } finally { if (bNewConnection) { try { trackerServer.close(); } catch (IOException ex1) { ex1.printStackTrace(); } } } </DeepExtract> if (servers == null) { return null; } else { return new StorageServer(servers[0].getIpAddr(), servers[0].getPort(), 0); } }
spring-boot-bulking
positive
4,009
public String getNetwork() { String protocolInfo = getProtocolInfo(); if (protocolInfo == null) return ""; String[] protocols = protocolInfo.split(":"); if (protocols == null || protocols.length <= 1) return ""; return protocols[1]; }
public String getNetwork() { <DeepExtract> String protocolInfo = getProtocolInfo(); if (protocolInfo == null) return ""; String[] protocols = protocolInfo.split(":"); if (protocols == null || protocols.length <= 1) return ""; return protocols[1]; </DeepExtract> }
CyberGarage4Android
positive
4,010
public void setLimited(boolean v) { USE_LIMITED_ACTIONS = v; setName("uct " + ((USE_SOFTMAX) ? "sof " : "") + ((USE_MACRO_ACTIONS) ? "mac " : "") + ((USE_PARTIAL_EXPANSION) ? "par " : "") + ((USE_ROULETTE_WHEEL_SELECTION) ? "rou " : "") + ((USE_HOLE_DETECTION) ? "hol " : "") + ((USE_LIMITED_ACTIONS) ? "lim " : "")); }
public void setLimited(boolean v) { USE_LIMITED_ACTIONS = v; <DeepExtract> setName("uct " + ((USE_SOFTMAX) ? "sof " : "") + ((USE_MACRO_ACTIONS) ? "mac " : "") + ((USE_PARTIAL_EXPANSION) ? "par " : "") + ((USE_ROULETTE_WHEEL_SELECTION) ? "rou " : "") + ((USE_HOLE_DETECTION) ? "hol " : "") + ((USE_LIMITED_ACTIONS) ? "lim " : "")); </DeepExtract> }
MCTSMario
positive
4,011
public Criteria andStatusLessThan(Integer value) { if (value == null) { throw new RuntimeException("Value for " + "status" + " cannot be null"); } criteria.add(new Criterion("status <", value)); return (Criteria) this; }
public Criteria andStatusLessThan(Integer value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "status" + " cannot be null"); } criteria.add(new Criterion("status <", value)); </DeepExtract> return (Criteria) this; }
common-admin
positive
4,012
@Deprecated public PartyCommand getPartyCommand() { return instance; }
@Deprecated public PartyCommand getPartyCommand() { <DeepExtract> return instance; </DeepExtract> }
BungeecordPartyAndFriends
positive
4,013
private void init(Analyzer analyzer, String keyspaceName, String cfName, String indexName, String vNodeName) throws IOException { this.indexName = indexName; this.keyspaceName = keyspaceName; this.cfName = cfName; this.analyzer = analyzer; this.vNodeName = vNodeName; if (logger.isDebugEnabled()) { logger.debug(indexName + " Lucene analyzer -" + analyzer); logger.debug(indexName + " Lucene version -" + Properties.luceneVersion); } file = LuceneUtils.getDirectory(keyspaceName, cfName, indexName, vNodeName); IndexWriterConfig config = new IndexWriterConfig(analyzer); config.setRAMBufferSizeMB(128); directory = FSDirectory.open(file.toPath()); if (logger.isInfoEnabled()) { logger.info(indexName + " SG Index - Opened dir[" + file.getAbsolutePath() + "] - OpenMode[" + OPEN_MODE + "]"); } return new IndexWriter(directory, config); searcherManager = new SearcherManager(indexWriter, true, new SearcherFactory()); }
private void init(Analyzer analyzer, String keyspaceName, String cfName, String indexName, String vNodeName) throws IOException { this.indexName = indexName; this.keyspaceName = keyspaceName; this.cfName = cfName; this.analyzer = analyzer; this.vNodeName = vNodeName; if (logger.isDebugEnabled()) { logger.debug(indexName + " Lucene analyzer -" + analyzer); logger.debug(indexName + " Lucene version -" + Properties.luceneVersion); } <DeepExtract> file = LuceneUtils.getDirectory(keyspaceName, cfName, indexName, vNodeName); IndexWriterConfig config = new IndexWriterConfig(analyzer); config.setRAMBufferSizeMB(128); directory = FSDirectory.open(file.toPath()); if (logger.isInfoEnabled()) { logger.info(indexName + " SG Index - Opened dir[" + file.getAbsolutePath() + "] - OpenMode[" + OPEN_MODE + "]"); } return new IndexWriter(directory, config); </DeepExtract> searcherManager = new SearcherManager(indexWriter, true, new SearcherFactory()); }
stargate-core
positive
4,014
public void incompleteList() throws Exception { this.search = "Needs Review"; ArrayList pms = Main.getSessionUser().getPermissions(); if (pms.contains(2)) { updateTable(getPatientList(Main.getSessionUser().getEmployeeId())); } else { updateTable(getPatientList()); } }
public void incompleteList() throws Exception { <DeepExtract> this.search = "Needs Review"; </DeepExtract> ArrayList pms = Main.getSessionUser().getPermissions(); if (pms.contains(2)) { updateTable(getPatientList(Main.getSessionUser().getEmployeeId())); } else { updateTable(getPatientList()); } }
RadiologyInformationSystem
positive
4,015
private void initializeViewPager() { pagerAdapter = new CoverImageAdapter(mPictureList, context); viewPager.setAdapter(pagerAdapter); viewPager.setCurrentItem(position, false); return this; }
private void initializeViewPager() { pagerAdapter = new CoverImageAdapter(mPictureList, context); viewPager.setAdapter(pagerAdapter); <DeepExtract> viewPager.setCurrentItem(position, false); return this; </DeepExtract> }
YCRefreshView
positive
4,016
@Override public void checkForAdd(User user) throws Exception { Result[] results = ServiceUtils.runChecks(checkDuplicateEmail(user.getEmail())); for (Result result : results) { if (!result.isSuccess()) { throw new Exception(result.getMessage()); } } }
@Override public void checkForAdd(User user) throws Exception { Result[] results = ServiceUtils.runChecks(checkDuplicateEmail(user.getEmail())); <DeepExtract> for (Result result : results) { if (!result.isSuccess()) { throw new Exception(result.getMessage()); } } </DeepExtract> }
javaBootcamp
positive
4,017
@Override public void onRequestCallback(String type, int result, String document) { super.onRequestCallback(type, result, document); String logInfo = String.format("onRequestCallback, type[%s], result[%d], document[%s]", type, result, document); mParent.printLogInfo(TAG, logInfo, mLogInfoText); }
@Override public void onRequestCallback(String type, int result, String document) { super.onRequestCallback(type, result, document); String logInfo = String.format("onRequestCallback, type[%s], result[%d], document[%s]", type, result, document); <DeepExtract> mParent.printLogInfo(TAG, logInfo, mLogInfoText); </DeepExtract> }
qcloud-iot-sdk-android
positive
4,018
public void extractHearst1() { ObjectArrayList<AnnotatedPhrase> tempProp = new ObjectArrayList<>(); this.rel = new AnnotatedPhrase(); IndexedWord beWord = new IndexedWord(); beWord.setWord("is"); beWord.setOriginalText("is"); beWord.setTag(POS_TAG.VBZ); beWord.setNER(NE_TYPE.NO_NER); beWord.setLemma("be"); beWord.setValue("is"); beWord.setIndex(-2); this.rel.addWordToList(beWord); this.rel.setRoot(beWord); this.tPattern = TokenSequencePattern.compile(REGEX.T_HEARST_1); this.tMatcher = this.tPattern.getMatcher(CoreNLPUtils.getCoreLabelListFromIndexedWordList(this.sentence)); while (this.tMatcher.find()) { ObjectArrayList<IndexedWord> matchedWords = CoreNLPUtils.listOfCoreMapWordsToIndexedWordList(this.tMatcher.groupNodes()); int objInd = -1; for (int i = 0; i < matchedWords.size(); i++) { if (!matchedWords.get(i).lemma().equals("such")) { tempWord = new IndexedWord(matchedWords.get(i)); tempWord.setWord(matchedWords.get(i).lemma()); this.obj.addWordToList(tempWord); objInd = i + 3; } else { break; } } IndexedWord w; if (objInd > -1) { for (int i = objInd; i < matchedWords.size(); i++) { w = matchedWords.get(i); if ((w.lemma().equals(CHARACTER.COMMA) || w.lemma().equals("and") || w.lemma().equals("or")) && w.ner().equals(NE_TYPE.NO_NER)) { subjRoot = CoreNLPUtils.getRootFromWordList(this.sentenceSemGraph, this.subj.getWordList()); objRoot = CoreNLPUtils.getRootFromWordList(this.sentenceSemGraph, this.obj.getWordList()); tempProp.add(new AnnotatedPhrase(this.subj.getWordList().clone(), subjRoot)); tempProp.add(new AnnotatedPhrase(this.rel.getWordList().clone(), this.rel.getRoot())); tempProp.add(new AnnotatedPhrase(this.obj.getWordList().clone(), objRoot)); this.propositions.add(new AnnotatedProposition(tempProp.clone(), new Attribution())); tempProp.clear(); this.subj.clear(); } else { this.subj.addWordToList(w); } } } subjRoot = CoreNLPUtils.getRootFromWordList(this.sentenceSemGraph, this.subj.getWordList()); objRoot = CoreNLPUtils.getRootFromWordList(this.sentenceSemGraph, this.obj.getWordList()); tempProp.add(new AnnotatedPhrase(this.subj.getWordList().clone(), subjRoot)); tempProp.add(new AnnotatedPhrase(this.rel.getWordList().clone(), this.rel.getRoot())); tempProp.add(new AnnotatedPhrase(this.obj.getWordList().clone(), objRoot)); this.propositions.add(new AnnotatedProposition(tempProp.clone(), new Attribution())); tempProp.clear(); this.subj.clear(); this.obj.clear(); } this.rel.clear(); }
public void extractHearst1() { ObjectArrayList<AnnotatedPhrase> tempProp = new ObjectArrayList<>(); <DeepExtract> this.rel = new AnnotatedPhrase(); IndexedWord beWord = new IndexedWord(); beWord.setWord("is"); beWord.setOriginalText("is"); beWord.setTag(POS_TAG.VBZ); beWord.setNER(NE_TYPE.NO_NER); beWord.setLemma("be"); beWord.setValue("is"); beWord.setIndex(-2); this.rel.addWordToList(beWord); this.rel.setRoot(beWord); </DeepExtract> this.tPattern = TokenSequencePattern.compile(REGEX.T_HEARST_1); this.tMatcher = this.tPattern.getMatcher(CoreNLPUtils.getCoreLabelListFromIndexedWordList(this.sentence)); while (this.tMatcher.find()) { ObjectArrayList<IndexedWord> matchedWords = CoreNLPUtils.listOfCoreMapWordsToIndexedWordList(this.tMatcher.groupNodes()); int objInd = -1; for (int i = 0; i < matchedWords.size(); i++) { if (!matchedWords.get(i).lemma().equals("such")) { tempWord = new IndexedWord(matchedWords.get(i)); tempWord.setWord(matchedWords.get(i).lemma()); this.obj.addWordToList(tempWord); objInd = i + 3; } else { break; } } IndexedWord w; if (objInd > -1) { for (int i = objInd; i < matchedWords.size(); i++) { w = matchedWords.get(i); if ((w.lemma().equals(CHARACTER.COMMA) || w.lemma().equals("and") || w.lemma().equals("or")) && w.ner().equals(NE_TYPE.NO_NER)) { subjRoot = CoreNLPUtils.getRootFromWordList(this.sentenceSemGraph, this.subj.getWordList()); objRoot = CoreNLPUtils.getRootFromWordList(this.sentenceSemGraph, this.obj.getWordList()); tempProp.add(new AnnotatedPhrase(this.subj.getWordList().clone(), subjRoot)); tempProp.add(new AnnotatedPhrase(this.rel.getWordList().clone(), this.rel.getRoot())); tempProp.add(new AnnotatedPhrase(this.obj.getWordList().clone(), objRoot)); this.propositions.add(new AnnotatedProposition(tempProp.clone(), new Attribution())); tempProp.clear(); this.subj.clear(); } else { this.subj.addWordToList(w); } } } subjRoot = CoreNLPUtils.getRootFromWordList(this.sentenceSemGraph, this.subj.getWordList()); objRoot = CoreNLPUtils.getRootFromWordList(this.sentenceSemGraph, this.obj.getWordList()); tempProp.add(new AnnotatedPhrase(this.subj.getWordList().clone(), subjRoot)); tempProp.add(new AnnotatedPhrase(this.rel.getWordList().clone(), this.rel.getRoot())); tempProp.add(new AnnotatedPhrase(this.obj.getWordList().clone(), objRoot)); this.propositions.add(new AnnotatedProposition(tempProp.clone(), new Attribution())); tempProp.clear(); this.subj.clear(); this.obj.clear(); } this.rel.clear(); }
SalIE
positive
4,019
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2022-01-18T11:03:45.534+08:00", comments = "Source Table: m_user") default Optional<MUser> selectByPrimaryKey(Long userId_) { return MyBatis3Utils.selectOne(this::selectOne, selectList, MUser, c -> c.where(userId, isEqualTo(userId_))); }
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2022-01-18T11:03:45.534+08:00", comments = "Source Table: m_user") default Optional<MUser> selectByPrimaryKey(Long userId_) { <DeepExtract> return MyBatis3Utils.selectOne(this::selectOne, selectList, MUser, c -> c.where(userId, isEqualTo(userId_))); </DeepExtract> }
harrier
positive
4,020
@Override public HttpResponse<byte[]> asByteArray() { final HttpResponse<T> response = sendWith(HttpResponse.BodyHandlers.ofByteArray()); context.afterResponse(this); return response; }
@Override public HttpResponse<byte[]> asByteArray() { <DeepExtract> final HttpResponse<T> response = sendWith(HttpResponse.BodyHandlers.ofByteArray()); context.afterResponse(this); return response; </DeepExtract> }
avaje-http
positive
4,021
@PreDestroy public void destroy() { final Map<String, Boolean> stoppedJobs = new HashMap<>(); synchronized (jobs) { final Iterator<Map.Entry<String, Future<?>>> iter = jobs.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<String, Future<?>> entry = iter.next(); stoppedJobs.put(entry.getKey(), entry.getValue().cancel(true)); iter.remove(); } } return stoppedJobs; }
@PreDestroy public void destroy() { <DeepExtract> final Map<String, Boolean> stoppedJobs = new HashMap<>(); synchronized (jobs) { final Iterator<Map.Entry<String, Future<?>>> iter = jobs.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<String, Future<?>> entry = iter.next(); stoppedJobs.put(entry.getKey(), entry.getValue().cancel(true)); iter.remove(); } } return stoppedJobs; </DeepExtract> }
wildfly-jar-maven-plugin
positive
4,023
public static double estimateThreshold(List<Sample> data, ThresholdStrategy strategy) throws TrainingException { if (data.size() < 2) { logger.info("EnergyDetector.estimateThreshold(): data.size() < 2!"); return 0.; } Mixture m = null; if (strategy == ThresholdStrategy.MEAN) { double t = 0.; for (Sample s : data) t += s.x[0]; return t / data.size(); } else if (strategy == ThresholdStrategy.CLUSTER || strategy == ThresholdStrategy.EM1 || strategy == ThresholdStrategy.EM5) { m = Initialization.hierarchicalGaussianClustering(data, 2, true, DensityRankingMethod.COVARIANCE); if (m.nd != 2) { logger.info("re-initializing with kMeans"); m = Initialization.kMeansClustering(data, 2, true); } } else throw new RuntimeException("EnergyDetector.estimateThreshold(): Invalid strategy!"); if (strategy == ThresholdStrategy.EM1 || strategy == ThresholdStrategy.EM5) m = Trainer.em(m, data); if (strategy == ThresholdStrategy.EM5) m = Trainer.em(m, data, 4); if (m.components.length != 2) throw new RuntimeException("EnergyDetector.decisionBoundary(): Mixture must be of 2 Gaussians!"); if (m.fd != 1) throw new RuntimeException("EnergyDetector.decisionBounrady(): Mixture feature dim must be 1!"); double[] x = { m.components[0].mue[0] }; double[] p = new double[2]; int n = 10000; double delta = (m.components[1].mue[0] - m.components[0].mue[0]) / n; while (n-- > 0) { m.evaluate(x); m.posteriors(p); if (p[1] > p[0]) break; else x[0] += delta; } return x[0]; }
public static double estimateThreshold(List<Sample> data, ThresholdStrategy strategy) throws TrainingException { if (data.size() < 2) { logger.info("EnergyDetector.estimateThreshold(): data.size() < 2!"); return 0.; } Mixture m = null; if (strategy == ThresholdStrategy.MEAN) { double t = 0.; for (Sample s : data) t += s.x[0]; return t / data.size(); } else if (strategy == ThresholdStrategy.CLUSTER || strategy == ThresholdStrategy.EM1 || strategy == ThresholdStrategy.EM5) { m = Initialization.hierarchicalGaussianClustering(data, 2, true, DensityRankingMethod.COVARIANCE); if (m.nd != 2) { logger.info("re-initializing with kMeans"); m = Initialization.kMeansClustering(data, 2, true); } } else throw new RuntimeException("EnergyDetector.estimateThreshold(): Invalid strategy!"); if (strategy == ThresholdStrategy.EM1 || strategy == ThresholdStrategy.EM5) m = Trainer.em(m, data); if (strategy == ThresholdStrategy.EM5) m = Trainer.em(m, data, 4); <DeepExtract> if (m.components.length != 2) throw new RuntimeException("EnergyDetector.decisionBoundary(): Mixture must be of 2 Gaussians!"); if (m.fd != 1) throw new RuntimeException("EnergyDetector.decisionBounrady(): Mixture feature dim must be 1!"); double[] x = { m.components[0].mue[0] }; double[] p = new double[2]; int n = 10000; double delta = (m.components[1].mue[0] - m.components[0].mue[0]) / n; while (n-- > 0) { m.evaluate(x); m.posteriors(p); if (p[1] > p[0]) break; else x[0] += delta; } return x[0]; </DeepExtract> }
crowdpp
positive
4,024
public void reset() { movePlayers(getTopLocation(), allPlayersProtected()); if (bossKilled == null) { System.err.println("[Catacombs] INTERNAL ERROR: bossKilled flag is null (attempt to set)"); } else { bossKilled.setBoolean(false); if (did <= 0) System.err.println("[Catacombs] INTERNAL ERROR: Attempt to set bossKilled on dungeon with no dungeon id " + name); else bossKilled.saveDB(plugin.getSql(), did); } for (CatLevel l : levels) { l.reset(plugin); } }
public void reset() { movePlayers(getTopLocation(), allPlayersProtected()); <DeepExtract> if (bossKilled == null) { System.err.println("[Catacombs] INTERNAL ERROR: bossKilled flag is null (attempt to set)"); } else { bossKilled.setBoolean(false); if (did <= 0) System.err.println("[Catacombs] INTERNAL ERROR: Attempt to set bossKilled on dungeon with no dungeon id " + name); else bossKilled.saveDB(plugin.getSql(), did); } </DeepExtract> for (CatLevel l : levels) { l.reset(plugin); } }
Catacombs
positive
4,025
private void handleFontFamily() { AlertDialog.Builder builder = new AlertDialog.Builder(this); final TextView title = new TextView(this); title.setText(R.string.dialog_font_family_title); title.setTextSize(Const.DIALOG_TITLE_SIZE); title.setPadding(Const.DIALOG_PADDING, Const.DIALOG_PADDING, Const.DIALOG_PADDING, Const.DIALOG_PADDING); boolean found = false; if (mFontFamily.equals("Monospace")) { title.setTypeface(Typeface.MONOSPACE); found = true; } else if (mFontFamily.equals("Sans Serif")) { title.setTypeface(Typeface.SANS_SERIF); found = true; } else if (mFontFamily.equals("Serif")) { title.setTypeface(Typeface.SERIF); found = true; } else if (mFontFamily.equals("Roboto Light")) { title.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL)); found = true; } else if (mFontFamily.equals("Roboto Medium")) { title.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); found = true; } else if (mFontFamily.equals("Roboto Condensed Light")) { title.setTypeface(FontCache.getFromAsset(this, "RobotoCondensed-Light.ttf")); found = true; } else if (mFontFamily.equals("Roboto Condensed Regular")) { title.setTypeface(Typeface.create("sans-serif-condensed", Typeface.NORMAL)); found = true; } else if (mFontFamily.equals("Roboto Mono Light")) { title.setTypeface(FontCache.getFromAsset(this, "RobotoMono-Light.ttf")); found = true; } else if (mFontFamily.equals("Roboto Mono Regular")) { title.setTypeface(FontCache.getFromAsset(this, "RobotoMono-Regular.ttf")); found = true; } else if (mFontFamily.equals("Roboto Slab Light")) { title.setTypeface(FontCache.getFromAsset(this, "RobotoSlab-Light.ttf")); found = true; } else if (mFontFamily.equals("Roboto Slab Regular")) { title.setTypeface(FontCache.getFromAsset(this, "RobotoSlab-Regular.ttf")); found = true; } else if (mFontFamily.equals("Roboto Slab Bold")) { title.setTypeface(FontCache.getFromAsset(this, "RobotoSlab-Bold.ttf")); found = true; } else if (mCustomFonts != null) { try { CustomFont font = (CustomFont) mCustomFonts.get(mFontFamily); if (font != null) { String path = mLocalRepoPath + "/" + Const.CUSTOM_FONTS_PATH + "/" + font.getPath(); title.setTypeface(FontCache.getFromFile(path)); found = true; } } catch (Exception e) { e.printStackTrace(); } } if (!found) { title.setTypeface(Typeface.SANS_SERIF); } builder.setCustomTitle(title); View view = getLayoutInflater().inflate(R.layout.number_picker, null); builder.setView(view); final NumberPicker picker = (NumberPicker) view.findViewById(R.id.numbers); List<String> fonts = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.font_family_values))); if (mCustomFonts != null) { Iterator iterator = mCustomFonts.entrySet().iterator(); while (iterator.hasNext()) { HashMap.Entry pair = (HashMap.Entry) iterator.next(); fonts.add(pair.getKey().toString()); } } Collections.sort(fonts, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.compareToIgnoreCase(s2); } }); final String[] items = fonts.toArray(new String[fonts.size()]); int pos = fonts.indexOf(mFontFamily); if (items.length > 0) { picker.setMinValue(0); picker.setMaxValue(items.length - 1); picker.setDisplayedValues(items); if (pos > 0) picker.setValue(pos); picker.setWrapSelectorWheel(true); } picker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { setFontFamily(title, items[picker.getValue()]); } }); builder.setPositiveButton(R.string.dialog_font_family_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mFontFamily = items[picker.getValue()]; mSharedPreferencesEditor.putString(Const.PREF_FONT_FAMILY, mFontFamily); mSharedPreferencesEditor.commit(); applyFontFamily(); return; } }); builder.setNegativeButton(R.string.dialog_font_family_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { return; } }); AlertDialog dialog = builder.show(); dialog.show(); }
private void handleFontFamily() { AlertDialog.Builder builder = new AlertDialog.Builder(this); final TextView title = new TextView(this); title.setText(R.string.dialog_font_family_title); title.setTextSize(Const.DIALOG_TITLE_SIZE); title.setPadding(Const.DIALOG_PADDING, Const.DIALOG_PADDING, Const.DIALOG_PADDING, Const.DIALOG_PADDING); <DeepExtract> boolean found = false; if (mFontFamily.equals("Monospace")) { title.setTypeface(Typeface.MONOSPACE); found = true; } else if (mFontFamily.equals("Sans Serif")) { title.setTypeface(Typeface.SANS_SERIF); found = true; } else if (mFontFamily.equals("Serif")) { title.setTypeface(Typeface.SERIF); found = true; } else if (mFontFamily.equals("Roboto Light")) { title.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL)); found = true; } else if (mFontFamily.equals("Roboto Medium")) { title.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); found = true; } else if (mFontFamily.equals("Roboto Condensed Light")) { title.setTypeface(FontCache.getFromAsset(this, "RobotoCondensed-Light.ttf")); found = true; } else if (mFontFamily.equals("Roboto Condensed Regular")) { title.setTypeface(Typeface.create("sans-serif-condensed", Typeface.NORMAL)); found = true; } else if (mFontFamily.equals("Roboto Mono Light")) { title.setTypeface(FontCache.getFromAsset(this, "RobotoMono-Light.ttf")); found = true; } else if (mFontFamily.equals("Roboto Mono Regular")) { title.setTypeface(FontCache.getFromAsset(this, "RobotoMono-Regular.ttf")); found = true; } else if (mFontFamily.equals("Roboto Slab Light")) { title.setTypeface(FontCache.getFromAsset(this, "RobotoSlab-Light.ttf")); found = true; } else if (mFontFamily.equals("Roboto Slab Regular")) { title.setTypeface(FontCache.getFromAsset(this, "RobotoSlab-Regular.ttf")); found = true; } else if (mFontFamily.equals("Roboto Slab Bold")) { title.setTypeface(FontCache.getFromAsset(this, "RobotoSlab-Bold.ttf")); found = true; } else if (mCustomFonts != null) { try { CustomFont font = (CustomFont) mCustomFonts.get(mFontFamily); if (font != null) { String path = mLocalRepoPath + "/" + Const.CUSTOM_FONTS_PATH + "/" + font.getPath(); title.setTypeface(FontCache.getFromFile(path)); found = true; } } catch (Exception e) { e.printStackTrace(); } } if (!found) { title.setTypeface(Typeface.SANS_SERIF); } </DeepExtract> builder.setCustomTitle(title); View view = getLayoutInflater().inflate(R.layout.number_picker, null); builder.setView(view); final NumberPicker picker = (NumberPicker) view.findViewById(R.id.numbers); List<String> fonts = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.font_family_values))); if (mCustomFonts != null) { Iterator iterator = mCustomFonts.entrySet().iterator(); while (iterator.hasNext()) { HashMap.Entry pair = (HashMap.Entry) iterator.next(); fonts.add(pair.getKey().toString()); } } Collections.sort(fonts, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.compareToIgnoreCase(s2); } }); final String[] items = fonts.toArray(new String[fonts.size()]); int pos = fonts.indexOf(mFontFamily); if (items.length > 0) { picker.setMinValue(0); picker.setMaxValue(items.length - 1); picker.setDisplayedValues(items); if (pos > 0) picker.setValue(pos); picker.setWrapSelectorWheel(true); } picker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { setFontFamily(title, items[picker.getValue()]); } }); builder.setPositiveButton(R.string.dialog_font_family_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mFontFamily = items[picker.getValue()]; mSharedPreferencesEditor.putString(Const.PREF_FONT_FAMILY, mFontFamily); mSharedPreferencesEditor.commit(); applyFontFamily(); return; } }); builder.setNegativeButton(R.string.dialog_font_family_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { return; } }); AlertDialog dialog = builder.show(); dialog.show(); }
neutrinote
positive
4,026
protected void receiveFloatFromSource(float val, String source) { if (min != 0 || max != 0) { val = Math.min(Math.max(val, min), max); } super.setValue(val); }
protected void receiveFloatFromSource(float val, String source) { <DeepExtract> if (min != 0 || max != 0) { val = Math.min(Math.max(val, min), max); } super.setValue(val); </DeepExtract> }
MobMuPlat
positive
4,027
@Override public void propagate(int evtmask) throws ContradictionException { for (int i = 0; i < n; i++) { t[i + i * n].instantiateTo(0, this); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (t[i + j * n].isInstantiatedTo(1)) { graph.enforceArc(i, j, this); } if (t[i + j * n].isInstantiatedTo(0)) { graph.removeArc(i, j, this); } } } for (int u = 0; u < n; u++) { for (int v : graph.getMandNeighOf(u)) { t[u + v * n].instantiateTo(1, this); } } for (int u = 0; u < n; u++) { Set<Integer> set = new HashSet<>(); for (int v : graph.getPotNeighOf(u)) { set.add(v); } for (int v = 0; v < n; v++) { if (!set.contains(v)) { t[u + v * n].instantiateTo(0, this); } } } gdm.unfreeze(); }
@Override public void propagate(int evtmask) throws ContradictionException { for (int i = 0; i < n; i++) { t[i + i * n].instantiateTo(0, this); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (t[i + j * n].isInstantiatedTo(1)) { graph.enforceArc(i, j, this); } if (t[i + j * n].isInstantiatedTo(0)) { graph.removeArc(i, j, this); } } } <DeepExtract> for (int u = 0; u < n; u++) { for (int v : graph.getMandNeighOf(u)) { t[u + v * n].instantiateTo(1, this); } } for (int u = 0; u < n; u++) { Set<Integer> set = new HashSet<>(); for (int v : graph.getPotNeighOf(u)) { set.add(v); } for (int v = 0; v < n; v++) { if (!set.contains(v)) { t[u + v * n].instantiateTo(0, this); } } } </DeepExtract> gdm.unfreeze(); }
choco-graph
positive
4,028
@Test public void writeReadInt16_PositiveValue_Succeeds() throws Exception { this.getWriter().writeInt16(null, POSITIVE_VALUE); assertEquals(POSITIVE_VALUE, this.getReader().readInt16(null)); }
@Test public void writeReadInt16_PositiveValue_Succeeds() throws Exception { <DeepExtract> this.getWriter().writeInt16(null, POSITIVE_VALUE); assertEquals(POSITIVE_VALUE, this.getReader().readInt16(null)); </DeepExtract> }
tesla
positive
4,029
@CheckReturnValue @Nonnull public KeyAffinityExecutorBuilder parallelism(int value) { return parallelism(value); return this; }
@CheckReturnValue @Nonnull public KeyAffinityExecutorBuilder parallelism(int value) { <DeepExtract> return parallelism(value); </DeepExtract> return this; }
more-lambdas-java
positive
4,030
@Override protected void onBindViewHolder2(ViewHolder holder, int position) { final Feed feed = getItem(position); mBinding.setVariable(com.mooc.ppjoke.BR.feed, feed); mBinding.setVariable(BR.lifeCycleOwner, mContext); if (mBinding instanceof LayoutFeedTypeImageBinding) { LayoutFeedTypeImageBinding imageBinding = (LayoutFeedTypeImageBinding) mBinding; feedImage = imageBinding.feedImage; imageBinding.feedImage.bindData(feed.width, feed.height, 16, feed.cover); } else if (mBinding instanceof LayoutFeedTypeVideoBinding) { LayoutFeedTypeVideoBinding videoBinding = (LayoutFeedTypeVideoBinding) mBinding; videoBinding.listPlayerView.bindData(mCategory, feed.width, feed.height, feed.cover, feed.url); listPlayerView = videoBinding.listPlayerView; } }
@Override protected void onBindViewHolder2(ViewHolder holder, int position) { final Feed feed = getItem(position); <DeepExtract> mBinding.setVariable(com.mooc.ppjoke.BR.feed, feed); mBinding.setVariable(BR.lifeCycleOwner, mContext); if (mBinding instanceof LayoutFeedTypeImageBinding) { LayoutFeedTypeImageBinding imageBinding = (LayoutFeedTypeImageBinding) mBinding; feedImage = imageBinding.feedImage; imageBinding.feedImage.bindData(feed.width, feed.height, 16, feed.cover); } else if (mBinding instanceof LayoutFeedTypeVideoBinding) { LayoutFeedTypeVideoBinding videoBinding = (LayoutFeedTypeVideoBinding) mBinding; videoBinding.listPlayerView.bindData(mCategory, feed.width, feed.height, feed.cover, feed.url); listPlayerView = videoBinding.listPlayerView; } </DeepExtract> }
Jetpack-MVVM-PPJoke
positive
4,031
public void run() { if (CarouselView.this.getChildCount() == 0) { endFling(true); return; } mShouldStopFling = false; synchronized (this) { rotator = mRotator; more = rotator.computeAngleOffset(); angle = rotator.getCurrAngle(); } float delta = mLastFlingAngle - angle; if (getChildCount() == 0) { return; } for (int i = 0; i < getAdapter().getCount(); i++) { CarouselItemView child = (CarouselItemView) getAdapter().getView(i, null, null); float angle = child.getCurrentAngle(); angle += delta; while (angle > 360.0f) angle -= 360.0f; while (angle < 0.0f) angle += 360.0f; child.setCurrentAngle(angle); Calculate3DPosition(child, getWidth(), angle); } mRecycler.clear(); invalidate(); if (more && !mShouldStopFling) { mLastFlingAngle = angle; post(this); } else { mLastFlingAngle = 0.0f; endFling(true); } }
public void run() { if (CarouselView.this.getChildCount() == 0) { endFling(true); return; } mShouldStopFling = false; synchronized (this) { rotator = mRotator; more = rotator.computeAngleOffset(); angle = rotator.getCurrAngle(); } float delta = mLastFlingAngle - angle; <DeepExtract> if (getChildCount() == 0) { return; } for (int i = 0; i < getAdapter().getCount(); i++) { CarouselItemView child = (CarouselItemView) getAdapter().getView(i, null, null); float angle = child.getCurrentAngle(); angle += delta; while (angle > 360.0f) angle -= 360.0f; while (angle < 0.0f) angle += 360.0f; child.setCurrentAngle(angle); Calculate3DPosition(child, getWidth(), angle); } mRecycler.clear(); invalidate(); </DeepExtract> if (more && !mShouldStopFling) { mLastFlingAngle = angle; post(this); } else { mLastFlingAngle = 0.0f; endFling(true); } }
createcjj
positive
4,032
public void addELResolver(ELResolver cELResolver) { if (elResolver == null) { CompositeELResolver resolver = new CompositeELResolver(); customResolvers = new CompositeELResolver(); resolver.add(customResolvers); resolver.add(new BeanNameELResolver(new LocalBeanNameResolver())); if (streamELResolver != null) { resolver.add(streamELResolver); } resolver.add(new StaticFieldELResolver()); resolver.add(new MapELResolver()); resolver.add(new ResourceBundleELResolver()); resolver.add(new ListELResolver()); resolver.add(new ArrayELResolver()); resolver.add(new BeanELResolver()); elResolver = resolver; } return elResolver; customResolvers.add(cELResolver); }
public void addELResolver(ELResolver cELResolver) { <DeepExtract> if (elResolver == null) { CompositeELResolver resolver = new CompositeELResolver(); customResolvers = new CompositeELResolver(); resolver.add(customResolvers); resolver.add(new BeanNameELResolver(new LocalBeanNameResolver())); if (streamELResolver != null) { resolver.add(streamELResolver); } resolver.add(new StaticFieldELResolver()); resolver.add(new MapELResolver()); resolver.add(new ResourceBundleELResolver()); resolver.add(new ListELResolver()); resolver.add(new ArrayELResolver()); resolver.add(new BeanELResolver()); elResolver = resolver; } return elResolver; </DeepExtract> customResolvers.add(cELResolver); }
uel-ri
positive
4,033
@Override public void setPaintMode() { if (isDisposed()) { return; } if (AlphaComposite.SrcOver == null) { throw new IllegalArgumentException("Cannot set a null composite."); } emit(new SetCompositeCommand(AlphaComposite.SrcOver)); state.setComposite(AlphaComposite.SrcOver); }
@Override public void setPaintMode() { <DeepExtract> if (isDisposed()) { return; } if (AlphaComposite.SrcOver == null) { throw new IllegalArgumentException("Cannot set a null composite."); } emit(new SetCompositeCommand(AlphaComposite.SrcOver)); state.setComposite(AlphaComposite.SrcOver); </DeepExtract> }
vectorgraphics2d
positive
4,034
private void txtValueActionPerformed(java.awt.event.ActionEvent evt) { String dataType = (String) lstValueDataType.getSelectedItem(); try { if ("String".equals(dataType)) { toReturn = txtValue.getText(); } else if ("int".equals(dataType)) { toReturn = Integer.parseInt(txtValue.getText()); } else if ("float".equals(dataType)) { toReturn = Float.parseFloat(txtValue.getText()); } else if ("boolean".equals(dataType)) { if (!"true".equalsIgnoreCase(txtValue.getText()) && !"false".equalsIgnoreCase(txtValue.getText())) { throw new Exception(); } toReturn = Boolean.parseBoolean(txtValue.getText()); } else if ("double".equals(dataType)) { toReturn = Double.parseDouble(txtValue.getText()); } else if ("long".equals(dataType)) { toReturn = Long.parseLong(txtValue.getText()); } else if ("byte".equals(dataType)) { toReturn = Byte.parseByte(txtValue.getText()); } dataType = (String) lstKeyDataType.getSelectedItem(); if ("String".equals(dataType)) { key = txtKey.getText(); } else if ("int".equals(dataType)) { key = Integer.parseInt(txtKey.getText()); } else if ("float".equals(dataType)) { key = Float.parseFloat(txtKey.getText()); } else if ("boolean".equals(dataType)) { if (!"true".equalsIgnoreCase(txtKey.getText()) && !"false".equalsIgnoreCase(txtKey.getText())) { throw new Exception(); } key = Boolean.parseBoolean(txtKey.getText()); } else if ("double".equals(dataType)) { key = Double.parseDouble(txtKey.getText()); } else if ("long".equals(dataType)) { key = Long.parseLong(txtKey.getText()); } else if ("byte".equals(dataType)) { key = Byte.parseByte(txtKey.getText()); } key = txtKey.getText(); dispose(); } catch (Exception e) { e.printStackTrace(); toReturn = null; key = null; } }
private void txtValueActionPerformed(java.awt.event.ActionEvent evt) { <DeepExtract> String dataType = (String) lstValueDataType.getSelectedItem(); try { if ("String".equals(dataType)) { toReturn = txtValue.getText(); } else if ("int".equals(dataType)) { toReturn = Integer.parseInt(txtValue.getText()); } else if ("float".equals(dataType)) { toReturn = Float.parseFloat(txtValue.getText()); } else if ("boolean".equals(dataType)) { if (!"true".equalsIgnoreCase(txtValue.getText()) && !"false".equalsIgnoreCase(txtValue.getText())) { throw new Exception(); } toReturn = Boolean.parseBoolean(txtValue.getText()); } else if ("double".equals(dataType)) { toReturn = Double.parseDouble(txtValue.getText()); } else if ("long".equals(dataType)) { toReturn = Long.parseLong(txtValue.getText()); } else if ("byte".equals(dataType)) { toReturn = Byte.parseByte(txtValue.getText()); } dataType = (String) lstKeyDataType.getSelectedItem(); if ("String".equals(dataType)) { key = txtKey.getText(); } else if ("int".equals(dataType)) { key = Integer.parseInt(txtKey.getText()); } else if ("float".equals(dataType)) { key = Float.parseFloat(txtKey.getText()); } else if ("boolean".equals(dataType)) { if (!"true".equalsIgnoreCase(txtKey.getText()) && !"false".equalsIgnoreCase(txtKey.getText())) { throw new Exception(); } key = Boolean.parseBoolean(txtKey.getText()); } else if ("double".equals(dataType)) { key = Double.parseDouble(txtKey.getText()); } else if ("long".equals(dataType)) { key = Long.parseLong(txtKey.getText()); } else if ("byte".equals(dataType)) { key = Byte.parseByte(txtKey.getText()); } key = txtKey.getText(); dispose(); } catch (Exception e) { e.printStackTrace(); toReturn = null; key = null; } </DeepExtract> }
JavaSnoop
positive
4,035
@Override protected FilterResults performFiltering(CharSequence charSequence) { String query = charSequence.toString(); if (query.isEmpty()) { sourceList = gc.getSources(); } else { List<Source> filteredList = new ArrayList<>(); for (Source source : gc.getSources()) { if (titoloFonte(source).toLowerCase().contains(query.toLowerCase())) { filteredList.add(source); } } sourceList = filteredList; } if (order > 0) { if (order == 5 || order == 6) { for (Source fonte : sourceList) { if (fonte.getExtension("citaz") == null) fonte.putExtension("citaz", quanteCitazioni(fonte)); } } Collections.sort(sourceList, (f1, f2) -> { switch(order) { case 1: return U.extractNum(f1.getId()) - U.extractNum(f2.getId()); case 2: return U.extractNum(f2.getId()) - U.extractNum(f1.getId()); case 3: return titoloFonte(f1).compareToIgnoreCase(titoloFonte(f2)); case 4: return titoloFonte(f2).compareToIgnoreCase(titoloFonte(f1)); case 5: return U.castJsonInt(f1.getExtension("citaz")) - U.castJsonInt(f2.getExtension("citaz")); case 6: return U.castJsonInt(f2.getExtension("citaz")) - U.castJsonInt(f1.getExtension("citaz")); } return 0; }); } FilterResults filterResults = new FilterResults(); filterResults.values = sourceList; return filterResults; }
@Override protected FilterResults performFiltering(CharSequence charSequence) { String query = charSequence.toString(); if (query.isEmpty()) { sourceList = gc.getSources(); } else { List<Source> filteredList = new ArrayList<>(); for (Source source : gc.getSources()) { if (titoloFonte(source).toLowerCase().contains(query.toLowerCase())) { filteredList.add(source); } } sourceList = filteredList; } <DeepExtract> if (order > 0) { if (order == 5 || order == 6) { for (Source fonte : sourceList) { if (fonte.getExtension("citaz") == null) fonte.putExtension("citaz", quanteCitazioni(fonte)); } } Collections.sort(sourceList, (f1, f2) -> { switch(order) { case 1: return U.extractNum(f1.getId()) - U.extractNum(f2.getId()); case 2: return U.extractNum(f2.getId()) - U.extractNum(f1.getId()); case 3: return titoloFonte(f1).compareToIgnoreCase(titoloFonte(f2)); case 4: return titoloFonte(f2).compareToIgnoreCase(titoloFonte(f1)); case 5: return U.castJsonInt(f1.getExtension("citaz")) - U.castJsonInt(f2.getExtension("citaz")); case 6: return U.castJsonInt(f2.getExtension("citaz")) - U.castJsonInt(f1.getExtension("citaz")); } return 0; }); } </DeepExtract> FilterResults filterResults = new FilterResults(); filterResults.values = sourceList; return filterResults; }
FamilyGem
positive
4,036
@Test public void getUserById118DisableFirstCache() { testService.getUserById118DisableFirstCache(118_118); try { Thread.sleep(2 * 1000); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } Collection<Cache> caches = cacheManager.getCache("user:info:118:3-0-2"); String key = "118118"; for (Cache cache : caches) { User result = cache.get(key, User.class); Assert.assertNotNull(result); result = ((LayeringCache) cache).getFirstCache().get(key, User.class); Assert.assertNull(result); result = ((LayeringCache) cache).getSecondCache().get(key, User.class); Assert.assertNotNull(result); } }
@Test public void getUserById118DisableFirstCache() { testService.getUserById118DisableFirstCache(118_118); <DeepExtract> try { Thread.sleep(2 * 1000); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } </DeepExtract> Collection<Cache> caches = cacheManager.getCache("user:info:118:3-0-2"); String key = "118118"; for (Cache cache : caches) { User result = cache.get(key, User.class); Assert.assertNotNull(result); result = ((LayeringCache) cache).getFirstCache().get(key, User.class); Assert.assertNull(result); result = ((LayeringCache) cache).getSecondCache().get(key, User.class); Assert.assertNotNull(result); } }
layering-cache
positive
4,037
public CompletableFuture<EntityWithIdAndVersion<T>> updateWithProvidedCommand(final String entityId, final Function<T, Optional<CT>> commandProvider, Optional<UpdateOptions> updateOptions) { CompletableFuture<T> result = new CompletableFuture<>(); attemptOperation(() -> { CompletableFuture<LoadedEntityWithMetadata> eo = aggregateStore.find(clasz, entityId, updateOptions.map(uo -> new FindOptions().withTriggeringEvent(uo.getTriggeringEvent()))).handleAsync((tEntityWithMetadata, throwable) -> { if (throwable == null) return new LoadedEntityWithMetadata(true, tEntityWithMetadata); else { logger.debug("Exception finding aggregate", throwable); Throwable unwrapped = CompletableFutureUtil.unwrap(throwable); if (unwrapped instanceof DuplicateTriggeringEventException) return new LoadedEntityWithMetadata(false, null); else if (unwrapped instanceof RuntimeException) throw (RuntimeException) unwrapped; else if (throwable instanceof RuntimeException) throw (RuntimeException) throwable; else throw new RuntimeException(throwable); } }); return eo.thenCompose(loadedEntityWithMetadata -> { if (loadedEntityWithMetadata.success) { EntityWithMetadata<T> entityWithMetaData = loadedEntityWithMetadata.ewmd; final T aggregate = entityWithMetaData.getEntity(); Outcome<List<Event>> commandResult = commandProvider.apply(aggregate).map(command -> { try { return new Outcome<>(aggregate.processCommand(command)); } catch (EventuateCommandProcessingFailedException e) { return new Outcome<List<Event>>(e.getCause()); } }).orElse(new Outcome<List<Event>>(Collections.emptyList())); UpdateEventsAndOptions transformed; if (commandResult.isFailure()) { Optional<UpdateEventsAndOptions> handled = interceptor.handleException(aggregate, commandResult.throwable, updateOptions); if (handled.isPresent()) transformed = handled.get(); else { throw new EventuateCommandProcessingFailedException(commandResult.throwable); } } else { List<Event> events = commandResult.result; Aggregates.applyEventsToMutableAggregate(aggregate, events, missingApplyEventMethodStrategy); UpdateEventsAndOptions original = new UpdateEventsAndOptions(events, updateOptions); transformed = updateOptions.flatMap(uo -> uo.getInterceptor()).orElse(interceptor).transformUpdate(aggregate, original); } List<Event> transformedEvents = transformed.getEvents(); Optional<UpdateOptions> transformedOptions = transformed.getOptions(); if (transformedEvents.isEmpty()) { return CompletableFuture.completedFuture(entityWithMetaData.toEntityWithIdAndVersion()); } else { CompletableFuture<EntityWithIdAndVersion<T>> result = new CompletableFuture<>(); aggregateStore.update(clasz, entityWithMetaData.getEntityIdAndVersion(), transformedEvents, withPossibleSnapshot(transformedOptions, aggregate, entityWithMetaData.getSnapshotVersion(), loadedEntityWithMetadata.ewmd.getEvents(), transformedEvents)).thenApply(entityIdAndVersion -> new EntityWithIdAndVersion<T>(entityIdAndVersion, aggregate)).handle((r, t) -> { if (t == null) { result.complete(r); } else { logger.debug("Exception updating aggregate", t); Throwable unwrapped = CompletableFutureUtil.unwrap(t); if (unwrapped instanceof DuplicateTriggeringEventException) { aggregateStore.find(clasz, entityId, Optional.empty()).handle((reloadedAggregate, findException) -> { if (findException == null) { result.complete(new EntityWithIdAndVersion<>(reloadedAggregate.getEntityIdAndVersion(), reloadedAggregate.getEntity())); } else { result.completeExceptionally(findException); } return null; }); } else result.completeExceptionally(unwrapped); } return null; }); return result; } } else { return aggregateStore.find(clasz, entityId, Optional.empty()).thenApply(EntityWithMetadata::toEntityWithIdAndVersion); } }); }, result, 0); return result; }
public CompletableFuture<EntityWithIdAndVersion<T>> updateWithProvidedCommand(final String entityId, final Function<T, Optional<CT>> commandProvider, Optional<UpdateOptions> updateOptions) { <DeepExtract> CompletableFuture<T> result = new CompletableFuture<>(); attemptOperation(() -> { CompletableFuture<LoadedEntityWithMetadata> eo = aggregateStore.find(clasz, entityId, updateOptions.map(uo -> new FindOptions().withTriggeringEvent(uo.getTriggeringEvent()))).handleAsync((tEntityWithMetadata, throwable) -> { if (throwable == null) return new LoadedEntityWithMetadata(true, tEntityWithMetadata); else { logger.debug("Exception finding aggregate", throwable); Throwable unwrapped = CompletableFutureUtil.unwrap(throwable); if (unwrapped instanceof DuplicateTriggeringEventException) return new LoadedEntityWithMetadata(false, null); else if (unwrapped instanceof RuntimeException) throw (RuntimeException) unwrapped; else if (throwable instanceof RuntimeException) throw (RuntimeException) throwable; else throw new RuntimeException(throwable); } }); return eo.thenCompose(loadedEntityWithMetadata -> { if (loadedEntityWithMetadata.success) { EntityWithMetadata<T> entityWithMetaData = loadedEntityWithMetadata.ewmd; final T aggregate = entityWithMetaData.getEntity(); Outcome<List<Event>> commandResult = commandProvider.apply(aggregate).map(command -> { try { return new Outcome<>(aggregate.processCommand(command)); } catch (EventuateCommandProcessingFailedException e) { return new Outcome<List<Event>>(e.getCause()); } }).orElse(new Outcome<List<Event>>(Collections.emptyList())); UpdateEventsAndOptions transformed; if (commandResult.isFailure()) { Optional<UpdateEventsAndOptions> handled = interceptor.handleException(aggregate, commandResult.throwable, updateOptions); if (handled.isPresent()) transformed = handled.get(); else { throw new EventuateCommandProcessingFailedException(commandResult.throwable); } } else { List<Event> events = commandResult.result; Aggregates.applyEventsToMutableAggregate(aggregate, events, missingApplyEventMethodStrategy); UpdateEventsAndOptions original = new UpdateEventsAndOptions(events, updateOptions); transformed = updateOptions.flatMap(uo -> uo.getInterceptor()).orElse(interceptor).transformUpdate(aggregate, original); } List<Event> transformedEvents = transformed.getEvents(); Optional<UpdateOptions> transformedOptions = transformed.getOptions(); if (transformedEvents.isEmpty()) { return CompletableFuture.completedFuture(entityWithMetaData.toEntityWithIdAndVersion()); } else { CompletableFuture<EntityWithIdAndVersion<T>> result = new CompletableFuture<>(); aggregateStore.update(clasz, entityWithMetaData.getEntityIdAndVersion(), transformedEvents, withPossibleSnapshot(transformedOptions, aggregate, entityWithMetaData.getSnapshotVersion(), loadedEntityWithMetadata.ewmd.getEvents(), transformedEvents)).thenApply(entityIdAndVersion -> new EntityWithIdAndVersion<T>(entityIdAndVersion, aggregate)).handle((r, t) -> { if (t == null) { result.complete(r); } else { logger.debug("Exception updating aggregate", t); Throwable unwrapped = CompletableFutureUtil.unwrap(t); if (unwrapped instanceof DuplicateTriggeringEventException) { aggregateStore.find(clasz, entityId, Optional.empty()).handle((reloadedAggregate, findException) -> { if (findException == null) { result.complete(new EntityWithIdAndVersion<>(reloadedAggregate.getEntityIdAndVersion(), reloadedAggregate.getEntity())); } else { result.completeExceptionally(findException); } return null; }); } else result.completeExceptionally(unwrapped); } return null; }); return result; } } else { return aggregateStore.find(clasz, entityId, Optional.empty()).thenApply(EntityWithMetadata::toEntityWithIdAndVersion); } }); }, result, 0); return result; </DeepExtract> }
light-eventuate-4j
positive
4,038
public void close_connection() { resultLines = new ArrayList<String>(); colNames = new ArrayList<String>(); colNamesStr = new String(); if (conn != null) { try { conn.close(); System.out.println("Database connection terminated"); } catch (Exception e) { } } }
public void close_connection() { <DeepExtract> resultLines = new ArrayList<String>(); colNames = new ArrayList<String>(); colNamesStr = new String(); </DeepExtract> if (conn != null) { try { conn.close(); System.out.println("Database connection terminated"); } catch (Exception e) { } } }
Topiary-Explorer
positive
4,039
public static void remove(Context mContext, String key) { SharedPreferences sp = mContext.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(key); try { if (sApplyMethod != null) { sApplyMethod.invoke(editor); return; } } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } editor.commit(); }
public static void remove(Context mContext, String key) { SharedPreferences sp = mContext.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(key); <DeepExtract> try { if (sApplyMethod != null) { sApplyMethod.invoke(editor); return; } } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } editor.commit(); </DeepExtract> }
Componentized
positive
4,040
public static prototest.Ex.AList parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { prototest.Ex.Hobby result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result).asInvalidProtocolBufferException(); } return result; }
public static prototest.Ex.AList parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { <DeepExtract> prototest.Ex.Hobby result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result).asInvalidProtocolBufferException(); } return result; </DeepExtract> }
hive-protobuf
positive
4,041
@Override public void onClick(View view, int position, MessageBean object) { Bundle bundle = new Bundle(); bundle.putString("peer", object.identifier); bundle.putString("type", "c2c"); Intent intent = new Intent(getActivity(), ChatActivity.class); intent.putExtras(bundle); startActivity(intent); }
@Override public void onClick(View view, int position, MessageBean object) { <DeepExtract> Bundle bundle = new Bundle(); bundle.putString("peer", object.identifier); bundle.putString("type", "c2c"); Intent intent = new Intent(getActivity(), ChatActivity.class); intent.putExtras(bundle); startActivity(intent); </DeepExtract> }
NoWordsChat
positive
4,042
@Test(groups = "integration", dependsOnMethods = { "testAuthorizationCapture" }) public void testAuthorizationVoid() throws PayPalRESTException { Payment payment = getPaymentAgainstAuthorization(); Payment authPayment = payment.create(TestConstants.SANDBOX_CONTEXT); Authorization authorization = authPayment.getTransactions().get(0).getRelatedResources().get(0).getAuthorization(); return authorization; }
@Test(groups = "integration", dependsOnMethods = { "testAuthorizationCapture" }) public void testAuthorizationVoid() throws PayPalRESTException { <DeepExtract> Payment payment = getPaymentAgainstAuthorization(); Payment authPayment = payment.create(TestConstants.SANDBOX_CONTEXT); Authorization authorization = authPayment.getTransactions().get(0).getRelatedResources().get(0).getAuthorization(); return authorization; </DeepExtract> }
PayPal-Java-SDK
positive
4,043
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActivityComponent().inject(this); setContentView(R.layout.activity_proxy); proxyRadioGroup = findViewById(R.id.proxyRadioGroup); proxyNoneRB = findViewById(R.id.proxyNone); proxyPsiphonRB = findViewById(R.id.proxyPsiphon); proxyCustomRB = findViewById(R.id.proxyCustom); customProxyRadioGroup = findViewById(R.id.customProxyRadioGroup); customProxySOCKS5 = findViewById(R.id.customProxySOCKS5); customProxyHostname = findViewById(R.id.customProxyHostname); customProxyPort = findViewById(R.id.customProxyPort); TextView proxyFooter = findViewById(R.id.proxyFooter); Markwon.setMarkdown(proxyFooter, getString(R.string.Settings_Proxy_Footer)); try { settings = ProxySettings.newProxySettings(preferenceManager); } catch (ProxySettings.InvalidProxyURL exc) { Log.w(TAG, "newProxySettings failed: " + exc); logger.w(TAG, "newProxySettings failed: " + exc); settings = new ProxySettings(); } configureInitialViewWithSettings(settings); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActivityComponent().inject(this); setContentView(R.layout.activity_proxy); proxyRadioGroup = findViewById(R.id.proxyRadioGroup); proxyNoneRB = findViewById(R.id.proxyNone); proxyPsiphonRB = findViewById(R.id.proxyPsiphon); proxyCustomRB = findViewById(R.id.proxyCustom); customProxyRadioGroup = findViewById(R.id.customProxyRadioGroup); customProxySOCKS5 = findViewById(R.id.customProxySOCKS5); customProxyHostname = findViewById(R.id.customProxyHostname); customProxyPort = findViewById(R.id.customProxyPort); TextView proxyFooter = findViewById(R.id.proxyFooter); Markwon.setMarkdown(proxyFooter, getString(R.string.Settings_Proxy_Footer)); <DeepExtract> try { settings = ProxySettings.newProxySettings(preferenceManager); } catch (ProxySettings.InvalidProxyURL exc) { Log.w(TAG, "newProxySettings failed: " + exc); logger.w(TAG, "newProxySettings failed: " + exc); settings = new ProxySettings(); } configureInitialViewWithSettings(settings); </DeepExtract> }
probe-android
positive
4,045
private int getContentItemCount() { return getHeaderCount() + getContentItemCount() + getFooterCount(); }
private int getContentItemCount() { <DeepExtract> return getHeaderCount() + getContentItemCount() + getFooterCount(); </DeepExtract> }
SwipeRecyclerView
positive
4,046
@Override public List<MimeRequest> precisionRequests(ExchangeInfo info, long delay) { MimeRequest request = new MimeRequest.Builder().url(ADDRESS + PRECISIONS).build(); return Collections.singletonList(request); }
@Override public List<MimeRequest> precisionRequests(ExchangeInfo info, long delay) { <DeepExtract> MimeRequest request = new MimeRequest.Builder().url(ADDRESS + PRECISIONS).build(); return Collections.singletonList(request); </DeepExtract> }
GOAi
positive
4,047