auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> List<String> findLastDonationForDonor(@ModelAttribute("addCollectionForm") CollectedSampleBackingForm form) { <END> CollectedSample collectedSample = form.getCollectedSample(); long diffInDays =0; Date dateofLastDonation = null; List<String> message = new ArrayList<String>(); try{ Donor donor =donorRepository.findDonorById(collectedSample.getDonor().getDonorNumber()); dateofLastDonation = donor.getDateOfLastDonation(); if(dateofLastDonation != null){ Date collectedOnDate = collectedSample.getCollectedOn(); long diff = collectedOnDate.getTime() - dateofLastDonation.getTime(); diffInDays = diff / (24 * 60 * 60 * 1000); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); message.add(String.valueOf(diffInDays)); message.add(formatter.format(dateofLastDonation).toString()); message.add(formatter.format(collectedOnDate).toString()); } else{ message.add("firstTime"); message.add("Doner is first time donar"); } } catch(NoResultException e){ message.add("notExist"); message.add("Doner does not exist"); } catch(NullPointerException e){ message.add("collectedOnRequired"); message.add("'Collected On' Date is required"); } catch(NumberFormatException e){ message.add("invalideDonor"); message.add("Invalide Donor Number"); } catch(Exception e){ message.add("error"); message.add(e.toString()); } return message; }</code><technical_language>@gtlnikita - thanks for picking this, forgot PR #143 merged in here. changes I suggested, this is for method I referenced in commit (findLastDonationForDonor). I merge new, more changes #143 this issue, code #60 is used. I this</technical_language>

Target:
Map<String, String> findLastDonationForDonor(@ModelAttribute("addCollectionForm") CollectedSampleBackingForm form) { CollectedSample collectedSample = form.getCollectedSample(); long diffInDays =0; Date dateofLastDonation = null; List<String> message = new ArrayList<String>(); Map<String, String> m = new HashMap<String, String>(); try{ if(donorRepository.findDonorByNumber(collectedSample.getDonor().getDonorNumber()) != null){ Donor donor = donorRepository.findDonorByNumber(collectedSample.getDonor().getDonorNumber()); if(donor.getDateOfLastDonation() != null){ dateofLastDonation = donor.getDateOfLastDonation(); Date collectedOnDate = collectedSample.getCollectedOn(); long diff = collectedOnDate.getTime() - dateofLastDonation.getTime(); diffInDays = diff / (24 * 60 * 60 * 1000); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); m.put("diffInDays",String.valueOf(diffInDays)); m.put("dateOfLastDonation",formatter.format(dateofLastDonation).toString()); m.put("collectedOnDate",formatter.format(collectedOnDate).toString()); } } } catch(Exception ex){ ex.printStackTrace(); } return m; }
Source:
<code>public String bulkDrop(@Sender EntityRef sender, @CommandParam("blockName") String blockName, @CommandParam("value") int value) { ClientComponent clientComponent = sender.getComponent(ClientComponent.class); LocationComponent characterLocation = clientComponent.character.getComponent(LocationComponent.class); Vector3f spawnPos = characterLocation.getWorldPosition(); Vector3f offset = characterLocation.getWorldDirection(); offset.scale(3); spawnPos.add(5,10,0); BlockFamily block = blockManager.getBlockFamily(blockName); if (block == null) <START> { <END> return "Sorry, your block is not found"; } BlockItemFactory blockItemFactory = new BlockItemFactory(entityManager); if(value > 5000) { return "sorry the value you have entered exceeds the limit of 5000"; } for (int i = 0; i <= value; i++) { EntityRef blockItem = blockItemFactory.newInstance(block); blockItem.send(new DropItemEvent(spawnPos)); } return "Dropped " + value + " " + blockName + " Blocks :)"; }</code><technical_language>Checkstyle set IntelliJ? Braces this next line is of common violations catches. Starting braces line statement begins new block :) Also, return more informative including actual block name in message</technical_language>

Target:
public String bulkDrop(@Sender EntityRef sender, @CommandParam("blockName") String blockName, @CommandParam("value") int value) { ClientComponent clientComponent = sender.getComponent(ClientComponent.class); LocationComponent characterLocation = clientComponent.character.getComponent(LocationComponent.class); Vector3f spawnPos = characterLocation.getWorldPosition(); Vector3f offset = characterLocation.getWorldDirection(); offset.scale(3); spawnPos.add(5, 10, 0); BlockFamily block = blockManager.getBlockFamily(blockName); if (block == null) { return "Sorry, your block is not found"; } BlockItemFactory blockItemFactory = new BlockItemFactory(entityManager); if (value > 5000) { return "Value exceeds the maximum limit of 5000 blocks. your value: " + value + " blocks"; } for (int i = 0; i < value; i++) { EntityRef blockItem = blockItemFactory.newInstance(block); blockItem.send(new DropItemEvent(spawnPos)); } return "Dropped " + value + " " + blockName + " Blocks :)"; }
Source:
<code>protected void executeQueryCommand() { String suggestedDiskName = null; if (getParameters().getVmId() == null) { getQueryReturnValue().setReturnValue(suggestedDiskName); } else { VM vm = getDbFacade().getVmDAO().get(getParameters().getVmId()); if (vm != null) { VmHandler.updateDisksFromDb(vm); suggestedDiskName = <START> ImagesHandler.getDefaultDiskAlias(vm.getvm_name(), Integer.toString(vm.getDiskMapCount())); <END> } getQueryReturnValue().setReturnValue(suggestedDiskName); } }</code><technical_language>calculation is wrong, calculate disk alias name number of VM disks instead increment number of disks. If VM disks alias Disk0. Adding a new disk a VM duplicate aliases</technical_language>

Target:
protected void executeQueryCommand() { String suggestedDiskName = null; if (getParameters().getVmId() == null) { getQueryReturnValue().setReturnValue(suggestedDiskName); } else { VM vm = getDbFacade().getVmDAO().get(getParameters().getVmId()); if (vm != null) { VmHandler.updateDisksFromDb(vm); suggestedDiskName = ImagesHandler.getDefaultDiskAlias(vm.getvm_name(), Integer.toString(vm.getDiskMapCount() + 1)); } getQueryReturnValue().setReturnValue(suggestedDiskName); } }
Source:
<code>public String toString() { <START> if (this.cluster == null || this.path == null) { <END> return ""; } return this.cluster + HdfsConstants.SEP + this.path; }</code><technical_language>I possible? check for empty string</technical_language>

