auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String[] call(String rootCommand, String[] args, File vagrantDir, Map<String, String> env, int timeout) throws IOException, TimeoutException { String[] envp = (env == null ? null : convertEnvironment(env)); List<String> cmd = new ArrayList<>(); cmd.add(rootCommand); cmd.addAll(Arrays.asList(args)); final Process p = Runtime.getRuntime().exec(cmd.toArray(new String[0]), envp, vagrantDir); InputStream errStream = p.getErrorStream(); InputStream inStream = p.getInputStream(); StreamGobbler inGobbler = new StreamGobbler(inStream); StreamGobbler errGobbler = new StreamGobbler(errStream); <START> <END> new Thread(inGobbler).start(); new Thread(errGobbler).start(); Integer exitCode = ThreadUtils.runWithTimeout(timeout, new Callable<Integer>() { @Override public Integer call() throws Exception { return p.waitFor(); } }); try { if( exitCode == null ) { inGobbler.cancel(); errGobbler.cancel(); throw new TimeoutException(getTimeoutError(inGobbler.getLines(), errGobbler.getLines())); } return inGobbler.getLines(); } finally { inGobbler.cleanup(); errGobbler.cleanup(); } }</code><technical_language>instanciate in try(...), if StreamGobbler is AutoCloseable</technical_language>

Target:
public static String[] call(String rootCommand, String[] args, File vagrantDir, Map<String, String> env, int timeout) throws IOException, TimeoutException { String[] envp = (env == null ? null : convertEnvironment(env)); List<String> cmd = new ArrayList<>(); cmd.add(rootCommand); cmd.addAll(Arrays.asList(args)); final Process p = Runtime.getRuntime().exec(cmd.toArray(new String[0]), envp, vagrantDir); InputStream errStream = p.getErrorStream(); InputStream inStream = p.getInputStream(); Integer exitCode = ThreadUtils.runWithTimeout(timeout, new Callable<Integer>() { @Override public Integer call() throws Exception { return p.waitFor(); } }); try ( StreamGobbler inGobbler = new StreamGobbler(inStream); StreamGobbler errGobbler = new StreamGobbler(errStream)) { new Thread(inGobbler).start(); new Thread(errGobbler).start(); if( exitCode == null ) { inGobbler.cancel(); errGobbler.cancel(); p.destroyForcibly(); throw new TimeoutException(getTimeoutError(inGobbler.getLines(), errGobbler.getLines())); } List<String> ret = inGobbler.getLines(); return (String[]) ret.toArray(new String[ret.size()]); } }
Source:
<code>public static BitmapDrawable scaleBitmapToFitDisplay(Bitmap image) { final Display display = ((WindowManager) cgeoapplication.getInstance().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); final int maxWidth = display.getWidth() - 25; final int maxHeight = display.getHeight() - 25; final int imgWidth = image.getWidth(); final int imgHeight = image.getHeight(); int width; int height; <START> Bitmap result = null; <END> if (imgWidth > maxWidth || imgHeight > maxHeight) { final double ratio = Math.min((double) maxHeight / (double) imgHeight, (double) maxWidth / (double) imgWidth); width = (int) Math.ceil(imgWidth * ratio); height = (int) Math.ceil(imgHeight * ratio); try { result = Bitmap.createScaledBitmap(image, width, height, true); } catch (Exception e) { Log.d("ImageHelper.scaleBitmapToFitDisplay: Failed to scale image"); return null; } } else { result = image; width = imgWidth; height = imgHeight; } BitmapDrawable resultDrawable = new BitmapDrawable(cgeoapplication.getInstance().getResources(), result); resultDrawable.setBounds(new Rect(0, 0, width, height)); return resultDrawable; }</code><technical_language>Please do initialize result here. null is overwritten in case, this prevents flow analyzer warning if code path forgets initialize a legal value</technical_language>

Target:
public static BitmapDrawable scaleBitmapToFitDisplay(Bitmap image) { if (image == null) { return null; } final Display display = ((WindowManager) cgeoapplication.getInstance().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); final int maxWidth = display.getWidth() - 25; final int maxHeight = display.getHeight() - 25; final int imgWidth = image.getWidth(); final int imgHeight = image.getHeight(); int width; int height; Bitmap result; if (imgWidth > maxWidth || imgHeight > maxHeight) { final double ratio = Math.min((double) maxHeight / (double) imgHeight, (double) maxWidth / (double) imgWidth); width = (int) Math.ceil(imgWidth * ratio); height = (int) Math.ceil(imgHeight * ratio); result = Bitmap.createScaledBitmap(image, width, height, true); } else { result = image; width = imgWidth; height = imgHeight; } BitmapDrawable resultDrawable = new BitmapDrawable(cgeoapplication.getInstance().getResources(), result); resultDrawable.setBounds(new Rect(0, 0, width, height)); return resultDrawable; }
Source:
<code>private static ProgramState handlePlusMinus(ProgramState previousState, ProgramState currentState) { List<SymbolicValue> operands = previousState.peekValues(2); SymbolicValue result = currentState.peekValue(); SymbolicValue op1 = operands.get(0); SymbolicValue op2 = operands.get(1); boolean op1Zero = isZero(currentState, op1); boolean op2Zero = isZero(currentState, op2); <START> if (op1Zero && op2Zero) { <END> return currentState.unstackValue(1).state.stackValue(op1); } else if (op1Zero) { return currentState.unstackValue(1).state.stackValue(op2); } else if (op2Zero) { return currentState.unstackValue(1).state.stackValue(op1); } return currentState.removeConstraintsOnDomain(result, BooleanConstraint.class); }</code><technical_language>this branch is redundant, replaced if (op2Zero)</technical_language>

