before
stringlengths
33
3.21M
after
stringlengths
63
3.21M
repo
stringlengths
1
56
type
stringclasses
1 value
__index_level_0__
int64
0
442k
@Override public void callbackValue(Object source, File[] ret) { boolean succ = true; if (ret == null || ret.length == 0 || !ret[0].isFile() || !ret[0].exists()) succ = false; if (succ) { PGPSecretKeyFinder finder = new PGPSecretKeyFinder(ret[0]); if (!finder.validFile()) { finder.close(); succ = false; } } if (!succ) { UICenter.message(_T.PGP_privkey_wrongfile.val()); return; } String tmppath = ResourceCenter.getSettings().get(Settings.lastpgp_privfile); if (tmppath == null || !tmppath.equals(ret[0].getAbsolutePath())) { ResourceCenter.getSettings().set(Settings.lastpgp_privfile, ret[0].getAbsolutePath()); ResourceCenter.getSettings().save(); } params.put(SuitePARAM.pgp_privkeyfile, ret[0].getAbsolutePath()); new PasswordInputdialog(source).main(cbpass, _T.PGP_privkeypasstitle.val()); }
@Override public void callbackValue(Object source, File[] ret) { <DeepExtract> boolean succ = true; if (ret == null || ret.length == 0 || !ret[0].isFile() || !ret[0].exists()) succ = false; if (succ) { PGPSecretKeyFinder finder = new PGPSecretKeyFinder(ret[0]); if (!finder.validFile()) { finder.close(); succ = false; } } if (!succ) { UICenter.message(_T.PGP_privkey_wrongfile.val()); return; } String tmppath = ResourceCenter.getSettings().get(Settings.lastpgp_privfile); if (tmppath == null || !tmppath.equals(ret[0].getAbsolutePath())) { ResourceCenter.getSettings().set(Settings.lastpgp_privfile, ret[0].getAbsolutePath()); ResourceCenter.getSettings().save(); } params.put(SuitePARAM.pgp_privkeyfile, ret[0].getAbsolutePath()); new PasswordInputdialog(source).main(cbpass, _T.PGP_privkeypasstitle.val()); </DeepExtract> }
CrococryptFile
positive
348
public void actionPerformed(java.awt.event.ActionEvent evt) { int[] sellist = listRestoreSelectedTables.getSelectedIndices(); for (int i = 0; i < sellist.length; i++) listRestoreSelectedModel.remove(listRestoreSelectedTables.getSelectedIndex()); }
public void actionPerformed(java.awt.event.ActionEvent evt) { <DeepExtract> int[] sellist = listRestoreSelectedTables.getSelectedIndices(); for (int i = 0; i < sellist.length; i++) listRestoreSelectedModel.remove(listRestoreSelectedTables.getSelectedIndex()); </DeepExtract> }
HBase-Manager
positive
349
protected void restart_lookahead() throws java.lang.Exception { for (int i = 1; i < error_sync_size(); i++) lookahead[i - 1] = lookahead[i]; lookahead[error_sync_size() - 1] = cur_token; Symbol sym = getScanner().next_token(); return (sym != null) ? sym : new Symbol(EOF_sym()); lookahead_pos = 0; }
protected void restart_lookahead() throws java.lang.Exception { for (int i = 1; i < error_sync_size(); i++) lookahead[i - 1] = lookahead[i]; lookahead[error_sync_size() - 1] = cur_token; <DeepExtract> Symbol sym = getScanner().next_token(); return (sym != null) ? sym : new Symbol(EOF_sym()); </DeepExtract> lookahead_pos = 0; }
Compiler
positive
350
public JSONObject editMulti(String multiPath, JSONObject multiObj) throws RedditApiException { if (!isLoggedIn()) { throw new RedditApiException("Reddit Login Required", true); } try { url = OAUTH_ENDPOINT + "/api/multi" + multiPath + "?model=" + URLEncoder.encode(multiObj.toString(), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new RedditApiException("Encoding error: " + e.getMessage()); } JSONObject jObj; try { String json = redditApiRequest(url, "PUT", REQUEST_MODE_AUTHED, null); jObj = new JSONObject(json); } catch (JSONException e) { e.printStackTrace(); throw new RedditApiException("Error: " + e.getMessage()); } return jObj; }
public JSONObject editMulti(String multiPath, JSONObject multiObj) throws RedditApiException { if (!isLoggedIn()) { throw new RedditApiException("Reddit Login Required", true); } try { url = OAUTH_ENDPOINT + "/api/multi" + multiPath + "?model=" + URLEncoder.encode(multiObj.toString(), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new RedditApiException("Encoding error: " + e.getMessage()); } <DeepExtract> JSONObject jObj; try { String json = redditApiRequest(url, "PUT", REQUEST_MODE_AUTHED, null); jObj = new JSONObject(json); } catch (JSONException e) { e.printStackTrace(); throw new RedditApiException("Error: " + e.getMessage()); } return jObj; </DeepExtract> }
reddinator
positive
351
public static String hexlify(final short[] value) { final StringBuilder builder = new StringBuilder("["); for (int i = 0, n = Array.getLength(value); i < n; i++) { if (i > 0) { builder.append(", "); } builder.append(String.format("0x%04x", Array.get(value, i))); } return builder.append("]").toString(); }
public static String hexlify(final short[] value) { <DeepExtract> final StringBuilder builder = new StringBuilder("["); for (int i = 0, n = Array.getLength(value); i < n; i++) { if (i > 0) { builder.append(", "); } builder.append(String.format("0x%04x", Array.get(value, i))); } return builder.append("]").toString(); </DeepExtract> }
aapt
positive
352
@Test public void unnecessaryChainId() { final BesuNodeConfig besuNodeConfig = BesuNodeConfigBuilder.aBesuNodeConfig().withGenesisFile("eth_hash_2018_no_replay_protection.json").build(); final SignerConfiguration signerConfig = new SignerConfigurationBuilder().build(); ethNode = BesuNodeFactory.create(besuNodeConfig); ethNode.start(); ethNode.awaitStartupCompletion(); ethSigner = new Signer(signerConfig, besuNodeConfig.getHostName(), ethNode.ports()); ethSigner.start(); ethSigner.awaitStartupCompletion(); final SignerResponse<JsonRpcErrorResponse> signerResponse = ethSigner.transactions().submitExceptional(Transaction.createEtherTransaction(richBenefactor().address(), richBenefactor().nextNonceAndIncrement(), GAS_PRICE, INTRINSIC_GAS, RECIPIENT, TRANSFER_AMOUNT_WEI)); assertThat(signerResponse.status()).isEqualTo(OK); assertThat(signerResponse.jsonRpc().getError()).isEqualTo(REPLAY_PROTECTED_SIGNATURES_NOT_SUPPORTED); }
@Test public void unnecessaryChainId() { <DeepExtract> final BesuNodeConfig besuNodeConfig = BesuNodeConfigBuilder.aBesuNodeConfig().withGenesisFile("eth_hash_2018_no_replay_protection.json").build(); final SignerConfiguration signerConfig = new SignerConfigurationBuilder().build(); ethNode = BesuNodeFactory.create(besuNodeConfig); ethNode.start(); ethNode.awaitStartupCompletion(); ethSigner = new Signer(signerConfig, besuNodeConfig.getHostName(), ethNode.ports()); ethSigner.start(); ethSigner.awaitStartupCompletion(); </DeepExtract> final SignerResponse<JsonRpcErrorResponse> signerResponse = ethSigner.transactions().submitExceptional(Transaction.createEtherTransaction(richBenefactor().address(), richBenefactor().nextNonceAndIncrement(), GAS_PRICE, INTRINSIC_GAS, RECIPIENT, TRANSFER_AMOUNT_WEI)); assertThat(signerResponse.status()).isEqualTo(OK); assertThat(signerResponse.jsonRpc().getError()).isEqualTo(REPLAY_PROTECTED_SIGNATURES_NOT_SUPPORTED); }
ethsigner
positive
354
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = request.getParameter("url"); String word = request.getParameter("word"); String dict = request.getParameter("dict"); if (url == null || word == null || dict == null) { return; } User user = (User) request.getSession().getAttribute("user"); UserWord userWord = new UserWord(); userWord.setDateTime(new Date()); userWord.setUserName(user == null ? "anonymity" : user.getUserName()); userWord.setWord(word); MySQLUtils.saveUserWordToDatabase(userWord); response.sendRedirect(url); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { <DeepExtract> String url = request.getParameter("url"); String word = request.getParameter("word"); String dict = request.getParameter("dict"); if (url == null || word == null || dict == null) { return; } User user = (User) request.getSession().getAttribute("user"); UserWord userWord = new UserWord(); userWord.setDateTime(new Date()); userWord.setUserName(user == null ? "anonymity" : user.getUserName()); userWord.setWord(word); MySQLUtils.saveUserWordToDatabase(userWord); response.sendRedirect(url); </DeepExtract> }
superword
positive
355
@SuppressLint("CommitTransaction") public void showFragment(Class<? extends Fragment> toFragmentClass) { if (toFragmentClass == null) { return; } String currentFragmentName = toFragmentClass.getSimpleName(); if (!TextUtils.isEmpty(mLastFragmentName) && mLastFragmentName.equals(currentFragmentName)) { return; } FragmentTransaction ft = mFragmentManager.beginTransaction(); ft.setCustomAnimations(R.animator.fade_in, R.animator.fade_out); if (mFragmentManager.findFragmentByTag(mLastFragmentName) != null && mFragmentManager.findFragmentByTag(mLastFragmentName).isVisible()) { ft.hide(mFragmentManager.findFragmentByTag(mLastFragmentName)); } Fragment toFragment = mFragmentManager.findFragmentByTag(currentFragmentName); if (toFragment != null) { ft.show(toFragment); } else { try { toFragment = toFragmentClass.newInstance(); } catch (InstantiationException | IllegalAccessException ignored) { } ft.add(mContentId, toFragment, currentFragmentName); } mLastFragmentName = currentFragmentName; ft.commitAllowingStateLoss(); }
@SuppressLint("CommitTransaction") public void showFragment(Class<? extends Fragment> toFragmentClass) { if (toFragmentClass == null) { return; } String currentFragmentName = toFragmentClass.getSimpleName(); if (!TextUtils.isEmpty(mLastFragmentName) && mLastFragmentName.equals(currentFragmentName)) { return; } FragmentTransaction ft = mFragmentManager.beginTransaction(); ft.setCustomAnimations(R.animator.fade_in, R.animator.fade_out); <DeepExtract> if (mFragmentManager.findFragmentByTag(mLastFragmentName) != null && mFragmentManager.findFragmentByTag(mLastFragmentName).isVisible()) { ft.hide(mFragmentManager.findFragmentByTag(mLastFragmentName)); } </DeepExtract> Fragment toFragment = mFragmentManager.findFragmentByTag(currentFragmentName); if (toFragment != null) { ft.show(toFragment); } else { try { toFragment = toFragmentClass.newInstance(); } catch (InstantiationException | IllegalAccessException ignored) { } ft.add(mContentId, toFragment, currentFragmentName); } mLastFragmentName = currentFragmentName; ft.commitAllowingStateLoss(); }
TimeTable
positive
357
@Test public void test10() throws Exception { if (null == null) { if (null == null) { Assert.assertTrue(config.parseArgs("data/potests/test10.asm", "-po", "size")); } else { Assert.assertTrue(config.parseArgs("data/potests/test10.asm", "-cpu", null, "-po", "size")); } } else { if (null == null) { Assert.assertTrue(config.parseArgs("data/potests/test10.asm", "-dialect", null, "-po", "size")); } else { Assert.assertTrue(config.parseArgs("data/potests/test10.asm", "-dialect", null, "-cpu", null, "-po", "size")); } } Assert.assertTrue("Could not parse file " + "data/potests/test10.asm", config.codeBaseParser.parseMainSourceFiles(config.inputFiles, code)); testInternal(2, 10, 10, "data/potests/test10-expected.asm"); }
@Test public void test10() throws Exception { <DeepExtract> if (null == null) { if (null == null) { Assert.assertTrue(config.parseArgs("data/potests/test10.asm", "-po", "size")); } else { Assert.assertTrue(config.parseArgs("data/potests/test10.asm", "-cpu", null, "-po", "size")); } } else { if (null == null) { Assert.assertTrue(config.parseArgs("data/potests/test10.asm", "-dialect", null, "-po", "size")); } else { Assert.assertTrue(config.parseArgs("data/potests/test10.asm", "-dialect", null, "-cpu", null, "-po", "size")); } } Assert.assertTrue("Could not parse file " + "data/potests/test10.asm", config.codeBaseParser.parseMainSourceFiles(config.inputFiles, code)); testInternal(2, 10, 10, "data/potests/test10-expected.asm"); </DeepExtract> }
mdlz80optimizer
positive
358
public Criteria andSignatureLessThanOrEqualTo(String value) { if (value == null) { throw new RuntimeException("Value for " + "signature" + " cannot be null"); } criteria.add(new Criterion("signature <=", value)); return (Criteria) this; }
public Criteria andSignatureLessThanOrEqualTo(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "signature" + " cannot be null"); } criteria.add(new Criterion("signature <=", value)); </DeepExtract> return (Criteria) this; }
wukong-framework
positive
359
public Criteria andCreateByNotIn(List<Long> values) { if (values == null) { throw new RuntimeException("Value for " + "createBy" + " cannot be null"); } criteria.add(new Criterion("create_by not in", values)); return (Criteria) this; }
public Criteria andCreateByNotIn(List<Long> values) { <DeepExtract> if (values == null) { throw new RuntimeException("Value for " + "createBy" + " cannot be null"); } criteria.add(new Criterion("create_by not in", values)); </DeepExtract> return (Criteria) this; }
CRM
positive
360
@Test @WithCredentials(credentialType = WithCredentials.USERNAME_PASSWORD, values = { MACHINE_USERNAME, "ath" }, id = SSH_CRED_ID) public void provisionSshSlaveWithPasswdAuthRetryOnFailedAuth() { ConfigFileProvider fileProvider = new ConfigFileProvider(jenkins); UserDataConfig cloudInit = fileProvider.addFile(UserDataConfig.class); cloudInit.name(CLOUD_INIT_NAME); cloudInit.content(resource("SeleniumTest/" + "cloud-init-authfix").asText()); cloudInit.save(); CloudsConfiguration.addCloud(jenkins, OpenstackCloud.class, cloud -> { if (OS_FIP_POOL_NAME != null) { cloud.associateFloatingIp(OS_FIP_POOL_NAME); } cloud.instanceCap(3); OpenstackSlaveTemplate template = cloud.addSlaveTemplate(); template.name(CLOUD_DEFAULT_TEMPLATE); template.labels("label"); template.hardwareId(OS_HARDWARE_ID); template.networkId(OS_NETWORK_ID); template.imageId(OS_IMAGE_ID); template.connectionType("SSH"); if ("SSH".equals("SSH")) { template.sshCredentials(SSH_CRED_ID); } template.userData(CLOUD_INIT_NAME); template.keyPair(OS_KEY_NAME); template.fsRoot("/tmp/jenkins"); }); FreeStyleJob job = jenkins.jobs.create(); job.configure(); job.setLabelExpression("label"); job.save(); job.scheduleBuild().waitUntilFinished(PROVISIONING_TIMEOUT).shouldSucceed(); }
@Test @WithCredentials(credentialType = WithCredentials.USERNAME_PASSWORD, values = { MACHINE_USERNAME, "ath" }, id = SSH_CRED_ID) public void provisionSshSlaveWithPasswdAuthRetryOnFailedAuth() { ConfigFileProvider fileProvider = new ConfigFileProvider(jenkins); UserDataConfig cloudInit = fileProvider.addFile(UserDataConfig.class); cloudInit.name(CLOUD_INIT_NAME); cloudInit.content(resource("SeleniumTest/" + "cloud-init-authfix").asText()); cloudInit.save(); <DeepExtract> CloudsConfiguration.addCloud(jenkins, OpenstackCloud.class, cloud -> { if (OS_FIP_POOL_NAME != null) { cloud.associateFloatingIp(OS_FIP_POOL_NAME); } cloud.instanceCap(3); OpenstackSlaveTemplate template = cloud.addSlaveTemplate(); template.name(CLOUD_DEFAULT_TEMPLATE); template.labels("label"); template.hardwareId(OS_HARDWARE_ID); template.networkId(OS_NETWORK_ID); template.imageId(OS_IMAGE_ID); template.connectionType("SSH"); if ("SSH".equals("SSH")) { template.sshCredentials(SSH_CRED_ID); } template.userData(CLOUD_INIT_NAME); template.keyPair(OS_KEY_NAME); template.fsRoot("/tmp/jenkins"); }); </DeepExtract> FreeStyleJob job = jenkins.jobs.create(); job.configure(); job.setLabelExpression("label"); job.save(); job.scheduleBuild().waitUntilFinished(PROVISIONING_TIMEOUT).shouldSucceed(); }
openstack-cloud-plugin
positive
362
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8")); workbook.write(response.getOutputStream()); } catch (Exception e) { throw new IOException(e.getMessage()); } }
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); <DeepExtract> try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8")); workbook.write(response.getOutputStream()); } catch (Exception e) { throw new IOException(e.getMessage()); } </DeepExtract> }
springboot
positive
363
public Criteria andGatewayPayTimeIsNotNull() { if ("gateway_pay_time is not null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("gateway_pay_time is not null")); return (Criteria) this; }
public Criteria andGatewayPayTimeIsNotNull() { <DeepExtract> if ("gateway_pay_time is not null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("gateway_pay_time is not null")); </DeepExtract> return (Criteria) this; }
springcloud-e-book
positive
364
@Override public void onSurfaceDestroyed() { if (mCaptureSession != null) { mCaptureSession.close(); mCaptureSession = null; } if (mCamera != null) { mCamera.close(); mCamera = null; } if (mStillImageReader != null) { mStillImageReader.close(); mStillImageReader = null; } if (mScanImageReader != null) { mScanImageReader.close(); mScanImageReader = null; } if (mMediaRecorder != null) { mMediaRecorder.stop(); mMediaRecorder.reset(); mMediaRecorder.release(); mMediaRecorder = null; if (mIsRecording) { mCallback.onRecordingEnd(); mCallback.onVideoRecorded(mVideoPath, 0, 0); mIsRecording = false; } } }
@Override public void onSurfaceDestroyed() { <DeepExtract> if (mCaptureSession != null) { mCaptureSession.close(); mCaptureSession = null; } if (mCamera != null) { mCamera.close(); mCamera = null; } if (mStillImageReader != null) { mStillImageReader.close(); mStillImageReader = null; } if (mScanImageReader != null) { mScanImageReader.close(); mScanImageReader = null; } if (mMediaRecorder != null) { mMediaRecorder.stop(); mMediaRecorder.reset(); mMediaRecorder.release(); mMediaRecorder = null; if (mIsRecording) { mCallback.onRecordingEnd(); mCallback.onVideoRecorded(mVideoPath, 0, 0); mIsRecording = false; } } </DeepExtract> }
react-native-camera
positive
365
@Override public String getCanonicalName() { return getClass().getSimpleName() + "(" + type + ")"; }
@Override public String getCanonicalName() { <DeepExtract> return getClass().getSimpleName() + "(" + type + ")"; </DeepExtract> }
jumi-actors
positive
366
public String getAwsSseCustomerKey() { checkProperty("aws.sse.customer.key"); return mProperties.getString("aws.sse.customer.key"); }
public String getAwsSseCustomerKey() { <DeepExtract> checkProperty("aws.sse.customer.key"); return mProperties.getString("aws.sse.customer.key"); </DeepExtract> }
secor
positive
367
public UserPlugins getRemotePluginList(String userName, List<String> modifiedKeys) throws UnauthorizedAccessException { if (!permissionManager.canAccessSpeakeasy(userName)) { log.warn("Unauthorized Speakeasy access by '" + userName + "'"); throw new UnauthorizedAccessException(userName, "Cannot access Speakeasy due to lack of permissions"); } Iterable<UserExtension> plugins = extensionManager.getAllUserExtensions(userName); UserPlugins userPlugins = new UserPlugins(filter(plugins, new AuthorAccessFilter(permissionManager.canAuthorExtensions(userName)))); userPlugins.setUpdated(modifiedKeys); return userPlugins; }
public UserPlugins getRemotePluginList(String userName, List<String> modifiedKeys) throws UnauthorizedAccessException { <DeepExtract> if (!permissionManager.canAccessSpeakeasy(userName)) { log.warn("Unauthorized Speakeasy access by '" + userName + "'"); throw new UnauthorizedAccessException(userName, "Cannot access Speakeasy due to lack of permissions"); } </DeepExtract> Iterable<UserExtension> plugins = extensionManager.getAllUserExtensions(userName); UserPlugins userPlugins = new UserPlugins(filter(plugins, new AuthorAccessFilter(permissionManager.canAuthorExtensions(userName)))); userPlugins.setUpdated(modifiedKeys); return userPlugins; }
speakeasy-plugin
positive
368
public static boolean regionEquals(String region, String regionThat) { if (region == null) { region = Constants.REGION_MAINLAND; } if (regionThat == null) { regionThat = Constants.REGION_MAINLAND; } return (region == regionThat) || (region != null && region.equals(regionThat)); }
public static boolean regionEquals(String region, String regionThat) { if (region == null) { region = Constants.REGION_MAINLAND; } if (regionThat == null) { regionThat = Constants.REGION_MAINLAND; } <DeepExtract> return (region == regionThat) || (region != null && region.equals(regionThat)); </DeepExtract> }
alibabacloud-httpdns-android-sdk
positive
369
@Test public void testArgumentFloatMinNormal() throws Exception { reparseSingleArgument(Float.MIN_NORMAL, EQUALS_COMPARATOR); }
@Test public void testArgumentFloatMinNormal() throws Exception { <DeepExtract> reparseSingleArgument(Float.MIN_NORMAL, EQUALS_COMPARATOR); </DeepExtract> }
JavaOSC
positive
370
public synchronized void headers(int flags, int streamId, List<String> nameValueBlock) throws IOException { nameValueBlockBuffer.reset(); int numberOfPairs = nameValueBlock.size() / 2; nameValueBlockOut.writeInt(numberOfPairs); for (String s : nameValueBlock) { nameValueBlockOut.writeInt(s.length()); nameValueBlockOut.write(s.getBytes("UTF-8")); } nameValueBlockOut.flush(); int type = SpdyConnection.TYPE_HEADERS; int length = nameValueBlockBuffer.size() + 4; out.writeInt(0x80000000 | (SpdyConnection.VERSION & 0x7fff) << 16 | type & 0xffff); out.writeInt((flags & 0xff) << 24 | length & 0xffffff); out.writeInt(streamId & 0x7fffffff); nameValueBlockBuffer.writeTo(out); out.flush(); }
public synchronized void headers(int flags, int streamId, List<String> nameValueBlock) throws IOException { <DeepExtract> nameValueBlockBuffer.reset(); int numberOfPairs = nameValueBlock.size() / 2; nameValueBlockOut.writeInt(numberOfPairs); for (String s : nameValueBlock) { nameValueBlockOut.writeInt(s.length()); nameValueBlockOut.write(s.getBytes("UTF-8")); } nameValueBlockOut.flush(); </DeepExtract> int type = SpdyConnection.TYPE_HEADERS; int length = nameValueBlockBuffer.size() + 4; out.writeInt(0x80000000 | (SpdyConnection.VERSION & 0x7fff) << 16 | type & 0xffff); out.writeInt((flags & 0xff) << 24 | length & 0xffffff); out.writeInt(streamId & 0x7fffffff); nameValueBlockBuffer.writeTo(out); out.flush(); }
phonegap-custom-camera-plugin
positive
371
public void setTypeface(Typeface tf, int style) { super.setTypeface(tf, style); requestLayout(); invalidate(); mTextPaint = new TextPaint(); mTextPaint.setAntiAlias(true); mTextPaint.setTextSize(getTextSize()); mTextPaint.setColor(mColor); mTextPaint.setStyle(Paint.Style.FILL); mTextPaint.setTypeface(getTypeface()); mTextPaintOutline = new TextPaint(); mTextPaintOutline.setAntiAlias(true); mTextPaintOutline.setTextSize(getTextSize()); mTextPaintOutline.setColor(mBorderColor); mTextPaintOutline.setStyle(Paint.Style.STROKE); mTextPaintOutline.setTypeface(getTypeface()); mTextPaintOutline.setStrokeWidth(mBorderSize); }
public void setTypeface(Typeface tf, int style) { super.setTypeface(tf, style); requestLayout(); invalidate(); <DeepExtract> mTextPaint = new TextPaint(); mTextPaint.setAntiAlias(true); mTextPaint.setTextSize(getTextSize()); mTextPaint.setColor(mColor); mTextPaint.setStyle(Paint.Style.FILL); mTextPaint.setTypeface(getTypeface()); mTextPaintOutline = new TextPaint(); mTextPaintOutline.setAntiAlias(true); mTextPaintOutline.setTextSize(getTextSize()); mTextPaintOutline.setColor(mBorderColor); mTextPaintOutline.setStyle(Paint.Style.STROKE); mTextPaintOutline.setTypeface(getTypeface()); mTextPaintOutline.setStrokeWidth(mBorderSize); </DeepExtract> }
BambooPlayer
positive
372
private void moveArcPosition() { double radians = Math.toRadians(currentRotation); float translateX = (float) Math.cos(radians) * (shipSpeedLevels[currentSpeedLevel]); float translateY = (float) Math.sin(radians) * (shipSpeedLevels[currentSpeedLevel]); arkSprite.translate(translateX, translateY); shipPosition.x = arkSprite.getX(); shipPosition.y = arkSprite.getY(); sprite.setPosition(shipPosition.x - sprite.getWidth() / 2, shipPosition.y - sprite.getHeight() / 2); tmpVector.set(shipPosition.x, shipPosition.y); body.setTransform(shipPosition.x, shipPosition.y, 0); }
private void moveArcPosition() { double radians = Math.toRadians(currentRotation); float translateX = (float) Math.cos(radians) * (shipSpeedLevels[currentSpeedLevel]); float translateY = (float) Math.sin(radians) * (shipSpeedLevels[currentSpeedLevel]); arkSprite.translate(translateX, translateY); shipPosition.x = arkSprite.getX(); shipPosition.y = arkSprite.getY(); <DeepExtract> sprite.setPosition(shipPosition.x - sprite.getWidth() / 2, shipPosition.y - sprite.getHeight() / 2); tmpVector.set(shipPosition.x, shipPosition.y); body.setTransform(shipPosition.x, shipPosition.y, 0); </DeepExtract> }
Alien-Ark
positive
373
public void initEvents() { List<EEvent> list = new LinkedList<>(); list.add(new EEvent(CPP_TIME, EEvent.CPP)); for (int i = 0; i < 10; ++i) { long time = i * SINGLE_CYCLE + OFFSET_10P; EEvent e = new EEvent(time, EEvent.PULSE_10P); list.add(e); } for (int i = 1; i < 10; ++i) { long time = i * SINGLE_CYCLE; EEvent e = new EEvent(time, EEvent.PULSE_9P); list.add(e); } list.add(new EEvent(10, EEvent.PULSE_1P)); list.add(new EEvent(20, EEvent.PULSE_2P)); list.add(new EEvent(30, EEvent.PULSE_2P)); list.add(new EEvent(40, EEvent.PULSE_2AP)); list.add(new EEvent(50, EEvent.PULSE_2AP)); list.add(new EEvent(60, EEvent.PULSE_4P)); list.add(new EEvent(70, EEvent.PULSE_4P)); list.add(new EEvent(80, EEvent.PULSE_4P)); list.add(new EEvent(90, EEvent.PULSE_4P)); list.add(new EEvent(100, EEvent.PULSE_1AP)); list.add(new EEvent(110, EEvent.CCG_UP)); list.add(new EEvent(180, EEvent.CCG_DOWN)); list.add(new EEvent(130, EEvent.RP)); list.add(new EEvent(190, EEvent.RP)); list.add(new EEvent(ADDITION_CYCLE, EEvent.GENERATE_NEW)); for (int i = 0; i < 20; ++i) { list.add(new EEvent(i * 10 + 6, EEvent.NOP)); } for (int i = 10; i < 20; ++i) { list.add(new EEvent(i * 10 + 3, EEvent.NOP)); list.add(new EEvent(i * 10 + 6, EEvent.NOP)); } list.add(new EEvent(120, EEvent.NOP)); list.add(new EEvent(140, EEvent.NOP)); list.add(new EEvent(150, EEvent.NOP)); list.add(new EEvent(160, EEvent.NOP)); _events = new EEvent[list.size()]; Collections.shuffle(list); list.toArray(_events); _queue.insert(_events); notifyAll(); }
public void initEvents() { List<EEvent> list = new LinkedList<>(); list.add(new EEvent(CPP_TIME, EEvent.CPP)); for (int i = 0; i < 10; ++i) { long time = i * SINGLE_CYCLE + OFFSET_10P; EEvent e = new EEvent(time, EEvent.PULSE_10P); list.add(e); } for (int i = 1; i < 10; ++i) { long time = i * SINGLE_CYCLE; EEvent e = new EEvent(time, EEvent.PULSE_9P); list.add(e); } list.add(new EEvent(10, EEvent.PULSE_1P)); list.add(new EEvent(20, EEvent.PULSE_2P)); list.add(new EEvent(30, EEvent.PULSE_2P)); list.add(new EEvent(40, EEvent.PULSE_2AP)); list.add(new EEvent(50, EEvent.PULSE_2AP)); list.add(new EEvent(60, EEvent.PULSE_4P)); list.add(new EEvent(70, EEvent.PULSE_4P)); list.add(new EEvent(80, EEvent.PULSE_4P)); list.add(new EEvent(90, EEvent.PULSE_4P)); list.add(new EEvent(100, EEvent.PULSE_1AP)); list.add(new EEvent(110, EEvent.CCG_UP)); list.add(new EEvent(180, EEvent.CCG_DOWN)); list.add(new EEvent(130, EEvent.RP)); list.add(new EEvent(190, EEvent.RP)); list.add(new EEvent(ADDITION_CYCLE, EEvent.GENERATE_NEW)); for (int i = 0; i < 20; ++i) { list.add(new EEvent(i * 10 + 6, EEvent.NOP)); } for (int i = 10; i < 20; ++i) { list.add(new EEvent(i * 10 + 3, EEvent.NOP)); list.add(new EEvent(i * 10 + 6, EEvent.NOP)); } list.add(new EEvent(120, EEvent.NOP)); list.add(new EEvent(140, EEvent.NOP)); list.add(new EEvent(150, EEvent.NOP)); list.add(new EEvent(160, EEvent.NOP)); _events = new EEvent[list.size()]; Collections.shuffle(list); list.toArray(_events); <DeepExtract> _queue.insert(_events); notifyAll(); </DeepExtract> }
eniac
positive
374
@Override public void clear() { if (mMemoryCache != null) { mMemoryCache.evictAll(); VolleyLog.d(TAG, "Memory cache cleared"); } }
@Override public void clear() { <DeepExtract> if (mMemoryCache != null) { mMemoryCache.evictAll(); VolleyLog.d(TAG, "Memory cache cleared"); } </DeepExtract> }
VolleyPlus
positive
375
private void sendSuccess(ResultReceiver receiver, Bundle data) { DataDroidLog.d(LOG_TAG, "sendResult : " + ((SUCCESS_CODE == SUCCESS_CODE) ? "Success" : "Failure")); if (receiver != null) { if (data == null) { data = new Bundle(); } receiver.send(SUCCESS_CODE, data); } }
private void sendSuccess(ResultReceiver receiver, Bundle data) { <DeepExtract> DataDroidLog.d(LOG_TAG, "sendResult : " + ((SUCCESS_CODE == SUCCESS_CODE) ? "Success" : "Failure")); if (receiver != null) { if (data == null) { data = new Bundle(); } receiver.send(SUCCESS_CODE, data); } </DeepExtract> }
Dribbble_rebuild
positive
378
private void init() { if (SCALE_TYPE != SCALE_TYPE) { throw new IllegalArgumentException(String.format("ScaleType %s not supported.", SCALE_TYPE)); } mReady = true; if (mSetupPending) { setup(); mSetupPending = false; } }
private void init() { <DeepExtract> if (SCALE_TYPE != SCALE_TYPE) { throw new IllegalArgumentException(String.format("ScaleType %s not supported.", SCALE_TYPE)); } </DeepExtract> mReady = true; if (mSetupPending) { setup(); mSetupPending = false; } }
book
positive
379
@Override protected final void onSizeChanged(int w, int h, int oldw, int oldh) { if (DEBUG) { Log.d(LOG_TAG, String.format("onSizeChanged. W: %d, H: %d", w, h)); } super.onSizeChanged(w, h, oldw, oldh); final int maximumPullScroll = (int) (getMaximumPullScroll() * 1.2f); int pLeft = getPaddingLeft(); int pTop = getPaddingTop(); int pRight = getPaddingRight(); int pBottom = getPaddingBottom(); switch(getPullToRefreshScrollDirection()) { case HORIZONTAL: if (mMode.showHeaderLoadingLayout()) { mHeaderLayout.setWidth(maximumPullScroll); pLeft = -maximumPullScroll; } else { pLeft = 0; } if (mMode.showFooterLoadingLayout()) { mFooterLayout.setWidth(maximumPullScroll); pRight = -maximumPullScroll; } else { pRight = 0; } break; case VERTICAL: if (mMode.showHeaderLoadingLayout()) { mHeaderLayout.setHeight(maximumPullScroll); pTop = -maximumPullScroll; } else { pTop = 0; } if (mMode.showFooterLoadingLayout()) { mFooterLayout.setHeight(maximumPullScroll); pBottom = -maximumPullScroll; } else { pBottom = 0; } break; } if (DEBUG) { Log.d(LOG_TAG, String.format("Setting Padding. L: %d, T: %d, R: %d, B: %d", pLeft, pTop, pRight, pBottom)); } setPadding(pLeft, pTop, pRight, pBottom); LayoutParams lp = (LayoutParams) mRefreshableViewWrapper.getLayoutParams(); switch(getPullToRefreshScrollDirection()) { case HORIZONTAL: if (lp.width != w) { lp.width = w; mRefreshableViewWrapper.requestLayout(); } break; case VERTICAL: if (lp.height != h) { lp.height = h; mRefreshableViewWrapper.requestLayout(); } break; } post(new Runnable() { @Override public void run() { requestLayout(); } }); }
@Override protected final void onSizeChanged(int w, int h, int oldw, int oldh) { if (DEBUG) { Log.d(LOG_TAG, String.format("onSizeChanged. W: %d, H: %d", w, h)); } super.onSizeChanged(w, h, oldw, oldh); final int maximumPullScroll = (int) (getMaximumPullScroll() * 1.2f); int pLeft = getPaddingLeft(); int pTop = getPaddingTop(); int pRight = getPaddingRight(); int pBottom = getPaddingBottom(); switch(getPullToRefreshScrollDirection()) { case HORIZONTAL: if (mMode.showHeaderLoadingLayout()) { mHeaderLayout.setWidth(maximumPullScroll); pLeft = -maximumPullScroll; } else { pLeft = 0; } if (mMode.showFooterLoadingLayout()) { mFooterLayout.setWidth(maximumPullScroll); pRight = -maximumPullScroll; } else { pRight = 0; } break; case VERTICAL: if (mMode.showHeaderLoadingLayout()) { mHeaderLayout.setHeight(maximumPullScroll); pTop = -maximumPullScroll; } else { pTop = 0; } if (mMode.showFooterLoadingLayout()) { mFooterLayout.setHeight(maximumPullScroll); pBottom = -maximumPullScroll; } else { pBottom = 0; } break; } if (DEBUG) { Log.d(LOG_TAG, String.format("Setting Padding. L: %d, T: %d, R: %d, B: %d", pLeft, pTop, pRight, pBottom)); } setPadding(pLeft, pTop, pRight, pBottom); <DeepExtract> LayoutParams lp = (LayoutParams) mRefreshableViewWrapper.getLayoutParams(); switch(getPullToRefreshScrollDirection()) { case HORIZONTAL: if (lp.width != w) { lp.width = w; mRefreshableViewWrapper.requestLayout(); } break; case VERTICAL: if (lp.height != h) { lp.height = h; mRefreshableViewWrapper.requestLayout(); } break; } </DeepExtract> post(new Runnable() { @Override public void run() { requestLayout(); } }); }
Android-Ptr-Comparison
positive
380
private void init() { if (true) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (isHardwareAccelerated()) { Paint hardwarePaint = new Paint(); hardwarePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.OVERLAY)); setLayerType(LAYER_TYPE_HARDWARE, hardwarePaint); } else { setLayerType(LAYER_TYPE_SOFTWARE, null); } } else { setDrawingCacheEnabled(true); } } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { setLayerType(LAYER_TYPE_SOFTWARE, null); } else { setDrawingCacheEnabled(true); } } boolean hasShot = getContext().getSharedPreferences(PREFS_SHOWCASE_INTERNAL, Context.MODE_PRIVATE).getBoolean("hasShot" + getConfigOptions().showcaseId, false); if (hasShot && mOptions.shotType == TYPE_ONE_SHOT) { setVisibility(View.GONE); isRedundant = true; return; } showcaseRadius = metricScale * INNER_CIRCLE_RADIUS; setOnTouchListener(this); if (!mOptions.noButton && mEndButton.getParent() == null) { RelativeLayout.LayoutParams lps = getConfigOptions().buttonLayoutParams; if (lps == null) { lps = (LayoutParams) generateDefaultLayoutParams(); lps.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); lps.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); int margin = ((Number) (metricScale * 12)).intValue(); lps.setMargins(margin, margin, margin, margin); } mEndButton.setLayoutParams(lps); mEndButton.setText(buttonText != null ? buttonText : getResources().getString(android.R.string.ok)); if (!hasCustomClickListener) { mEndButton.setOnClickListener(this); } addView(mEndButton); } }
private void init() { <DeepExtract> if (true) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (isHardwareAccelerated()) { Paint hardwarePaint = new Paint(); hardwarePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.OVERLAY)); setLayerType(LAYER_TYPE_HARDWARE, hardwarePaint); } else { setLayerType(LAYER_TYPE_SOFTWARE, null); } } else { setDrawingCacheEnabled(true); } } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { setLayerType(LAYER_TYPE_SOFTWARE, null); } else { setDrawingCacheEnabled(true); } } </DeepExtract> boolean hasShot = getContext().getSharedPreferences(PREFS_SHOWCASE_INTERNAL, Context.MODE_PRIVATE).getBoolean("hasShot" + getConfigOptions().showcaseId, false); if (hasShot && mOptions.shotType == TYPE_ONE_SHOT) { setVisibility(View.GONE); isRedundant = true; return; } showcaseRadius = metricScale * INNER_CIRCLE_RADIUS; setOnTouchListener(this); if (!mOptions.noButton && mEndButton.getParent() == null) { RelativeLayout.LayoutParams lps = getConfigOptions().buttonLayoutParams; if (lps == null) { lps = (LayoutParams) generateDefaultLayoutParams(); lps.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); lps.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); int margin = ((Number) (metricScale * 12)).intValue(); lps.setMargins(margin, margin, margin, margin); } mEndButton.setLayoutParams(lps); mEndButton.setText(buttonText != null ? buttonText : getResources().getString(android.R.string.ok)); if (!hasCustomClickListener) { mEndButton.setOnClickListener(this); } addView(mEndButton); } }
tinfoil-sms
positive
381
public Criteria andDeletedLessThan(Boolean value) { if (value == null) { throw new RuntimeException("Value for " + "deleted" + " cannot be null"); } criteria.add(new Criterion("deleted <", value)); return (Criteria) this; }
public Criteria andDeletedLessThan(Boolean value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "deleted" + " cannot be null"); } criteria.add(new Criterion("deleted <", value)); </DeepExtract> return (Criteria) this; }
mybatis-generator-gui-extension
positive
382
void waitAndPrintChangeSetEvents(String stack, String changeSet, Waiter<DescribeChangeSetRequest> waiter, PollConfiguration pollConfiguration) throws ExecutionException { final BasicFuture<AmazonWebServiceRequest> waitResult = new BasicFuture<>(null); waiter.runAsync(new WaiterParameters<>(new DescribeChangeSetRequest().withStackName(stack).withChangeSetName(changeSet)).withPollingStrategy(this.pollingStrategy(pollConfiguration)), new WaiterHandler() { @Override public void onWaitSuccess(AmazonWebServiceRequest request) { waitResult.completed(request); } @Override public void onWaitFailure(Exception e) { waitResult.failed(e); } }); Date startDate = new Date(); String lastEventId = null; this.printLine(); this.printStackName(stack); this.printLine(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); boolean run = true; if (pollConfiguration.getPollInterval().toMillis() > 0) { while (run && !waitResult.isDone()) { try { DescribeStackEventsResult result = this.client.describeStackEvents(new DescribeStackEventsRequest().withStackName(stack)); List<StackEvent> stackEvents = new ArrayList<>(); for (StackEvent event : result.getStackEvents()) { if (event.getEventId().equals(lastEventId) || event.getTimestamp().before(startDate)) { break; } stackEvents.add(event); } if (!stackEvents.isEmpty()) { Collections.reverse(stackEvents); for (StackEvent event : stackEvents) { this.printEvent(sdf, event); this.printLine(); } lastEventId = stackEvents.get(stackEvents.size() - 1).getEventId(); } } catch (AmazonCloudFormationException e) { } try { Thread.sleep(pollConfiguration.getPollInterval().toMillis()); } catch (InterruptedException e) { this.listener.getLogger().print("Task interrupted. Stopping event printer."); run = false; } } } try { waitResult.get(); } catch (InterruptedException e) { this.listener.getLogger().format("Failed to wait for CFN action to complete: %s", e.getMessage()); } }
void waitAndPrintChangeSetEvents(String stack, String changeSet, Waiter<DescribeChangeSetRequest> waiter, PollConfiguration pollConfiguration) throws ExecutionException { final BasicFuture<AmazonWebServiceRequest> waitResult = new BasicFuture<>(null); waiter.runAsync(new WaiterParameters<>(new DescribeChangeSetRequest().withStackName(stack).withChangeSetName(changeSet)).withPollingStrategy(this.pollingStrategy(pollConfiguration)), new WaiterHandler() { @Override public void onWaitSuccess(AmazonWebServiceRequest request) { waitResult.completed(request); } @Override public void onWaitFailure(Exception e) { waitResult.failed(e); } }); <DeepExtract> Date startDate = new Date(); String lastEventId = null; this.printLine(); this.printStackName(stack); this.printLine(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); boolean run = true; if (pollConfiguration.getPollInterval().toMillis() > 0) { while (run && !waitResult.isDone()) { try { DescribeStackEventsResult result = this.client.describeStackEvents(new DescribeStackEventsRequest().withStackName(stack)); List<StackEvent> stackEvents = new ArrayList<>(); for (StackEvent event : result.getStackEvents()) { if (event.getEventId().equals(lastEventId) || event.getTimestamp().before(startDate)) { break; } stackEvents.add(event); } if (!stackEvents.isEmpty()) { Collections.reverse(stackEvents); for (StackEvent event : stackEvents) { this.printEvent(sdf, event); this.printLine(); } lastEventId = stackEvents.get(stackEvents.size() - 1).getEventId(); } } catch (AmazonCloudFormationException e) { } try { Thread.sleep(pollConfiguration.getPollInterval().toMillis()); } catch (InterruptedException e) { this.listener.getLogger().print("Task interrupted. Stopping event printer."); run = false; } } } try { waitResult.get(); } catch (InterruptedException e) { this.listener.getLogger().format("Failed to wait for CFN action to complete: %s", e.getMessage()); } </DeepExtract> }
pipeline-aws-plugin
positive
383
@Override public void onSurfaceCreated(PineMediaPlayerView mediaPlayerView, SurfaceView surfaceView) { mSurfaceView = (PineSurfaceView) surfaceView; if (mMediaPlayer != null) { if (isAttachViewMode() && mSurfaceView != null) { mMediaPlayer.setDisplay(mSurfaceView.getHolder()); } else { mMediaPlayer.setDisplay(null); } } }
@Override public void onSurfaceCreated(PineMediaPlayerView mediaPlayerView, SurfaceView surfaceView) { mSurfaceView = (PineSurfaceView) surfaceView; <DeepExtract> if (mMediaPlayer != null) { if (isAttachViewMode() && mSurfaceView != null) { mMediaPlayer.setDisplay(mSurfaceView.getHolder()); } else { mMediaPlayer.setDisplay(null); } } </DeepExtract> }
PinePlayer
positive
384
@Test public void testConversionFromCartesian() { double cartesianEpsilon = 1E-8; Position pEq1 = new Position(0.0, 0.0, Position.WGS84_EQUATORIAL_RADIUS, true); if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pEq1.getLongitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pEq1.getLongitude()), 0.0, (pEq1.getLongitude() - 0.0) / 0.0, cartesianEpsilon); } if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pEq1.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pEq1.getLatitude()), 0.0, (pEq1.getLatitude() - 0.0) / 0.0, cartesianEpsilon); } Position pEq2 = new Position(Position.WGS84_EQUATORIAL_RADIUS, 0.0, 0.0, true); if (Math.abs(90.0) < 1.0) { Assert.assertEquals(90.0, pEq2.getLongitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 90.0, pEq2.getLongitude()), 0.0, (pEq2.getLongitude() - 90.0) / 90.0, cartesianEpsilon); } if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pEq2.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pEq2.getLatitude()), 0.0, (pEq2.getLatitude() - 0.0) / 0.0, cartesianEpsilon); } Position pEq3 = new Position(0.0, 0.0, -Position.WGS84_EQUATORIAL_RADIUS, true); if (Math.abs(-180.0) < 1.0) { Assert.assertEquals(-180.0, pEq3.getLongitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", -180.0, pEq3.getLongitude()), 0.0, (pEq3.getLongitude() - -180.0) / -180.0, cartesianEpsilon); } if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pEq3.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pEq3.getLatitude()), 0.0, (pEq3.getLatitude() - 0.0) / 0.0, cartesianEpsilon); } Position pEq4 = new Position(-Position.WGS84_EQUATORIAL_RADIUS, 0.0, 0.0, true); if (Math.abs(-90.0) < 1.0) { Assert.assertEquals(-90.0, pEq4.getLongitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", -90.0, pEq4.getLongitude()), 0.0, (pEq4.getLongitude() - -90.0) / -90.0, cartesianEpsilon); } if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pEq4.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pEq4.getLatitude()), 0.0, (pEq4.getLatitude() - 0.0) / 0.0, cartesianEpsilon); } Position pEq5 = new Position(Position.WGS84_EQUATORIAL_RADIUS / Math.sqrt(2), 0.0, Position.WGS84_EQUATORIAL_RADIUS / Math.sqrt(2), true); if (Math.abs(45.0) < 1.0) { Assert.assertEquals(45.0, pEq5.getLongitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 45.0, pEq5.getLongitude()), 0.0, (pEq5.getLongitude() - 45.0) / 45.0, cartesianEpsilon); } if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pEq5.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pEq5.getLatitude()), 0.0, (pEq5.getLatitude() - 0.0) / 0.0, cartesianEpsilon); } Position pN = new Position(0.0, Position.WGS84_POLAR_RADIUS, 0.0, true); if (Math.abs(90.0) < 1.0) { Assert.assertEquals(90.0, pN.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 90.0, pN.getLatitude()), 0.0, (pN.getLatitude() - 90.0) / 90.0, cartesianEpsilon); } Position pS = new Position(0.0, -Position.WGS84_POLAR_RADIUS, 0.0, true); if (Math.abs(-90.0) < 1.0) { Assert.assertEquals(-90.0, pS.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", -90.0, pS.getLatitude()), 0.0, (pS.getLatitude() - -90.0) / -90.0, cartesianEpsilon); } Position pHalfN = new Position(0.0, Position.WGS84_POLAR_RADIUS / Math.sqrt(2), Position.WGS84_EQUATORIAL_RADIUS / Math.sqrt(2), true); if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pHalfN.getLongitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pHalfN.getLongitude()), 0.0, (pHalfN.getLongitude() - 0.0) / 0.0, cartesianEpsilon); } if (Math.abs(45.0) < 1.0) { Assert.assertEquals(45.0, pHalfN.getLatitude(), 5E-3); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 45.0, pHalfN.getLatitude()), 0.0, (pHalfN.getLatitude() - 45.0) / 45.0, 5E-3); } }
@Test public void testConversionFromCartesian() { double cartesianEpsilon = 1E-8; Position pEq1 = new Position(0.0, 0.0, Position.WGS84_EQUATORIAL_RADIUS, true); if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pEq1.getLongitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pEq1.getLongitude()), 0.0, (pEq1.getLongitude() - 0.0) / 0.0, cartesianEpsilon); } if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pEq1.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pEq1.getLatitude()), 0.0, (pEq1.getLatitude() - 0.0) / 0.0, cartesianEpsilon); } Position pEq2 = new Position(Position.WGS84_EQUATORIAL_RADIUS, 0.0, 0.0, true); if (Math.abs(90.0) < 1.0) { Assert.assertEquals(90.0, pEq2.getLongitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 90.0, pEq2.getLongitude()), 0.0, (pEq2.getLongitude() - 90.0) / 90.0, cartesianEpsilon); } if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pEq2.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pEq2.getLatitude()), 0.0, (pEq2.getLatitude() - 0.0) / 0.0, cartesianEpsilon); } Position pEq3 = new Position(0.0, 0.0, -Position.WGS84_EQUATORIAL_RADIUS, true); if (Math.abs(-180.0) < 1.0) { Assert.assertEquals(-180.0, pEq3.getLongitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", -180.0, pEq3.getLongitude()), 0.0, (pEq3.getLongitude() - -180.0) / -180.0, cartesianEpsilon); } if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pEq3.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pEq3.getLatitude()), 0.0, (pEq3.getLatitude() - 0.0) / 0.0, cartesianEpsilon); } Position pEq4 = new Position(-Position.WGS84_EQUATORIAL_RADIUS, 0.0, 0.0, true); if (Math.abs(-90.0) < 1.0) { Assert.assertEquals(-90.0, pEq4.getLongitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", -90.0, pEq4.getLongitude()), 0.0, (pEq4.getLongitude() - -90.0) / -90.0, cartesianEpsilon); } if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pEq4.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pEq4.getLatitude()), 0.0, (pEq4.getLatitude() - 0.0) / 0.0, cartesianEpsilon); } Position pEq5 = new Position(Position.WGS84_EQUATORIAL_RADIUS / Math.sqrt(2), 0.0, Position.WGS84_EQUATORIAL_RADIUS / Math.sqrt(2), true); if (Math.abs(45.0) < 1.0) { Assert.assertEquals(45.0, pEq5.getLongitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 45.0, pEq5.getLongitude()), 0.0, (pEq5.getLongitude() - 45.0) / 45.0, cartesianEpsilon); } if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pEq5.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pEq5.getLatitude()), 0.0, (pEq5.getLatitude() - 0.0) / 0.0, cartesianEpsilon); } Position pN = new Position(0.0, Position.WGS84_POLAR_RADIUS, 0.0, true); if (Math.abs(90.0) < 1.0) { Assert.assertEquals(90.0, pN.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 90.0, pN.getLatitude()), 0.0, (pN.getLatitude() - 90.0) / 90.0, cartesianEpsilon); } Position pS = new Position(0.0, -Position.WGS84_POLAR_RADIUS, 0.0, true); if (Math.abs(-90.0) < 1.0) { Assert.assertEquals(-90.0, pS.getLatitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", -90.0, pS.getLatitude()), 0.0, (pS.getLatitude() - -90.0) / -90.0, cartesianEpsilon); } Position pHalfN = new Position(0.0, Position.WGS84_POLAR_RADIUS / Math.sqrt(2), Position.WGS84_EQUATORIAL_RADIUS / Math.sqrt(2), true); if (Math.abs(0.0) < 1.0) { Assert.assertEquals(0.0, pHalfN.getLongitude(), cartesianEpsilon); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 0.0, pHalfN.getLongitude()), 0.0, (pHalfN.getLongitude() - 0.0) / 0.0, cartesianEpsilon); } <DeepExtract> if (Math.abs(45.0) < 1.0) { Assert.assertEquals(45.0, pHalfN.getLatitude(), 5E-3); } else { Assert.assertEquals(String.format("Expected %.4f, got %.4f", 45.0, pHalfN.getLatitude()), 0.0, (pHalfN.getLatitude() - 45.0) / 45.0, 5E-3); } </DeepExtract> }
ensemble-clustering
positive
385
public static void drawFullFace(final AxisAlignedBB bb, final BlockPos blockPos, final float width, final int red, final int green, final int blue, final int alpha, final int alpha2) { NordTessellator.prepareGL(); NordTessellator.begin(7); drawFace(INSTANCE.getBuffer(), (float) blockPos.x, (float) blockPos.y, (float) blockPos.z, 1.0f, 1.0f, 1.0f, red, green, blue, alpha, 63); NordTessellator.render(); NordTessellator.releaseGL(); GlStateManager.pushMatrix(); GlStateManager.enableBlend(); GlStateManager.disableDepth(); GlStateManager.tryBlendFuncSeparate(770, 771, 0, 1); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); GL11.glEnable(2848); GL11.glHint(3154, 4354); GL11.glLineWidth(width); final Tessellator tessellator = Tessellator.getInstance(); final BufferBuilder bufferbuilder = tessellator.getBuffer(); bufferbuilder.begin(3, DefaultVertexFormats.POSITION_COLOR); bufferbuilder.pos(bb.minX, bb.minY, bb.minZ).color(red, green, blue, alpha2).endVertex(); bufferbuilder.pos(bb.minX, bb.minY, bb.maxZ).color(red, green, blue, alpha2).endVertex(); bufferbuilder.pos(bb.maxX, bb.minY, bb.maxZ).color(red, green, blue, alpha2).endVertex(); bufferbuilder.pos(bb.maxX, bb.minY, bb.minZ).color(red, green, blue, alpha2).endVertex(); bufferbuilder.pos(bb.minX, bb.minY, bb.minZ).color(red, green, blue, alpha2).endVertex(); tessellator.draw(); GL11.glDisable(2848); GlStateManager.depthMask(true); GlStateManager.enableDepth(); GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); GlStateManager.popMatrix(); }
public static void drawFullFace(final AxisAlignedBB bb, final BlockPos blockPos, final float width, final int red, final int green, final int blue, final int alpha, final int alpha2) { NordTessellator.prepareGL(); NordTessellator.begin(7); drawFace(INSTANCE.getBuffer(), (float) blockPos.x, (float) blockPos.y, (float) blockPos.z, 1.0f, 1.0f, 1.0f, red, green, blue, alpha, 63); NordTessellator.render(); NordTessellator.releaseGL(); <DeepExtract> GlStateManager.pushMatrix(); GlStateManager.enableBlend(); GlStateManager.disableDepth(); GlStateManager.tryBlendFuncSeparate(770, 771, 0, 1); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); GL11.glEnable(2848); GL11.glHint(3154, 4354); GL11.glLineWidth(width); final Tessellator tessellator = Tessellator.getInstance(); final BufferBuilder bufferbuilder = tessellator.getBuffer(); bufferbuilder.begin(3, DefaultVertexFormats.POSITION_COLOR); bufferbuilder.pos(bb.minX, bb.minY, bb.minZ).color(red, green, blue, alpha2).endVertex(); bufferbuilder.pos(bb.minX, bb.minY, bb.maxZ).color(red, green, blue, alpha2).endVertex(); bufferbuilder.pos(bb.maxX, bb.minY, bb.maxZ).color(red, green, blue, alpha2).endVertex(); bufferbuilder.pos(bb.maxX, bb.minY, bb.minZ).color(red, green, blue, alpha2).endVertex(); bufferbuilder.pos(bb.minX, bb.minY, bb.minZ).color(red, green, blue, alpha2).endVertex(); tessellator.draw(); GL11.glDisable(2848); GlStateManager.depthMask(true); GlStateManager.enableDepth(); GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); GlStateManager.popMatrix(); </DeepExtract> }
CousinWare
positive
386
@Override protected void initialize() throws Exception { TextFieldUtil.applyPositiveIntegerFilter(textFieldRandomInputSize, AppConstant.DEFAULT_INPUT_SIZE); TextFieldUtil.applyPositiveDoubleFilter(textFieldRandomInputRangeMin, AppConstant.DEFAULT_RANDOM_RANGE_MIN); TextFieldUtil.applyPositiveDoubleFilter(textFieldRandomInputRangeMax, AppConstant.DEFAULT_RANDOM_RANGE_MAX); TextFieldUtil.applyPositiveIntegerFilter(textFieldRandomRecordNumber, AppConstant.DEFAULT_RANDOM_RECORD_NUMBER); toggleGroupDataType.selectedToggleProperty().addListener(event -> { if (radioButtonGaussianType.isSelected()) { textFieldRandomInputRangeMin.setDisable(true); textFieldRandomInputRangeMax.setDisable(true); } else { textFieldRandomInputRangeMin.setDisable(false); textFieldRandomInputRangeMax.setDisable(false); } }); buttonGenerateRandomData.setOnAction(event -> { int inputSize = TextFieldUtil.parseInteger(textFieldRandomInputSize); int recordNumber = TextFieldUtil.parseInteger(textFieldRandomRecordNumber); double randomRangeMin = TextFieldUtil.parseDouble(textFieldRandomInputRangeMin); double randomRangeMax = TextFieldUtil.parseDouble(textFieldRandomInputRangeMax); NumericRecordSet numericRecordSet = new NumericRecordSet(); for (int i = 0; i < recordNumber; i++) { double[] values = new double[inputSize]; if (radioButtonIntegerType.isSelected()) { for (int j = 0; j < inputSize; j++) values[j] = (double) RandomUtil.getInt(randomRangeMin, randomRangeMax); } else if (radioButtonDoubleType.isSelected()) { for (int j = 0; j < inputSize; j++) values[j] = RandomUtil.getDouble(randomRangeMin, randomRangeMax); } else if (radioButtonGaussianType.isSelected()) { for (int j = 0; j < inputSize; j++) values[j] = RandomUtil.getGaussian(); } numericRecordSet.addRecord(values); } String[] headers = new String[inputSize]; for (int i = 0; i < inputSize; i++) headers[i] = "Column " + i; numericRecordSet.setHeader(headers); AIFacade.getTestFeatureSet().setNumericRecordSet(numericRecordSet); getTabModelTestController().getModelTestFeatureController().getModelTestFeatureTableController().refreshTableView(); }); titledPane.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.title")); labelRandomMin.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.min")); labelRandomMax.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.max")); labelRandom.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.randomRange")); labelRandomInputSize.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.inputSize")); labelRandomRecordNumber.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.totalDataSize")); labelRandomDataType.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.dataType")); radioButtonIntegerType.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.integer")); radioButtonDoubleType.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.float")); radioButtonGaussianType.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.gaussian")); buttonGenerateRandomData.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.generate")); }
@Override protected void initialize() throws Exception { TextFieldUtil.applyPositiveIntegerFilter(textFieldRandomInputSize, AppConstant.DEFAULT_INPUT_SIZE); TextFieldUtil.applyPositiveDoubleFilter(textFieldRandomInputRangeMin, AppConstant.DEFAULT_RANDOM_RANGE_MIN); TextFieldUtil.applyPositiveDoubleFilter(textFieldRandomInputRangeMax, AppConstant.DEFAULT_RANDOM_RANGE_MAX); TextFieldUtil.applyPositiveIntegerFilter(textFieldRandomRecordNumber, AppConstant.DEFAULT_RANDOM_RECORD_NUMBER); toggleGroupDataType.selectedToggleProperty().addListener(event -> { if (radioButtonGaussianType.isSelected()) { textFieldRandomInputRangeMin.setDisable(true); textFieldRandomInputRangeMax.setDisable(true); } else { textFieldRandomInputRangeMin.setDisable(false); textFieldRandomInputRangeMax.setDisable(false); } }); <DeepExtract> buttonGenerateRandomData.setOnAction(event -> { int inputSize = TextFieldUtil.parseInteger(textFieldRandomInputSize); int recordNumber = TextFieldUtil.parseInteger(textFieldRandomRecordNumber); double randomRangeMin = TextFieldUtil.parseDouble(textFieldRandomInputRangeMin); double randomRangeMax = TextFieldUtil.parseDouble(textFieldRandomInputRangeMax); NumericRecordSet numericRecordSet = new NumericRecordSet(); for (int i = 0; i < recordNumber; i++) { double[] values = new double[inputSize]; if (radioButtonIntegerType.isSelected()) { for (int j = 0; j < inputSize; j++) values[j] = (double) RandomUtil.getInt(randomRangeMin, randomRangeMax); } else if (radioButtonDoubleType.isSelected()) { for (int j = 0; j < inputSize; j++) values[j] = RandomUtil.getDouble(randomRangeMin, randomRangeMax); } else if (radioButtonGaussianType.isSelected()) { for (int j = 0; j < inputSize; j++) values[j] = RandomUtil.getGaussian(); } numericRecordSet.addRecord(values); } String[] headers = new String[inputSize]; for (int i = 0; i < inputSize; i++) headers[i] = "Column " + i; numericRecordSet.setHeader(headers); AIFacade.getTestFeatureSet().setNumericRecordSet(numericRecordSet); getTabModelTestController().getModelTestFeatureController().getModelTestFeatureTableController().refreshTableView(); }); </DeepExtract> titledPane.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.title")); labelRandomMin.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.min")); labelRandomMax.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.max")); labelRandom.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.randomRange")); labelRandomInputSize.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.inputSize")); labelRandomRecordNumber.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.totalDataSize")); labelRandomDataType.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.dataType")); radioButtonIntegerType.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.integer")); radioButtonDoubleType.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.float")); radioButtonGaussianType.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.gaussian")); buttonGenerateRandomData.setText(AppPropertiesSingleton.getInstance().get("frame.testTab.dataSetting.dataRandomGenerate.generate")); }
Dluid
positive
387
@Override public void startDragging() { if (actionMode != null) { actionMode.finish(); actionMode = null; try { int selected = getMultiSelectListSingleCheckedItemPosition(userList); userList.setItemChecked(selected, false); } catch (IllegalStateException e) { Log.e(getString(R.string.app_name), LOCAL_TAG, e); } } }
@Override public void startDragging() { <DeepExtract> if (actionMode != null) { actionMode.finish(); actionMode = null; try { int selected = getMultiSelectListSingleCheckedItemPosition(userList); userList.setItemChecked(selected, false); } catch (IllegalStateException e) { Log.e(getString(R.string.app_name), LOCAL_TAG, e); } } </DeepExtract> }
google-authenticator-android
positive
388
public static LookupSet read(URL url, boolean mustExist, int minFreq, int maxFreq, Io.StringToIntsErr si) { LookupSetBuilder lsb = new LookupSetBuilder(minFreq, maxFreq); lsb.setMessage(String.format(" in %s", url.getPath())); LineReader lr = new LineReader(url, mustExist); StringBuilder err = new StringBuilder(); while ((line = lr.readLine()) != null) { int[] in = si.cvt(line.trim(), err); if (in.length < 1 || in[0] == Io.sm_PARSE_FAILED || (in.length >= 2 && in[1] == Io.sm_PARSE_FAILED)) { Log.parseErr(lr, err.toString(), line); err = new StringBuilder(); } if (in.length == 1) { lsb.add(in[0]); } else { lsb.add(in[0], in[1]); } } lr.close(); return super.implement(); }
public static LookupSet read(URL url, boolean mustExist, int minFreq, int maxFreq, Io.StringToIntsErr si) { LookupSetBuilder lsb = new LookupSetBuilder(minFreq, maxFreq); lsb.setMessage(String.format(" in %s", url.getPath())); LineReader lr = new LineReader(url, mustExist); StringBuilder err = new StringBuilder(); while ((line = lr.readLine()) != null) { int[] in = si.cvt(line.trim(), err); if (in.length < 1 || in[0] == Io.sm_PARSE_FAILED || (in.length >= 2 && in[1] == Io.sm_PARSE_FAILED)) { Log.parseErr(lr, err.toString(), line); err = new StringBuilder(); } if (in.length == 1) { lsb.add(in[0]); } else { lsb.add(in[0], in[1]); } } lr.close(); <DeepExtract> return super.implement(); </DeepExtract> }
twidlit
positive
389
public Criteria andStudentIdNotIn(List<Long> values) { if (values == null) { throw new RuntimeException("Value for " + "studentId" + " cannot be null"); } criteria.add(new Criterion("student_id not in", values)); return (Criteria) this; }
public Criteria andStudentIdNotIn(List<Long> values) { <DeepExtract> if (values == null) { throw new RuntimeException("Value for " + "studentId" + " cannot be null"); } criteria.add(new Criterion("student_id not in", values)); </DeepExtract> return (Criteria) this; }
IDEAPractice
positive
390
@Override public int executeUpdate(final String sql, final String[] columnNames) throws SQLException { if (isClosed) throw new SQLAlreadyClosedException(this.getClass().getSimpleName()); return 0; }
@Override public int executeUpdate(final String sql, final String[] columnNames) throws SQLException { <DeepExtract> if (isClosed) throw new SQLAlreadyClosedException(this.getClass().getSimpleName()); </DeepExtract> return 0; }
mongo-jdbc-driver
positive
391
public static JSONObject successJSONWithToken(String token, Object data) { JSONObject returnJson = new JSONObject(); returnJson.put("code", PinConstants.StatusCode.SUCCESS); returnJson.put("message", "Token needs update."); returnJson.put("data", data); returnJson.put("token", token); returnJson.put("serverHost", hostAddress); return returnJson; }
public static JSONObject successJSONWithToken(String token, Object data) { JSONObject returnJson = new JSONObject(); returnJson.put("code", PinConstants.StatusCode.SUCCESS); returnJson.put("message", "Token needs update."); returnJson.put("data", data); returnJson.put("token", token); <DeepExtract> returnJson.put("serverHost", hostAddress); return returnJson; </DeepExtract> }
Shop-pin-Backend
positive
392
private void cancelAnimations() { if (mSecondAnimation != null && mSecondAnimation.isRunning()) { mSecondAnimation.stop(); } if (mThirdAnimation != null && mThirdAnimation.isRunning()) { mThirdAnimation.stop(); } }
private void cancelAnimations() { if (mSecondAnimation != null && mSecondAnimation.isRunning()) { mSecondAnimation.stop(); } <DeepExtract> if (mThirdAnimation != null && mThirdAnimation.isRunning()) { mThirdAnimation.stop(); } </DeepExtract> }
androidRapid
positive
393
public void componentMoved(ComponentEvent e) { Rectangle b = e.getComponent().getBounds(); try { if (absCoords) { final Container cp = SwingUtilities.getRootPane(e.getComponent()).getContentPane(); b = GUIUtil.convertRectangle(e.getComponent(), b, cp); } replyArgs[1] = "moved"; replyArgs[2] = new Integer(b.x); replyArgs[3] = new Integer(b.y); replyArgs[4] = new Integer(b.width); replyArgs[5] = new Integer(b.height); client.reply(new OSCMessage(getOSCCommand(), replyArgs)); } catch (IOException ex) { SwingOSC.printException(ex, getOSCCommand()); } }
public void componentMoved(ComponentEvent e) { <DeepExtract> Rectangle b = e.getComponent().getBounds(); try { if (absCoords) { final Container cp = SwingUtilities.getRootPane(e.getComponent()).getContentPane(); b = GUIUtil.convertRectangle(e.getComponent(), b, cp); } replyArgs[1] = "moved"; replyArgs[2] = new Integer(b.x); replyArgs[3] = new Integer(b.y); replyArgs[4] = new Integer(b.width); replyArgs[5] = new Integer(b.height); client.reply(new OSCMessage(getOSCCommand(), replyArgs)); } catch (IOException ex) { SwingOSC.printException(ex, getOSCCommand()); } </DeepExtract> }
SwingOSC
positive
394
@Override public void debug(final String format, final Object... argArray) { if (!DEBUG.isGreaterOrEqual(minimum)) throw new IllegalStateException(format("%s logging disabled for logger \"%s\" [%s]", DEBUG, getName(), getClass().getName())); super.debug(format, argArray); }
@Override public void debug(final String format, final Object... argArray) { <DeepExtract> if (!DEBUG.isGreaterOrEqual(minimum)) throw new IllegalStateException(format("%s logging disabled for logger \"%s\" [%s]", DEBUG, getName(), getClass().getName())); </DeepExtract> super.debug(format, argArray); }
binkley
positive
395
private JSONObject execute() throws IOException { assert (client != null); response = this.client.send(buildRequest()); if (response == null) { throw new IOException("No response received"); } if (response.get("type").equals("error")) { logger.error("Invalid response: {}", response.toString()); throw new IOException(response.get("text").toString()); } return response; }
private JSONObject execute() throws IOException { <DeepExtract> </DeepExtract> assert (client != null); <DeepExtract> </DeepExtract> response = this.client.send(buildRequest()); <DeepExtract> </DeepExtract> if (response == null) { <DeepExtract> </DeepExtract> throw new IOException("No response received"); <DeepExtract> </DeepExtract> } <DeepExtract> </DeepExtract> if (response.get("type").equals("error")) { <DeepExtract> </DeepExtract> logger.error("Invalid response: {}", response.toString()); <DeepExtract> </DeepExtract> throw new IOException(response.get("text").toString()); <DeepExtract> </DeepExtract> } <DeepExtract> </DeepExtract> return response; <DeepExtract> </DeepExtract> }
archivo
positive
396
@Override public void onClick(View v) { if (windowToken != null) { InputMethodManager imm = (InputMethodManager) context.get().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(windowToken, 0); } if (onOtherButtonClickListener != null) { if (!onOtherButtonClickListener.onClick(InputDialog.this, v, getInputText())) materialAlertDialog.dismiss(); } else { materialAlertDialog.dismiss(); } }
@Override public void onClick(View v) { <DeepExtract> if (windowToken != null) { InputMethodManager imm = (InputMethodManager) context.get().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(windowToken, 0); } </DeepExtract> if (onOtherButtonClickListener != null) { if (!onOtherButtonClickListener.onClick(InputDialog.this, v, getInputText())) materialAlertDialog.dismiss(); } else { materialAlertDialog.dismiss(); } }
DialogV3
positive
397
@Test public void testSetStatus() throws Throwable { this.requestAction = http -> http.setStatus(HttpStatus.NOT_FOUND).end(); client.newRequest(uri()).send(new Response.Listener.Adapter() { @Override public void onSuccess(Response response) { threadAssertEquals(response.getStatus(), 404); resume(); } }); await(); }
@Test public void testSetStatus() throws Throwable { <DeepExtract> this.requestAction = http -> http.setStatus(HttpStatus.NOT_FOUND).end(); </DeepExtract> client.newRequest(uri()).send(new Response.Listener.Adapter() { @Override public void onSuccess(Response response) { threadAssertEquals(response.getStatus(), 404); resume(); } }); await(); }
asity
positive
398
public void drawLineOrder(LineOrder line) { int x1 = line.getStartX(); int y1 = line.getStartY(); int x2 = line.getEndX(); int y2 = line.getEndY(); int fgcolor = line.getPen().getColor(); int opcode = line.getOpcode() - 1; fgcolor = Bitmap.convertTo24(fgcolor); if (x1 == x2 || y1 == y2) { drawLineVerticalHorizontal(x1, y1, x2, y2, fgcolor, opcode); return; } int deltax = Math.abs(x2 - x1); int deltay = Math.abs(y2 - y1); int x = x1; int y = y1; int xinc1, xinc2, yinc1, yinc2; int num, den, numadd, numpixels; if (x2 >= x1) { xinc1 = 1; xinc2 = 1; } else { xinc1 = -1; xinc2 = -1; } if (y2 >= y1) { yinc1 = 1; yinc2 = 1; } else { yinc1 = -1; yinc2 = -1; } if (deltax >= deltay) { xinc1 = 0; yinc2 = 0; den = deltax; num = deltax / 2; numadd = deltay; numpixels = deltax; } else { xinc2 = 0; yinc1 = 0; den = deltay; num = deltay / 2; numadd = deltax; numpixels = deltay; } for (int curpixel = 0; curpixel <= numpixels; curpixel++) { setPixel(opcode, x, y, fgcolor); num += numadd; if (num >= den) { num -= den; x += xinc1; y += yinc1; } x += xinc2; y += yinc2; } int x_min = x1 < x2 ? x1 : x2; int x_max = x1 > x2 ? x1 : x2; int y_min = y1 < y2 ? y1 : y2; int y_max = y1 > y2 ? y1 : y2; Common.currentImageViewer.postInvalidate(); }
public void drawLineOrder(LineOrder line) { int x1 = line.getStartX(); int y1 = line.getStartY(); int x2 = line.getEndX(); int y2 = line.getEndY(); int fgcolor = line.getPen().getColor(); int opcode = line.getOpcode() - 1; <DeepExtract> fgcolor = Bitmap.convertTo24(fgcolor); if (x1 == x2 || y1 == y2) { drawLineVerticalHorizontal(x1, y1, x2, y2, fgcolor, opcode); return; } int deltax = Math.abs(x2 - x1); int deltay = Math.abs(y2 - y1); int x = x1; int y = y1; int xinc1, xinc2, yinc1, yinc2; int num, den, numadd, numpixels; if (x2 >= x1) { xinc1 = 1; xinc2 = 1; } else { xinc1 = -1; xinc2 = -1; } if (y2 >= y1) { yinc1 = 1; yinc2 = 1; } else { yinc1 = -1; yinc2 = -1; } if (deltax >= deltay) { xinc1 = 0; yinc2 = 0; den = deltax; num = deltax / 2; numadd = deltay; numpixels = deltax; } else { xinc2 = 0; yinc1 = 0; den = deltay; num = deltay / 2; numadd = deltax; numpixels = deltay; } for (int curpixel = 0; curpixel <= numpixels; curpixel++) { setPixel(opcode, x, y, fgcolor); num += numadd; if (num >= den) { num -= den; x += xinc1; y += yinc1; } x += xinc2; y += yinc2; } int x_min = x1 < x2 ? x1 : x2; int x_max = x1 > x2 ? x1 : x2; int y_min = y1 < y2 ? y1 : y2; int y_max = y1 > y2 ? y1 : y2; Common.currentImageViewer.postInvalidate(); </DeepExtract> }
omnidesk
positive
399
public UiSelector description(String desc) { UiSelector selector = new UiSelector(this); if (SELECTOR_DESCRIPTION == SELECTOR_CHILD || SELECTOR_DESCRIPTION == SELECTOR_PARENT) selector.getLastSubSelector().mSelectorAttributes.put(SELECTOR_DESCRIPTION, desc); else selector.mSelectorAttributes.put(SELECTOR_DESCRIPTION, desc); return selector; }
public UiSelector description(String desc) { <DeepExtract> UiSelector selector = new UiSelector(this); if (SELECTOR_DESCRIPTION == SELECTOR_CHILD || SELECTOR_DESCRIPTION == SELECTOR_PARENT) selector.getLastSubSelector().mSelectorAttributes.put(SELECTOR_DESCRIPTION, desc); else selector.mSelectorAttributes.put(SELECTOR_DESCRIPTION, desc); return selector; </DeepExtract> }
GodHand
positive
400
public List<String> wordBreak(String s, List<String> wordDict) { if (map.containsKey(0)) { return map.get(0); } List<String> res = new ArrayList<>(); if (0 == s.length()) { res.add(""); } for (int end = 0 + 1; end <= s.length(); end++) { if (wordDict.contains(s.substring(0, end))) { List<String> list = dfs(s, wordDict, end); for (String temp : list) { res.add(s.substring(0, end) + (temp.equals("") ? "" : " ") + temp); } } } map.put(0, res); return res; }
public List<String> wordBreak(String s, List<String> wordDict) { <DeepExtract> if (map.containsKey(0)) { return map.get(0); } List<String> res = new ArrayList<>(); if (0 == s.length()) { res.add(""); } for (int end = 0 + 1; end <= s.length(); end++) { if (wordDict.contains(s.substring(0, end))) { List<String> list = dfs(s, wordDict, end); for (String temp : list) { res.add(s.substring(0, end) + (temp.equals("") ? "" : " ") + temp); } } } map.put(0, res); return res; </DeepExtract> }
cspiration
positive
401
@Override public void addInterceptors(InterceptorRegistry registry) { SentinelWebMvcConfig config = new SentinelWebMvcConfig(); config.setHttpMethodSpecify(true); registry.addInterceptor(new SentinelWebInterceptor(config)).addPathPatterns("/**"); }
@Override public void addInterceptors(InterceptorRegistry registry) { <DeepExtract> SentinelWebMvcConfig config = new SentinelWebMvcConfig(); config.setHttpMethodSpecify(true); registry.addInterceptor(new SentinelWebInterceptor(config)).addPathPatterns("/**"); </DeepExtract> }
distributed-dev-learning
positive
402
@Override public SliceOutput appendByte(int value) { ensureWritableBytes(SIZE_OF_BYTE); slice.setByteUnchecked(bufferPosition, value); bufferPosition += SIZE_OF_BYTE; return this; }
@Override public SliceOutput appendByte(int value) { <DeepExtract> ensureWritableBytes(SIZE_OF_BYTE); slice.setByteUnchecked(bufferPosition, value); bufferPosition += SIZE_OF_BYTE; </DeepExtract> return this; }
slice
positive
403
public Criteria andItemsnumLessThanOrEqualTo(String value) { if (value == null) { throw new RuntimeException("Value for " + "itemsnum" + " cannot be null"); } criteria.add(new Criterion("itemsNum <=", value)); return (Criteria) this; }
public Criteria andItemsnumLessThanOrEqualTo(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "itemsnum" + " cannot be null"); } criteria.add(new Criterion("itemsNum <=", value)); </DeepExtract> return (Criteria) this; }
Maven-Spring-SpringMVC-Mybatis
positive
404
public Criteria andClazzNameGreaterThanOrEqualTo(String value) { if (value == null) { throw new RuntimeException("Value for " + "clazzName" + " cannot be null"); } criteria.add(new Criterion("clazz_name >=", value)); return (Criteria) this; }
public Criteria andClazzNameGreaterThanOrEqualTo(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "clazzName" + " cannot be null"); } criteria.add(new Criterion("clazz_name >=", value)); </DeepExtract> return (Criteria) this; }
dtsopensource
positive
405
public void setOnLanSongSDKPlayProgressListener(OnLanSongSDKPlayProgressListener listener) { if (renderer == null) { renderer = new LSOAexPlayerRender(getContext()); setupSuccess = false; } if (renderer != null) { renderer.setOnLanSongSDKPlayProgressListener(listener); } }
public void setOnLanSongSDKPlayProgressListener(OnLanSongSDKPlayProgressListener listener) { <DeepExtract> if (renderer == null) { renderer = new LSOAexPlayerRender(getContext()); setupSuccess = false; } </DeepExtract> if (renderer != null) { renderer.setOnLanSongSDKPlayProgressListener(listener); } }
video-edit-sdk-android
positive
406
public Criteria andPasswordGreaterThanOrEqualTo(String value) { if (value == null) { throw new RuntimeException("Value for " + "password" + " cannot be null"); } criteria.add(new Criterion("password >=", value)); return (Criteria) this; }
public Criteria andPasswordGreaterThanOrEqualTo(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "password" + " cannot be null"); } criteria.add(new Criterion("password >=", value)); </DeepExtract> return (Criteria) this; }
oauth4j
positive
408
@Override protected void checkEvent(final EntityDamageByEntityEvent e) { if (player().isNot(e.getDamager())) return; final Player player = (Player) e.getDamager(); if (!(e.getEntity() instanceof LivingEntity)) { return; } final LivingEntity entity = (LivingEntity) e.getEntity(); final NessPlayer nessPlayer = player(); double maxReach = this.maxReach; final Ray ray = Ray.from(nessPlayer, useBukkitLocationForRayTrace); final AABB aabb = AABB.from(entity, this.ness(), this.reachExpansion); double range = aabb.collidesD(ray, 0, 10); final float angle1 = (float) nessPlayer.getMovementValues().getHelper().getAngle(nessPlayer.getBukkitPlayer(), entity.getLocation()); angleList.add((long) (angle1 * 10000)); if (player.getGameMode().equals(GameMode.CREATIVE)) { maxReach = (5.5 * this.maxReach) / 3; } if (range > maxReach && range < 6.5D) { final double bufferAdder = range / maxReach; buffer += bufferAdder; if (buffer > rayTraceReachBuffer) { flag("Reach: " + range); } } else if (buffer > 0) { buffer -= 0.5; } if (range == -1) { if (angleList.size() > this.angleListSize) { double average = angleList.average() / 10000.0; nessPlayer.sendDevMessage("Hitbox: " + average); if (average < maxAngle) { final double bufferAdder = average / maxAngle; angleBuffer += bufferAdder; if (angleBuffer > this.rayTraceHitboxBuffer) { flag("Hitbox"); } } else if (angleBuffer > 0) { angleBuffer -= 0.25; } } } else if (angleBuffer > 0) { angleBuffer -= 0.5; } if (angleList.size() > this.angleListSize) { angleList.clear(); } Player player = (Player) e.getDamager(); final Location loc = player.getLocation(); runTaskLater(() -> { Location loc1 = player.getLocation(); float grade = loc.getYaw() - loc1.getYaw(); if (Math.round(grade) > maxYaw) { flag("HighYaw"); } }, durationOfTicks(2)); Player player = (Player) e.getDamager(); if (player.isDead()) { flag("Impossible"); } Player player = (Player) e.getDamager(); if (player.hasLineOfSight(e.getEntity())) { return; } Block b = player.getTargetBlock(null, 5); final RayCaster customCaster = new RayCaster(player, 6, RayCaster.RaycastType.BLOCK, this.ness()).compute(); Block bCustom = customCaster.getBlockFound(); Material material = b.getType(); Material materialCustom; if (bCustom == null) { materialCustom = material; } else { materialCustom = bCustom.getType(); } if (b.getType().isSolid() && (material.isOccluding() && !material.name().contains("GLASS")) && (materialCustom.isOccluding() && !materialCustom.name().contains("GLASS"))) { flag("WallHit"); } if (!(e.getEntity() instanceof LivingEntity)) { return; } if (!Bukkit.getVersion().contains("1.8")) { return; } NessPlayer nessPlayer = player(); nessPlayer.addEntityToAttackedEntities(e.getEntity().getEntityId()); if (nessPlayer.getAttackedEntities().size() > 2) { flag("MultiAura Entities: " + nessPlayer.getAttackedEntities().size()); } }
@Override protected void checkEvent(final EntityDamageByEntityEvent e) { if (player().isNot(e.getDamager())) return; final Player player = (Player) e.getDamager(); if (!(e.getEntity() instanceof LivingEntity)) { return; } final LivingEntity entity = (LivingEntity) e.getEntity(); final NessPlayer nessPlayer = player(); double maxReach = this.maxReach; final Ray ray = Ray.from(nessPlayer, useBukkitLocationForRayTrace); final AABB aabb = AABB.from(entity, this.ness(), this.reachExpansion); double range = aabb.collidesD(ray, 0, 10); final float angle1 = (float) nessPlayer.getMovementValues().getHelper().getAngle(nessPlayer.getBukkitPlayer(), entity.getLocation()); angleList.add((long) (angle1 * 10000)); if (player.getGameMode().equals(GameMode.CREATIVE)) { maxReach = (5.5 * this.maxReach) / 3; } if (range > maxReach && range < 6.5D) { final double bufferAdder = range / maxReach; buffer += bufferAdder; if (buffer > rayTraceReachBuffer) { flag("Reach: " + range); } } else if (buffer > 0) { buffer -= 0.5; } if (range == -1) { if (angleList.size() > this.angleListSize) { double average = angleList.average() / 10000.0; nessPlayer.sendDevMessage("Hitbox: " + average); if (average < maxAngle) { final double bufferAdder = average / maxAngle; angleBuffer += bufferAdder; if (angleBuffer > this.rayTraceHitboxBuffer) { flag("Hitbox"); } } else if (angleBuffer > 0) { angleBuffer -= 0.25; } } } else if (angleBuffer > 0) { angleBuffer -= 0.5; } if (angleList.size() > this.angleListSize) { angleList.clear(); } Player player = (Player) e.getDamager(); final Location loc = player.getLocation(); runTaskLater(() -> { Location loc1 = player.getLocation(); float grade = loc.getYaw() - loc1.getYaw(); if (Math.round(grade) > maxYaw) { flag("HighYaw"); } }, durationOfTicks(2)); Player player = (Player) e.getDamager(); if (player.isDead()) { flag("Impossible"); } Player player = (Player) e.getDamager(); if (player.hasLineOfSight(e.getEntity())) { return; } Block b = player.getTargetBlock(null, 5); final RayCaster customCaster = new RayCaster(player, 6, RayCaster.RaycastType.BLOCK, this.ness()).compute(); Block bCustom = customCaster.getBlockFound(); Material material = b.getType(); Material materialCustom; if (bCustom == null) { materialCustom = material; } else { materialCustom = bCustom.getType(); } if (b.getType().isSolid() && (material.isOccluding() && !material.name().contains("GLASS")) && (materialCustom.isOccluding() && !materialCustom.name().contains("GLASS"))) { flag("WallHit"); } <DeepExtract> if (!(e.getEntity() instanceof LivingEntity)) { return; } if (!Bukkit.getVersion().contains("1.8")) { return; } NessPlayer nessPlayer = player(); nessPlayer.addEntityToAttackedEntities(e.getEntity().getEntityId()); if (nessPlayer.getAttackedEntities().size() > 2) { flag("MultiAura Entities: " + nessPlayer.getAttackedEntities().size()); } </DeepExtract> }
NESS-Reloaded
positive
409
@Override protected void onDraw(Canvas canvas) { if (mBitmap == null || mBitmapShader == null) { return; } if (mBitmap.getHeight() == 0 || mBitmap.getWidth() == 0) return; if (mBitmap == null) return; int canvasSize = Math.min(getWidth(), getHeight()); if (canvasSize == 0) return; if (canvasSize != mBitmap.getWidth() || canvasSize != mBitmap.getHeight()) { Matrix matrix = new Matrix(); float scale = (float) canvasSize / (float) mBitmap.getWidth(); matrix.setScale(scale, scale); mBitmapShader.setLocalMatrix(matrix); } paint.setShader(mBitmapShader); canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, Math.min(getWidth() / 2.0f, getHeight() / 2.0f), paint); }
@Override protected void onDraw(Canvas canvas) { if (mBitmap == null || mBitmapShader == null) { return; } if (mBitmap.getHeight() == 0 || mBitmap.getWidth() == 0) return; <DeepExtract> if (mBitmap == null) return; int canvasSize = Math.min(getWidth(), getHeight()); if (canvasSize == 0) return; if (canvasSize != mBitmap.getWidth() || canvasSize != mBitmap.getHeight()) { Matrix matrix = new Matrix(); float scale = (float) canvasSize / (float) mBitmap.getWidth(); matrix.setScale(scale, scale); mBitmapShader.setLocalMatrix(matrix); } </DeepExtract> paint.setShader(mBitmapShader); canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, Math.min(getWidth() / 2.0f, getHeight() / 2.0f), paint); }
TimDemo-Android
positive
410
private static String getMimeType(File file) { String extension; if (file.getName() == null) { extension = null; } int dot = file.getName().lastIndexOf("."); if (dot >= 0) { extension = file.getName().substring(dot); } else { extension = ""; } if (extension.length() > 0) return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1)); return "application/octet-stream"; }
private static String getMimeType(File file) { <DeepExtract> String extension; if (file.getName() == null) { extension = null; } int dot = file.getName().lastIndexOf("."); if (dot >= 0) { extension = file.getName().substring(dot); } else { extension = ""; } </DeepExtract> if (extension.length() > 0) return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1)); return "application/octet-stream"; }
routerkeygenAndroid
positive
411
public Object parseValue(String value, String type) throws ResourceParseException { if (value.equals("")) { throw new XMLResourceParseException(PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument", ARG_VAL_ATTR, "is required for an argument of type '" + type + "'!"); } try { int val = Integer.parseInt(value); return new Float(val); } catch (NumberFormatException e) { throw new XMLResourceParseException(PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument", ARG_VAL_ATTR, "has an invalid '" + type + "'-value : '" + value + "'!", e); } }
public Object parseValue(String value, String type) throws ResourceParseException { <DeepExtract> if (value.equals("")) { throw new XMLResourceParseException(PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument", ARG_VAL_ATTR, "is required for an argument of type '" + type + "'!"); } </DeepExtract> try { int val = Integer.parseInt(value); return new Float(val); } catch (NumberFormatException e) { throw new XMLResourceParseException(PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument", ARG_VAL_ATTR, "has an invalid '" + type + "'-value : '" + value + "'!", e); } }
jlatexmath
positive
412
public static void registerPrefix(final String prefix, final String uri) { this.uri2pfx.put(uri, prefix); this.pfx2uri.put(prefix, uri); }
public static void registerPrefix(final String prefix, final String uri) { <DeepExtract> this.uri2pfx.put(uri, prefix); this.pfx2uri.put(prefix, uri); </DeepExtract> }
laverca
positive
413
@Override protected Object replaceHookedMethod(MethodHookParam param) throws Throwable { if (!hasAction(HwKey.HOME)) { XposedBridge.invokeOriginalMethod(param.method, param.thisObject, param.args); return null; } if (Build.VERSION.SDK_INT > 17) { XposedHelpers.setBooleanField(param.thisObject, "mHomeConsumed", true); } else { XposedHelpers.setBooleanField(param.thisObject, "mHomeLongPressed", true); } int action = getActionForHwKeyTrigger(HwKeyTrigger.HOME_LONGPRESS); if (DEBUG) log("Performing action " + action + " for HWKEY trigger " + HwKeyTrigger.HOME_LONGPRESS.toString()); if (action == GravityBoxSettings.HWKEY_ACTION_DEFAULT) return; if (action == GravityBoxSettings.HWKEY_ACTION_SEARCH) { launchSearchActivity(); } else if (action == GravityBoxSettings.HWKEY_ACTION_VOICE_SEARCH) { launchVoiceSearchActivity(); } else if (action == GravityBoxSettings.HWKEY_ACTION_PREV_APP) { switchToLastApp(); } else if (action == GravityBoxSettings.HWKEY_ACTION_KILL) { killForegroundApp(); } else if (action == GravityBoxSettings.HWKEY_ACTION_SLEEP) { goToSleep(); } else if (action == GravityBoxSettings.HWKEY_ACTION_RECENT_APPS) { toggleRecentApps(); } else if (action == GravityBoxSettings.HWKEY_ACTION_CUSTOM_APP || action == GravityBoxSettings.HWKEY_ACTION_CUSTOM_APP2) { launchCustomApp(action); } else if (action == GravityBoxSettings.HWKEY_ACTION_MENU) { injectKey(KeyEvent.KEYCODE_MENU); } else if (action == GravityBoxSettings.HWKEY_ACTION_EXPANDED_DESKTOP) { toggleExpandedDesktop(); } else if (action == GravityBoxSettings.HWKEY_ACTION_TORCH) { toggleTorch(); } else if (action == GravityBoxSettings.HWKEY_ACTION_APP_LAUNCHER) { showAppLauncher(); } else if (action == GravityBoxSettings.HWKEY_ACTION_HOME) { injectKey(KeyEvent.KEYCODE_HOME); } else if (action == GravityBoxSettings.HWKEY_ACTION_BACK) { injectKey(KeyEvent.KEYCODE_BACK); } return null; }
@Override protected Object replaceHookedMethod(MethodHookParam param) throws Throwable { if (!hasAction(HwKey.HOME)) { XposedBridge.invokeOriginalMethod(param.method, param.thisObject, param.args); return null; } if (Build.VERSION.SDK_INT > 17) { XposedHelpers.setBooleanField(param.thisObject, "mHomeConsumed", true); } else { XposedHelpers.setBooleanField(param.thisObject, "mHomeLongPressed", true); } <DeepExtract> int action = getActionForHwKeyTrigger(HwKeyTrigger.HOME_LONGPRESS); if (DEBUG) log("Performing action " + action + " for HWKEY trigger " + HwKeyTrigger.HOME_LONGPRESS.toString()); if (action == GravityBoxSettings.HWKEY_ACTION_DEFAULT) return; if (action == GravityBoxSettings.HWKEY_ACTION_SEARCH) { launchSearchActivity(); } else if (action == GravityBoxSettings.HWKEY_ACTION_VOICE_SEARCH) { launchVoiceSearchActivity(); } else if (action == GravityBoxSettings.HWKEY_ACTION_PREV_APP) { switchToLastApp(); } else if (action == GravityBoxSettings.HWKEY_ACTION_KILL) { killForegroundApp(); } else if (action == GravityBoxSettings.HWKEY_ACTION_SLEEP) { goToSleep(); } else if (action == GravityBoxSettings.HWKEY_ACTION_RECENT_APPS) { toggleRecentApps(); } else if (action == GravityBoxSettings.HWKEY_ACTION_CUSTOM_APP || action == GravityBoxSettings.HWKEY_ACTION_CUSTOM_APP2) { launchCustomApp(action); } else if (action == GravityBoxSettings.HWKEY_ACTION_MENU) { injectKey(KeyEvent.KEYCODE_MENU); } else if (action == GravityBoxSettings.HWKEY_ACTION_EXPANDED_DESKTOP) { toggleExpandedDesktop(); } else if (action == GravityBoxSettings.HWKEY_ACTION_TORCH) { toggleTorch(); } else if (action == GravityBoxSettings.HWKEY_ACTION_APP_LAUNCHER) { showAppLauncher(); } else if (action == GravityBoxSettings.HWKEY_ACTION_HOME) { injectKey(KeyEvent.KEYCODE_HOME); } else if (action == GravityBoxSettings.HWKEY_ACTION_BACK) { injectKey(KeyEvent.KEYCODE_BACK); } </DeepExtract> return null; }
GravityBox
positive
414
protected List<StatWorkloadGenerator> generateWorkloadsDC1() { double nullPoint = 0; String[] periods = new String[] { String.format("[%d,%d] m=6 std=1", HOURS[0], HOURS[5]), String.format("(%d,%d] m=20 std=2", HOURS[5], HOURS[6]), String.format("(%d,%d] m=40 std=2", HOURS[6], HOURS[7]), String.format("(%d,%d] m=50 std=4", HOURS[7], HOURS[8]), String.format("(%d,%d] m=80 std=4", HOURS[8], HOURS[9]), String.format("(%d,%d] m=100 std=5", HOURS[9], HOURS[12]), String.format("(%d,%d] m=50 std=2", HOURS[12], HOURS[13]), String.format("(%d,%d] m=90 std=5", HOURS[13], HOURS[14]), String.format("(%d,%d] m=100 std=5", HOURS[14], HOURS[17]), String.format("(%d,%d] m=80 std=2", HOURS[17], HOURS[18]), String.format("(%d,%d] m=50 std=2", HOURS[18], HOURS[19]), String.format("(%d,%d] m=40 std=2", HOURS[19], HOURS[20]), String.format("(%d,%d] m=20 std=2", HOURS[20], HOURS[21]), String.format("(%d,%d] m=6 std=1", HOURS[21], HOURS[24]) }; int asCloudletLength = 200; int asRam = 1; int dbCloudletLength = 50; int dbRam = 1; int dbCloudletIOLength = 50; int duration = 200; return generateWorkload(nullPoint, periods, asCloudletLength, asRam, dbCloudletLength, dbRam, dbCloudletIOLength, duration); }
protected List<StatWorkloadGenerator> generateWorkloadsDC1() { double nullPoint = 0; String[] periods = new String[] { String.format("[%d,%d] m=6 std=1", HOURS[0], HOURS[5]), String.format("(%d,%d] m=20 std=2", HOURS[5], HOURS[6]), String.format("(%d,%d] m=40 std=2", HOURS[6], HOURS[7]), String.format("(%d,%d] m=50 std=4", HOURS[7], HOURS[8]), String.format("(%d,%d] m=80 std=4", HOURS[8], HOURS[9]), String.format("(%d,%d] m=100 std=5", HOURS[9], HOURS[12]), String.format("(%d,%d] m=50 std=2", HOURS[12], HOURS[13]), String.format("(%d,%d] m=90 std=5", HOURS[13], HOURS[14]), String.format("(%d,%d] m=100 std=5", HOURS[14], HOURS[17]), String.format("(%d,%d] m=80 std=2", HOURS[17], HOURS[18]), String.format("(%d,%d] m=50 std=2", HOURS[18], HOURS[19]), String.format("(%d,%d] m=40 std=2", HOURS[19], HOURS[20]), String.format("(%d,%d] m=20 std=2", HOURS[20], HOURS[21]), String.format("(%d,%d] m=6 std=1", HOURS[21], HOURS[24]) }; <DeepExtract> int asCloudletLength = 200; int asRam = 1; int dbCloudletLength = 50; int dbRam = 1; int dbCloudletIOLength = 50; int duration = 200; return generateWorkload(nullPoint, periods, asCloudletLength, asRam, dbCloudletLength, dbRam, dbCloudletIOLength, duration); </DeepExtract> }
CloudSimEx
positive
415
public String updateByExampleSelective(Map<String, Object> parameter) { Resource record = (Resource) parameter.get("record"); ResourceExample example = (ResourceExample) parameter.get("example"); SQL sql = new SQL(); sql.UPDATE("wk_resource"); if (record.getResourceId() != null) { sql.SET("resource_id = #{record.resourceId,jdbcType=INTEGER}"); } if (record.getResourceName() != null) { sql.SET("resource_name = #{record.resourceName,jdbcType=VARCHAR}"); } if (record.getUrl() != null) { sql.SET("url = #{record.url,jdbcType=VARCHAR}"); } if (record.getDescription() != null) { sql.SET("description = #{record.description,jdbcType=VARCHAR}"); } if (record.getSort() != null) { sql.SET("sort = #{record.sort,jdbcType=INTEGER}"); } if (record.getParentId() != null) { sql.SET("parent_id = #{record.parentId,jdbcType=INTEGER}"); } if (example == null) { return; } String parmPhrase1; String parmPhrase1_th; String parmPhrase2; String parmPhrase2_th; String parmPhrase3; String parmPhrase3_th; if (true) { parmPhrase1 = "%s #{example.oredCriteria[%d].allCriteria[%d].value}"; parmPhrase1_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}"; parmPhrase2 = "%s #{example.oredCriteria[%d].allCriteria[%d].value} and #{example.oredCriteria[%d].criteria[%d].secondValue}"; parmPhrase2_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{example.oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}"; parmPhrase3 = "#{example.oredCriteria[%d].allCriteria[%d].value[%d]}"; parmPhrase3_th = "#{example.oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}"; } else { parmPhrase1 = "%s #{oredCriteria[%d].allCriteria[%d].value}"; parmPhrase1_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}"; parmPhrase2 = "%s #{oredCriteria[%d].allCriteria[%d].value} and #{oredCriteria[%d].criteria[%d].secondValue}"; parmPhrase2_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}"; parmPhrase3 = "#{oredCriteria[%d].allCriteria[%d].value[%d]}"; parmPhrase3_th = "#{oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}"; } StringBuilder sb = new StringBuilder(); List<Criteria> oredCriteria = example.getOredCriteria(); boolean firstCriteria = true; for (int i = 0; i < oredCriteria.size(); i++) { Criteria criteria = oredCriteria.get(i); if (criteria.isValid()) { if (firstCriteria) { firstCriteria = false; } else { sb.append(" or "); } sb.append('('); List<Criterion> criterions = criteria.getAllCriteria(); boolean firstCriterion = true; for (int j = 0; j < criterions.size(); j++) { Criterion criterion = criterions.get(j); if (firstCriterion) { firstCriterion = false; } else { sb.append(" and "); } if (criterion.isNoValue()) { sb.append(criterion.getCondition()); } else if (criterion.isSingleValue()) { if (criterion.getTypeHandler() == null) { sb.append(String.format(parmPhrase1, criterion.getCondition(), i, j)); } else { sb.append(String.format(parmPhrase1_th, criterion.getCondition(), i, j, criterion.getTypeHandler())); } } else if (criterion.isBetweenValue()) { if (criterion.getTypeHandler() == null) { sb.append(String.format(parmPhrase2, criterion.getCondition(), i, j, i, j)); } else { sb.append(String.format(parmPhrase2_th, criterion.getCondition(), i, j, criterion.getTypeHandler(), i, j, criterion.getTypeHandler())); } } else if (criterion.isListValue()) { sb.append(criterion.getCondition()); sb.append(" ("); List<?> listItems = (List<?>) criterion.getValue(); boolean comma = false; for (int k = 0; k < listItems.size(); k++) { if (comma) { sb.append(", "); } else { comma = true; } if (criterion.getTypeHandler() == null) { sb.append(String.format(parmPhrase3, i, j, k)); } else { sb.append(String.format(parmPhrase3_th, i, j, k, criterion.getTypeHandler())); } } sb.append(')'); } } sb.append(')'); } } if (sb.length() > 0) { sql.WHERE(sb.toString()); } return sql.toString(); }
public String updateByExampleSelective(Map<String, Object> parameter) { Resource record = (Resource) parameter.get("record"); ResourceExample example = (ResourceExample) parameter.get("example"); SQL sql = new SQL(); sql.UPDATE("wk_resource"); if (record.getResourceId() != null) { sql.SET("resource_id = #{record.resourceId,jdbcType=INTEGER}"); } if (record.getResourceName() != null) { sql.SET("resource_name = #{record.resourceName,jdbcType=VARCHAR}"); } if (record.getUrl() != null) { sql.SET("url = #{record.url,jdbcType=VARCHAR}"); } if (record.getDescription() != null) { sql.SET("description = #{record.description,jdbcType=VARCHAR}"); } if (record.getSort() != null) { sql.SET("sort = #{record.sort,jdbcType=INTEGER}"); } if (record.getParentId() != null) { sql.SET("parent_id = #{record.parentId,jdbcType=INTEGER}"); } <DeepExtract> if (example == null) { return; } String parmPhrase1; String parmPhrase1_th; String parmPhrase2; String parmPhrase2_th; String parmPhrase3; String parmPhrase3_th; if (true) { parmPhrase1 = "%s #{example.oredCriteria[%d].allCriteria[%d].value}"; parmPhrase1_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}"; parmPhrase2 = "%s #{example.oredCriteria[%d].allCriteria[%d].value} and #{example.oredCriteria[%d].criteria[%d].secondValue}"; parmPhrase2_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{example.oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}"; parmPhrase3 = "#{example.oredCriteria[%d].allCriteria[%d].value[%d]}"; parmPhrase3_th = "#{example.oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}"; } else { parmPhrase1 = "%s #{oredCriteria[%d].allCriteria[%d].value}"; parmPhrase1_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}"; parmPhrase2 = "%s #{oredCriteria[%d].allCriteria[%d].value} and #{oredCriteria[%d].criteria[%d].secondValue}"; parmPhrase2_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}"; parmPhrase3 = "#{oredCriteria[%d].allCriteria[%d].value[%d]}"; parmPhrase3_th = "#{oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}"; } StringBuilder sb = new StringBuilder(); List<Criteria> oredCriteria = example.getOredCriteria(); boolean firstCriteria = true; for (int i = 0; i < oredCriteria.size(); i++) { Criteria criteria = oredCriteria.get(i); if (criteria.isValid()) { if (firstCriteria) { firstCriteria = false; } else { sb.append(" or "); } sb.append('('); List<Criterion> criterions = criteria.getAllCriteria(); boolean firstCriterion = true; for (int j = 0; j < criterions.size(); j++) { Criterion criterion = criterions.get(j); if (firstCriterion) { firstCriterion = false; } else { sb.append(" and "); } if (criterion.isNoValue()) { sb.append(criterion.getCondition()); } else if (criterion.isSingleValue()) { if (criterion.getTypeHandler() == null) { sb.append(String.format(parmPhrase1, criterion.getCondition(), i, j)); } else { sb.append(String.format(parmPhrase1_th, criterion.getCondition(), i, j, criterion.getTypeHandler())); } } else if (criterion.isBetweenValue()) { if (criterion.getTypeHandler() == null) { sb.append(String.format(parmPhrase2, criterion.getCondition(), i, j, i, j)); } else { sb.append(String.format(parmPhrase2_th, criterion.getCondition(), i, j, criterion.getTypeHandler(), i, j, criterion.getTypeHandler())); } } else if (criterion.isListValue()) { sb.append(criterion.getCondition()); sb.append(" ("); List<?> listItems = (List<?>) criterion.getValue(); boolean comma = false; for (int k = 0; k < listItems.size(); k++) { if (comma) { sb.append(", "); } else { comma = true; } if (criterion.getTypeHandler() == null) { sb.append(String.format(parmPhrase3, i, j, k)); } else { sb.append(String.format(parmPhrase3_th, i, j, k, criterion.getTypeHandler())); } } sb.append(')'); } } sb.append(')'); } } if (sb.length() > 0) { sql.WHERE(sb.toString()); } </DeepExtract> return sql.toString(); }
wukong-framework
positive
416
@Override public void onAnimationUpdate(ValueAnimator animation) { childV.setTranslationY((float) animation.getAnimatedValue()); childV.setTranslationX(mCurrentTranslationX); float percent = Math.abs((float) animation.getAnimatedValue() / (maxExitY + childV.getHeight())); float scale = 1 - percent; if (scale < minScale) { scale = minScale; } childV.setScaleX(scale); childV.setScaleY(scale); }
@Override public void onAnimationUpdate(ValueAnimator animation) { <DeepExtract> childV.setTranslationY((float) animation.getAnimatedValue()); childV.setTranslationX(mCurrentTranslationX); float percent = Math.abs((float) animation.getAnimatedValue() / (maxExitY + childV.getHeight())); float scale = 1 - percent; if (scale < minScale) { scale = minScale; } childV.setScaleX(scale); childV.setScaleY(scale); </DeepExtract> }
fresco-helper
positive
417
@Override public Triple<Third, First, Second> shitfRight() { return new Triple<First, Second, Third>(third, first, second); }
@Override public Triple<Third, First, Second> shitfRight() { <DeepExtract> return new Triple<First, Second, Third>(third, first, second); </DeepExtract> }
gdx-kiwi
positive
418
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gos_config_failed); setToolBar(false, R.string.join_failed_title); TextView tvLeft = (TextView) findViewById(R.id.tvLeft); tvLeft.setVisibility(View.VISIBLE); SpannableString ssTitle = new SpannableString(this.getString(R.string.cancel)); ssTitle.setSpan(new ForegroundColorSpan(GosDeploy.appConfig_Contrast()), 0, ssTitle.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); tvLeft.setText(ssTitle); tvLeft.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(GosConfigFailedActivity.this, GosMainActivity.class); quitAlert(GosConfigFailedActivity.this, intent); } }); btnAgain = (Button) findViewById(R.id.btnAgain); btnAgain.setBackgroundDrawable(GosDeploy.appConfig_BackgroundColor()); btnAgain.setTextColor(GosDeploy.appConfig_Contrast()); btnAgain.setOnClickListener(this); isAirLink = getIntent().getBooleanExtra("isAirLink", false); promptText = (String) getText(R.string.prompt); cancelBesureText = (String) getText(R.string.cancel_besure); beSureText = (String) getText(R.string.besure); cancelText = (String) getText(R.string.cancel); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gos_config_failed); setToolBar(false, R.string.join_failed_title); TextView tvLeft = (TextView) findViewById(R.id.tvLeft); tvLeft.setVisibility(View.VISIBLE); SpannableString ssTitle = new SpannableString(this.getString(R.string.cancel)); ssTitle.setSpan(new ForegroundColorSpan(GosDeploy.appConfig_Contrast()), 0, ssTitle.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); tvLeft.setText(ssTitle); tvLeft.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(GosConfigFailedActivity.this, GosMainActivity.class); quitAlert(GosConfigFailedActivity.this, intent); } }); btnAgain = (Button) findViewById(R.id.btnAgain); btnAgain.setBackgroundDrawable(GosDeploy.appConfig_BackgroundColor()); btnAgain.setTextColor(GosDeploy.appConfig_Contrast()); btnAgain.setOnClickListener(this); <DeepExtract> isAirLink = getIntent().getBooleanExtra("isAirLink", false); promptText = (String) getText(R.string.prompt); cancelBesureText = (String) getText(R.string.cancel_besure); beSureText = (String) getText(R.string.besure); cancelText = (String) getText(R.string.cancel); </DeepExtract> }
GOpenSource_AppKit_Android_AS
positive
419
@Override public void surfaceDestroyed(SurfaceHolder holder) { if (timer != null) { timer.cancel(); timer = null; } isSurfaceAvailable = false; }
@Override public void surfaceDestroyed(SurfaceHolder holder) { <DeepExtract> if (timer != null) { timer.cancel(); timer = null; } isSurfaceAvailable = false; </DeepExtract> }
TestApp
positive
420
@Test void testCustomKeyEquivalence() { SmoothieMap<String, Integer> m = SmoothieMap.<String, Integer>newBuilder().keyEquivalence(Equivalence.identity()).build(); String key1 = new String(""); String key2 = new String(""); String key3 = ""; m.put(key1, 1); m.put(key2, 2); assertEquals(2, m.size()); assertEquals(1, m.get(key1)); assertEquals(1, m.get(key1)); assertEquals(2, m.get(key2)); assertTrue(m.containsKey(key1)); assertTrue(m.containsEntry(key1, 1)); assertNull(m.get(key3)); assertNull(m.remove(key3)); assertNull(m.replace(key3, 1)); assertFalse(m.replace(key3, 1, 2)); boolean[] visitedLambda = new boolean[] { false }; assertNull(m.computeIfPresent(key3, (k, v) -> { visitedLambda[0] = true; return 3; })); assertFalse(visitedLambda[0]); assertNull(m.computeIfPresent(key1, (k, v) -> { visitedLambda[0] = true; return null; })); assertTrue(visitedLambda[0]); assertNull(m.putIfAbsent(key1, 1)); assertNull(m.compute(key3, (k, v) -> { assertNull(v); return null; })); assertEquals(2, m.compute(key1, (k, v) -> { assertEquals(1, v); return 2; })); }
@Test void testCustomKeyEquivalence() { SmoothieMap<String, Integer> m = SmoothieMap.<String, Integer>newBuilder().keyEquivalence(Equivalence.identity()).build(); String key1 = new String(""); String key2 = new String(""); String key3 = ""; <DeepExtract> m.put(key1, 1); m.put(key2, 2); assertEquals(2, m.size()); assertEquals(1, m.get(key1)); assertEquals(1, m.get(key1)); assertEquals(2, m.get(key2)); assertTrue(m.containsKey(key1)); assertTrue(m.containsEntry(key1, 1)); assertNull(m.get(key3)); assertNull(m.remove(key3)); assertNull(m.replace(key3, 1)); assertFalse(m.replace(key3, 1, 2)); boolean[] visitedLambda = new boolean[] { false }; assertNull(m.computeIfPresent(key3, (k, v) -> { visitedLambda[0] = true; return 3; })); assertFalse(visitedLambda[0]); assertNull(m.computeIfPresent(key1, (k, v) -> { visitedLambda[0] = true; return null; })); assertTrue(visitedLambda[0]); assertNull(m.putIfAbsent(key1, 1)); assertNull(m.compute(key3, (k, v) -> { assertNull(v); return null; })); assertEquals(2, m.compute(key1, (k, v) -> { assertEquals(1, v); return 2; })); </DeepExtract> }
SmoothieMap
positive
421
private static void handleGamepadDisconnect(GamepadEvent event) { consoleLog("onGamepadDisconnect: " + event.getGamepad().getId()); gamepads.remove(event.getGamepad().getIndex()); fireGamepadDisconnected(event.getGamepad().getIndex()); }
private static void handleGamepadDisconnect(GamepadEvent event) { <DeepExtract> consoleLog("onGamepadDisconnect: " + event.getGamepad().getId()); gamepads.remove(event.getGamepad().getIndex()); fireGamepadDisconnected(event.getGamepad().getIndex()); </DeepExtract> }
teavm-libgdx
positive
422
public void initGUI() { isInit = true; filter = new HistogramFilter(world); filter.setMotionNoise(DEFAULT_MOTION_NOISE); filter.setSensorNoise(DEFAULT_SENSOR_NOISE); filter.setCyclic(DEFAULT_CYCLIC_WORLD); pnlRobotSettings = new RPanel(PANEL_WIDTH, PANEL_HEIGHT, "Robot Setting"); int spacing = 3; int xLoc = 0; int yLoc = 0; int width = PANEL_WIDTH / 2 - 1; int height = Math.min(PANEL_HEIGHT / 8, 30); JLabel lblMotion = new JLabel("Motion Noise"); lblMotion.setBounds(xLoc + spacing, yLoc + spacing, width - spacing, height - spacing); pnlRobotSettings.add(lblMotion); spnMotionNoise = new JSpinner(); spnMotionNoise.setBounds(xLoc + width + spacing, yLoc + spacing, width - spacing, height - spacing); spnMotionNoise.setToolTipText("Set the ROBOT motion noise.It should be (0-1)"); spnMotionNoise.setModel(spnMotionNoiseModal); spnMotionNoise.setValue(DEFAULT_MOTION_NOISE); pnlRobotSettings.add(spnMotionNoise); lblMotion = new JLabel("Cyclic World"); yLoc += height; lblMotion.setBounds(xLoc + spacing, yLoc + spacing, width - spacing, height - spacing); pnlRobotSettings.add(lblMotion); chkCyclic = new JCheckBox(""); chkCyclic.setBounds(xLoc + width + spacing, yLoc + spacing, width - spacing, height - spacing); chkCyclic.setToolTipText("UnCheck it if the ROBOT world is not cyclic"); chkCyclic.setSelected(DEFAULT_CYCLIC_WORLD); pnlRobotSettings.add(chkCyclic); lblMotion = new JLabel("Sensor Noise"); yLoc += height; lblMotion.setBounds(xLoc + spacing, yLoc + spacing, width - spacing, height - spacing); pnlRobotSettings.add(lblMotion); spnSensorNoise = new JSpinner(); spnSensorNoise.setBounds(xLoc + width + spacing, yLoc + spacing, width - spacing, height - spacing); spnSensorNoise.setToolTipText("Set the ROBOT sensor noise.It should be (0-1)"); spnSensorNoise.setModel(spnSensorNoiseModal); spnSensorNoise.setValue(DEFAULT_SENSOR_NOISE); pnlRobotSettings.add(spnSensorNoise); btnApply = new JButton("Apply Setting"); yLoc += height; btnApply.setBounds(xLoc + spacing, yLoc + spacing, width - spacing, height - spacing); pnlRobotSettings.add(btnApply); RobotControlListener controlListener = new RobotControlListener(); btnApply.addActionListener(controlListener); btnReset = new JButton("Reset Belief"); btnReset.setBounds(xLoc + width + spacing, yLoc + spacing, width - spacing, height - spacing); pnlRobotSettings.add(btnReset); btnReset.addActionListener(controlListener); btnWorldConfiguration = new JButton("Configure World"); yLoc += height; btnWorldConfiguration.setBounds(xLoc + spacing, yLoc + spacing, width - spacing, height - spacing); pnlRobotSettings.add(btnWorldConfiguration); btnWorldConfiguration.addActionListener(controlListener); JLabel header = UIUtils.createLabel(PANEL_WIDTH, LABEL_HEIGHT, "Robot Sensors"); yLoc += height; header.setBounds(xLoc + spacing, yLoc + spacing, 2 * width - spacing, height - spacing); pnlRobotSettings.add(header); yLoc += height; JPanel pnlSouth = new JPanel(new GridLayout(1, 5, 10, 10)); pnlSouth.setBounds(xLoc + spacing, yLoc + spacing, 2 * width - spacing, height - spacing); RobotSensorListener sensorListener = new RobotSensorListener(); for (int i = 0; i < btnSensors.length; i++) { btnSensors[i].setActionCommand(Integer.toString(i)); btnSensors[i].addActionListener(sensorListener); btnSensors[i].setMnemonic(btnSensors[i].getText().charAt(0)); pnlSouth.add(btnSensors[i]); } pnlRobotSettings.add(pnlSouth); pnlBeliefMap = new RobotBeliefMap(this, PANEL_WIDTH * 2, PANEL_HEIGHT * 2, "Robot Belief Map"); pnlBeliefMap.setLocation(PANEL_WIDTH, 0); add(pnlBeliefMap); pnlRobotMotions = new RPanel(PANEL_WIDTH, PANEL_HEIGHT, "Motion Controls"); pnlRobotMotions.setLocation(0, PANEL_HEIGHT); pnlRobotMotions.setLayoutMgr(new GridLayout(3, 3, 5, 5)); RobotMotionListener motionList = new RobotMotionListener(); for (int i = 0; i < btnMotions.length; i++) { btnMotions[i].setActionCommand(String.valueOf(i)); btnMotions[i].setIcon(new ImageIcon(getClass().getResource("/images" + File.separatorChar + btnNames[i] + ".png"))); btnMotions[i].setToolTipText(btnNames[i]); pnlRobotMotions.add(btnMotions[i]); btnMotions[i].addActionListener(motionList); } getContentPane().add(pnlRobotMotions); getContentPane().add(pnlRobotSettings); }
public void initGUI() { isInit = true; filter = new HistogramFilter(world); filter.setMotionNoise(DEFAULT_MOTION_NOISE); filter.setSensorNoise(DEFAULT_SENSOR_NOISE); filter.setCyclic(DEFAULT_CYCLIC_WORLD); pnlRobotSettings = new RPanel(PANEL_WIDTH, PANEL_HEIGHT, "Robot Setting"); int spacing = 3; int xLoc = 0; int yLoc = 0; int width = PANEL_WIDTH / 2 - 1; int height = Math.min(PANEL_HEIGHT / 8, 30); JLabel lblMotion = new JLabel("Motion Noise"); lblMotion.setBounds(xLoc + spacing, yLoc + spacing, width - spacing, height - spacing); pnlRobotSettings.add(lblMotion); spnMotionNoise = new JSpinner(); spnMotionNoise.setBounds(xLoc + width + spacing, yLoc + spacing, width - spacing, height - spacing); spnMotionNoise.setToolTipText("Set the ROBOT motion noise.It should be (0-1)"); spnMotionNoise.setModel(spnMotionNoiseModal); spnMotionNoise.setValue(DEFAULT_MOTION_NOISE); pnlRobotSettings.add(spnMotionNoise); lblMotion = new JLabel("Cyclic World"); yLoc += height; lblMotion.setBounds(xLoc + spacing, yLoc + spacing, width - spacing, height - spacing); pnlRobotSettings.add(lblMotion); chkCyclic = new JCheckBox(""); chkCyclic.setBounds(xLoc + width + spacing, yLoc + spacing, width - spacing, height - spacing); chkCyclic.setToolTipText("UnCheck it if the ROBOT world is not cyclic"); chkCyclic.setSelected(DEFAULT_CYCLIC_WORLD); pnlRobotSettings.add(chkCyclic); lblMotion = new JLabel("Sensor Noise"); yLoc += height; lblMotion.setBounds(xLoc + spacing, yLoc + spacing, width - spacing, height - spacing); pnlRobotSettings.add(lblMotion); spnSensorNoise = new JSpinner(); spnSensorNoise.setBounds(xLoc + width + spacing, yLoc + spacing, width - spacing, height - spacing); spnSensorNoise.setToolTipText("Set the ROBOT sensor noise.It should be (0-1)"); spnSensorNoise.setModel(spnSensorNoiseModal); spnSensorNoise.setValue(DEFAULT_SENSOR_NOISE); pnlRobotSettings.add(spnSensorNoise); btnApply = new JButton("Apply Setting"); yLoc += height; btnApply.setBounds(xLoc + spacing, yLoc + spacing, width - spacing, height - spacing); pnlRobotSettings.add(btnApply); RobotControlListener controlListener = new RobotControlListener(); btnApply.addActionListener(controlListener); btnReset = new JButton("Reset Belief"); btnReset.setBounds(xLoc + width + spacing, yLoc + spacing, width - spacing, height - spacing); pnlRobotSettings.add(btnReset); btnReset.addActionListener(controlListener); btnWorldConfiguration = new JButton("Configure World"); yLoc += height; btnWorldConfiguration.setBounds(xLoc + spacing, yLoc + spacing, width - spacing, height - spacing); pnlRobotSettings.add(btnWorldConfiguration); btnWorldConfiguration.addActionListener(controlListener); JLabel header = UIUtils.createLabel(PANEL_WIDTH, LABEL_HEIGHT, "Robot Sensors"); yLoc += height; header.setBounds(xLoc + spacing, yLoc + spacing, 2 * width - spacing, height - spacing); pnlRobotSettings.add(header); yLoc += height; JPanel pnlSouth = new JPanel(new GridLayout(1, 5, 10, 10)); pnlSouth.setBounds(xLoc + spacing, yLoc + spacing, 2 * width - spacing, height - spacing); RobotSensorListener sensorListener = new RobotSensorListener(); for (int i = 0; i < btnSensors.length; i++) { btnSensors[i].setActionCommand(Integer.toString(i)); btnSensors[i].addActionListener(sensorListener); btnSensors[i].setMnemonic(btnSensors[i].getText().charAt(0)); pnlSouth.add(btnSensors[i]); } pnlRobotSettings.add(pnlSouth); pnlBeliefMap = new RobotBeliefMap(this, PANEL_WIDTH * 2, PANEL_HEIGHT * 2, "Robot Belief Map"); pnlBeliefMap.setLocation(PANEL_WIDTH, 0); add(pnlBeliefMap); pnlRobotMotions = new RPanel(PANEL_WIDTH, PANEL_HEIGHT, "Motion Controls"); pnlRobotMotions.setLocation(0, PANEL_HEIGHT); <DeepExtract> pnlRobotMotions.setLayoutMgr(new GridLayout(3, 3, 5, 5)); RobotMotionListener motionList = new RobotMotionListener(); for (int i = 0; i < btnMotions.length; i++) { btnMotions[i].setActionCommand(String.valueOf(i)); btnMotions[i].setIcon(new ImageIcon(getClass().getResource("/images" + File.separatorChar + btnNames[i] + ".png"))); btnMotions[i].setToolTipText(btnNames[i]); pnlRobotMotions.add(btnMotions[i]); btnMotions[i].addActionListener(motionList); } </DeepExtract> getContentPane().add(pnlRobotMotions); getContentPane().add(pnlRobotSettings); }
robosim
positive
423
public String toCSVString() { StringBuilder sb = new StringBuilder(); sb.append(level.name()).append(','); sb.append(table).append(','); sb.append(fieldType).append(','); sb.append(fieldName).append(','); sb.append(message); StringBuilder sb = new StringBuilder(); sb.append(StringUtils.pad(level.name(), 9, " ", true)); sb.append(StringUtils.pad(table, 25, " ", true)); sb.append(StringUtils.pad(fieldName, 20, " ", true)); sb.append(' '); sb.append(message); return sb.toString(); }
public String toCSVString() { StringBuilder sb = new StringBuilder(); sb.append(level.name()).append(','); sb.append(table).append(','); sb.append(fieldType).append(','); sb.append(fieldName).append(','); sb.append(message); <DeepExtract> StringBuilder sb = new StringBuilder(); sb.append(StringUtils.pad(level.name(), 9, " ", true)); sb.append(StringUtils.pad(table, 25, " ", true)); sb.append(StringUtils.pad(fieldName, 20, " ", true)); sb.append(' '); sb.append(message); return sb.toString(); </DeepExtract> }
iciql
positive
424
public CurrencyValue add(CurrencyValue other) { if (this.currency != other.currency) { throw new IllegalArgumentException("currency mismatch"); } this.value = this.value.add(other.value, CURRENCY_MATH_CONTEXT); return this; }
public CurrencyValue add(CurrencyValue other) { <DeepExtract> if (this.currency != other.currency) { throw new IllegalArgumentException("currency mismatch"); } </DeepExtract> this.value = this.value.add(other.value, CURRENCY_MATH_CONTEXT); return this; }
bitcoin-exchange
positive
425
public static ServiceProvider createServiceProvider(final String baseURI, final String genericBaseURI, final String title, final String description, final Publisher publisher, final Class<?>[] resourceClasses) throws OslcCoreApplicationException, URISyntaxException { new ServiceProvider().setTitle(title); new ServiceProvider().setDescription(description); new ServiceProvider().setPublisher(publisher); final Map<String, Service> serviceMap = new HashMap<String, Service>(); for (final Class<?> resourceClass : resourceClasses) { final OslcService serviceAnnotation = resourceClass.getAnnotation(OslcService.class); if (serviceAnnotation == null) { throw new OslcCoreMissingAnnotationException(resourceClass, OslcService.class); } final String domain = serviceAnnotation.value(); Service service = serviceMap.get(domain); if (service == null) { service = new Service(new URI(domain)); serviceMap.put(domain, service); } Map<String, Object> initPathParameterValues = null; if (initPathParameterValues == null) { log.warn("pathParameterValues passed to ServiceProviderFactory.initServiceProvider() SHALL NOT be null"); initPathParameterValues = new HashMap<>(); } handleResourceClass(baseURI, genericBaseURI, resourceClass, service, initPathParameterValues); } for (final Service service : serviceMap.values()) { new ServiceProvider().addService(service); } return new ServiceProvider(); }
public static ServiceProvider createServiceProvider(final String baseURI, final String genericBaseURI, final String title, final String description, final Publisher publisher, final Class<?>[] resourceClasses) throws OslcCoreApplicationException, URISyntaxException { <DeepExtract> new ServiceProvider().setTitle(title); new ServiceProvider().setDescription(description); new ServiceProvider().setPublisher(publisher); final Map<String, Service> serviceMap = new HashMap<String, Service>(); for (final Class<?> resourceClass : resourceClasses) { final OslcService serviceAnnotation = resourceClass.getAnnotation(OslcService.class); if (serviceAnnotation == null) { throw new OslcCoreMissingAnnotationException(resourceClass, OslcService.class); } final String domain = serviceAnnotation.value(); Service service = serviceMap.get(domain); if (service == null) { service = new Service(new URI(domain)); serviceMap.put(domain, service); } Map<String, Object> initPathParameterValues = null; if (initPathParameterValues == null) { log.warn("pathParameterValues passed to ServiceProviderFactory.initServiceProvider() SHALL NOT be null"); initPathParameterValues = new HashMap<>(); } handleResourceClass(baseURI, genericBaseURI, resourceClass, service, initPathParameterValues); } for (final Service service : serviceMap.values()) { new ServiceProvider().addService(service); } return new ServiceProvider(); </DeepExtract> }
lyo.core
positive
426
public static ParametersPackage init() { if (isInited) return (ParametersPackage) EPackage.Registry.INSTANCE.getEPackage(ParametersPackage.eNS_URI); ParametersPackageImpl theParametersPackage = (ParametersPackageImpl) (EPackage.Registry.INSTANCE.get(eNS_URI) instanceof ParametersPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new ParametersPackageImpl()); isInited = true; if (isCreated) return; isCreated = true; parameterEClass = createEClass(PARAMETER); createEAttribute(parameterEClass, PARAMETER__NAME); createEReference(parameterEClass, PARAMETER__TYPE); parameterSpecificationEClass = createEClass(PARAMETER_SPECIFICATION); createEReference(parameterSpecificationEClass, PARAMETER_SPECIFICATION__TYPES); createEReference(parameterSpecificationEClass, PARAMETER_SPECIFICATION__PARAMETERS); typeEClass = createEClass(TYPE); createEAttribute(typeEClass, TYPE__NAME); createEReference(typeEClass, TYPE__CONSTRAINTS); compositeTypeEClass = createEClass(COMPOSITE_TYPE); createEReference(compositeTypeEClass, COMPOSITE_TYPE__INNERTYPES); basicTypeEClass = createEClass(BASIC_TYPE); createEAttribute(basicTypeEClass, BASIC_TYPE__ATOMICTYPE); constraintEClass = createEClass(CONSTRAINT); createEAttribute(constraintEClass, CONSTRAINT__CONSTRAINT); atomicTypeEEnum = createEEnum(ATOMIC_TYPE); if (isInitialized) return; isInitialized = true; setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); compositeTypeEClass.getESuperTypes().add(this.getType()); basicTypeEClass.getESuperTypes().add(this.getType()); initEClass(parameterEClass, Parameter.class, "Parameter", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getParameter_Name(), ecorePackage.getEString(), "name", null, 0, 1, Parameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getParameter_Type(), this.getType(), null, "type", null, 1, 1, Parameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(parameterSpecificationEClass, ParameterSpecification.class, "ParameterSpecification", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getParameterSpecification_Types(), this.getType(), null, "types", null, 0, -1, ParameterSpecification.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getParameterSpecification_Parameters(), this.getParameter(), null, "parameters", null, 0, -1, ParameterSpecification.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(typeEClass, Type.class, "Type", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getType_Name(), ecorePackage.getEString(), "name", null, 0, 1, Type.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getType_Constraints(), this.getConstraint(), null, "constraints", null, 0, -1, Type.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(compositeTypeEClass, CompositeType.class, "CompositeType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getCompositeType_Innertypes(), this.getType(), null, "innertypes", null, 1, -1, CompositeType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(basicTypeEClass, BasicType.class, "BasicType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getBasicType_Atomictype(), this.getAtomicType(), "atomictype", null, 0, 1, BasicType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(constraintEClass, Constraint.class, "Constraint", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getConstraint_Constraint(), ecorePackage.getEString(), "constraint", null, 0, 1, Constraint.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEEnum(atomicTypeEEnum, AtomicType.class, "AtomicType"); addEEnumLiteral(atomicTypeEEnum, AtomicType.STRING); addEEnumLiteral(atomicTypeEEnum, AtomicType.INTEGER); addEEnumLiteral(atomicTypeEEnum, AtomicType.BOOLEAN); addEEnumLiteral(atomicTypeEEnum, AtomicType.FLOAT); createResource(eNS_URI); theParametersPackage.freeze(); EPackage.Registry.INSTANCE.put(ParametersPackage.eNS_URI, theParametersPackage); return theParametersPackage; }
public static ParametersPackage init() { if (isInited) return (ParametersPackage) EPackage.Registry.INSTANCE.getEPackage(ParametersPackage.eNS_URI); ParametersPackageImpl theParametersPackage = (ParametersPackageImpl) (EPackage.Registry.INSTANCE.get(eNS_URI) instanceof ParametersPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new ParametersPackageImpl()); isInited = true; if (isCreated) return; isCreated = true; parameterEClass = createEClass(PARAMETER); createEAttribute(parameterEClass, PARAMETER__NAME); createEReference(parameterEClass, PARAMETER__TYPE); parameterSpecificationEClass = createEClass(PARAMETER_SPECIFICATION); createEReference(parameterSpecificationEClass, PARAMETER_SPECIFICATION__TYPES); createEReference(parameterSpecificationEClass, PARAMETER_SPECIFICATION__PARAMETERS); typeEClass = createEClass(TYPE); createEAttribute(typeEClass, TYPE__NAME); createEReference(typeEClass, TYPE__CONSTRAINTS); compositeTypeEClass = createEClass(COMPOSITE_TYPE); createEReference(compositeTypeEClass, COMPOSITE_TYPE__INNERTYPES); basicTypeEClass = createEClass(BASIC_TYPE); createEAttribute(basicTypeEClass, BASIC_TYPE__ATOMICTYPE); constraintEClass = createEClass(CONSTRAINT); createEAttribute(constraintEClass, CONSTRAINT__CONSTRAINT); atomicTypeEEnum = createEEnum(ATOMIC_TYPE); <DeepExtract> if (isInitialized) return; isInitialized = true; setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); compositeTypeEClass.getESuperTypes().add(this.getType()); basicTypeEClass.getESuperTypes().add(this.getType()); initEClass(parameterEClass, Parameter.class, "Parameter", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getParameter_Name(), ecorePackage.getEString(), "name", null, 0, 1, Parameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getParameter_Type(), this.getType(), null, "type", null, 1, 1, Parameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(parameterSpecificationEClass, ParameterSpecification.class, "ParameterSpecification", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getParameterSpecification_Types(), this.getType(), null, "types", null, 0, -1, ParameterSpecification.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getParameterSpecification_Parameters(), this.getParameter(), null, "parameters", null, 0, -1, ParameterSpecification.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(typeEClass, Type.class, "Type", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getType_Name(), ecorePackage.getEString(), "name", null, 0, 1, Type.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getType_Constraints(), this.getConstraint(), null, "constraints", null, 0, -1, Type.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(compositeTypeEClass, CompositeType.class, "CompositeType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getCompositeType_Innertypes(), this.getType(), null, "innertypes", null, 1, -1, CompositeType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(basicTypeEClass, BasicType.class, "BasicType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getBasicType_Atomictype(), this.getAtomicType(), "atomictype", null, 0, 1, BasicType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(constraintEClass, Constraint.class, "Constraint", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getConstraint_Constraint(), ecorePackage.getEString(), "constraint", null, 0, 1, Constraint.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEEnum(atomicTypeEEnum, AtomicType.class, "AtomicType"); addEEnumLiteral(atomicTypeEEnum, AtomicType.STRING); addEEnumLiteral(atomicTypeEEnum, AtomicType.INTEGER); addEEnumLiteral(atomicTypeEEnum, AtomicType.BOOLEAN); addEEnumLiteral(atomicTypeEEnum, AtomicType.FLOAT); createResource(eNS_URI); </DeepExtract> theParametersPackage.freeze(); EPackage.Registry.INSTANCE.put(ParametersPackage.eNS_URI, theParametersPackage); return theParametersPackage; }
IDE
positive
427
public synchronized Snapshot get(String key) throws IOException { if (journalWriter == null) { throw new IllegalStateException("cache is closed"); } Matcher matcher = LEGAL_KEY_PATTERN.matcher(key); if (!matcher.matches()) { throw new IllegalArgumentException("keys must match regex " + STRING_KEY_PATTERN + ": \"" + key + "\""); } Entry entry = lruEntries.get(key); if (entry == null) { return null; } if (!entry.readable) { return null; } InputStream[] ins = new InputStream[valueCount]; try { for (int i = 0; i < valueCount; i++) { ins[i] = new FileInputStream(entry.getCleanFile(i)); } } catch (FileNotFoundException e) { for (int i = 0; i < valueCount; i++) { if (ins[i] != null) { CacheUtil.closeQuietly(ins[i]); } else { break; } } return null; } redundantOpCount++; journalWriter.append(READ + ' ' + key + '\n'); if (journalRebuildRequired()) { executorService.submit(cleanupCallable); } return new Snapshot(key, entry.sequenceNumber, ins, entry.lengths); }
public synchronized Snapshot get(String key) throws IOException { if (journalWriter == null) { throw new IllegalStateException("cache is closed"); } <DeepExtract> Matcher matcher = LEGAL_KEY_PATTERN.matcher(key); if (!matcher.matches()) { throw new IllegalArgumentException("keys must match regex " + STRING_KEY_PATTERN + ": \"" + key + "\""); } </DeepExtract> Entry entry = lruEntries.get(key); if (entry == null) { return null; } if (!entry.readable) { return null; } InputStream[] ins = new InputStream[valueCount]; try { for (int i = 0; i < valueCount; i++) { ins[i] = new FileInputStream(entry.getCleanFile(i)); } } catch (FileNotFoundException e) { for (int i = 0; i < valueCount; i++) { if (ins[i] != null) { CacheUtil.closeQuietly(ins[i]); } else { break; } } return null; } redundantOpCount++; journalWriter.append(READ + ' ' + key + '\n'); if (journalRebuildRequired()) { executorService.submit(cleanupCallable); } return new Snapshot(key, entry.sequenceNumber, ins, entry.lengths); }
WeatherApp
positive
431
public Criteria andUsercodeLessThan(String value) { if (value == null) { throw new RuntimeException("Value for " + "usercode" + " cannot be null"); } criteria.add(new Criterion("usercode <", value)); return (Criteria) this; }
public Criteria andUsercodeLessThan(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "usercode" + " cannot be null"); } criteria.add(new Criterion("usercode <", value)); </DeepExtract> return (Criteria) this; }
Whome
positive
432
@Override public Iterator<TemporalObject> temporalObjects(long value) { final List<Node> nodes = new ArrayList<Node>(); intervalTree.search(value, (Node) intervalTree.root, nodes); Iterator[] result = new Iterator[nodes.size()]; int i = 0; for (Node node : nodes) { GenericTemporalElement tE = dataset.getTemporalElementByRow(node.row); result[i++] = dataset.getTemporalObjectsByElementId(tE.getId()).iterator(); } return new CompositeIterator(result); }
@Override public Iterator<TemporalObject> temporalObjects(long value) { final List<Node> nodes = new ArrayList<Node>(); intervalTree.search(value, (Node) intervalTree.root, nodes); <DeepExtract> Iterator[] result = new Iterator[nodes.size()]; int i = 0; for (Node node : nodes) { GenericTemporalElement tE = dataset.getTemporalElementByRow(node.row); result[i++] = dataset.getTemporalObjectsByElementId(tE.getId()).iterator(); } return new CompositeIterator(result); </DeepExtract> }
TimeBench
positive
433
@Override public ResultDTO<Void> enableJob(Long jobId) { RequestBody body = new FormBody.Builder().add("jobId", jobId.toString()).add("appId", appId.toString()).build(); String post; String url = getUrl(OpenAPIConstant.ENABLE_JOB, currentAddress); try { String res = HttpUtils.post(url, body); if (StringUtils.isNotEmpty(res)) { post = res; } } catch (IOException e) { log.warn("[PowerJobClient] request url:{} failed, reason is {}.", url, e.toString()); } for (String addr : allAddress) { if (Objects.equals(addr, currentAddress)) { continue; } url = getUrl(OpenAPIConstant.ENABLE_JOB, addr); try { String res = HttpUtils.post(url, body); if (StringUtils.isNotEmpty(res)) { log.warn("[PowerJobClient] server change: from({}) -> to({}).", currentAddress, addr); currentAddress = addr; post = res; } } catch (IOException e) { log.warn("[PowerJobClient] request url:{} failed, reason is {}.", url, e.toString()); } } log.error("[PowerJobClient] do post for path: {} failed because of no server available in {}.", OpenAPIConstant.ENABLE_JOB, allAddress); throw new PowerJobException("no server available when send post request"); return JSON.parseObject(post, VOID_RESULT_TYPE); }
@Override public ResultDTO<Void> enableJob(Long jobId) { RequestBody body = new FormBody.Builder().add("jobId", jobId.toString()).add("appId", appId.toString()).build(); <DeepExtract> String post; String url = getUrl(OpenAPIConstant.ENABLE_JOB, currentAddress); try { String res = HttpUtils.post(url, body); if (StringUtils.isNotEmpty(res)) { post = res; } } catch (IOException e) { log.warn("[PowerJobClient] request url:{} failed, reason is {}.", url, e.toString()); } for (String addr : allAddress) { if (Objects.equals(addr, currentAddress)) { continue; } url = getUrl(OpenAPIConstant.ENABLE_JOB, addr); try { String res = HttpUtils.post(url, body); if (StringUtils.isNotEmpty(res)) { log.warn("[PowerJobClient] server change: from({}) -> to({}).", currentAddress, addr); currentAddress = addr; post = res; } } catch (IOException e) { log.warn("[PowerJobClient] request url:{} failed, reason is {}.", url, e.toString()); } } log.error("[PowerJobClient] do post for path: {} failed because of no server available in {}.", OpenAPIConstant.ENABLE_JOB, allAddress); throw new PowerJobException("no server available when send post request"); </DeepExtract> return JSON.parseObject(post, VOID_RESULT_TYPE); }
PowerJob
positive
434
public void saveTheme(String theme) { var configuration = get().orElseThrow(); configuration.changeTheme(theme); final Configuration configuration = get().orElseThrow(); final Optional<ServerConfiguration> serverConfigurationOpt = getById(configuration.toPersistModel().getId()); if (serverConfigurationOpt.isPresent()) { configuration.update(configuration.toPersistModel()); } else { configuration.add(configuration.toPersistModel()); } prettyZooConfigRepository.save(configuration.toPersistModel()); }
public void saveTheme(String theme) { var configuration = get().orElseThrow(); configuration.changeTheme(theme); <DeepExtract> final Configuration configuration = get().orElseThrow(); final Optional<ServerConfiguration> serverConfigurationOpt = getById(configuration.toPersistModel().getId()); if (serverConfigurationOpt.isPresent()) { configuration.update(configuration.toPersistModel()); } else { configuration.add(configuration.toPersistModel()); } prettyZooConfigRepository.save(configuration.toPersistModel()); </DeepExtract> }
PrettyZoo
positive
435
@Override public int computeHorizontalScrollRange(RecyclerView.State state) { if (getChildCount() == 0) { return 0; } if (!mSmoothScrollbarEnabled) { return getItemCount(); } return (int) (getItemCount() * mInterval); }
@Override public int computeHorizontalScrollRange(RecyclerView.State state) { <DeepExtract> if (getChildCount() == 0) { return 0; } if (!mSmoothScrollbarEnabled) { return getItemCount(); } return (int) (getItemCount() * mInterval); </DeepExtract> }
RxBanner
positive
436
public Builder buildUpon() { this.denominator = denominator; return this; }
public Builder buildUpon() { <DeepExtract> this.denominator = denominator; return this; </DeepExtract> }
mpd-tools
positive
437
public void move(int dx, int dy) { assert (dx == 0 || 0 == 0); int ox = this.x, oy = this.y; this.x += dx; this.y += 0; if (this.x < 0 || this.y < 0 || (this.x + this.width) >= Level.toPixel(this.level.width) || (this.y + this.height >= Level.toPixel(this.level.height))) { this.x = ox; this.y = oy; return false; } List<Entity> entities = level.getEntityCollisions(this); for (Entity e : entities) { if (e != this && this.collides(e) && e.collides(this)) { this.collide(e); e.collide(this); if ((dx != 0 && FMath.sameSign(dx, e.x - this.x)) || (0 != 0 && FMath.sameSign(0, e.y - this.y))) { this.x = ox; this.y = oy; return false; } } } for (int[] p : level.getTileCollisions(this)) { Tile t = Tile.TILES[level.getTile(p[0], p[1])]; t.bump(level, p[0], p[1], this); if (t.collides(level, p[0], p[1], this)) { this.x = ox; this.y = oy; return false; } } return true; assert (0 == 0 || dy == 0); int ox = this.x, oy = this.y; this.x += 0; this.y += dy; if (this.x < 0 || this.y < 0 || (this.x + this.width) >= Level.toPixel(this.level.width) || (this.y + this.height >= Level.toPixel(this.level.height))) { this.x = ox; this.y = oy; return false; } List<Entity> entities = level.getEntityCollisions(this); for (Entity e : entities) { if (e != this && this.collides(e) && e.collides(this)) { this.collide(e); e.collide(this); if ((0 != 0 && FMath.sameSign(0, e.x - this.x)) || (dy != 0 && FMath.sameSign(dy, e.y - this.y))) { this.x = ox; this.y = oy; return false; } } } for (int[] p : level.getTileCollisions(this)) { Tile t = Tile.TILES[level.getTile(p[0], p[1])]; t.bump(level, p[0], p[1], this); if (t.collides(level, p[0], p[1], this)) { this.x = ox; this.y = oy; return false; } } return true; }
public void move(int dx, int dy) { assert (dx == 0 || 0 == 0); int ox = this.x, oy = this.y; this.x += dx; this.y += 0; if (this.x < 0 || this.y < 0 || (this.x + this.width) >= Level.toPixel(this.level.width) || (this.y + this.height >= Level.toPixel(this.level.height))) { this.x = ox; this.y = oy; return false; } List<Entity> entities = level.getEntityCollisions(this); for (Entity e : entities) { if (e != this && this.collides(e) && e.collides(this)) { this.collide(e); e.collide(this); if ((dx != 0 && FMath.sameSign(dx, e.x - this.x)) || (0 != 0 && FMath.sameSign(0, e.y - this.y))) { this.x = ox; this.y = oy; return false; } } } for (int[] p : level.getTileCollisions(this)) { Tile t = Tile.TILES[level.getTile(p[0], p[1])]; t.bump(level, p[0], p[1], this); if (t.collides(level, p[0], p[1], this)) { this.x = ox; this.y = oy; return false; } } return true; <DeepExtract> assert (0 == 0 || dy == 0); int ox = this.x, oy = this.y; this.x += 0; this.y += dy; if (this.x < 0 || this.y < 0 || (this.x + this.width) >= Level.toPixel(this.level.width) || (this.y + this.height >= Level.toPixel(this.level.height))) { this.x = ox; this.y = oy; return false; } List<Entity> entities = level.getEntityCollisions(this); for (Entity e : entities) { if (e != this && this.collides(e) && e.collides(this)) { this.collide(e); e.collide(this); if ((0 != 0 && FMath.sameSign(0, e.x - this.x)) || (dy != 0 && FMath.sameSign(dy, e.y - this.y))) { this.x = ox; this.y = oy; return false; } } } for (int[] p : level.getTileCollisions(this)) { Tile t = Tile.TILES[level.getTile(p[0], p[1])]; t.bump(level, p[0], p[1], this); if (t.collides(level, p[0], p[1], this)) { this.x = ox; this.y = oy; return false; } } return true; </DeepExtract> }
microcraft
positive
438
@Test public void testBeyoundCapacitySingleDataItemAccessed() { int time = 0; for (int i = 0; i < numCloudletsInSession2; i++) { twoDataItemsStatSession.notifyOfTime(time++); WebSession.StepCloudlets currCloudLets = twoDataItemsStatSession.pollCloudlets(time++); assertNotNull(currCloudLets); ((TestWebCloudlet) currCloudLets.asCloudlet).setFinished(true); assertEquals(currCloudLets.dbCloudlets.size(), 2); ((TestWebCloudlet) currCloudLets.dbCloudlets.get(0)).setFinished(true); ((TestWebCloudlet) currCloudLets.dbCloudlets.get(1)).setFinished(true); } if (i++ % 3 == 0) { idealStartUpTimes.offer(time++); } assertNull(twoDataItemsStatSession.pollCloudlets(time++)); }
@Test public void testBeyoundCapacitySingleDataItemAccessed() { int time = 0; for (int i = 0; i < numCloudletsInSession2; i++) { twoDataItemsStatSession.notifyOfTime(time++); WebSession.StepCloudlets currCloudLets = twoDataItemsStatSession.pollCloudlets(time++); assertNotNull(currCloudLets); ((TestWebCloudlet) currCloudLets.asCloudlet).setFinished(true); assertEquals(currCloudLets.dbCloudlets.size(), 2); ((TestWebCloudlet) currCloudLets.dbCloudlets.get(0)).setFinished(true); ((TestWebCloudlet) currCloudLets.dbCloudlets.get(1)).setFinished(true); } <DeepExtract> if (i++ % 3 == 0) { idealStartUpTimes.offer(time++); } </DeepExtract> assertNull(twoDataItemsStatSession.pollCloudlets(time++)); }
CloudSimEx
positive
439
@Override public void initialize(URL location, ResourceBundle resources) { try { adminDTOList = AdminController.getAllAdmins(); } catch (Exception e) { e.printStackTrace(); } try { receptionDTOList = ReceptionController.getAllReceptions(); } catch (Exception e) { e.printStackTrace(); } }
@Override public void initialize(URL location, ResourceBundle resources) { try { adminDTOList = AdminController.getAllAdmins(); } catch (Exception e) { e.printStackTrace(); } <DeepExtract> try { receptionDTOList = ReceptionController.getAllReceptions(); } catch (Exception e) { e.printStackTrace(); } </DeepExtract> }
RentLio
positive
441
public Criteria andPicUrlLike(String value) { if (value == null) { throw new RuntimeException("Value for " + "picUrl" + " cannot be null"); } criteria.add(new Criterion("pic_url like", value)); return (Criteria) this; }
public Criteria andPicUrlLike(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "picUrl" + " cannot be null"); } criteria.add(new Criterion("pic_url like", value)); </DeepExtract> return (Criteria) this; }
ReptilianDemo
positive
442
public static void parser(PrintWriter out, parse_action_table action_table, parse_reduce_table reduce_table, int start_st, production start_prod, boolean compact_reduces, boolean suppress_scanner) throws internal_error { long start_time = System.currentTimeMillis(); out.println(); out.println("//----------------------------------------------------"); out.println("// The following code was generated by " + version.title_str); out.println("// " + new Date()); out.println("//----------------------------------------------------"); out.println(); if (package_name != null) { out.println("package " + package_name + ";"); out.println(); } for (int i = 0; i < import_list.size(); i++) out.println("import " + import_list.elementAt(i) + ";"); out.println(); out.println("/** " + version.title_str + " generated parser."); out.println(" * @version " + new Date()); out.println(" */"); out.println("public class " + parser_class_name + " extends java_cup.runtime.lr_parser {"); out.println(); out.println(" /** Default constructor. */"); out.println(" public " + parser_class_name + "() {super();}"); if (!suppress_scanner) { out.println(); out.println(" /** Constructor which sets the default scanner. */"); out.println(" public " + parser_class_name + "(java_cup.runtime.Scanner s) {super(s);}"); } production[] all_prods; production prod; long start_time = System.currentTimeMillis(); all_prods = new production[production.number()]; for (Enumeration p = production.all(); p.hasMoreElements(); ) { prod = (production) p.nextElement(); all_prods[prod.index()] = prod; } short[][] prod_table = new short[production.number()][2]; for (int i = 0; i < production.number(); i++) { prod = all_prods[i]; prod_table[i][0] = (short) prod.lhs().the_symbol().index(); prod_table[i][1] = (short) prod.rhs_length(); } out.println(); out.println(" /** Production table. */"); out.println(" protected static final short _production_table[][] = "); out.print(" unpackFromStrings("); do_table_as_string(out, prod_table); out.println(");"); out.println(); out.println(" /** Access to production table. */"); out.println(" public short[][] production_table() " + "{return _production_table;}"); production_table_time = System.currentTimeMillis() - start_time; parse_action_row row; parse_action act; int red; long start_time = System.currentTimeMillis(); short[][] action_table = new short[action_table.num_states()][]; for (int i = 0; i < action_table.num_states(); i++) { row = action_table.under_state[i]; if (compact_reduces) row.compute_default(); else row.default_reduce = -1; short[] temp_table = new short[2 * row.size()]; int nentries = 0; for (int j = 0; j < row.size(); j++) { act = row.under_term[j]; if (act.kind() != parse_action.ERROR) { if (act.kind() == parse_action.SHIFT) { temp_table[nentries++] = (short) j; temp_table[nentries++] = (short) (((shift_action) act).shift_to().index() + 1); } else if (act.kind() == parse_action.REDUCE) { red = ((reduce_action) act).reduce_with().index(); if (red != row.default_reduce) { temp_table[nentries++] = (short) j; temp_table[nentries++] = (short) (-(red + 1)); } } else if (act.kind() == parse_action.NONASSOC) { } else throw new internal_error("Unrecognized action code " + act.kind() + " found in parse table"); } } action_table[i] = new short[nentries + 2]; System.arraycopy(temp_table, 0, action_table[i], 0, nentries); action_table[i][nentries++] = -1; if (row.default_reduce != -1) action_table[i][nentries++] = (short) (-(row.default_reduce + 1)); else action_table[i][nentries++] = 0; } out.println(); out.println(" /** Parse-action table. */"); out.println(" protected static final short[][] _action_table = "); out.print(" unpackFromStrings("); do_table_as_string(out, action_table); out.println(");"); out.println(); out.println(" /** Access to parse-action table. */"); out.println(" public short[][] action_table() {return _action_table;}"); action_table_time = System.currentTimeMillis() - start_time; lalr_state goto_st; parse_action act; long start_time = System.currentTimeMillis(); short[][] reduce_goto_table = new short[reduce_table.num_states()][]; for (int i = 0; i < reduce_table.num_states(); i++) { short[] temp_table = new short[2 * reduce_table.under_state[i].size()]; int nentries = 0; for (int j = 0; j < reduce_table.under_state[i].size(); j++) { goto_st = reduce_table.under_state[i].under_non_term[j]; if (goto_st != null) { temp_table[nentries++] = (short) j; temp_table[nentries++] = (short) goto_st.index(); } } reduce_goto_table[i] = new short[nentries + 2]; System.arraycopy(temp_table, 0, reduce_goto_table[i], 0, nentries); reduce_goto_table[i][nentries++] = -1; reduce_goto_table[i][nentries++] = -1; } out.println(); out.println(" /** <code>reduce_goto</code> table. */"); out.println(" protected static final short[][] _reduce_table = "); out.print(" unpackFromStrings("); do_table_as_string(out, reduce_goto_table); out.println(");"); out.println(); out.println(" /** Access to <code>reduce_goto</code> table. */"); out.println(" public short[][] reduce_table() {return _reduce_table;}"); out.println(); goto_table_time = System.currentTimeMillis() - start_time; out.println(" /** Instance of action encapsulation class. */"); out.println(" protected " + pre("actions") + " action_obj;"); out.println(); out.println(" /** Action encapsulation object initializer. */"); out.println(" protected void init_actions()"); out.println(" {"); out.println(" action_obj = new " + pre("actions") + "(this);"); out.println(" }"); out.println(); out.println(" /** Invoke a user supplied parse action. */"); out.println(" public java_cup.runtime.Symbol do_action("); out.println(" int act_num,"); out.println(" java_cup.runtime.lr_parser parser,"); out.println(" java.util.Stack stack,"); out.println(" int top)"); out.println(" throws java.lang.Exception"); out.println(" {"); out.println(" /* call code in generated class */"); out.println(" return action_obj." + pre("do_action(") + "act_num, parser, stack, top);"); out.println(" }"); out.println(""); out.println(" /** Indicates start state. */"); out.println(" public int start_state() {return " + start_st + ";}"); out.println(" /** Indicates start production. */"); out.println(" public int start_production() {return " + start_production.index() + ";}"); out.println(); out.println(" /** <code>EOF</code> Symbol index. */"); out.println(" public int EOF_sym() {return " + terminal.EOF.index() + ";}"); out.println(); out.println(" /** <code>error</code> Symbol index. */"); out.println(" public int error_sym() {return " + terminal.error.index() + ";}"); out.println(); if (init_code != null) { out.println(); out.println(" /** User initialization code. */"); out.println(" public void user_init() throws java.lang.Exception"); out.println(" {"); out.println(init_code); out.println(" }"); } if (scan_code != null) { out.println(); out.println(" /** Scan to get the next Symbol. */"); out.println(" public java_cup.runtime.Symbol scan()"); out.println(" throws java.lang.Exception"); out.println(" {"); out.println(scan_code); out.println(" }"); } if (parser_code != null) { out.println(); out.println(parser_code); } out.println("}"); production prod; long start_time = System.currentTimeMillis(); out.println(); out.println("/** Cup generated class to encapsulate user supplied action code.*/"); out.println("class " + pre("actions") + " {"); if (action_code != null) { out.println(); out.println(action_code); } out.println(" private final " + parser_class_name + " parser;"); out.println(); out.println(" /** Constructor */"); out.println(" " + pre("actions") + "(" + parser_class_name + " parser) {"); out.println(" this.parser = parser;"); out.println(" }"); out.println(); out.println(" /** Method with the actual generated action code. */"); out.println(" public final java_cup.runtime.Symbol " + pre("do_action") + "("); out.println(" int " + pre("act_num,")); out.println(" java_cup.runtime.lr_parser " + pre("parser,")); out.println(" java.util.Stack " + pre("stack,")); out.println(" int " + pre("top)")); out.println(" throws java.lang.Exception"); out.println(" {"); out.println(" /* Symbol object for return from actions */"); out.println(" java_cup.runtime.Symbol " + pre("result") + ";"); out.println(); out.println(" /* select the action based on the action number */"); out.println(" switch (" + pre("act_num") + ")"); out.println(" {"); for (Enumeration p = production.all(); p.hasMoreElements(); ) { prod = (production) p.nextElement(); out.println(" /*. . . . . . . . . . . . . . . . . . . .*/"); out.println(" case " + prod.index() + ": // " + prod.to_simple_string()); out.println(" {"); out.println(" " + prod.lhs().the_symbol().stack_type() + " RESULT = null;"); for (int i = 0; i < prod.rhs_length(); i++) { if (!(prod.rhs(i) instanceof symbol_part)) continue; symbol s = ((symbol_part) prod.rhs(i)).the_symbol(); if (!(s instanceof non_terminal)) continue; if (((non_terminal) s).is_embedded_action == false) continue; int index = prod.rhs_length() - i - 1; out.println(" " + "// propagate RESULT from " + s.name()); out.println(" " + "if ( " + "((java_cup.runtime.Symbol) " + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + index + ")).value != null )"); out.println(" " + "RESULT = " + "(" + prod.lhs().the_symbol().stack_type() + ") " + "((java_cup.runtime.Symbol) " + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + index + ")).value;"); } if (prod.action() != null && prod.action().code_string() != null && !prod.action().equals("")) out.println(prod.action().code_string()); if (emit.lr_values()) { int loffset; String leftstring, rightstring; int roffset = 0; rightstring = "((java_cup.runtime.Symbol)" + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + roffset + ")).right"; if (prod.rhs_length() == 0) leftstring = rightstring; else { loffset = prod.rhs_length() - 1; leftstring = "((java_cup.runtime.Symbol)" + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + loffset + ")).left"; } out.println(" " + pre("result") + " = new java_cup.runtime.Symbol(" + prod.lhs().the_symbol().index() + "/*" + prod.lhs().the_symbol().name() + "*/" + ", " + leftstring + ", " + rightstring + ", RESULT);"); } else { out.println(" " + pre("result") + " = new java_cup.runtime.Symbol(" + prod.lhs().the_symbol().index() + "/*" + prod.lhs().the_symbol().name() + "*/" + ", RESULT);"); } out.println(" }"); if (prod == start_prod) { out.println(" /* ACCEPT */"); out.println(" " + pre("parser") + ".done_parsing();"); } out.println(" return " + pre("result") + ";"); out.println(); } out.println(" /* . . . . . .*/"); out.println(" default:"); out.println(" throw new Exception("); out.println(" \"Invalid action number found in " + "internal parse table\");"); out.println(); out.println(" }"); out.println(" }"); out.println("}"); out.println(); action_code_time = System.currentTimeMillis() - start_time; parser_time = System.currentTimeMillis() - start_time; }
public static void parser(PrintWriter out, parse_action_table action_table, parse_reduce_table reduce_table, int start_st, production start_prod, boolean compact_reduces, boolean suppress_scanner) throws internal_error { long start_time = System.currentTimeMillis(); out.println(); out.println("//----------------------------------------------------"); out.println("// The following code was generated by " + version.title_str); out.println("// " + new Date()); out.println("//----------------------------------------------------"); out.println(); if (package_name != null) { out.println("package " + package_name + ";"); out.println(); } for (int i = 0; i < import_list.size(); i++) out.println("import " + import_list.elementAt(i) + ";"); out.println(); out.println("/** " + version.title_str + " generated parser."); out.println(" * @version " + new Date()); out.println(" */"); out.println("public class " + parser_class_name + " extends java_cup.runtime.lr_parser {"); out.println(); out.println(" /** Default constructor. */"); out.println(" public " + parser_class_name + "() {super();}"); if (!suppress_scanner) { out.println(); out.println(" /** Constructor which sets the default scanner. */"); out.println(" public " + parser_class_name + "(java_cup.runtime.Scanner s) {super(s);}"); } production[] all_prods; production prod; long start_time = System.currentTimeMillis(); all_prods = new production[production.number()]; for (Enumeration p = production.all(); p.hasMoreElements(); ) { prod = (production) p.nextElement(); all_prods[prod.index()] = prod; } short[][] prod_table = new short[production.number()][2]; for (int i = 0; i < production.number(); i++) { prod = all_prods[i]; prod_table[i][0] = (short) prod.lhs().the_symbol().index(); prod_table[i][1] = (short) prod.rhs_length(); } out.println(); out.println(" /** Production table. */"); out.println(" protected static final short _production_table[][] = "); out.print(" unpackFromStrings("); do_table_as_string(out, prod_table); out.println(");"); out.println(); out.println(" /** Access to production table. */"); out.println(" public short[][] production_table() " + "{return _production_table;}"); production_table_time = System.currentTimeMillis() - start_time; parse_action_row row; parse_action act; int red; long start_time = System.currentTimeMillis(); short[][] action_table = new short[action_table.num_states()][]; for (int i = 0; i < action_table.num_states(); i++) { row = action_table.under_state[i]; if (compact_reduces) row.compute_default(); else row.default_reduce = -1; short[] temp_table = new short[2 * row.size()]; int nentries = 0; for (int j = 0; j < row.size(); j++) { act = row.under_term[j]; if (act.kind() != parse_action.ERROR) { if (act.kind() == parse_action.SHIFT) { temp_table[nentries++] = (short) j; temp_table[nentries++] = (short) (((shift_action) act).shift_to().index() + 1); } else if (act.kind() == parse_action.REDUCE) { red = ((reduce_action) act).reduce_with().index(); if (red != row.default_reduce) { temp_table[nentries++] = (short) j; temp_table[nentries++] = (short) (-(red + 1)); } } else if (act.kind() == parse_action.NONASSOC) { } else throw new internal_error("Unrecognized action code " + act.kind() + " found in parse table"); } } action_table[i] = new short[nentries + 2]; System.arraycopy(temp_table, 0, action_table[i], 0, nentries); action_table[i][nentries++] = -1; if (row.default_reduce != -1) action_table[i][nentries++] = (short) (-(row.default_reduce + 1)); else action_table[i][nentries++] = 0; } out.println(); out.println(" /** Parse-action table. */"); out.println(" protected static final short[][] _action_table = "); out.print(" unpackFromStrings("); do_table_as_string(out, action_table); out.println(");"); out.println(); out.println(" /** Access to parse-action table. */"); out.println(" public short[][] action_table() {return _action_table;}"); action_table_time = System.currentTimeMillis() - start_time; lalr_state goto_st; parse_action act; long start_time = System.currentTimeMillis(); short[][] reduce_goto_table = new short[reduce_table.num_states()][]; for (int i = 0; i < reduce_table.num_states(); i++) { short[] temp_table = new short[2 * reduce_table.under_state[i].size()]; int nentries = 0; for (int j = 0; j < reduce_table.under_state[i].size(); j++) { goto_st = reduce_table.under_state[i].under_non_term[j]; if (goto_st != null) { temp_table[nentries++] = (short) j; temp_table[nentries++] = (short) goto_st.index(); } } reduce_goto_table[i] = new short[nentries + 2]; System.arraycopy(temp_table, 0, reduce_goto_table[i], 0, nentries); reduce_goto_table[i][nentries++] = -1; reduce_goto_table[i][nentries++] = -1; } out.println(); out.println(" /** <code>reduce_goto</code> table. */"); out.println(" protected static final short[][] _reduce_table = "); out.print(" unpackFromStrings("); do_table_as_string(out, reduce_goto_table); out.println(");"); out.println(); out.println(" /** Access to <code>reduce_goto</code> table. */"); out.println(" public short[][] reduce_table() {return _reduce_table;}"); out.println(); goto_table_time = System.currentTimeMillis() - start_time; out.println(" /** Instance of action encapsulation class. */"); out.println(" protected " + pre("actions") + " action_obj;"); out.println(); out.println(" /** Action encapsulation object initializer. */"); out.println(" protected void init_actions()"); out.println(" {"); out.println(" action_obj = new " + pre("actions") + "(this);"); out.println(" }"); out.println(); out.println(" /** Invoke a user supplied parse action. */"); out.println(" public java_cup.runtime.Symbol do_action("); out.println(" int act_num,"); out.println(" java_cup.runtime.lr_parser parser,"); out.println(" java.util.Stack stack,"); out.println(" int top)"); out.println(" throws java.lang.Exception"); out.println(" {"); out.println(" /* call code in generated class */"); out.println(" return action_obj." + pre("do_action(") + "act_num, parser, stack, top);"); out.println(" }"); out.println(""); out.println(" /** Indicates start state. */"); out.println(" public int start_state() {return " + start_st + ";}"); out.println(" /** Indicates start production. */"); out.println(" public int start_production() {return " + start_production.index() + ";}"); out.println(); out.println(" /** <code>EOF</code> Symbol index. */"); out.println(" public int EOF_sym() {return " + terminal.EOF.index() + ";}"); out.println(); out.println(" /** <code>error</code> Symbol index. */"); out.println(" public int error_sym() {return " + terminal.error.index() + ";}"); out.println(); if (init_code != null) { out.println(); out.println(" /** User initialization code. */"); out.println(" public void user_init() throws java.lang.Exception"); out.println(" {"); out.println(init_code); out.println(" }"); } if (scan_code != null) { out.println(); out.println(" /** Scan to get the next Symbol. */"); out.println(" public java_cup.runtime.Symbol scan()"); out.println(" throws java.lang.Exception"); out.println(" {"); out.println(scan_code); out.println(" }"); } if (parser_code != null) { out.println(); out.println(parser_code); } out.println("}"); <DeepExtract> production prod; long start_time = System.currentTimeMillis(); out.println(); out.println("/** Cup generated class to encapsulate user supplied action code.*/"); out.println("class " + pre("actions") + " {"); if (action_code != null) { out.println(); out.println(action_code); } out.println(" private final " + parser_class_name + " parser;"); out.println(); out.println(" /** Constructor */"); out.println(" " + pre("actions") + "(" + parser_class_name + " parser) {"); out.println(" this.parser = parser;"); out.println(" }"); out.println(); out.println(" /** Method with the actual generated action code. */"); out.println(" public final java_cup.runtime.Symbol " + pre("do_action") + "("); out.println(" int " + pre("act_num,")); out.println(" java_cup.runtime.lr_parser " + pre("parser,")); out.println(" java.util.Stack " + pre("stack,")); out.println(" int " + pre("top)")); out.println(" throws java.lang.Exception"); out.println(" {"); out.println(" /* Symbol object for return from actions */"); out.println(" java_cup.runtime.Symbol " + pre("result") + ";"); out.println(); out.println(" /* select the action based on the action number */"); out.println(" switch (" + pre("act_num") + ")"); out.println(" {"); for (Enumeration p = production.all(); p.hasMoreElements(); ) { prod = (production) p.nextElement(); out.println(" /*. . . . . . . . . . . . . . . . . . . .*/"); out.println(" case " + prod.index() + ": // " + prod.to_simple_string()); out.println(" {"); out.println(" " + prod.lhs().the_symbol().stack_type() + " RESULT = null;"); for (int i = 0; i < prod.rhs_length(); i++) { if (!(prod.rhs(i) instanceof symbol_part)) continue; symbol s = ((symbol_part) prod.rhs(i)).the_symbol(); if (!(s instanceof non_terminal)) continue; if (((non_terminal) s).is_embedded_action == false) continue; int index = prod.rhs_length() - i - 1; out.println(" " + "// propagate RESULT from " + s.name()); out.println(" " + "if ( " + "((java_cup.runtime.Symbol) " + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + index + ")).value != null )"); out.println(" " + "RESULT = " + "(" + prod.lhs().the_symbol().stack_type() + ") " + "((java_cup.runtime.Symbol) " + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + index + ")).value;"); } if (prod.action() != null && prod.action().code_string() != null && !prod.action().equals("")) out.println(prod.action().code_string()); if (emit.lr_values()) { int loffset; String leftstring, rightstring; int roffset = 0; rightstring = "((java_cup.runtime.Symbol)" + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + roffset + ")).right"; if (prod.rhs_length() == 0) leftstring = rightstring; else { loffset = prod.rhs_length() - 1; leftstring = "((java_cup.runtime.Symbol)" + emit.pre("stack") + ".elementAt(" + emit.pre("top") + "-" + loffset + ")).left"; } out.println(" " + pre("result") + " = new java_cup.runtime.Symbol(" + prod.lhs().the_symbol().index() + "/*" + prod.lhs().the_symbol().name() + "*/" + ", " + leftstring + ", " + rightstring + ", RESULT);"); } else { out.println(" " + pre("result") + " = new java_cup.runtime.Symbol(" + prod.lhs().the_symbol().index() + "/*" + prod.lhs().the_symbol().name() + "*/" + ", RESULT);"); } out.println(" }"); if (prod == start_prod) { out.println(" /* ACCEPT */"); out.println(" " + pre("parser") + ".done_parsing();"); } out.println(" return " + pre("result") + ";"); out.println(); } out.println(" /* . . . . . .*/"); out.println(" default:"); out.println(" throw new Exception("); out.println(" \"Invalid action number found in " + "internal parse table\");"); out.println(); out.println(" }"); out.println(" }"); out.println("}"); out.println(); action_code_time = System.currentTimeMillis() - start_time; </DeepExtract> parser_time = System.currentTimeMillis() - start_time; }
Compiler
positive
443
private void jTextFieldRst0ActionPerformed(java.awt.event.ActionEvent evt) { boolean tick = o.engine.isFunction(jTextFieldRst0.getText()); vanishTickMark(); if ("Rst0".equalsIgnoreCase("Rst0")) { if (tick) jLabelTickRst0.setVisible(true); else jLabelCrossRst0.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst1")) { if (tick) jLabelTickRst1.setVisible(true); else jLabelCrossRst1.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst2")) { if (tick) jLabelTickRst2.setVisible(true); else jLabelCrossRst2.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst3")) { if (tick) jLabelTickRst3.setVisible(true); else jLabelCrossRst3.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst4")) { if (tick) jLabelTickRst4.setVisible(true); else jLabelCrossRst4.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst5")) { if (tick) jLabelTickRst5.setVisible(true); else jLabelCrossRst5.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst6")) { if (tick) jLabelTickRst6.setVisible(true); else jLabelCrossRst6.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst7")) { if (tick) jLabelTickRst7.setVisible(true); else jLabelCrossRst7.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst55")) { if (tick) jLabelTickRst55.setVisible(true); else jLabelCrossRst55.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst65")) { if (tick) jLabelTickRst65.setVisible(true); else jLabelCrossRst65.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst75")) { if (tick) jLabelTickRst75.setVisible(true); else jLabelCrossRst75.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Trap")) { if (tick) jLabelTickTrap.setVisible(true); else jLabelCrossTrap.setVisible(true); } if (tick) { jTextFieldRst0.setText(o.engine.funcLabeltofuncCode(jTextFieldRst0.getText())); } }
private void jTextFieldRst0ActionPerformed(java.awt.event.ActionEvent evt) { boolean tick = o.engine.isFunction(jTextFieldRst0.getText()); <DeepExtract> vanishTickMark(); if ("Rst0".equalsIgnoreCase("Rst0")) { if (tick) jLabelTickRst0.setVisible(true); else jLabelCrossRst0.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst1")) { if (tick) jLabelTickRst1.setVisible(true); else jLabelCrossRst1.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst2")) { if (tick) jLabelTickRst2.setVisible(true); else jLabelCrossRst2.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst3")) { if (tick) jLabelTickRst3.setVisible(true); else jLabelCrossRst3.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst4")) { if (tick) jLabelTickRst4.setVisible(true); else jLabelCrossRst4.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst5")) { if (tick) jLabelTickRst5.setVisible(true); else jLabelCrossRst5.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst6")) { if (tick) jLabelTickRst6.setVisible(true); else jLabelCrossRst6.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst7")) { if (tick) jLabelTickRst7.setVisible(true); else jLabelCrossRst7.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst55")) { if (tick) jLabelTickRst55.setVisible(true); else jLabelCrossRst55.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst65")) { if (tick) jLabelTickRst65.setVisible(true); else jLabelCrossRst65.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Rst75")) { if (tick) jLabelTickRst75.setVisible(true); else jLabelCrossRst75.setVisible(true); } else if ("Rst0".equalsIgnoreCase("Trap")) { if (tick) jLabelTickTrap.setVisible(true); else jLabelCrossTrap.setVisible(true); } </DeepExtract> if (tick) { jTextFieldRst0.setText(o.engine.funcLabeltofuncCode(jTextFieldRst0.getText())); } }
8085simulator
positive
444
@Override protected void onDetachedFromWindow() { if (!mRunning) { return; } mRunning = false; mObjectAnimatorAngle.cancel(); mObjectAnimatorSweep.cancel(); super.onDetachedFromWindow(); }
@Override protected void onDetachedFromWindow() { <DeepExtract> if (!mRunning) { return; } mRunning = false; mObjectAnimatorAngle.cancel(); mObjectAnimatorSweep.cancel(); </DeepExtract> super.onDetachedFromWindow(); }
MyBlogDemo
positive
445
public Criteria andCommentCountIn(List<Integer> values) { if (values == null) { throw new RuntimeException("Value for " + "commentCount" + " cannot be null"); } criteria.add(new Criterion("comment_count in", values)); return (Criteria) this; }
public Criteria andCommentCountIn(List<Integer> values) { <DeepExtract> if (values == null) { throw new RuntimeException("Value for " + "commentCount" + " cannot be null"); } criteria.add(new Criterion("comment_count in", values)); </DeepExtract> return (Criteria) this; }
community
positive
446
@Override public void onClick(View view) { if (isAniming) { return; } if (mContainer.getVisibility() == View.VISIBLE) { hideMenu(); return; } mContainer.setVisibility(VISIBLE); animateCircle(0, mScreenWidth, new ToolbarCollapseListener(true)); }
@Override public void onClick(View view) { if (isAniming) { return; } if (mContainer.getVisibility() == View.VISIBLE) { hideMenu(); return; } <DeepExtract> mContainer.setVisibility(VISIBLE); animateCircle(0, mScreenWidth, new ToolbarCollapseListener(true)); </DeepExtract> }
AndroidBlog
positive
447
@Override public void onDestroy() { try { if (wakeLock != null) { wakeLock.release(); } Tracker.get().stopTracking(); undoSoundVolume(); Speaker.clear(); SensorProducer.clear(); BeepBeeper.clear(); NumericViewUpdater.clear(); DataAccessObject.clear(); Donate.get().clear(); if (Preferences.use_sensbox) { BTScanner.get().clear(); } Logger.get().log("App terminated..."); Logger.get().close(); } catch (Throwable ex) { Logger.get().log("Fail terminating awake " + ex.getMessage()); } super.onDestroy(); }
@Override public void onDestroy() { <DeepExtract> try { if (wakeLock != null) { wakeLock.release(); } Tracker.get().stopTracking(); undoSoundVolume(); Speaker.clear(); SensorProducer.clear(); BeepBeeper.clear(); NumericViewUpdater.clear(); DataAccessObject.clear(); Donate.get().clear(); if (Preferences.use_sensbox) { BTScanner.get().clear(); } Logger.get().log("App terminated..."); Logger.get().close(); } catch (Throwable ex) { Logger.get().log("Fail terminating awake " + ex.getMessage()); } </DeepExtract> super.onDestroy(); }
AVario
positive
448
public Criteria andUsernameIsNull() { if ("userName is null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("userName is null")); return (Criteria) this; }
public Criteria andUsernameIsNull() { <DeepExtract> if ("userName is null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("userName is null")); </DeepExtract> return (Criteria) this; }
Examination_System
positive
449
public TypeK nextElement() { if (_idx != 0 && _nextV == null) throw new NoSuchElementException(); _prevK = _nextK; _prevV = _nextV; _nextV = null; while (_idx < length()) { _nextK = key(_idx++); if (_nextK != null && _nextK != TOMBSTONE && (_nextV = get(_nextK)) != null) break; } return _prevV; }
public TypeK nextElement() { <DeepExtract> if (_idx != 0 && _nextV == null) throw new NoSuchElementException(); _prevK = _nextK; _prevV = _nextV; _nextV = null; while (_idx < length()) { _nextK = key(_idx++); if (_nextK != null && _nextK != TOMBSTONE && (_nextV = get(_nextK)) != null) break; } return _prevV; </DeepExtract> }
high-scale-java-lib
positive
450
private void enq(MutationNode<P1, P2, P3, C> myNode, int TID) { long phase = maxPhase() + 1; state.set(TID, new OpDesc<P1, P2, P3, C>(phase, true, myNode)); for (int i = 0; i < state.length(); i++) { OpDesc<P1, P2, P3, C> desc = state.get(i); if (desc.pending && desc.phase <= phase) { help_enq(i, phase); } } final MutationNode<P1, P2, P3, C> last = tail; final MutationNode<P1, P2, P3, C> next = last.next; if (next != null) { int tid = next.enqTid; final OpDesc<P1, P2, P3, C> curDesc = state.get(tid); if (last == tail && state.get(tid).node == next) { final OpDesc<P1, P2, P3, C> newDesc = new OpDesc<P1, P2, P3, C>(state.get(tid).phase, false, next); state.compareAndSet(tid, curDesc, newDesc); casTail(last, next); } } }
private void enq(MutationNode<P1, P2, P3, C> myNode, int TID) { long phase = maxPhase() + 1; state.set(TID, new OpDesc<P1, P2, P3, C>(phase, true, myNode)); for (int i = 0; i < state.length(); i++) { OpDesc<P1, P2, P3, C> desc = state.get(i); if (desc.pending && desc.phase <= phase) { help_enq(i, phase); } } <DeepExtract> final MutationNode<P1, P2, P3, C> last = tail; final MutationNode<P1, P2, P3, C> next = last.next; if (next != null) { int tid = next.enqTid; final OpDesc<P1, P2, P3, C> curDesc = state.get(tid); if (last == tail && state.get(tid).node == next) { final OpDesc<P1, P2, P3, C> newDesc = new OpDesc<P1, P2, P3, C>(state.get(tid).phase, false, next); state.compareAndSet(tid, curDesc, newDesc); casTail(last, next); } } </DeepExtract> }
ConcurrencyFreaks
positive
451
@Subscribe public void receiveSubscribe(WalletSubscribeUpdate walletSubscribeUpdate) { if (wallet != null) { binding.setWallet(wallet); if (wallet.getAccountBalanceBananoRaw() != null) { if (wallet.getAccountBalanceBananoRaw().compareTo(new BigDecimal(0)) == 1) { binding.homeSendButton.setEnabled(true); binding.homeSendButton.setBackground(getResources().getDrawable(R.drawable.bg_solid_button)); } else { binding.homeSendButton.setEnabled(false); binding.homeSendButton.setBackground(getResources().getDrawable(R.drawable.bg_solid_button_disabled)); } binding.bananoPlaceholder.setVisibility(View.GONE); binding.amountBananoSymbol.setVisibility(View.VISIBLE); binding.amountBananoTitle.setVisibility(View.VISIBLE); switch(sharedPreferencesUtil.getPriceConversion()) { case BTC: binding.btcPrice.setVisibility(View.VISIBLE); binding.amountLocalCurrencyTitle.setVisibility(View.VISIBLE); binding.nanoPrice.setVisibility(View.GONE); break; case NANO: binding.nanoPrice.setVisibility(View.VISIBLE); binding.amountLocalCurrencyTitle.setVisibility(View.VISIBLE); binding.btcPrice.setVisibility(View.GONE); break; default: binding.nanoPrice.setVisibility(View.GONE); binding.btcPrice.setVisibility(View.GONE); binding.amountLocalCurrencyTitle.setVisibility(View.GONE); break; } String balBanano = wallet.getAccountBalanceBanano(); binding.amountBananoTitle.setText(balBanano); if (balBanano.length() >= 9 && balBanano.length() < 12) { binding.amountBananoTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.main_balance_md_text)); } else if (balBanano.length() >= 12) { binding.amountBananoTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.main_balance_sm_text)); } else { binding.amountBananoTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.main_balance_lg_text)); } } else { binding.homeSendButton.setEnabled(false); binding.homeSendButton.setBackground(getResources().getDrawable(R.drawable.bg_solid_button_disabled)); } } if (wallet.getOpenBlock() == null) { binding.introText.exampleIntroText.setText(UIUtil.colorizeBanano(binding.introText.exampleIntroText.getText().toString(), getContext())); binding.loadingAnimation.setVisibility(View.GONE); binding.exampleCards.setVisibility(View.VISIBLE); } else if (mIntroUri != null) { Address address = new Address(mIntroUri); if (address.isValidAddress()) { if (getActivity() instanceof WindowControl) { SendDialogFragment dialog = SendDialogFragment.newInstance(address.getAddress(), address.getAmount()); dialog.show(((WindowControl) getActivity()).getFragmentUtility().getFragmentManager(), SendDialogFragment.TAG); ((WindowControl) getActivity()).getFragmentUtility().getFragmentManager().executePendingTransactions(); } } mIntroUri = null; } }
@Subscribe public void receiveSubscribe(WalletSubscribeUpdate walletSubscribeUpdate) { <DeepExtract> if (wallet != null) { binding.setWallet(wallet); if (wallet.getAccountBalanceBananoRaw() != null) { if (wallet.getAccountBalanceBananoRaw().compareTo(new BigDecimal(0)) == 1) { binding.homeSendButton.setEnabled(true); binding.homeSendButton.setBackground(getResources().getDrawable(R.drawable.bg_solid_button)); } else { binding.homeSendButton.setEnabled(false); binding.homeSendButton.setBackground(getResources().getDrawable(R.drawable.bg_solid_button_disabled)); } binding.bananoPlaceholder.setVisibility(View.GONE); binding.amountBananoSymbol.setVisibility(View.VISIBLE); binding.amountBananoTitle.setVisibility(View.VISIBLE); switch(sharedPreferencesUtil.getPriceConversion()) { case BTC: binding.btcPrice.setVisibility(View.VISIBLE); binding.amountLocalCurrencyTitle.setVisibility(View.VISIBLE); binding.nanoPrice.setVisibility(View.GONE); break; case NANO: binding.nanoPrice.setVisibility(View.VISIBLE); binding.amountLocalCurrencyTitle.setVisibility(View.VISIBLE); binding.btcPrice.setVisibility(View.GONE); break; default: binding.nanoPrice.setVisibility(View.GONE); binding.btcPrice.setVisibility(View.GONE); binding.amountLocalCurrencyTitle.setVisibility(View.GONE); break; } String balBanano = wallet.getAccountBalanceBanano(); binding.amountBananoTitle.setText(balBanano); if (balBanano.length() >= 9 && balBanano.length() < 12) { binding.amountBananoTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.main_balance_md_text)); } else if (balBanano.length() >= 12) { binding.amountBananoTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.main_balance_sm_text)); } else { binding.amountBananoTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.main_balance_lg_text)); } } else { binding.homeSendButton.setEnabled(false); binding.homeSendButton.setBackground(getResources().getDrawable(R.drawable.bg_solid_button_disabled)); } } </DeepExtract> if (wallet.getOpenBlock() == null) { binding.introText.exampleIntroText.setText(UIUtil.colorizeBanano(binding.introText.exampleIntroText.getText().toString(), getContext())); binding.loadingAnimation.setVisibility(View.GONE); binding.exampleCards.setVisibility(View.VISIBLE); } else if (mIntroUri != null) { Address address = new Address(mIntroUri); if (address.isValidAddress()) { if (getActivity() instanceof WindowControl) { SendDialogFragment dialog = SendDialogFragment.newInstance(address.getAddress(), address.getAmount()); dialog.show(((WindowControl) getActivity()).getFragmentUtility().getFragmentManager(), SendDialogFragment.TAG); ((WindowControl) getActivity()).getFragmentUtility().getFragmentManager().executePendingTransactions(); } } mIntroUri = null; } }
kalium-android-wallet
positive
453
public void changed(ProgressEvent e) { if (e.total <= 0 || e.total < e.current) { return; } isLoading = true; if (JWebBrowser.this.loadingProgress != e.current == e.total ? 100 : Math.min(e.current * 100 / e.total, 99)) { JWebBrowser.this.loadingProgress = e.current == e.total ? 100 : Math.min(e.current * 100 / e.total, 99); WebBrowserEvent e = null; for (int i = listenerList.size() - 1; i >= 0; i--) { if (e == null) { e = new WebBrowserEvent(JWebBrowser.this); } listenerList.get(i).loadingProgressChanged(e); } } }
public void changed(ProgressEvent e) { if (e.total <= 0 || e.total < e.current) { return; } isLoading = true; <DeepExtract> if (JWebBrowser.this.loadingProgress != e.current == e.total ? 100 : Math.min(e.current * 100 / e.total, 99)) { JWebBrowser.this.loadingProgress = e.current == e.total ? 100 : Math.min(e.current * 100 / e.total, 99); WebBrowserEvent e = null; for (int i = listenerList.size() - 1; i >= 0; i--) { if (e == null) { e = new WebBrowserEvent(JWebBrowser.this); } listenerList.get(i).loadingProgressChanged(e); } } </DeepExtract> }
DJ-Sweet
positive
454
public static <T> Class<T> getSecondSuperClassGenricType(final Class clazz) { Type genType = clazz.getGenericSuperclass(); if (!(genType instanceof ParameterizedType)) { return Object.class; } Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (1 >= params.length || 1 < 0) { return Object.class; } if (!(params[1] instanceof Class)) { return Object.class; } return (Class) params[1]; }
public static <T> Class<T> getSecondSuperClassGenricType(final Class clazz) { <DeepExtract> Type genType = clazz.getGenericSuperclass(); if (!(genType instanceof ParameterizedType)) { return Object.class; } Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (1 >= params.length || 1 < 0) { return Object.class; } if (!(params[1] instanceof Class)) { return Object.class; } return (Class) params[1]; </DeepExtract> }
database-oop
positive
455
@Test public void testPatchSearchableField() throws Exception { String newBrandName = "Shisano"; Supplier<SearchResult> searchCall = () -> doSimpleSearch(newBrandName.toLowerCase()); SearchResultSlice searchResultSlice = searchCall.get().slices.get(0); assumeTrue(searchResultSlice.matchCount == 0 || searchResultSlice.matchCount > 1); getImportClient().patchDocuments(indexName, Arrays.asList(new Document("001").set("brand", newBrandName), new Document("003").set("title", "bike light compatible with " + newBrandName))); getElasticsearchClient().performRequest(new Request("POST", indexName + "/_flush/synced")); Unreliables.retryUntilTrue(10, TimeUnit.SECONDS, () -> getSearchClient().getDocument(indexName, "001").data.get("brand").equals(newBrandName)); assertThat(getSearchClient().getDocument(indexName, "001").data.get("brand")).isEqualTo(newBrandName); Unreliables.retryUntilTrue(10, TimeUnit.SECONDS, () -> searchCall.get().slices.get(0).matchCount > 0); SearchResultSlice searchResultSlice2 = searchCall.get().slices.get(0); assertThat(searchResultSlice2.matchCount).isEqualTo(2); Optional<Facet> brandFacet = searchResultSlice2.facets.stream().filter(facet -> facet.fieldName.equals("brand")).findFirst(); assertTrue(brandFacet.isPresent(), () -> "expecting brand facet present, but was not part of facets: " + searchResultSlice2.facets.stream().map(Facet::getFieldName).collect(Collectors.joining(" "))); assertTrue(brandFacet.get().entries.stream().anyMatch(entry -> newBrandName.equals(entry.getKey())), () -> "expecting brand facet to contain '" + newBrandName + "' but was not part of entries:" + brandFacet.get().entries.stream().map(FacetEntry::getKey).collect(Collectors.joining(" "))); }
@Test public void testPatchSearchableField() throws Exception { String newBrandName = "Shisano"; Supplier<SearchResult> searchCall = () -> doSimpleSearch(newBrandName.toLowerCase()); SearchResultSlice searchResultSlice = searchCall.get().slices.get(0); assumeTrue(searchResultSlice.matchCount == 0 || searchResultSlice.matchCount > 1); getImportClient().patchDocuments(indexName, Arrays.asList(new Document("001").set("brand", newBrandName), new Document("003").set("title", "bike light compatible with " + newBrandName))); <DeepExtract> getElasticsearchClient().performRequest(new Request("POST", indexName + "/_flush/synced")); </DeepExtract> Unreliables.retryUntilTrue(10, TimeUnit.SECONDS, () -> getSearchClient().getDocument(indexName, "001").data.get("brand").equals(newBrandName)); assertThat(getSearchClient().getDocument(indexName, "001").data.get("brand")).isEqualTo(newBrandName); Unreliables.retryUntilTrue(10, TimeUnit.SECONDS, () -> searchCall.get().slices.get(0).matchCount > 0); SearchResultSlice searchResultSlice2 = searchCall.get().slices.get(0); assertThat(searchResultSlice2.matchCount).isEqualTo(2); Optional<Facet> brandFacet = searchResultSlice2.facets.stream().filter(facet -> facet.fieldName.equals("brand")).findFirst(); assertTrue(brandFacet.isPresent(), () -> "expecting brand facet present, but was not part of facets: " + searchResultSlice2.facets.stream().map(Facet::getFieldName).collect(Collectors.joining(" "))); assertTrue(brandFacet.get().entries.stream().anyMatch(entry -> newBrandName.equals(entry.getKey())), () -> "expecting brand facet to contain '" + newBrandName + "' but was not part of entries:" + brandFacet.get().entries.stream().map(FacetEntry::getKey).collect(Collectors.joining(" "))); }
open-commerce-search
positive
457
public static int getPopupDefaultResolution(Context context, List<VideoStream> videoStreams) { SharedPreferences defaultPreferences = PreferenceManager.getDefaultSharedPreferences(context); if (defaultPreferences == null) return 0; String defaultResolution = defaultPreferences.getString(context.getString(R.string.default_popup_resolution_key), context.getString(R.string.default_popup_resolution_value)); String preferredFormat = defaultPreferences.getString(context.getString(R.string.preferred_video_format_key), context.getString(R.string.preferred_video_format_default)); if (defaultResolution.equals("Best resolution")) { return 0; } int selectedFormat = 0; for (int i = 0; i < videoStreams.size(); i++) { VideoStream item = videoStreams.get(i); if (defaultResolution.equals(item.resolution)) { selectedFormat = i; } } for (int i = 0; i < videoStreams.size(); i++) { VideoStream item = videoStreams.get(i); if (defaultResolution.equals(item.resolution) && preferredFormat.equals(MediaFormat.getNameById(item.format))) { selectedFormat = i; } } if (selectedFormat == 0 && !videoStreams.get(selectedFormat).resolution.contains(defaultResolution.replace("p60", "p"))) { String replace = defaultResolution.replace("p60", "p"); for (int i = 0; i < videoStreams.size(); i++) { VideoStream item = videoStreams.get(i); if (replace.equals(item.resolution)) selectedFormat = i; } for (int i = 0; i < videoStreams.size(); i++) { VideoStream item = videoStreams.get(i); if (replace.equals(item.resolution) && preferredFormat.equals(MediaFormat.getNameById(item.format))) { selectedFormat = i; } } } return selectedFormat; }
public static int getPopupDefaultResolution(Context context, List<VideoStream> videoStreams) { SharedPreferences defaultPreferences = PreferenceManager.getDefaultSharedPreferences(context); if (defaultPreferences == null) return 0; String defaultResolution = defaultPreferences.getString(context.getString(R.string.default_popup_resolution_key), context.getString(R.string.default_popup_resolution_value)); String preferredFormat = defaultPreferences.getString(context.getString(R.string.preferred_video_format_key), context.getString(R.string.preferred_video_format_default)); <DeepExtract> if (defaultResolution.equals("Best resolution")) { return 0; } int selectedFormat = 0; for (int i = 0; i < videoStreams.size(); i++) { VideoStream item = videoStreams.get(i); if (defaultResolution.equals(item.resolution)) { selectedFormat = i; } } for (int i = 0; i < videoStreams.size(); i++) { VideoStream item = videoStreams.get(i); if (defaultResolution.equals(item.resolution) && preferredFormat.equals(MediaFormat.getNameById(item.format))) { selectedFormat = i; } } if (selectedFormat == 0 && !videoStreams.get(selectedFormat).resolution.contains(defaultResolution.replace("p60", "p"))) { String replace = defaultResolution.replace("p60", "p"); for (int i = 0; i < videoStreams.size(); i++) { VideoStream item = videoStreams.get(i); if (replace.equals(item.resolution)) selectedFormat = i; } for (int i = 0; i < videoStreams.size(); i++) { VideoStream item = videoStreams.get(i); if (replace.equals(item.resolution) && preferredFormat.equals(MediaFormat.getNameById(item.format))) { selectedFormat = i; } } } return selectedFormat; </DeepExtract> }
Float-Tube
positive
458
private int getLeelazEngineVersion() { List<String> listCommandsResponse = null; ListenableFuture<List<String>> future = gtpClient.postCommand("list_commands"); try { listCommandsResponse = future.get(5, TimeUnit.SECONDS); } catch (ExecutionException | TimeoutException | InterruptedException e) { } if (!GtpCommand.isSuccessfulResponse(listCommandsResponse)) { throw new GenericLizzieException(ImmutableMap.of(REASON, ENGINE_NOT_FUNCTION)); } GtpCommand.removeResponseHeaderInPlace(listCommandsResponse); assert listCommandsResponse != null; boolean isOldVersion = listCommandsResponse.stream().noneMatch(s -> StringUtils.equalsIgnoreCase(s.trim(), "lz-analyze")); if (isOldVersion) { return 0; } OfficialV2LeelazEngineDetector detector = new OfficialV2LeelazEngineDetector(); gtpClient.registerStdoutLineConsumer(detector); try { gtpClient.postCommand("lz-analyze 20", true, null); if (!detector.latch.await(8, TimeUnit.SECONDS)) { throw new GenericLizzieException(ImmutableMap.of(REASON, ENGINE_NOT_SUPPORTED)); } gtpClient.sendCommand("name"); } catch (InterruptedException e) { } finally { gtpClient.unregisterStdoutLineConsumer(detector); } return detector.version; }
private int getLeelazEngineVersion() { List<String> listCommandsResponse = null; ListenableFuture<List<String>> future = gtpClient.postCommand("list_commands"); try { listCommandsResponse = future.get(5, TimeUnit.SECONDS); } catch (ExecutionException | TimeoutException | InterruptedException e) { } if (!GtpCommand.isSuccessfulResponse(listCommandsResponse)) { throw new GenericLizzieException(ImmutableMap.of(REASON, ENGINE_NOT_FUNCTION)); } GtpCommand.removeResponseHeaderInPlace(listCommandsResponse); assert listCommandsResponse != null; boolean isOldVersion = listCommandsResponse.stream().noneMatch(s -> StringUtils.equalsIgnoreCase(s.trim(), "lz-analyze")); if (isOldVersion) { return 0; } <DeepExtract> OfficialV2LeelazEngineDetector detector = new OfficialV2LeelazEngineDetector(); gtpClient.registerStdoutLineConsumer(detector); try { gtpClient.postCommand("lz-analyze 20", true, null); if (!detector.latch.await(8, TimeUnit.SECONDS)) { throw new GenericLizzieException(ImmutableMap.of(REASON, ENGINE_NOT_SUPPORTED)); } gtpClient.sendCommand("name"); } catch (InterruptedException e) { } finally { gtpClient.unregisterStdoutLineConsumer(detector); } return detector.version; </DeepExtract> }
mylizzie
positive
459