Target:
public String toString() { if (StringUtils.isBlank(this.cluster) || StringUtils.isBlank(this.path)) { return ""; } return this.cluster + HdfsConstants.SEP + this.path; }
Source:
<code>public Response exit(final Response res, final Identity idt) throws IOException { final String text; if (idt.equals(Identity.ANONYMOUS)) { text = ""; } else { text = new String(this.codec.encode(idt)); } final long millis = System.currentTimeMillis(); return new RsWithCookie( res, this.cookie, text, "Path=/", "HttpOnly", String.format( Locale.ENGLISH, "Expires=%1$ta, %1$td %1$tb %1$tY %1$tT GMT", new Date( <START> millis + TimeUnit.DAYS.toMillis(this.age) <END> - TimeZone.getDefault().getOffset(millis) ) ) ); }</code><technical_language>@danff dont want method in tests ? a constant final SimpleDateFormat format = new SimpleDateFormat( "'Expires='EEE, dd MMM yyyy HH:mm:ss 'GMT'" Locale.ENGLISH ); set time zone in a static initializer format.setTimeZone(TimeZone.getTimeZone("GMT")); remove variable millis expression simplier</technical_language>

Target:
public Response exit(final Response res, final Identity idt) throws IOException { final String text; if (idt.equals(Identity.ANONYMOUS)) { text = ""; } else { text = new String(this.codec.encode(idt)); } return new RsWithCookie( res, this.cookie, text, new Opt.Single<Date>( new Date( System.currentTimeMillis() + TimeUnit.DAYS.toMillis(this.age) ) ), "Path=/", "HttpOnly" ); }
Source:
<code>public void run() throws IOException { InputStream in = VersionGenerator.class.getResourceAsStream("/parquet-version.properties"); if (in == null) { throw new IOException("/parquet-version.properties not found"); } Properties props = new Properties(); props.load(in); add("package org.apache.parquet;\n" + "\n" + " \n"); add("public class Version {\n"); add(" public static final String VERSION_NUMBER = \""); add(props.getProperty("versionNumber")); add("\";\n"); add(" public static final String FULL_VERSION = \""); add(props.getProperty("fullVersion")); add("\";\n"); add("}\n"); <START> writer.close(); <END> }</code><technical_language>Other main method, this compatible Version class me. While nit-picking over-cautious, I include main</technical_language>

Target:
public void run() throws IOException { InputStream in = VersionGenerator.class.getResourceAsStream("/parquet-version.properties"); if (in == null) { throw new IOException("/parquet-version.properties not found"); } Properties props = new Properties(); props.load(in); add("package org.apache.parquet;\n" + "\n" + " \n"); add("public class Version {\n"); add(" public static final String VERSION_NUMBER = \""); add(props.getProperty("versionNumber")); add("\";\n"); add(" public static final String FULL_VERSION = \""); add(props.getProperty("fullVersion")); add("\";\n\n"); add(" public static void main(String[] args) {\n"); add(" System.out.println(FULL_VERSION);\n"); add(" }\n"); add("}\n"); writer.close(); }
Source:
<code>public boolean supports(Event<?> event) { boolean supports = super.supports(event); try { if (listenerMethod.isAnnotationPresent(EventBusListenerMethod.class)) { EventBusListenerMethod annotation = listenerMethod.getAnnotation(EventBusListenerMethod.class); EventBusListenerMethodFilter filter = annotation.filter().newInstance(); String target = annotation.target(); EventScope scope = annotation.scope(); if (scope.equals(EventScope.UNDEFINED)) { scope = event.getScope(); } supports = supports && filter.filter(event.getPayload()) && event.getScope().equals(scope) <START> && event.getTarget().startsWith(target); <END> } } catch (Exception e) { throw new RuntimeException("A checked exception occurred while invoking listener method " + listenerMethod.getName(), e); } return supports; }</code><technical_language>startsWith() instead of equals()? This strange side effects IMO</technical_language>

Target:
public boolean supports(Event<?> event) { boolean supports = super.supports(event); try { if (listenerMethod.isAnnotationPresent(EventBusListenerMethod.class)) { supports = supports && isInterestedListenerMethod(event); } if (listenerMethod.isAnnotationPresent(EventBusListenerTopic.class) && supports) { supports = isInTopic(event); } } catch (Exception e) { throw new RuntimeException("A checked exception occurred while invoking listener method " + listenerMethod.getName(), e); } return supports; }
Source:
<code>private boolean hasPerceivedContribution(String email, FeedbackQuestionAttributes question, FeedbackSessionResultsBundle bundle) { Map<String, StudentResultSummary> stats = FeedbackContributionResponseDetails.getContribQnStudentResultSummary(question, bundle); if (stats.containsKey(email)) { return true; } else { return false; <START> } <END> }</code><technical_language>return stats.containsKey(email)</technical_language>

Target:
private boolean hasPerceivedContribution(String email, FeedbackQuestionAttributes question, FeedbackSessionResultsBundle bundle) { Map<String, StudentResultSummary> stats = FeedbackContributionResponseDetails.getContribQnStudentResultSummary(question, bundle); return stats.containsKey(email); }
Source:
<code>protected void addInfos(BlobHolder blobHolder) { if (blobHolder instanceof DocumentBlobHolder) { DocumentBlobHolder documentBlobHolder = (DocumentBlobHolder) blobHolder; addInfo(String.format("Document Id = %s", documentBlobHolder.getDocument().getId())); } Collection<Blob> blobs = new HashSet<>(); if (blobHolder.getBlob() != null) { blobs.add(blobHolder.getBlob()); } <START> if (CollectionUtils.isNotEmpty(blobHolder.getBlobs())) { <END> blobs.addAll(blobHolder.getBlobs()); } addInfos(blobs); }</code><technical_language>want test nullity there? save import</technical_language>