Target:
private static ProgramState handlePlusMinus(ProgramState previousState, ProgramState currentState) { List<SymbolicValue> operands = previousState.peekValues(2); SymbolicValue result = currentState.peekValue(); SymbolicValue op1 = operands.get(0); SymbolicValue op2 = operands.get(1); boolean op1Zero = isZero(currentState, op1); boolean op2Zero = isZero(currentState, op2); if (op2Zero) { return currentState.unstackValue(1).state.stackValue(op1); } else if (op1Zero) { return currentState.unstackValue(1).state.stackValue(op2); } return currentState.removeConstraintsOnDomain(result, BooleanConstraint.class); }
Source:
<code>public void integerType() { final JsonSchemaValidator validator = factory.newInstance(jsonFactory.createObjectBuilder() .add("type", "object") .add("properties", jsonFactory.createObjectBuilder() .add("age", jsonFactory.createObjectBuilder() .add("type", "integer") .build()) .build()) .build()); assertTrue(validator.apply(jsonFactory.createObjectBuilder().build()).isSuccess()); assertTrue(validator.apply(jsonFactory.createObjectBuilder().add("age", 30).build()).isSuccess()); <START> assertFalse(validator.apply(jsonFactory.createObjectBuilder() .add("age", 30.3) .build()).isSuccess()); <END> validator.close(); }</code><technical_language>need test BigInteger BigDecimal I guess</technical_language>

Target:
public void integerType() { final JsonSchemaValidator validator = factory.newInstance(jsonFactory.createObjectBuilder() .add("type", "object") .add("properties", jsonFactory.createObjectBuilder() .add("age", jsonFactory.createObjectBuilder() .add("type", "integer") .build()) .build()) .build()); assertTrue(validator.apply(jsonFactory.createObjectBuilder().build()).isSuccess()); assertTrue(validator.apply(jsonFactory.createObjectBuilder().add("age", 30).build()).isSuccess()); assertTrue(validator.apply(jsonFactory.createObjectBuilder().add("age", -10).build()).isSuccess()); assertTrue(validator.apply(jsonFactory.createObjectBuilder().add("age", BigInteger.valueOf(50)).build()).isSuccess()); assertFalse(validator.apply(jsonFactory.createObjectBuilder() .add("age", 30.3f) .build()).isSuccess()); assertFalse(validator.apply(jsonFactory.createObjectBuilder() .add("age", -7.4d) .build()).isSuccess()); assertFalse(validator.apply(jsonFactory.createObjectBuilder() .add("age", BigDecimal.valueOf(50.35613d)).build()).isSuccess()); validator.close(); }
Source:
<code>public OrderedRealmCollectionSnapshot<E> createSnapshot() { if (className != null) { return new OrderedRealmCollectionSnapshot<E>(realm, collection, className); } else { <START> assert classSpec != null; <END> return new OrderedRealmCollectionSnapshot<E>(realm, collection, classSpec); } }</code><technical_language>Generally, java asserts before. I a bit hesitant here? is reason for adding them</technical_language>

Target:
public OrderedRealmCollectionSnapshot<E> createSnapshot() { if (className != null) { return new OrderedRealmCollectionSnapshot<E>(realm, collection, className); } else { return new OrderedRealmCollectionSnapshot<E>(realm, collection, classSpec); } }
Source:
<code>public boolean execute(short a, BlockComponentHolder b) { try { <START> for (Component c : b.values()) { <END> c.onAttached(); } } catch (Exception e) { Spout.getLogger().log(Level.SEVERE, "Unhandled exception attaching block component", e); } return true; }</code><technical_language>Formatting is here, try onAttached() 1 bad component break of components</technical_language>

Target:
public boolean execute(short a, BlockComponentHolder b) { for (Component c : b.values()) { try { c.onAttached(); } catch (Exception e) { Spout.getLogger().log(Level.SEVERE, "Unhandled exception attaching block component", e); } } return true; }
Source:
<code>public AvroRpcWorkflowManager(int port){ logger.info("Starting workflow manager on port: as {}", port, System.getProperty("user.name", "unknown")); Preconditions.checkArgument(port > 0, "Must specify a port greater than 0"); logger.debug("Getting workflow engine"); engine = getWorkflowEngineFromProperty(); if(engine == null){ throw new IllegalStateException("Null engine"); } <START> URL workflowManagerUrl = safeGetUrlFromString("http://localhost" + ":" + port); <END> if(workflowManagerUrl == null){ throw new IllegalStateException("Null workflow manager URL"); } logger.debug("Setting workflow engine url: {}", workflowManagerUrl.toString()); engine.setWorkflowManagerUrl(safeGetUrlFromString("http://localhost" + ":" + port)); repo = getWorkflowRepositoryFromProperty(); logger.debug("Starting Http Server..."); try { server = new HttpServer(new SpecificResponder( org.apache.oodt.cas.workflow.struct.avrotypes.WorkflowManager.class,this), port); } catch (IOException e) { logger.error("Unable to create http server on port: {}", e); throw new IllegalStateException("Unable to start http server on port: " + port, e); } logger.debug("Server created. Starting ..."); server.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { shutdown(); } }); logger.info("Workflow Manager started by for url: {}", System.getProperty("user.name", "unknown"), workflowManagerUrl); }</code><technical_language>This changed</technical_language>