Target:
protected void addInfos(BlobHolder blobHolder) { if (blobHolder instanceof DocumentBlobHolder) { DocumentBlobHolder documentBlobHolder = (DocumentBlobHolder) blobHolder; addInfo(String.format("Document: %s", documentBlobHolder.getDocument())); } List<Blob> blobs = blobHolder.getBlobs(); if (blobs != null) { blobs.forEach(this::addInfo); } }
Source:
<code><START> public void setNextDocId(int docId) throws IOException { <END> this.docId = docId; }</code><technical_language>remove exception annotation parent class</technical_language>

Target:
public void setNextDocId(int docId) { this.docId = docId; }
Source:
<code>public SessionFactory<F> resolve(Message<?> message) { if(beanFactory != null) { <START> return beanFactory.getBean(this.sessionFactoryExpression.getValue(message).toString(), SessionFactory.class); <END> } return null; }</code><technical_language>this.beanFactory. No, toString(), this this.sessionFactoryExpression.getValue(message, String.class) EvaluationContext supported too. IntegrationEvaluationContextAware. I headers['sessionFactory'] resolved entire SessionFactory object, beanId. @garyrussell</technical_language>

Target:
public SessionFactory<F> resolve(Message<?> message) { if(this.beanFactory != null) { if(evaluationContext != null) { return this.beanFactory.getBean(this.sessionFactoryExpression.getValue(evaluationContext, message, String.class), SessionFactory.class); } return this.beanFactory.getBean(this.sessionFactoryExpression.getValue(message, String.class), SessionFactory.class); } return null; }
Source:
<code>private NewVersionAvailableEvent(@Nullable final Version newVersion, @Nullable final Date lastSupportedDate, final boolean isUnsupported) throws IllegalArgumentException { if (!isUnsupported && lastSupportedDate == null) { if (newVersion == null) { throw new IllegalArgumentException( "At least one parameter needs to be non-null or true."); } else { final Version currentVersion; try { currentVersion = new Version(BuildConfig.VERSION_NAME); } catch (ParseException e) { <START> logger.error(e); <END> throw new IllegalStateException("The version number of the current" + "build doesn't correspond to the schema.", e); } if (newVersion.compareTo(currentVersion) <= 0) { throw new IllegalArgumentException( "The new update version is lesser than the current version."); } } } this.newVersion = newVersion; this.lastSupportedDate = lastSupportedDate == null ? null : (Date) lastSupportedDate.clone(); this.isUnsupported = isUnsupported; }</code><technical_language>I this logged Crashlytics well, broken functionality</technical_language>

Target:
public NewVersionAvailableEvent(@Nullable final Version newVersion, @Nullable final Date lastSupportedDate, final boolean isUnsupported) throws IllegalArgumentException { if (!isUnsupported && lastSupportedDate == null) { if (newVersion == null) { throw new IllegalArgumentException( "At least one parameter needs to be non-null or true."); } else { final Version currentVersion; try { currentVersion = new Version(BuildConfig.VERSION_NAME); } catch (ParseException e) { logger.error(e, true); throw new IllegalStateException("The version number of the current" + "build doesn't correspond to the schema.", e); } if (newVersion.compareTo(currentVersion) <= 0) { throw new IllegalArgumentException( "The new update version is lesser than the current version."); } } } this.newVersion = newVersion; this.lastSupportedDate = lastSupportedDate == null ? null : (Date) lastSupportedDate.clone(); this.isUnsupported = isUnsupported; }
Source:
<code>public void testLiveGetDisputeList() throws IOException, OmiseException { Request<ScopedList<Dispute>> request = new Dispute.ListRequestBuilder() .status(DisputeStatus.Lost) .options(new ScopedList.Options().order(Ordering.ReverseChronological)).build(); ScopedList<Dispute> disputes = client.sendRequest(request, new TypeReference<ScopedList<Dispute>>() {}); System.out.println("retrieved dispute list total no.: " + disputes.getTotal()); <START> assertNotNull(disputes.getData().get(0)); <END> }</code><technical_language>good test options too</technical_language>

Target:
public void testLiveGetDisputeList() throws IOException, OmiseException { Request<ScopedList<Dispute>> request = new Dispute.ListRequestBuilder().build(); ScopedList<Dispute> disputes = client.sendRequest(request, new TypeReference<ScopedList<Dispute>>() {}); System.out.println("retrieved dispute list total no.: " + disputes.getTotal()); assertNotNull(disputes.getData().get(0)); }
Source:
<code>private void timerOff(final String version, final Stat currentStatOfBarrierDone) { try { zkUtils.getZkClient().writeData(barrierDonePath, BARRIER_TIMED_OUT, currentStatOfBarrierDone.getVersion()); <START> } catch (Exception e) { <END> LOG.info("Barrier timeout write failed"); String done = zkUtils.getZkClient().<String>readData(barrierDonePath); if (!done.equals(BARRIER_DONE)) { throw new SamzaException("Failed to write to the barrier_done, version=" + version, e); } } }</code><technical_language>more specific in handling exception here? I exception handling behavior is for write failure due bad version write failure due other reason</technical_language>

Target:
private void timerOff(final String version, final Stat currentStatOfBarrierDone) { try { zkUtils.getZkClient().writeData(barrierDonePath, BARRIER_TIMED_OUT, currentStatOfBarrierDone.getVersion()); } catch (ZkBadVersionException e) { LOG.warn("Barrier timeout write failed"); String done = zkUtils.getZkClient().<String>readData(barrierDonePath); if (!done.equals(BARRIER_DONE)) { throw new SamzaException("Failed to write to the barrier_done, version=" + version, e); } } }
Source:
<code>private void showPostsPerPageDialog() { Bundle args = new Bundle(); args.putBoolean(NumberPickerDialog.SHOW_SWITCH_KEY, false); args.putString(NumberPickerDialog.TITLE_KEY, getString(R.string.site_settings_posts_per_page_title)); <START> args.putInt(NumberPickerDialog.MIN_VALUE_KEY, 0); <END> args.putInt(NumberPickerDialog.MAX_VALUE_KEY, getResources().getInteger(R.integer.posts_per_page_limit)); args.putInt(NumberPickerDialog.CUR_VALUE_KEY, mSiteSettings.getPostsPerPage()); showNumberPickerDialog(args, POSTS_PER_PAGE_REQUEST_CODE, "posts-per-page-dialog"); }</code><technical_language>user pick 0 "Posts page". get overridden remote 1</technical_language>

Target:
private void showPostsPerPageDialog() { Bundle args = new Bundle(); args.putBoolean(NumberPickerDialog.SHOW_SWITCH_KEY, false); args.putString(NumberPickerDialog.TITLE_KEY, getString(R.string.site_settings_posts_per_page_title)); args.putInt(NumberPickerDialog.MIN_VALUE_KEY, 1); args.putInt(NumberPickerDialog.MAX_VALUE_KEY, getResources().getInteger(R.integer.posts_per_page_limit)); args.putInt(NumberPickerDialog.CUR_VALUE_KEY, mSiteSettings.getPostsPerPage()); showNumberPickerDialog(args, POSTS_PER_PAGE_REQUEST_CODE, "posts-per-page-dialog"); }
Source:
<code>public boolean equals(Object that) { <START> logger.entering(this.getClass().getName(),"equals",that); <END> if(!(that instanceof AbstractTreeNode)) { return false; } AbstractTreeNode a = (AbstractTreeNode)that; return this.getData().equals(a.getData()); }</code><technical_language>of this.getClass().getName</technical_language>

Target:
public boolean equals(Object that) { logger.entering("AbstractTreeNode","equals",that); if(!(that instanceof AbstractTreeNode)) { return false; } AbstractTreeNode a = (AbstractTreeNode)that; return this.getData().equals(a.getData()); }
Source:
<code>private boolean isPublicApi(DetailAST token) { final DetailAST modifiersAST = token.findFirstToken(TokenTypes.MODIFIERS); final boolean isStatic = modifiersAST.findFirstToken(TokenTypes.LITERAL_STATIC) != null; <START> final boolean isPublic = modifiersAST <END> .findFirstToken(TokenTypes.LITERAL_PUBLIC) != null; final boolean isProtected = modifiersAST.findFirstToken(TokenTypes.LITERAL_PROTECTED) != null; return (isPublic || isProtected) && !isStatic; }</code><technical_language>FYI, AccessModifier another define modifier accessibility: final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersAST); accessModifier.equals(AccessModifier.PUBLIC)</technical_language>

Target:
private boolean isPublicApi(DetailAST token) { final DetailAST modifiersAST = token.findFirstToken(TokenTypes.MODIFIERS); final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersAST); final boolean isStatic = modifiersAST.findFirstToken(TokenTypes.LITERAL_STATIC) != null; return (accessModifier.equals(AccessModifier.PUBLIC) || accessModifier.equals(AccessModifier.PROTECTED)) && !isStatic; }
Source:
<code>private static SnapshotStatus toSnapshotStatus( Map<?, ?> json) { if (json == null) { return null; } int snapshotID = getInt(json, "snapshotID", 0); <START> boolean isDeleted = ((String)json.get("deletionStatus")). contentEquals("DELETED"); <END> String fullPath = ((String) json.get("fullPath")); HdfsFileStatus dirStatus = toFileStatus((Map<?, ?>) json.get("dirStatus"), false); SnapshotStatus snapshotStatus = new SnapshotStatus(dirStatus, snapshotID, isDeleted, DFSUtilClient.string2Bytes( SnapshotStatus.getParentPath(fullPath))); return snapshotStatus; }</code><technical_language>"DELETED".equal(..) in order avoid NPE? final boolean isDeleted = "DELETED".equals(json.get("deletionStatus"));</technical_language>

Target:
private static SnapshotStatus toSnapshotStatus( Map<?, ?> json) { if (json == null) { return null; } int snapshotID = getInt(json, "snapshotID", 0); boolean isDeleted = "DELETED".equalsIgnoreCase( (String)json.get("deletionStatus")); String fullPath = ((String) json.get("fullPath")); HdfsFileStatus dirStatus = toFileStatus((Map<?, ?>) json.get("dirStatus"), false); SnapshotStatus snapshotStatus = new SnapshotStatus(dirStatus, snapshotID, isDeleted, DFSUtilClient.string2Bytes( SnapshotStatus.getParentPath(fullPath))); return snapshotStatus; }
Source:
<code>public void testReadingInvalidJsonFile() throws Exception { <START> final String fileDirectoryPath = JSON_INVALID_SAMPLE_DATA_FILE.getParent(); <END> final TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName("testTable").build(); final Schema fakeSchema = new Schema.SchemaBuilder().build(); Files.write(Paths.get(fileDirectoryPath + "/tmpTableConfig.json"), tableConfig.toJsonString().getBytes()); Files.write(Paths.get(fileDirectoryPath + "/tmpSchema.json"), fakeSchema.toSingleLineJsonString().getBytes()); _createSegmentCommand.setDataDir(fileDirectoryPath); _createSegmentCommand.setFormat(FileFormat.JSON); _createSegmentCommand.setOutDir(fileDirectoryPath); _createSegmentCommand.setTableConfigFile(fileDirectoryPath + "/tmpTableConfig.json"); _createSegmentCommand.setSchemaFile(fileDirectoryPath + "/tmpSchema.json"); _createSegmentCommand.execute(); }</code><technical_language>(nit) put final for local variables</technical_language>

Target:
public void testReadingInvalidJsonFile() throws Exception { String fileDirectoryPath = JSON_INVALID_SAMPLE_DATA_FILE.getParent(); TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName("testTable").build(); Schema fakeSchema = new Schema.SchemaBuilder().build(); Files.write(Paths.get(fileDirectoryPath + "/tmpTableConfig.json"), tableConfig.toJsonString().getBytes()); Files.write(Paths.get(fileDirectoryPath + "/tmpSchema.json"), fakeSchema.toSingleLineJsonString().getBytes()); _createSegmentCommand.setDataDir(fileDirectoryPath); _createSegmentCommand.setFormat(FileFormat.JSON); _createSegmentCommand.setOutDir(fileDirectoryPath); _createSegmentCommand.setTableConfigFile(fileDirectoryPath + "/tmpTableConfig.json"); _createSegmentCommand.setSchemaFile(fileDirectoryPath + "/tmpSchema.json"); _createSegmentCommand.execute(); }
Source:
<code>private void <START> update(boolean <END> checked) { ITextEditor editor= getTextEditor(); if (editor instanceof ITextEditorExtension6) { setEnabled(true); setChecked(checked); return; } setEnabled(false); setChecked(false); }</code><technical_language>fine pass initial state, implement public void update() method, similar BlockSelectionModeToggleAction.update()</technical_language>