Target:
public AvroRpcWorkflowManager(int port){ logger.info("Starting workflow manager on port: as {}", port, System.getProperty("user.name", "unknown")); Preconditions.checkArgument(port > 0, "Must specify a port greater than 0"); logger.debug("Getting workflow engine"); engine = getWorkflowEngineFromProperty(); if(engine == null){ throw new IllegalStateException("Null engine"); } URL workflowManagerUrl = safeGetUrlFromString("http://" + getHostname() + ":" + port); if(workflowManagerUrl == null){ throw new IllegalStateException("Null workflow manager URL"); } logger.debug("Setting workflow engine url: {}", workflowManagerUrl.toString()); engine.setWorkflowManagerUrl(safeGetUrlFromString("http://" + getHostname() + ":" + port)); repo = getWorkflowRepositoryFromProperty(); logger.debug("Starting Http Server..."); try { server = new HttpServer(new SpecificResponder( org.apache.oodt.cas.workflow.struct.avrotypes.WorkflowManager.class,this), port); } catch (IOException e) { logger.error("Unable to create http server on port: {}", e); throw new IllegalStateException("Unable to start http server on port: " + port, e); } logger.debug("Server created. Starting ..."); server.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { shutdown(); } }); logger.info("Workflow Manager started by for url: {}", System.getProperty("user.name", "unknown"), workflowManagerUrl); }
Source:
<code>public void patchJavaParameters(@Nullable Module module, @NotNull JavaParameters javaParameters) { if (module == null) { return; } AndroidFacet androidFacet = AndroidFacet.getInstance(module); if (androidFacet == null) { return; } IdeaAndroidProject ideaAndroidProject = androidFacet.getIdeaAndroidProject(); if (ideaAndroidProject == null) { return; } BaseArtifact testArtifact = ideaAndroidProject.findSelectedTestArtifactInSelectedVariant(); if (testArtifact == null) { return; } if (!AndroidProject.ARTIFACT_UNIT_TEST.equals(testArtifact.getName()) || !(testArtifact instanceof JavaArtifact)) { return; } PathsList classPath = javaParameters.getClassPath(); AndroidPlatform platform = AndroidPlatform.getInstance(module); if (platform == null) { return; } String originalClassPath = classPath.getPathsString(); try { handlePlatformJar(classPath, platform, (JavaArtifact)testArtifact); handleJavaResources(module, ideaAndroidProject, classPath); } catch (Exception e) { throw new RuntimeException("Error patching the JUnit class path. Original class path: " + <START> originalClassPath, e); <END> } }</code><technical_language>classpath in a separate line. time comes, easier read, select/copy clipboard, etc</technical_language>

Target:
public void patchJavaParameters(@Nullable Module module, @NotNull JavaParameters javaParameters) { if (module == null) { return; } AndroidFacet androidFacet = AndroidFacet.getInstance(module); if (androidFacet == null) { return; } IdeaAndroidProject ideaAndroidProject = androidFacet.getIdeaAndroidProject(); if (ideaAndroidProject == null) { return; } BaseArtifact testArtifact = ideaAndroidProject.findSelectedTestArtifactInSelectedVariant(); if (testArtifact == null) { return; } if (!AndroidProject.ARTIFACT_UNIT_TEST.equals(testArtifact.getName()) || !(testArtifact instanceof JavaArtifact)) { return; } PathsList classPath = javaParameters.getClassPath(); AndroidPlatform platform = AndroidPlatform.getInstance(module); if (platform == null) { return; } String originalClassPath = classPath.getPathsString(); try { handlePlatformJar(classPath, platform, (JavaArtifact)testArtifact); handleJavaResources(module, ideaAndroidProject, classPath); } catch (Exception e) { throw new RuntimeException(String.format("Error patching the JUnit class path. Original class path:%n%s", originalClassPath), e); } }
Source:
<code>private static String getCertificateExpiration(String certificate) { String certWithoutBegin = certificate.replaceFirst("-----BEGIN CERTIFICATE-----", ""); String rawCert = certWithoutBegin.replaceFirst("-----END CERTIFICATE-----", ""); <START> try (ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(rawCert.getBytes()))) { <END> CertificateFactory certFact = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate)certFact.generateCertificate(bis); DateFormat dateFormat = DateFormat.getDateInstance(); return dateFormat.format(cert.getNotAfter()); } catch (IllegalArgumentException e) { throw new ConsistencyErrorException("Certificate is not in base64 format!", e); } catch (IOException | CertificateException e) { throw new InternalError(e); } }</code><technical_language>test not-null certificate variable</technical_language>

Target:
private static String getCertificateExpiration(String certificate) { Utils.notNull(certificate, "certificate"); String certWithoutBegin = certificate.replaceFirst("-----BEGIN CERTIFICATE-----", ""); String rawCert = certWithoutBegin.replaceFirst("-----END CERTIFICATE-----", ""); try (ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(rawCert.getBytes()))) { CertificateFactory certFact = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate)certFact.generateCertificate(bis); DateFormat dateFormat = DateFormat.getDateInstance(); return dateFormat.format(cert.getNotAfter()); } catch (IllegalArgumentException e) { throw new ConsistencyErrorException("Certificate is not in base64 format!", e); } catch (IOException | CertificateException e) { throw new InternalError(e); } }
Source:
<code>public static org.ovirt.engine.core.common.businessentities.VmBackupPhase map(BackupPhase action) { switch (action) { case INITIALIZING: return <START> org.ovirt.engine.core.common.businessentities.VmBackupPhase.Initializing; <END> case STARTING: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.Starting; case READY: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.Ready; case FINALIZING: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.Finalizing; default: return null; } }</code><technical_language>please this upper case</technical_language>

Target:
public static org.ovirt.engine.core.common.businessentities.VmBackupPhase map(BackupPhase action) { switch (action) { case INITIALIZING: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.INITIALIZING; case STARTING: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.STARTING; case READY: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.READY; case FINALIZING: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.FINALIZING; default: return null; } }
Source:
<code>private String getStackTrace(Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); throwable.printStackTrace(pw); <START> return sw.getBuffer().toString(); <END> }</code><technical_language>do sw.toString()</technical_language>