Target:
private void update(boolean checked) { setEnabled(isWordWrapPossible()); setChecked(checked); }
Source:
<code><START> public static Boolean hasAny(JsonObject object, Collection<String> coll){ <END> for(String key : coll){ if(object.has(key)) return true; } return false; }</code><technical_language>is this declared returning Boolean (object) primitive boolean</technical_language>

Target:
public static boolean hasAny(JsonObject object, Collection<String> coll){ for(String key : coll){ if(object.has(key)) return true; } return false; }
Source:
<code>protected void createDocumentWithFiles() throws Exception { startTransaction(); DocumentModel doc = session.createDocumentModel("/", "myFile", "File"); List<Map<String, Serializable>> blobs = new ArrayList<>(); for (int i = 1; i <= 5; i++) { String name = "testfile" + i + ".txt"; <START> Blob nblob = Blobs.createBlob(new String(new char[i]).replace('\0', 'a')); <END> nblob.setFilename(name); Map<String, Serializable> filesEntry = new HashMap<>(); filesEntry.put("file", (Serializable) nblob); blobs.add(filesEntry); } doc.setPropertyValue("files:files", (Serializable) blobs); doc = session.createDocument(doc); TransactionHelper.commitOrRollbackTransaction(); waitForCompletion(); startTransaction(); }</code><technical_language>blob</technical_language>

Target:
protected void createDocumentWithFiles() throws Exception { startTransaction(); DocumentModel doc = session.createDocumentModel("/", "myFile", "File"); var blobs = new ArrayList<>(); for (int i = 1; i <= 5; i++) { Blob blob = Blobs.createBlob(new String(new char[i]).replace('\0', 'a')); blob.setFilename(String.format("testfile%d.txt", i)); blobs.add(Map.of("file", (Serializable) blob)); } doc.setPropertyValue("files:files", blobs); session.createDocument(doc); TransactionHelper.commitOrRollbackTransaction(); waitForCompletion(); startTransaction(); }
Source:
<code>private IStatus copy(String src, IFileStore destinationParent, IFileSystem fileSystem, IProgressMonitor monitor) throws CoreException { Path srcPath = new Path(src); IFileStore source = fileSystem.getStore(srcPath); String elementName = srcPath.segment(srcPath.segmentCount() - 1); IFileStore destination = destinationParent.getChild(elementName); SubMonitor subMonitor = <START> SubMonitor.convert(monitor, <END> 2); if (destination.fetchInfo().exists()) { subMonitor.worked(1); return Status.OK_STATUS; } if (source.fetchInfo().isDirectory()) { destination.mkdir(EFS.NONE, new NullProgressMonitor()); } source.copy(destination, EFS.OVERWRITE, subMonitor.newChild(1)); return Status.OK_STATUS; }</code><technical_language>Ticks line up. method body consumes 1 tick</technical_language>

Target:
private IStatus copy(String src, IFileStore destinationParent, IFileSystem fileSystem, IProgressMonitor monitor) throws CoreException { Path srcPath = new Path(src); IFileStore source = fileSystem.getStore(srcPath); String elementName = srcPath.segment(srcPath.segmentCount() - 1); IFileStore destination = destinationParent.getChild(elementName); SubMonitor subMonitor = SubMonitor.convert(monitor, 1); if (destination.fetchInfo().exists()) { return Status.OK_STATUS; } if (source.fetchInfo().isDirectory()) { destination.mkdir(EFS.NONE, new NullProgressMonitor()); } source.copy(destination, EFS.OVERWRITE, subMonitor.newChild(1)); return Status.OK_STATUS; }
Source:
<code>public Object getParent(Object element) { if (element instanceof IBuild) { return ((IBuild) element).getParent(); } <START> return NO_ELEMENTS; <END> }</code><technical_language>return null</technical_language>

Target:
public Object getParent(Object element) { if (element instanceof IBuild) { return ((IBuild) element).getParent(); } return null; }
Source:
<code>public boolean generate() { Element enclosingElement = classType.getEnclosingElement(); if (!enclosingElement.getKind().equals(ElementKind.PACKAGE)) { Utils.error("The RealmClass annotation does not support nested classes", classType); return false; } TypeElement parentElement = (TypeElement) Utils.getSuperClass(classType); <START> if (!Utils.isJavaLangObject(parentElement) && !Utils.isRealmObject(parentElement)) { <END> Utils.error("A RealmClass annotated object must be derived from RealmObject", classType); return false; } PackageElement packageElement = (PackageElement) enclosingElement; packageName = packageElement.getQualifiedName().toString(); if (!categorizeClassElements()) return false; if (!checkListTypes()) return false; if (!checkDefaultConstructor()) return false; if (!checkForFinalFields()) return false; if (!checkForTransientFields()) return false; if (!checkForVolatileFields()) return false; return true; }</code><technical_language>is purpose of checking if parent is Object? catch annotation interfaces? this catch e.g. Foo extends Bar Bar is RealmObject</technical_language>

Target:
public boolean generate() { Element enclosingElement = classType.getEnclosingElement(); if (!enclosingElement.getKind().equals(ElementKind.PACKAGE)) { Utils.error("The RealmClass annotation does not support nested classes", classType); return false; } TypeElement parentElement = (TypeElement) Utils.getSuperClass(classType); if (!parentElement.toString().equals("java.lang.Object") && !parentElement.toString().equals("io.realm.RealmObject")) { Utils.error("Realm model classes must either extend RealmObject or implement RealmModel to be considered a valid model class", classType); return false; } PackageElement packageElement = (PackageElement) enclosingElement; packageName = packageElement.getQualifiedName().toString(); if (!categorizeClassElements()) return false; if (!checkListTypes()) return false; if (!checkDefaultConstructor()) return false; if (!checkForFinalFields()) return false; if (!checkForTransientFields()) return false; if (!checkForVolatileFields()) return false; return true; }
Source:
<code>public static boolean isValid(InputStream stream) { try { ZipInputStream zip = new ZipInputStream(stream); <START> ZipEntry entry = zip.getNextEntry(); <END> return entry != null; } catch (IOException e) { return false; } }</code><technical_language>Please close input stream (maybe try-with-resources statement) java try (ZipInputStream zip = new ZipInputStream(stream)) { ... }</technical_language>

Target:
public static boolean isValid(InputStream stream) { try (ZipInputStream zip = new ZipInputStream(stream)) { return zip.getNextEntry() != null; } catch (IOException e) { return false; } }
Source:
<code>public BlobIndexValue(long size, long offset) { <START> this(size, offset, (byte)0, -1); <END> }</code><technical_language>1 -> TTL_Infinite constant</technical_language>

Target:
public BlobIndexValue(long size, long offset) { this(size, offset, (byte)0, TTL_Infinite); }
Source:
<code><START> @Override public void close(Duration duration) { <END> delegate.close(duration); }</code><technical_language>is compiling method in IT? is a good question</technical_language>

Target:
public void close(Duration duration) { delegate.close(duration); }
Source:
<code>private void scanDeltaAndRefresh( GitResourceVariantTreeSubscriber subscriber, RepositoryMapping mapping, IResourceDelta delta) { Repository repo = mapping.getRepository(); GitResourceDeltaVisitor visitor = new GitResourceDeltaVisitor(repo); try { delta.accept(visitor); Collection<IFile> files = visitor.getFileResourcesToUpdate(); <START> if (files != null && !files.isEmpty()) <END> return; for (GitSynchronizeData gsd : gsds) { if (repo.equals(gsd.getRepository())) refreshResources(subscriber, files); } } catch (CoreException e) { Activator.logError(e.getMessage(), e); } }</code><technical_language>This means return non-empty collections. I return for empty collections</technical_language>

Target:
private void scanDeltaAndRefresh( GitResourceVariantTreeSubscriber subscriber, RepositoryMapping mapping, IResourceDelta delta) { Repository repo = mapping.getRepository(); GitResourceDeltaVisitor visitor = new GitResourceDeltaVisitor(repo); try { delta.accept(visitor); Collection<IFile> files = visitor.getFileResourcesToUpdate(); if (files != null && files.isEmpty()) return; for (GitSynchronizeData gsd : gsds) { if (repo.equals(gsd.getRepository())) refreshResources(subscriber, files); } } catch (CoreException e) { Activator.logError(e.getMessage(), e); } }
Source:
<code>private Map<String, Object> buildStringKeyMap(ByteBuffer input) throws ParseException { int payloadSize = input.remaining(); if (chars == null || chars.remaining() < payloadSize) { chars = CharBuffer.allocate(payloadSize); } final CoderResult coderResult = Charsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE) .decode(input, chars, true); Map<String, Object> theMap; if (coderResult.isUnderflow()) { chars.flip(); try { theMap = parseString(chars.toString()); } finally { chars.clear(); } } else { <START> throw new IAE("Failed with CoderResult[%s]", coderResult); <END> } return theMap; }</code><technical_language>ParseException I think, this bad UTF-8 encoding</technical_language>

Target:
private Map<String, Object> buildStringKeyMap(ByteBuffer input) throws ParseException { int payloadSize = input.remaining(); if (chars == null || chars.remaining() < payloadSize) { chars = CharBuffer.allocate(payloadSize); } final CoderResult coderResult = Charsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE) .decode(input, chars, true); Map<String, Object> theMap; if (coderResult.isUnderflow()) { chars.flip(); try { theMap = parseString(chars.toString()); } finally { chars.clear(); } } else { throw new ParseException("Failed with CoderResult[%s]", coderResult); } return theMap; }
Source:
<code>public void testEndpointProfileUpdate() { TargetingClient targetingClient = pinpointManager.getTargetingClient(); assertNotNull(targetingClient); targetingClient.updateEndpointProfile(); EndpointProfile endpointProfile = targetingClient.currentEndpoint(); assertNotNull(endpointProfile); assertNull(endpointProfile.getUser().getUserId()); assertNull(endpointProfile.getUser().getUserAttributes()); EndpointProfileUser user = new EndpointProfileUser(); user.setUserId(credentialsProvider.getIdentityId()); <START> user.setUserAttributes(Collections.singletonMap("user-key", Arrays.asList("user-value"))); <END> endpointProfile.setUser(user); targetingClient.updateEndpointProfile(); endpointProfile = targetingClient.currentEndpoint(); assertNotNull(endpointProfile); assertEquals(credentialsProvider.getIdentityId(), endpointProfile.getUser().getUserId()); assertNotNull(endpointProfile.getUser().getUserAttributes()); assertEquals(Collections.singletonMap("user-key", Arrays.asList("user-value")), endpointProfile.getUser().getUserAttributes()); endpointProfile.addAttribute("key", Arrays.asList("value")); targetingClient.updateEndpointProfile(); endpointProfile = targetingClient.currentEndpoint(); assertNotNull(endpointProfile); assertEquals(credentialsProvider.getIdentityId(), endpointProfile.getUser().getUserId()); assertEquals("value", endpointProfile.getAllAttributes().get("key").get(0)); }</code><technical_language>Collections.singletonList("user-value")</technical_language>