Target:
private String getStackTrace(Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); throwable.printStackTrace(pw); return sw.toString(); }
Source:
<code>private void launchEditTagsDialog(final Context context, final Pojo app) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(context.getResources().getString(R.string.tags_add_title)); final EditText tag = new EditText(context); tag.setInputType(InputType.TYPE_CLASS_TEXT); tag.setText(app.tags); builder.setView(tag); <START> builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { <END> @Override public void onClick(DialogInterface dialog, int which) { KissApplication.getTagsHandler(context).setTags(app.id, tag.getText().toString()); app.tags = tag.getText().toString(); app.displayTags = app.tags; String msg = context.getResources().getString(R.string.tags_confirmation_added); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); }</code><technical_language>android.R.string.ok</technical_language>

Target:
private void launchEditTagsDialog(final Context context, final Pojo app) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(context.getResources().getString(R.string.tags_add_title)); final EditText tag = new EditText(context); tag.setInputType(InputType.TYPE_CLASS_TEXT); tag.setText(app.tags); builder.setView(tag); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { KissApplication.getDataHandler(context).getTagsHandler().setTags(app.id, tag.getText().toString()); app.tags = tag.getText().toString(); app.displayTags = app.tags; String msg = context.getResources().getString(R.string.tags_confirmation_added); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); }
Source:
<code>public boolean initialize(List<StorageDomain> sds, StoragePool dc, String okCommandName, String cancelCommandName, ICommandTarget target) { List<StorageDomain> sdsToUpgrade = sds.stream().filter(getComparePredicate(dc)).collect(Collectors.toList()); <START> <END> if (sdsToUpgrade.isEmpty()) { return false; } UICommand okCommand = UICommand.createDefaultOkUiCommand(okCommandName, target); UICommand cancelCommand = UICommand.createCancelUiCommand(cancelCommandName, target); getCommands().add(okCommand); getCommands().add(cancelCommand); setTitle(ConstantsManager.getInstance().getConstants().areYouSureTitle()); if (sdsToUpgrade.size() > 1) { setMessage(ConstantsManager.getInstance() .getMessages() .compareMultipleStorageFormatsToDataCenterWarningMessage( dc.getName(), sdsToUpgrade.stream() .map(StorageDomain::getName) .collect(Collectors.joining(", ")))); } else { setMessage(ConstantsManager.getInstance() .getMessages() .compareStorageFormatToDataCenterWarningMessage( dc.getName(), sdsToUpgrade.get(0).getName(), sdsToUpgrade.get(0).getStorageFormat().getValue(), dc.getStoragePoolFormatType().getValue())); } return true; }</code><technical_language>Blank line 'if' more readable</technical_language>

Target:
public boolean initialize(List<StorageDomain> sds, StoragePool dc, String okCommandName, String cancelCommandName, ICommandTarget target) { List<StorageDomain> sdsToUpgrade = sds.stream().filter(getComparePredicate(dc)).collect(Collectors.toList()); if (sdsToUpgrade.isEmpty()) { return false; } UICommand okCommand = UICommand.createDefaultOkUiCommand(okCommandName, target); UICommand cancelCommand = UICommand.createCancelUiCommand(cancelCommandName, target); getCommands().add(okCommand); getCommands().add(cancelCommand); setTitle(ConstantsManager.getInstance().getConstants().updatingStorageDomainTitle()); setMessage(getFormatWarningMessage(dc,sdsToUpgrade)); setHelpTag(HelpTag.attach_storage_domain_confirmation); setHashName("attach_storage_domain_confirmation"); return true; }
Source:
<code>public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof SimpleLawJournalEntry)) return false; SimpleLawJournalEntry other = (SimpleLawJournalEntry) obj; if (entry != other.entry) return false; if (id != other.id) return false; if (journalNo != other.journalNo) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; if (year != other.year) return false; return true; <START> } <END></code><technical_language>wrong, consider java.util.Objects (see: EnrichmentTag). I shifted eclipse generated equals/hashCode Objects easier read change</technical_language>

Target:
public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SimpleLawJournalEntry other = (SimpleLawJournalEntry) obj; return Objects.equals(this.id, other.id) && Objects.equals(this.year, other.year) && Objects.equals(this.journalNo, other.journalNo) && Objects.equals(this.entry, other.entry) && Objects.equals(this.title, other.title); }
Source:
<code>public static Matcher<? super View> withUsageHintOnClick(@StringRes final int resourceId) { return new TypeSafeMatcher<View>() { private String resourceName = null; private String expectedText = null; @Override protected boolean matchesSafely(View view) { if (!view.isClickable()) { return false; } <START> if (null == this.expectedText) { <END> try { expectedText = view.getResources().getString(resourceId); resourceName = view.getResources().getResourceEntryName(resourceId); } catch (Resources.NotFoundException ignored) { } } if (null != expectedText) { AccessibilityNodeInfo accessibilityNodeInfo = view.createAccessibilityNodeInfo(); AccessibilityNodeInfo.AccessibilityAction clickAction = findAction(accessibilityNodeInfo, AccessibilityNodeInfo.ACTION_CLICK); return expectedText.equals(clickAction.getLabel()); } else { return false; } } @Override public void describeTo(Description description) { description.appendText("is clickable and has custom usage hint for ACTION_CLICK from resource id: "); description.appendValue(resourceId); if (null != this.resourceName) { description.appendText("["); description.appendText(resourceName); description.appendText("]"); } if (null != this.expectedText) { description.appendText(" value: "); description.appendText(expectedText); } } }; }</code><technical_language>[Joda notation](<LINK_0></technical_language>

Target:
public static Matcher<? super View> withUsageHintOnClick(@StringRes final int resourceId) { return new TypeSafeMatcher<View>() { private String resourceName; private String expectedText; @Override protected boolean matchesSafely(View view) { if (!view.isClickable()) { return false; } expectedText = view.getResources().getString(resourceId); resourceName = view.getResources().getResourceEntryName(resourceId); if (expectedText == null) { return false; } AccessibilityNodeInfo.AccessibilityAction clickAction = findAction(view, AccessibilityNodeInfo.ACTION_CLICK); return expectedText.equals(clickAction.getLabel()); } @Override public void describeTo(Description description) { description.appendText("is clickable and has custom usage hint for ACTION_CLICK from resource id: ").appendValue(resourceId); appendResourceNameAndExpectedTextToDescription(description, resourceName, expectedText); } }; }
Source:
<code>public void setMinValue(final BigDecimal minValue) { BigDecimal currMin = getMinValue(); <START> <END> if ((minValue != null && currMin == null) || (currMin != null && (minValue == null || !(currMin.compareTo(minValue) == 0)))) { getOrCreateComponentModel().minValue = minValue; } }</code><technical_language>consistent, this Objects.equals</technical_language>

Target:
public void setMinValue(final BigDecimal minValue) { BigDecimal currMin = getMinValue(); if (!Objects.equals(minValue, currMin)) { getOrCreateComponentModel().minValue = minValue; } }
Source:
<code>public void aggregate(int length, AggregationResultHolder aggregationResultHolder, Map<TransformExpressionTree, BlockValSet> blockValSetMap) { <START> HyperLogLog hyperLogLog = getDefaultHyperLogLog(aggregationResultHolder, _log2M); <END> BlockValSet blockValSet = blockValSetMap.get(_expression); DataType valueType = blockValSet.getValueType(); switch (valueType) { case INT: int[][] intValuesArray = blockValSet.getIntValuesMV(); for (int i = 0; i < length; i++) { for (int value : intValuesArray[i]) { hyperLogLog.offer(value); } } break; case LONG: long[][] longValuesArray = blockValSet.getLongValuesMV(); for (int i = 0; i < length; i++) { for (long value : longValuesArray[i]) { hyperLogLog.offer(value); } } break; case FLOAT: float[][] floatValuesArray = blockValSet.getFloatValuesMV(); for (int i = 0; i < length; i++) { for (float value : floatValuesArray[i]) { hyperLogLog.offer(value); } } break; case DOUBLE: double[][] doubleValuesArray = blockValSet.getDoubleValuesMV(); for (int i = 0; i < length; i++) { for (double value : doubleValuesArray[i]) { hyperLogLog.offer(value); } } break; case STRING: String[][] stringValuesArray = blockValSet.getStringValuesMV(); for (int i = 0; i < length; i++) { for (String value : stringValuesArray[i]) { hyperLogLog.offer(value); } } break; default: throw new IllegalStateException( "Illegal data type for DISTINCT_COUNT_HLL_MV aggregation function: " + valueType); } }</code><technical_language>here, pass _log2M</technical_language>

Target:
public void aggregate(int length, AggregationResultHolder aggregationResultHolder, Map<TransformExpressionTree, BlockValSet> blockValSetMap) { HyperLogLog hyperLogLog = getDefaultHyperLogLog(aggregationResultHolder); BlockValSet blockValSet = blockValSetMap.get(_expression); DataType valueType = blockValSet.getValueType(); switch (valueType) { case INT: int[][] intValuesArray = blockValSet.getIntValuesMV(); for (int i = 0; i < length; i++) { for (int value : intValuesArray[i]) { hyperLogLog.offer(value); } } break; case LONG: long[][] longValuesArray = blockValSet.getLongValuesMV(); for (int i = 0; i < length; i++) { for (long value : longValuesArray[i]) { hyperLogLog.offer(value); } } break; case FLOAT: float[][] floatValuesArray = blockValSet.getFloatValuesMV(); for (int i = 0; i < length; i++) { for (float value : floatValuesArray[i]) { hyperLogLog.offer(value); } } break; case DOUBLE: double[][] doubleValuesArray = blockValSet.getDoubleValuesMV(); for (int i = 0; i < length; i++) { for (double value : doubleValuesArray[i]) { hyperLogLog.offer(value); } } break; case STRING: String[][] stringValuesArray = blockValSet.getStringValuesMV(); for (int i = 0; i < length; i++) { for (String value : stringValuesArray[i]) { hyperLogLog.offer(value); } } break; default: throw new IllegalStateException( "Illegal data type for DISTINCT_COUNT_HLL_MV aggregation function: " + valueType); } }
Source:
<code>public void addMember(PerunSession sess, Group group, Member member) throws InternalErrorException, MemberNotExistsException, PrivilegeException, AlreadyMemberException, GroupNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, NotMemberOfParentGroupException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternalyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if (attrSynchronizeEnabled.getValue() != null) { String synchronizeEnabled = (String) attrSynchronizeEnabled.getValue(); if (synchronizeEnabled.equals("true")) { <START> throw new ExternalyManagedException("Adding of member is not allowed. Group is externaly managed."); <END> } } if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "addMember"); } if (member.getVoId() != (group.getVoId())) { throw new MembershipMismatchException("Member and group are form the different VO"); } getGroupsManagerBl().addMember(sess, group, member); }</code><technical_language>Externaly -> Externally in a exception message</technical_language>

Target:
public void addMember(PerunSession sess, Group group, Member member) throws InternalErrorException, MemberNotExistsException, PrivilegeException, AlreadyMemberException, GroupNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, NotMemberOfParentGroupException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "addMember"); } if (member.getVoId() != (group.getVoId())) { throw new MembershipMismatchException("Member and group are form the different VO"); } Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if (Objects.equals("true", (String) attrSynchronizeEnabled.getValue())) { throw new ExternallyManagedException("Adding of member is not allowed. Group is externally managed."); } getGroupsManagerBl().addMember(sess, group, member); }
Source:
<code>private void scheduleExpiryTimerAfterSessionTimeout() { if (_timer == null) { _timer = new Timer(true); } <START> TimerTask timerTask = new TimerTask() { public void run() { if (resetSession.get()) { onSessionExpired(); } } }; <END> _timer.schedule(timerTask, _sessionTimeoutMs); }</code><technical_language>If decide _timer, stash this variable in a private field need create a new time this method is called</technical_language>