Target:
public void testEndpointProfileUpdate() { TargetingClient targetingClient = pinpointManager.getTargetingClient(); assertNotNull(targetingClient); targetingClient.updateEndpointProfile(); EndpointProfile endpointProfile = targetingClient.currentEndpoint(); assertNotNull(endpointProfile); assertNull(endpointProfile.getUser().getUserId()); assertNull(endpointProfile.getUser().getUserAttributes()); EndpointProfileUser user = new EndpointProfileUser(); user.setUserId(credentialsProvider.getIdentityId()); user.addUserAttribute("user-key", Collections.singletonList("user-value")); endpointProfile.setUser(user); targetingClient.updateEndpointProfile(); endpointProfile = targetingClient.currentEndpoint(); assertNotNull(endpointProfile); assertEquals(credentialsProvider.getIdentityId(), endpointProfile.getUser().getUserId()); assertNotNull(endpointProfile.getUser().getUserAttributes()); assertEquals(Collections.singletonMap("user-key", Collections.singletonList("user-value")), endpointProfile.getUser().getUserAttributes()); endpointProfile.addAttribute("key", Arrays.asList("value")); targetingClient.updateEndpointProfile(); endpointProfile = targetingClient.currentEndpoint(); assertNotNull(endpointProfile); assertEquals(credentialsProvider.getIdentityId(), endpointProfile.getUser().getUserId()); assertEquals("value", endpointProfile.getAllAttributes().get("key").get(0)); }
Source:
<code>public static Gff3Directive toDirective(final String line) { for (final Gff3Directive directive : Gff3Directive.values()) { <START> if(Pattern.matches(directive.regexPattern, line)) { <END> return directive; } } return null; }</code><technical_language>store compiled pattern instead of regex pay overhead of recompiling time match it</technical_language>

Target:
public static Gff3Directive toDirective(final String line) { for (final Gff3Directive directive : Gff3Directive.values()) { if(directive.regexPattern.matcher(line).matches()) { return directive; } } return null; }
Source:
<code>private void testProvider(final Class<? extends WindupRuleProvider> provider, final String expectedCatsStr) throws IOException { String name = TestCategoryUnsetRuleProvider.class.getSimpleName(); final Set<String> expectedCats = new HashSet(Arrays.asList(StringUtils.split(expectedCatsStr, ", "))); try (GraphContext context = factory.create()) { Predicate<WindupRuleProvider> rulesToRun = new EnumeratedRuleProviderFilter(provider); Configuration conf = loader.loadConfiguration(context, rulesToRun).getConfiguration(); Assert.assertTrue("Rule loaded", !conf.getRules().isEmpty()); Assert.assertTrue("Rule instanceof Context", conf.getRules().get(0) instanceof Context); Context subRule = (Context) conf.getRules().get(0); Object category = subRule.get(RuleMetadata.CATEGORY); Assert.assertTrue("CATEGORY is set in the Context: " + category, category != null); Assert.assertTrue("Category is a Set: " + category.getClass(), category instanceof Set); Set<String> cats = (Set<String>)category; Assert.assertEquals("" + expectedCats.size() + " categories in " + name, expectedCats.size(), cats.size()); for (String expCat : expectedCats) Assert.assertTrue(name + " has category " + expCat, cats.contains(expCat)); } catch(Exception ex) { if(ex instanceof InvocationTargetException) <START> throw new WindupException("" + ((InvocationTargetException)ex).getTargetException(), ex); <END> throw ex; } }</code><technical_language>wrap this</technical_language>

Target:
private void testProvider(final Class<? extends WindupRuleProvider> provider, final String expectedCatsStr) throws IOException { String name = TestTagsUnsetRuleProvider.class.getSimpleName(); final Set<String> expectedCats = new HashSet(Arrays.asList(StringUtils.split(expectedCatsStr, ", "))); try (GraphContext context = factory.create()) { Predicate<WindupRuleProvider> rulesToRun = new EnumeratedRuleProviderFilter(provider); Configuration conf = loader.loadConfiguration(context, rulesToRun).getConfiguration(); Assert.assertTrue("Rule loaded", !conf.getRules().isEmpty()); Assert.assertTrue("Rule instanceof Context", conf.getRules().get(0) instanceof Context); Context subRule = (Context) conf.getRules().get(0); Object tag = subRule.get(RuleMetadata.TAGS); Assert.assertTrue("TAGS is set in the Context: " + tag, tag != null); Assert.assertTrue("Tags is a Set: " + tag.getClass(), tag instanceof Set); Set<String> cats = (Set<String>)tag; Assert.assertEquals("" + expectedCats.size() + " tags in " + name, expectedCats.size(), cats.size()); for (String expCat : expectedCats) Assert.assertTrue(name + " has tag " + expCat, cats.contains(expCat)); } catch(Exception ex) { if(ex instanceof InvocationTargetException) throw new WindupException("" + ((InvocationTargetException)ex).getTargetException(), ex); throw ex; } }
Source:
<code>public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { DropTableMessage msg = deserializer.getDropTableMessage(context.dmd.getPayload()); String actualDbName = context.isDbNameEmpty() ? msg.getDB() : context.dbName; String actualTblName = context.isTableNameEmpty() ? msg.getTable() : context.tableName; DropTableDesc dropTableDesc = new DropTableDesc( actualDbName + "." + actualTblName, null, true, true, context.eventOnlyReplicationSpec(), false ); Task<DDLWork> dropTableTask = TaskFactory.get( new DDLWork(readEntitySet, writeEntitySet, dropTableDesc), context.hiveConf ); context.log.debug( "Added drop tbl task : {}:{}", dropTableTask.getId(), dropTableDesc.getTableName() ); updatedMetadata.set(context.dmd.getEventTo().toString(), actualDbName, null, null); try { <START> return Collections.singletonList(ReplUtils.appendOpenTxnTaskForMigration(actualDbName, actualTblName, <END> context.hiveConf, updatedMetadata, dropTableTask, msg.getTableObj())); } catch (Exception e) { throw new SemanticException(e.getMessage()); } }</code><technical_language>Drop table drop partition need start txn write new. though</technical_language>

Target:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { DropTableMessage msg = deserializer.getDropTableMessage(context.dmd.getPayload()); String actualDbName = context.isDbNameEmpty() ? msg.getDB() : context.dbName; String actualTblName = context.isTableNameEmpty() ? msg.getTable() : context.tableName; DropTableDesc dropTableDesc = new DropTableDesc( actualDbName + "." + actualTblName, null, true, true, context.eventOnlyReplicationSpec(), false ); Task<DDLWork> dropTableTask = TaskFactory.get( new DDLWork(readEntitySet, writeEntitySet, dropTableDesc), context.hiveConf ); context.log.debug( "Added drop tbl task : {}:{}", dropTableTask.getId(), dropTableDesc.getTableName() ); updatedMetadata.set(context.dmd.getEventTo().toString(), actualDbName, null, null); return Collections.singletonList(dropTableTask); }
Source:
<code>public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { <START> api = new OpenFoodAPIClient(requireActivity()); <END> binding = FragmentEnvironmentProductBinding.inflate(inflater); return binding.getRoot(); }</code><technical_language>Put in onCreate</technical_language>