Target:
private void scheduleExpiryTimerAfterSessionTimeout() { _zkSessionExpiryFuture = _scheduledExecutorService.schedule(ZkAdapter.this::onSessionExpired, _sessionTimeoutMs, TimeUnit.MILLISECONDS); }
Source:
<code>public HailStorm(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{1}{G}{G}"); this.getSpellAbility().addEffect(new DamageAllEffect(2, new FilterAttackingCreature())); this.getSpellAbility().addEffect(new DamageControllerEffect(1)); <START> this.getSpellAbility().addEffect(new DamageAllEffect(1, filter)); <END> }</code><technical_language>effects need text changed</technical_language>

Target:
public HailStorm(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{1}{G}{G}"); this.getSpellAbility().addEffect(new DamageAllEffect(2, new FilterAttackingCreature())); this.getSpellAbility().addEffect(new DamageControllerEffect(1).setText("and 1 damage to you ")); this.getSpellAbility().addEffect(new DamageAllEffect(1, filter).setText("and each creature you control.")); }
Source:
<code>private void logMetrics() { try { Thread.sleep(METRIC_INIT_DELAY_MS); while (true) { Thread.sleep(metricsWindowMs); final double totalPullTimeSec = getTotalProcTimeSec(pullStats); final double totalPushTime = getTotalProcTimeSec(pushStats); <START> final double totalReqProcTime = getTotalProcTimeSec(requestStats); <END> final int totalPullCount = getTotalProcCount(pullStats); final int totalPushCount = getTotalProcCount(pushStats); final int totalReqCount = getTotalProcCount(requestStats); resetStats(); final ServerMetrics metricsMessage = ServerMetrics.newBuilder() .setWindowIndex(windowIndex) .setNumModelBlocks(0) .setMetricWindowMs(metricsWindowMs) .setTotalPullProcessingTimeSec(totalPullTimeSec) .setTotalPushProcessingTimeSec(totalPushTime) .setTotalReqProcessingTimeSec(totalReqProcTime) .setTotalPullProcessed(totalPullCount) .setTotalPushProcessed(totalPushCount) .setTotalReqProcessed(totalReqCount) .build(); LOG.log(Level.FINE, "ServerMetrics {0}", metricsMessage); windowIndex++; } } catch (final InterruptedException e) { LOG.log(Level.SEVERE, "Exception Occurred", e); throw new RuntimeException(e); } }</code><technical_language>totalPushTime & totalReqProcTime totalPushTimeSec & totalReqProcTimeSec</technical_language>

Target:
private void logMetrics() { try { Thread.sleep(METRIC_INIT_DELAY_MS); while (true) { Thread.sleep(metricsWindowMs); final double totalPullTimeSec = getTotalProcTimeSec(pullStats); final double totalPushTimeSec = getTotalProcTimeSec(pushStats); final double totalReqProcTimeSec = getTotalProcTimeSec(requestStats); final int totalPullCount = getTotalProcCount(pullStats); final int totalPushCount = getTotalProcCount(pushStats); final int totalReqCount = getTotalProcCount(requestStats); resetStats(); final ServerMetrics metricsMessage = ServerMetrics.newBuilder() .setWindowIndex(windowIndex) .setNumModelBlocks(0) .setMetricWindowMs(metricsWindowMs) .setTotalPullProcessingTimeSec(totalPullTimeSec) .setTotalPushProcessingTimeSec(totalPushTimeSec) .setTotalReqProcessingTimeSec(totalReqProcTimeSec) .setTotalPullProcessed(totalPullCount) .setTotalPushProcessed(totalPushCount) .setTotalReqProcessed(totalReqCount) .build(); LOG.log(Level.FINE, "ServerMetrics {0}", metricsMessage); windowIndex++; } } catch (final InterruptedException e) { LOG.log(Level.SEVERE, "Exception Occurred", e); throw new RuntimeException(e); } }
Source:
<code>protected Object doWork() { final String sampleName = SegmentUtils.getSampleNameForCLIsFromSegmentFile(segmentsFile); Utils.regularReadableUserFile(snpCountsFile); Utils.regularReadableUserFile(coverageFile); <START> Utils.regularReadableUserFile(segmentsFile); <END> ACNVPlotter.writeSegmentedAlleleFractionPlot(sampleName, snpCountsFile, coverageFile, segmentsFile, outputDir, useSexChromosomes); ACNVPlotter.writeSegmentedAlleleFractionPlotPerSeg(sampleName, snpCountsFile, coverageFile, segmentsFile, outputDir, useSexChromosomes); return "SUCCESS"; }</code><technical_language>way, java Varargs in regularReadableUserFile, i.e. input more Files, making method signature (File... files)? this call</technical_language>

Target:
protected Object doWork() { final String sampleName = SegmentUtils.getSampleNameForCLIsFromSegmentFile(segmentsFile); Utils.regularReadableUserFile(snpCountsFile); Utils.regularReadableUserFile(coverageFile); Utils.regularReadableUserFile(segmentsFile); ACNVPlotter.writeSegmentedAlleleFractionPlot(sampleName, snpCountsFile, coverageFile, segmentsFile, outputDir, outputPrefix, useSexChromosomes); ACNVPlotter.writeSegmentedAlleleFractionPlotPerSeg(sampleName, snpCountsFile, coverageFile, segmentsFile, outputDir, outputPrefix, useSexChromosomes); return "SUCCESS"; }
Source:
<code>public void testExceptionPropagation(boolean isOwner, WriteMethod method) { Object key = getKey(isOwner); try { method.action.eval(key, wo, rw, (Function<ReadEntryView<Object, String>, Void> & Serializable) view -> null, (BiConsumer<WriteEntryView<String>, Void> & Serializable) (view, nil) -> { throw new TestException(); }, getClass()); fail("Should throw [CompletionException:]CacheException:TestException"); <START> } catch (CacheException | CompletionException e) { END> Throwable t = e; if (Boolean.TRUE.equals(transactional) && t.getCause() instanceof RollbackException) { Throwable[] suppressed = t.getCause().getSuppressed(); if (suppressed != null && suppressed.length > 0) { t = suppressed[0]; assertEquals(XAException.class, t.getClass()); t = t.getCause(); } } while (t.getCause() instanceof RemoteException && t != t.getCause()) { t = t.getCause(); } if (t instanceof CompletionException) { t = t.getCause(); } assertEquals(t.getCause().getClass(), TestException.class); } }</code><technical_language>more comfortable knowing a CompletionException is expected instead of assuming of method ownership</technical_language>

Target:
public void testExceptionPropagation(boolean isOwner, WriteMethod method) { Object key = getKey(isOwner); try { method.action.eval(key, wo, rw, (Function<ReadEntryView<Object, String>, Void> & Serializable) view -> null, (BiConsumer<WriteEntryView<String>, Void> & Serializable) (view, nil) -> { throw new TestException(); }, getClass()); fail("Should throw CompletionException:CacheException:[RemoteException:]*TestException"); } catch (CacheException | CompletionException e) { Throwable t = e; if (Boolean.TRUE.equals(transactional) && t.getCause() instanceof RollbackException) { Throwable[] suppressed = t.getCause().getSuppressed(); if (suppressed != null && suppressed.length > 0) { t = suppressed[0]; assertEquals(XAException.class, t.getClass()); t = t.getCause(); } } assertException(CompletionException.class, t); t = t.getCause(); assertExceptionNonStrict(CacheException.class, t); while (t.getCause() instanceof RemoteException && t != t.getCause()) { t = t.getCause(); } assertException(TestException.class, t.getCause()); } }
Source:
<code>public void createTopic(String topic, int partitions, short replicationFactor) { log.info("Creating topic: " + topic + ", partitions: " + partitions + ", replications: " + replicationFactor); CreateTopicsResult ret = adminClient.createTopics( Collections.singletonList(new NewTopic(topic, partitions, replicationFactor))); try { ret.all().get(5, TimeUnit.MINUTES); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new StreamRuntimeException(e); } catch (ExecutionException e) { <START> if ((e.getCause() instanceof TopicExistsException)) { <END> log.info("topic: " + topic + " exists"); } else { throw new StreamRuntimeException(e); } } catch (TimeoutException e) { throw new StreamRuntimeException("Unable to create topics " + topic + " within the timeout", e); } }</code><technical_language>Redundant parentheses</technical_language>

Target:
public void createTopic(String topic, int partitions, short replicationFactor) { log.info("Creating topic: " + topic + ", partitions: " + partitions + ", replications: " + replicationFactor); CreateTopicsResult ret = adminClient.createTopics( Collections.singletonList(new NewTopic(topic, partitions, replicationFactor))); try { ret.all().get(5, TimeUnit.MINUTES); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new StreamRuntimeException(e); } catch (ExecutionException e) { if (e.getCause() instanceof TopicExistsException) { log.info("topic: " + topic + " exists"); } else { throw new StreamRuntimeException(e); } } catch (TimeoutException e) { throw new StreamRuntimeException("Unable to create topics " + topic + " within the timeout", e); } }
Source:
<code>public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_removeWatched: <START> android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getActivity()); builder.setMessage(R.string.remove_watched_popup_warning) .setTitle(R.string.remove_watched_popup_title) .setPositiveButton(R.string.remove_watched_popup_yes, (DialogInterface d, int id) -> removeWatchedStreams(false)) .setNeutralButton( R.string.remove_watched_popup_yes_and_partially_watched_videos, (DialogInterface d, int id) -> removeWatchedStreams(true)) .setNegativeButton(R.string.remove_watched_popup_cancel, (DialogInterface d, int id) -> d.cancel()); builder.create().show(); <END> break; default: return super.onOptionsItemSelected(item); } return true; }</code><technical_language>a "Builder" variable is saved, is needed once. Also, AlertDialog full path specification? suggestion new AlertDialog.Builder(getActivity()) .setMessage(R.string.remove_watched_popup_warning) .setTitle(R.string.remove_watched_popup_title) .setPositiveButton(R.string.remove_watched_popup_yes, (DialogInterface d, int id) -> removeWatchedStreams(false)) .setNeutralButton( R.string.remove_watched_popup_yes_and_partially_watched_videos, (DialogInterface d, int id) -> removeWatchedStreams(true)) .setNegativeButton(R.string.remove_watched_popup_cancel, (DialogInterface d, int id) -> d.cancel()); .create() .show();</technical_language>

Target:
public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_remove_watched: if (!isRemovingWatched) { new AlertDialog.Builder(requireContext()) .setMessage(R.string.remove_watched_popup_warning) .setTitle(R.string.remove_watched_popup_title) .setPositiveButton(R.string.yes, (DialogInterface d, int id) -> removeWatchedStreams(false)) .setNeutralButton( R.string.remove_watched_popup_yes_and_partially_watched_videos, (DialogInterface d, int id) -> removeWatchedStreams(true)) .setNegativeButton(R.string.cancel, (DialogInterface d, int id) -> d.cancel()) .create() .show(); } break; default: return super.onOptionsItemSelected(item); } return true; }
Source:
<code>public void releaseWhenMergeCumulateThrows() { WriteFailingByteBuf oldCumulation = new WriteFailingByteBuf(1, 64); ByteBuf in = Unpooled.buffer().writeZero(12); Throwable thrown = null; try { ByteToMessageDecoder.MERGE_CUMULATOR.cumulate(UnpooledByteBufAllocator.DEFAULT, oldCumulation, in); } catch (Throwable t) { thrown = t; } assertSame(oldCumulation.writeError(), thrown); assertEquals(0, in.refCnt()); <START> assertEquals(1, oldCumulation.refCnt()); <END> }</code><technical_language>missed this before... need call oldCumulation .release()</technical_language>