Target:
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentEnvironmentProductBinding.inflate(inflater); return binding.getRoot(); }
Source:
<code>public FeedRangePartitionKeyRangeImpl(final String partitionKeyRangeId) { if (partitionKeyRangeId == null) { <START> throw new NullPointerException("partitionKeyRangeId"); <END> } this.partitionKeyRangeId = partitionKeyRangeId; this.partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(partitionKeyRangeId); }</code><technical_language>I checkNotNull pattern consistent more succinct</technical_language>

Target:
public FeedRangePartitionKeyRangeImpl(final String partitionKeyRangeId) { checkNotNull(partitionKeyRangeId, "Argument 'partitionKeyRangeId' must not be null"); this.partitionKeyRangeId = partitionKeyRangeId; this.partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(partitionKeyRangeId); }
Source:
<code><START> public IDecorator[] getDecorators(PictogramElement pe) { <END> int xOrigin = -20, yOrigin = 0; int xGap = 0, yGap = -10; EObject bo = Graphiti.getLinkService() .getBusinessObjectForLinkedPictogramElement(pe); ArrayList<Diagnostic> diagnostics = ((BehaviorEditor) getDiagramTypeProvider() .getDiagramEditor()).getDiagnosingModelObserver() .getElementDiagonsticMap().get(bo); ArrayList<IDecorator> decorators = DecoratorUtil .getMarkersFromDiagnostics(diagnostics); if (decorators.isEmpty()) return super.getDecorators(pe); else { int i = 0; for (IDecorator decorator : decorators) { ((ImageDecorator) decorator).setX(xOrigin + i * xGap); ((ImageDecorator) decorator).setY(yOrigin + i * yGap); i++; } return (IDecorator[]) decorators .toArray(new IDecorator[decorators.size()]); } }</code><technical_language>I inspect this debugger I pe is instanceof ConnectionDecorator bo is null. get connection (pe.eContainer()). Is pe a ConnectionDecorator</technical_language>

Target:
public IDecorator[] getDecorators(PictogramElement pe) { if (pe.isVisible()) { int xOrigin = -20, yOrigin = 0; int xGap = 0, yGap = -10; EObject bo = Graphiti.getLinkService() .getBusinessObjectForLinkedPictogramElement( (PictogramElement) pe.eContainer()); ArrayList<Diagnostic> diagnostics = ((BehaviorEditor) getDiagramTypeProvider() .getDiagramBehavior().getDiagramContainer()) .getDiagnosingModelObserver().getElementDiagonsticMap() .get(bo); ArrayList<IDecorator> decorators = DecoratorUtil .getMarkersFromDiagnostics(diagnostics); if (!decorators.isEmpty()) { int i = 0; for (IDecorator decorator : decorators) { ((ImageDecorator) decorator).setX(xOrigin + i * xGap); ((ImageDecorator) decorator).setY(yOrigin + i * yGap); i++; } return (IDecorator[]) decorators .toArray(new IDecorator[decorators.size()]); } } return super.getDecorators(pe); }
Source:
<code>public PreparedQuery prepareQuery(Session session, Statement wrappedStatement) throws ParsingException, PrestoException, SemanticException { Statement statement = wrappedStatement; String prepareSql = null; <START> if (wrappedStatement instanceof Execute) { <END> prepareSql = session.getPreparedStatementFromExecute((Execute) statement); statement = sqlParser.createStatement(prepareSql, createParsingOptions(session)); } if (statement instanceof Explain && ((Explain) statement).isAnalyze()) { Statement innerStatement = ((Explain) statement).getStatement(); Optional<QueryType> innerQueryType = StatementUtils.getQueryType(innerStatement.getClass()); if (!innerQueryType.isPresent() || innerQueryType.get() == QueryType.DATA_DEFINITION) { throw new PrestoException(NOT_SUPPORTED, "EXPLAIN ANALYZE doesn't support statement type: " + innerStatement.getClass().getSimpleName()); } } List<Expression> parameters = ImmutableList.of(); if (wrappedStatement instanceof Execute) { parameters = ((Execute) wrappedStatement).getParameters(); } validateParameters(statement, parameters); return new PreparedQuery(statement, parameters, Optional.ofNullable(prepareSql)); }</code><technical_language>Change this statement matches cast next line (even better)</technical_language>

Target:
public PreparedQuery prepareQuery(Session session, Statement wrappedStatement) throws ParsingException, PrestoException, SemanticException { Statement statement = wrappedStatement; Optional<String> prepareSql = Optional.empty(); if (statement instanceof Execute) { prepareSql = Optional.of(session.getPreparedStatementFromExecute((Execute) statement)); statement = sqlParser.createStatement(prepareSql.get(), createParsingOptions(session)); } if (statement instanceof Explain && ((Explain) statement).isAnalyze()) { Statement innerStatement = ((Explain) statement).getStatement(); Optional<QueryType> innerQueryType = StatementUtils.getQueryType(innerStatement.getClass()); if (!innerQueryType.isPresent() || innerQueryType.get() == QueryType.DATA_DEFINITION) { throw new PrestoException(NOT_SUPPORTED, "EXPLAIN ANALYZE doesn't support statement type: " + innerStatement.getClass().getSimpleName()); } } List<Expression> parameters = ImmutableList.of(); if (wrappedStatement instanceof Execute) { parameters = ((Execute) wrappedStatement).getParameters(); } validateParameters(statement, parameters); return new PreparedQuery(statement, parameters, prepareSql); }
Source:
<code>public void onInVisible(IObservableValue detailsViewModel, DataBindingContext dbc) { dispose(); setCheckboxVisible(false); <START> ((GridData)rememberTokenCheckbox.getLayoutData()).heightHint = 1; <END> }</code><technical_language>UIUtils.setVisibleAndExclude(boolean visible, final Control control)</technical_language>

Target:
public void onInVisible(IObservableValue detailsViewModel, DataBindingContext dbc) { dispose(); DataBindingUtils.dispose(rememberTokenBinding); }