Target:
public void releaseWhenMergeCumulateThrows() { WriteFailingByteBuf oldCumulation = new WriteFailingByteBuf(1, 64); ByteBuf in = Unpooled.buffer().writeZero(12); Throwable thrown = null; try { ByteToMessageDecoder.MERGE_CUMULATOR.cumulate(UnpooledByteBufAllocator.DEFAULT, oldCumulation, in); } catch (Throwable t) { thrown = t; } assertSame(oldCumulation.writeError(), thrown); assertEquals(0, in.refCnt()); assertEquals(1, oldCumulation.refCnt()); oldCumulation.release(); }
Source:
<code>public void test_matching() { when(discovery.getServices()).thenReturn(Collections.singletonList("service")); when(discovery.getInstances("service")).thenReturn(Collections.singletonList( (ServiceInstance) new DefaultServiceInstance("service", "localhost", 80, false))); <START> listener.setMatchingServices(Collections.singleton("notService")); <END> listener.onInstanceRegistered(new InstanceRegisteredEvent<>(new Object(), null)); assertEquals(0, registry.getApplications().size()); }</code><technical_language>Please fix this codacy issue</technical_language>

Target:
public void test_matching() { when(discovery.getServices()).thenReturn(Collections.singletonList("service")); when(discovery.getInstances("service")).thenReturn(Collections.singletonList( (ServiceInstance) new DefaultServiceInstance("service", "localhost", 80, false))); listener.setServices(singleton("notService")); listener.onInstanceRegistered(new InstanceRegisteredEvent<>(new Object(), null)); assertEquals(0, registry.getApplications().size()); }
Source:
<code>public TestResult invoke(File ws, VirtualChannel channel) throws IOException { final long nowSlave = System.currentTimeMillis(); FileSet fs = Util.createFileSet(ws, testResults); DirectoryScanner ds = fs.getDirectoryScanner(); String[] files = ds.getIncludedFiles(); if (files.length == 0) { throw new AbortException(Messages.JUnitResultArchiver_NoTestReportFound()); } <START> TestResult result = new TestResult(buildTime + (nowSlave - nowMaster), ds, keepLongStdio, listener); <END> result.tally(); return result; }</code><technical_language>Invoke is executed slave's side. TaskListener behave expect</technical_language>

Target:
public TestResult invoke(File ws, VirtualChannel channel) throws IOException { final long nowSlave = System.currentTimeMillis(); FileSet fs = Util.createFileSet(ws, testResults); DirectoryScanner ds = fs.getDirectoryScanner(); String[] files = ds.getIncludedFiles(); if (files.length == 0) { throw new AbortException(Messages.JUnitResultArchiver_NoTestReportFound()); } TestResult result = new TestResult(buildTime + (nowSlave - nowMaster), ds, keepLongStdio); result.tally(); return result; }
Source:
<code>public void testExpiredCheckpointExceedsTolerableFailureNumber() { ExecutionVertex vertex1 = mockExecutionVertex(new ExecutionAttemptID()); ExecutionVertex vertex2 = mockExecutionVertex(new ExecutionAttemptID()); final String errorMsg = "Exceeded checkpoint failure tolerance number!"; CheckpointFailureManager checkpointFailureManager = getCheckpointFailureManager(errorMsg); CheckpointCoordinator coord = getCheckpointCoordinator(new JobID(), vertex1, vertex2, checkpointFailureManager); try { final CompletableFuture<CompletedCheckpoint> checkPointFuture = coord.triggerCheckpoint(false); manuallyTriggeredScheduledExecutor.triggerAll(); assertFalse(checkPointFuture.isCompletedExceptionally()); coord.abortPendingCheckpoints(new CheckpointException(CHECKPOINT_EXPIRED)); fail("Test failed."); } <START> catch (Exception e) { END> assertTrue(e instanceof RuntimeException); assertEquals(errorMsg, e.getMessage()); } finally { try { coord.shutdown(JobStatus.FINISHED); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } }</code><technical_language>I org.junit.Test#expected (and a specific exception class) more expressive verbose here</technical_language>

Target:
public void testExpiredCheckpointExceedsTolerableFailureNumber() throws Exception { ExecutionVertex vertex1 = mockExecutionVertex(new ExecutionAttemptID()); ExecutionVertex vertex2 = mockExecutionVertex(new ExecutionAttemptID()); final String errorMsg = "Exceeded checkpoint failure tolerance number!"; CheckpointFailureManager checkpointFailureManager = getCheckpointFailureManager(errorMsg); CheckpointCoordinator coord = getCheckpointCoordinator(new JobID(), vertex1, vertex2, checkpointFailureManager); try { coord.triggerCheckpoint(false); manuallyTriggeredScheduledExecutor.triggerAll(); coord.abortPendingCheckpoints(new CheckpointException(CHECKPOINT_EXPIRED)); fail("Test failed."); } catch (Exception e) { assertTrue(e instanceof RuntimeException); assertEquals(errorMsg, e.getMessage()); } finally { coord.shutdown(JobStatus.FINISHED); } }