auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Writer getWriter(XMLResource res, File dest) throws XMLDBException, FileNotFoundException { final Writer writer; if (dest.isDirectory()) { String fname = res.getId(); final File file = new File(dest, fname); <START> writer = new OutputStreamWriter(new FileOutputStream(file), UTF_8); <END> } else { writer = new OutputStreamWriter(new FileOutputStream(dest), UTF_8); } return writer; }</code><technical_language>biggie, for Java 8 this be: java final Path file = dest.toPath().resolve(fname); writer = Files.newBufferedWriter(file, UTF_8);</technical_language>

Target:
private Writer getWriter(XMLResource res, File dest) throws XMLDBException, IOException { final Writer writer; if (dest.isDirectory()) { final Path file = dest.toPath().resolve(res.getId()); writer = Files.newBufferedWriter(file, UTF_8); } else { writer = Files.newBufferedWriter(destFile.toPath(), UTF_8); } return writer; }
Source:
<code>public ValidationResult validateDiskNotAlreadyExistOnDB(List<DiskImage> images, boolean allowPartial, Map<Guid, Guid> imageToDestinationDomainMap, Map<Guid, String> failedDisksToImport) { for (DiskImage image : <START> new ArrayList<>(images)) <END> { DiskImage diskImage = getDiskImageDao().get(image.getImageId()); if (diskImage != null) { log.info("Disk '{}' with id '{}', already exist on storage domain '{}'", diskImage.getDiskAlias(), diskImage.getImageId(), diskImage.getStoragesNames().get(0)); if (!allowPartial) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_IMPORT_DISKS_ALREADY_EXIST, String.format("$diskAlias %s", diskImage.getDiskAlias())); } failedDisksToImport.putIfAbsent(image.getId(), image.getDiskAlias()); imageToDestinationDomainMap.remove(image.getId()); images.remove(image); } } return ValidationResult.VALID; }</code><technical_language>I this necessary</technical_language>

Target:
public ValidationResult validateDiskNotAlreadyExistOnDB(List<DiskImage> images, boolean allowPartial, Map<Guid, Guid> imageToDestinationDomainMap, Map<Guid, String> failedDisksToImport) { for (DiskImage image : images) { DiskImage diskImage = getDiskImageDao().get(image.getImageId()); if (diskImage != null) { log.info("Disk '{}' with id '{}', already exist on storage domain '{}'", diskImage.getDiskAlias(), diskImage.getImageId(), diskImage.getStoragesNames().get(0)); if (!allowPartial) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_IMPORT_DISKS_ALREADY_EXIST, String.format("$diskAlias %s", diskImage.getDiskAlias())); } failedDisksToImport.putIfAbsent(image.getId(), image.getDiskAlias()); imageToDestinationDomainMap.remove(image.getId()); images.remove(image); } } return ValidationResult.VALID; }
Source:
<code>public void testInvalidContentDRL() throws Exception { final String error102 = "[ERR 102] Line 1:7 mismatched input ''"; final String error107 = "[ERR 107] Line 1:0 mismatched input 'asd' " + "expecting one of the following tokens: " + "'[package, unit, import, global, declare, function, rule, query]'."; final String errorPackage = "Parser returned a null Package"; final String regexpExpression = "\\A\\[(.*?)\\][:]\\s"; validateResource(INVALID_CONTENT_DRL); Assertions.assertThat(validationMessages).hasSize(6); Assertions.assertThat(validationMessages .stream() .map(validationMessage -> validationMessage .getText() .replaceAll(regexpExpression, ""))) <START> .contains(error102, error107, errorPackage); <END> }</code><technical_language>Please containsOnly instead of contains good</technical_language>

Target:
public void testInvalidContentDRL() throws Exception { final String error102 = "[ERR 102] Line 1:7 mismatched input ''"; final String error107 = "[ERR 107] Line 1:0 mismatched input 'asd' " + "expecting one of the following tokens: " + "'[package, unit, import, global, declare, function, rule, query]'."; final String errorPackage = "Parser returned a null Package"; final String regexpExpression = "\\A\\[(.*?)\\][:]\\s"; validateResource(INVALID_CONTENT_DRL); Assertions.assertThat(validationMessages).hasSize(6); Assertions.assertThat(validationMessages .stream() .map(validationMessage -> validationMessage .getText() .replaceAll(regexpExpression, ""))) .containsOnly(error102, error107, errorPackage); }
Source:
<code>Stream<DynamicTest> runFastAndFullAssert() { <START> checkRunTurtleTests(); <END> CommonApp<Solution_> commonApp = createCommonApp(); ProblemFactory<Solution_> problemFactory = createProblemFactory(commonApp); return getSolutionFiles(commonApp).stream() .map(solutionFile -> DynamicTest.dynamicTest(solutionFile.getName(), () -> runFastAndFullAssert( buildSolverConfig(commonApp.getSolverConfigResource()), problemFactory.loadProblem(solutionFile) ))); }</code><technical_language>Thank for pointing out. sense. skipped tests count comparison this account ignores difference - fine</technical_language>

Target:
Stream<DynamicTest> runFastAndFullAssert() { CommonApp<Solution_> commonApp = createCommonApp(); ProblemFactory<Solution_> problemFactory = createProblemFactory(commonApp); return getSolutionFiles(commonApp).stream() .map(solutionFile -> dynamicTest(solutionFile.getName(), () -> runFastAndFullAssert( buildSolverConfig(commonApp.getSolverConfigResource()), problemFactory.loadProblem(solutionFile) ))); }
Source:
<code>public final void updateSliders() { getChart().getXYPlot().clearAnnotations(); final ValueAxis domainAxis = getChart().getXYPlot().getDomainAxis(); final ValueAxis rangeAxis = getChart().getXYPlot().getRangeAxis(); <START> final double SLIDER_CONST = 0.001; <END> if (horizontalMaximum - domainAxis.getRange().getUpperBound() > SLIDER_CONST) { horizontalSlider.setVisible(true); horizontalSlider.setEnabled(true); horizontalRatio = horizontalSlider.getMaximum() / horizontalMaximum; horizontalSlider.setThumb( (int) Math.round((domainAxis.getUpperBound() - domainAxis.getLowerBound()) * horizontalRatio)); horizontalSlider.setSelection((int) Math.round(domainAxis.getLowerBound() * horizontalRatio)); } else { horizontalSlider.setVisible(false); horizontalSlider.setEnabled(false); } if (verticalMaximum - rangeAxis.getRange().getUpperBound() > SLIDER_CONST) { verticalSlider.setVisible(true); verticalSlider.setEnabled(true); verticalRatio = verticalSlider.getMaximum() / verticalMaximum; verticalSlider.setThumb( (int) Math.round((rangeAxis.getUpperBound() - rangeAxis.getLowerBound()) * verticalRatio)); verticalSlider .setSelection((int) Math.round((verticalMaximum - rangeAxis.getUpperBound()) * verticalRatio)); } else { verticalSlider.setVisible(false); verticalSlider.setEnabled(false); } }</code><technical_language>SLIDER_CONST -> SHOW_SLIDER_EPSILON</technical_language>

Target:
public final void updateSliders() { getChart().getXYPlot().clearAnnotations(); final ValueAxis domainAxis = getChart().getXYPlot().getDomainAxis(); final ValueAxis rangeAxis = getChart().getXYPlot().getRangeAxis(); final double SLIDER_EPSILON = 0.001; if (Math.abs(horizontalMaximum - domainAxis.getRange().getUpperBound()) > SLIDER_EPSILON) { horizontalSlider.setVisible(true); horizontalSlider.setEnabled(true); horizontalRatio = horizontalSlider.getMaximum() / horizontalMaximum; horizontalSlider.setThumb( (int) Math.round((domainAxis.getUpperBound() - domainAxis.getLowerBound()) * horizontalRatio)); horizontalSlider.setSelection((int) Math.round(domainAxis.getLowerBound() * horizontalRatio)); } else { horizontalSlider.setVisible(false); horizontalSlider.setEnabled(false); } if (Math.abs(verticalMaximum - rangeAxis.getRange().getUpperBound()) > SLIDER_EPSILON) { verticalSlider.setVisible(true); verticalSlider.setEnabled(true); verticalRatio = verticalSlider.getMaximum() / verticalMaximum; verticalSlider.setThumb( (int) Math.round((rangeAxis.getUpperBound() - rangeAxis.getLowerBound()) * verticalRatio)); verticalSlider .setSelection((int) Math.round((verticalMaximum - rangeAxis.getUpperBound()) * verticalRatio)); } else { verticalSlider.setVisible(false); verticalSlider.setEnabled(false); } }
Source:
<code>public void onHighAlchemistJoin(cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent evt) { <START> if (true) END> { ChatComponentText joinMsg = new ChatComponentText(String.format( EnumChatFormatting.BLUE + StatCollector.translateToLocal("pe.server.high_alchemist") + EnumChatFormatting.GOLD + " %s " + EnumChatFormatting.BLUE + StatCollector.translateToLocal("pe.server.has_joined"), evt.player.getDisplayName())); MinecraftServer.getServer().getConfigurationManager().sendChatMsg(joinMsg); } }</code><technical_language>master</technical_language>

Target:
public void onHighAlchemistJoin(cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent evt) { if (PECore.uuids.contains((evt.player.getUniqueID().toString()))) { ChatComponentText joinMsg = new ChatComponentText(String.format( EnumChatFormatting.BLUE + StatCollector.translateToLocal("pe.server.high_alchemist") + EnumChatFormatting.GOLD + " %s " + EnumChatFormatting.BLUE + StatCollector.translateToLocal("pe.server.has_joined"), evt.player.getDisplayName())); MinecraftServer.getServer().getConfigurationManager().sendChatMsg(joinMsg); } }
Source:
<code>private static CompletableFuture<Exception> publishItem( final Producer<String, String> producer, final String topicId, final BatchItem item) throws EventPublishingException { try { final CompletableFuture<Exception> result = new CompletableFuture<>(); final ProducerRecord<String, String> kafkaRecord = new ProducerRecord<>( topicId, toKafkaPartition(item.getPartition()), item.getPartition(), item.getEvent().toString()); producer.send(kafkaRecord, ((metadata, exception) -> { <START> if (null != exception) { <END> item.setStep(EventPublishingStep.FAILED_PUBLISH); item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); result.complete(exception); } else { item.setStep(EventPublishingStep.PUBLISHED); item.updateStatusAndDetail(EventPublishingStatus.SUBMITTED, ""); result.complete(null); } })); return result; } catch (final InterruptException e) { Thread.currentThread().interrupt(); item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); throw new EventPublishingException("Error publishing message to kafka", e); } catch (final RuntimeException e) { item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); throw new EventPublishingException("Error publishing message to kafka", e); } }</code><technical_language>Unused method in code detected kafkaSendCallback</technical_language>

Target:
private static CompletableFuture<Exception> publishItem( final Producer<String, String> producer, final String topicId, final BatchItem item) throws EventPublishingException { try { final CompletableFuture<Exception> result = new CompletableFuture<>(); final ProducerRecord<String, String> kafkaRecord = new ProducerRecord<>( topicId, toKafkaPartition(item.getPartition()), item.getPartition(), item.getEvent().toString()); producer.send(kafkaRecord, ((metadata, exception) -> { if (null != exception) { item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); result.complete(exception); } else { item.updateStatusAndDetail(EventPublishingStatus.SUBMITTED, ""); result.complete(null); } })); return result; } catch (final InterruptException e) { Thread.currentThread().interrupt(); item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); throw new EventPublishingException("Error publishing message to kafka", e); } catch (final RuntimeException e) { item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); throw new EventPublishingException("Error publishing message to kafka", e); } }
Source:
<code>private void postNicInit() { initSelectedType(); getName().setEntity(AsyncDataProvider.getNewNicName(getVmNicList())); initMAC(); if (!hotPlugSupported) { getPlugged().setChangeProhibitionReason(ConstantsManager.getInstance() .getMessages() .hotPlugNotSupported(getClusterCompatibilityVersion().toString())); } <START> getPlugged().setIsChangable(hotPlugSupported || vmStatus.equals(VMStatus.Down)); <END> getPlugged().setEntity(hotPlugSupported || vmStatus.equals(VMStatus.Down)); initLinked(); initProfiles(); initCommands(); }</code><technical_language>BaseEditVmInterfaceModel, happen in VmInterfaceModel</technical_language>

Target:
private void postNicInit() { initSelectedType(); getName().setEntity(AsyncDataProvider.getNewNicName(getVmNicList())); initMAC(); if (!hotPlugSupported) { getPlugged().setChangeProhibitionReason(ConstantsManager.getInstance() .getMessages() .hotPlugNotSupported(getClusterCompatibilityVersion().toString())); } getPlugged().setIsChangable(allowHotPlug()); getPlugged().setEntity(allowHotPlug()); initLinked(); initProfiles(); initCommands(); }
Source:
<code>private PreUploadHookChain(List<PreUploadHook> hooks) { this.hooks = new <START> ArrayList<>(hooks); <END> }</code><technical_language>previous commit - for consistency, Collections.unmodifiableList</technical_language>

Target:
private PreUploadHookChain(List<PreUploadHook> hooks) { this.hooks = Collections.unmodifiableList(hooks); }
Source:
<code>public static String removeEnclosingSquareBrackets(String str) { <START> if (str != null) { <END> String trimmedString = str.trim(); if (trimmedString.startsWith("[") && trimmedString.endsWith("]")) { return trimmedString.substring(1, trimmedString.length() - 1).trim(); } } return str; }</code><technical_language>a guard condition reduce nesting</technical_language>

Target:
public static String removeEnclosingSquareBrackets(String str) { if (str == null) { return null; } if (!str.startsWith("[") || !str.endsWith("]")) { return str; } return str.substring(1, str.length() - 1); }
Source:
<code>private List<AuditEntry> getRuleHistory( final String dataSourceName, final String interval, final Integer count ) throws IllegalArgumentException { <START> Interval theInterval = interval == null ? null : new Interval(interval); <END> if (theInterval == null && count != null) { if (dataSourceName != null) { return auditManager.fetchAuditHistory(dataSourceName, "rules", count); } return auditManager.fetchAuditHistory("rules", count); } if (dataSourceName != null) { return auditManager.fetchAuditHistory(dataSourceName, "rules", theInterval); } return auditManager.fetchAuditHistory("rules", theInterval); }</code><technical_language>move this line if statement below</technical_language>

Target:
private List<AuditEntry> getRuleHistory( final String dataSourceName, final String interval, final Integer count ) throws IllegalArgumentException { if (interval == null && count != null) { if (dataSourceName != null) { return auditManager.fetchAuditHistory(dataSourceName, "rules", count); } return auditManager.fetchAuditHistory("rules", count); } Interval theInterval = interval == null ? null : new Interval(interval); if (dataSourceName != null) { return auditManager.fetchAuditHistory(dataSourceName, "rules", theInterval); } return auditManager.fetchAuditHistory("rules", theInterval); }
Source:
<code>public void setCustomDisplayName(String name) { <START> ((TileEntityLockableLoot) (Object) this).setCustomName(name); <END> }</code><technical_language>Shadow this method instead</technical_language>

Target:
public void setCustomDisplayName(String name) { setCustomName(name); }
Source:
<code>private static void handleDeleteDialog(boolean deleteResources, SWTWorkbenchBot bot) { SWTBotShell parentShell = bot.shell("Delete Resources"); if (deleteResources) { parentShell.setFocus(); final SWTBotCheckBox checkBox = <START> bot.checkBox(); <END> bot.waitUntil(Conditions.widgetIsEnabled(checkBox)); checkBox.click(); } final SWTBotButton okButton = bot.button("OK"); bot.waitUntil(Conditions.widgetIsEnabled(okButton)); okButton.click(); bot.waitWhile(new DefaultCondition() { @Override public boolean test() throws Exception { boolean deleteShellFound = false; for (SWTBotShell shell : bot.shells()) { if (shell.getText().equals("Delete Resources")) { deleteShellFound = true; if (shell.widget != parentShell.widget) { shell.bot().button("Continue").click(); } } } return deleteShellFound; } @Override public String getFailureMessage() { return "Unable to delete project the project"; } }); }</code><technical_language>safer if parentShell.bot(), this search in active shell gave focus..</technical_language>

Target:
private static void handleDeleteDialog(boolean deleteResources, SWTWorkbenchBot bot) { SWTBotShell parentShell = bot.shell("Delete Resources"); if (deleteResources) { parentShell.setFocus(); final SWTBotCheckBox checkBox = parentShell.bot().checkBox(); checkBox.click(); } final SWTBotButton okButton = parentShell.bot().button("OK"); okButton.click(); bot.waitWhile(new DefaultCondition() { @Override public boolean test() throws Exception { boolean deleteShellFound = false; for (SWTBotShell shell : bot.shells()) { if (shell.getText().equals("Delete Resources")) { deleteShellFound = true; if (shell.widget != parentShell.widget) { shell.bot().button("Continue").click(); } } } return deleteShellFound; } @Override public String getFailureMessage() { return "Delete Resources shell did not close"; } }); }
Source:
<code>protected IndentLevel getChildrenExpectedIndent() { final IndentLevel expectedIndent = new IndentLevel(getIndent(), getIndentCheck().getArrayInitIndent(), <START> getLineWrappingIndentation()); <END> final int firstLine = getFirstLine(Integer.MAX_VALUE, getListChild()); final int lcurlyPos = expandedTabsColumnNo(getLeftCurly()); final int firstChildPos = getNextFirstNonBlankOnLineAfter(firstLine, lcurlyPos); if (firstChildPos >= 0) { expectedIndent.addAcceptedIndent(firstChildPos); expectedIndent.addAcceptedIndent(lcurlyPos + getLineWrappingIndentation()); } return expectedIndent; }</code><technical_language>I assume this is a code simplification change necessary this issue</technical_language>

Target:
protected IndentLevel getChildrenExpectedIndent() { final IndentLevel expectedIndent = new IndentLevel(getIndent(), getIndentCheck().getArrayInitIndent(), getIndentCheck().getLineWrappingIndentation()); final int firstLine = getFirstLine(Integer.MAX_VALUE, getListChild()); final int lcurlyPos = expandedTabsColumnNo(getLeftCurly()); final int firstChildPos = getNextFirstNonBlankOnLineAfter(firstLine, lcurlyPos); if (firstChildPos >= 0) { expectedIndent.addAcceptedIndent(firstChildPos); expectedIndent.addAcceptedIndent(lcurlyPos + getLineWrappingIndentation()); } return expectedIndent; }
Source:
<code>protected URL[] getRedirectURLs(RepoObject repoObject) throws RepoException{ URL[] urls = null; try { String[] paths = getFilePaths(repoObject); if( paths != null && paths.length > 0 ) { int pathCount = paths.length; urls = new URL[pathCount]; for (int i = 0; i < pathCount; i++) { urls[i] = new URL(paths[i]); } } else { urls = new URL[0]; repoObject.setStatus(Status.MISSING_DATA); log.info(" Missing Data when trying to fetch reproxy url, key: , bucket name: , content checksum: , version number: ", repoObject.getKey(), repoObject.getBucketName(), repoObject.getChecksum(), repoObject.getVersionNumber()); } <START> } catch (MalformedURLException e) { <END> throw new RepoException(RepoException.Type.ServerError); } catch (Exception e) { throw new RepoException(e); } return urls; }</code><technical_language>This caught in a smaller try block</technical_language>

Target:
protected URL[] getRedirectURLs(RepoObject repoObject) throws RepoException{ URL[] urls = new URL[0]; try { String[] paths = getFilePaths(repoObject); if(paths.length > 0) { int pathCount = paths.length; urls = new URL[pathCount]; for (int i = 0; i < pathCount; i++) { urls[i] = new URL(paths[i]); } } } catch (RepoException e){ if(RepoException.Type.ObjectFilePathMissing.equals(e.getType()) ) { repoObject.setStatus(Status.MISSING_DATA); log.error(" Missing Data when trying to fetch reproxy url, key: , bucket name: , content checksum: , version number: ", repoObject.getKey(), repoObject.getBucketName(), repoObject.getChecksum(), repoObject.getVersionNumber()); } else { throw e; } } catch (MalformedURLException e) { throw new RepoException(RepoException.Type.ServerError); } catch (Exception e) { throw new RepoException(e); } return urls; }
Source:
<code>private ExecRow buildTemplateRow(DataTypeDescriptor[] dataTypeDescriptors) throws StandardException{ ExecRow row = new ValueRow(dataTypeDescriptors.length); int outputCol = 0; for (DataTypeDescriptor dtd : dataTypeDescriptors) { row.setColumn(outputCol + 1, dtd.getNull()); if (row.getColumn(outputCol + 1 ) instanceof SQLDecimal) { ((SQLDecimal) row.getColumn(outputCol + 1)).setPrecision(dtd.getPrecision()); ((SQLDecimal) row.getColumn(outputCol + 1)).setScale(dtd.getScale()); } <START> outputCol++; <END> } return row; }</code><technical_language>null SQLDecimal precision scale, need set</technical_language>

Target:
private ExecRow buildTemplateRow(DataTypeDescriptor[] dataTypeDescriptors) throws StandardException{ ExecRow row = new ValueRow(dataTypeDescriptors.length); int outputCol = 0; for (DataTypeDescriptor dtd : dataTypeDescriptors) { row.setColumn(outputCol + 1, dtd.getNull()); outputCol++; } return row; }
Source:
<code>public Map<String, String> getExtensionArtifacts(final String extensionName) throws FalconException { Map<String, String> extensionFileMap = new HashMap<>(); Path extensionPath; try { RemoteIterator<LocatedFileStatus> fileStatusListIterator; if (AbstractExtension.isExtensionTrusted(extensionName)){ extensionPath = new Path(storePath, extensionName.toLowerCase()); fileStatusListIterator = fs.listFiles(extensionPath, true); }else{ ExtensionBean extensionBean = metaStore.getDetail(extensionName); extensionPath = new Path(extensionBean.getLocation()); FileSystem fileSystem = getHdfsFileSystem(extensionBean.getLocation()); fileStatusListIterator = fileSystem.listFiles(extensionPath, true); } if (!fileStatusListIterator.hasNext()) { <START> throw new StoreAccessException(new Exception(" For extension " + extensionName <END> + " there are no artifacts at the extension store path " + storePath)); } while (fileStatusListIterator.hasNext()) { LocatedFileStatus fileStatus = fileStatusListIterator.next(); Path filePath = fileStatus.getPath(); extensionFileMap.put(filePath.getName(), filePath.toString()); } } catch (IOException e) { throw new StoreAccessException(e); } return extensionFileMap; }</code><technical_language>I this is part of patch, but, while it. fix this nested exception creation, please</technical_language>

Target:
public Map<String, String> getExtensionArtifacts(final String extensionName) throws FalconException { Map<String, String> extensionFileMap = new HashMap<>(); Path extensionPath; try { RemoteIterator<LocatedFileStatus> fileStatusListIterator; if (AbstractExtension.isExtensionTrusted(extensionName)){ extensionPath = new Path(storePath, extensionName.toLowerCase()); fileStatusListIterator = fs.listFiles(extensionPath, true); }else{ ExtensionBean extensionBean = metaStore.getDetail(extensionName); extensionPath = new Path(extensionBean.getLocation()); FileSystem fileSystem = getHdfsFileSystem(extensionBean.getLocation()); fileStatusListIterator = fileSystem.listFiles(extensionPath, true); } if (!fileStatusListIterator.hasNext()) { throw new StoreAccessException(" For extension " + extensionName + " there are no artifacts at the extension store path " + storePath); } while (fileStatusListIterator.hasNext()) { LocatedFileStatus fileStatus = fileStatusListIterator.next(); Path filePath = fileStatus.getPath(); extensionFileMap.put(filePath.getName(), filePath.toString()); } } catch (IOException e) { throw new StoreAccessException(e); } return extensionFileMap; }
Source:
<code>private void score(final String id) { if (id.equals(Plus.PeopleApi.getCurrentPerson(getGoogleApiClient()).getId())) { Toast.makeText(this, R.string.arrow_selfie, Toast.LENGTH_LONG).show(); return; } <START> storeInAppState(id); <END> storeInSnapshot(id, null, 0); }</code><technical_language>Do this is working? I thought AppState API is readonly now. store data here. if migration code is working well, storing snapshot sufficient</technical_language>

Target:
private void score(final String id) { if (id.equals(Plus.PeopleApi.getCurrentPerson(getGoogleApiClient()).getId())) { Toast.makeText(this, R.string.arrow_selfie, Toast.LENGTH_LONG).show(); return; } new StoreSnapshotTask(getGoogleApiClient()).execute(id); }
Source:
<code>public static boolean isShowingEntireContents(StyledText widget) { if (widget.getTopPixel() != 0) return false; int lastVisiblePixel= computeLastVisiblePixel(widget); int lineCount= widget.getLineCount(); <START> if (lineCount > 400) { <END> int linePixel400= widget.getLinePixel(400); if (linePixel400 > lastVisiblePixel) { return false; } } int lastPossiblePixel= widget.getLinePixel(lineCount); return lastPossiblePixel <= lastVisiblePixel; }</code><technical_language>I this arbitrary limit of 400. Instead, I check index of visible line is lineCount. about: public static boolean isShowingEntireContents(StyledText widget) { if (widget.getTopPixel() != 0) // more efficient shortcut return false; int lastVisiblePixel= computeLastVisiblePixel(widget); int bottom= widget.getLineIndex(lastVisiblePixel); if (bottom + 1 < widget.getLineCount()) { // more lines return false; } // Check line is fully visible int bottomTopPixel= getLinePixel(widget, bottom); int bottomHeight= computeLineHeight(widget, bottom); return bottomTopPixel + bottomHeight <= lastVisiblePixel; } faster worst compute line heights for visible lines, need arbitrary magic number</technical_language>

Target:
public static boolean isShowingEntireContents(StyledText widget) { if (widget.getTopPixel() != 0) return false; int lastVisiblePixel= computeLastVisiblePixel(widget); int bottom= widget.getLineIndex(lastVisiblePixel); if (bottom + 1 < widget.getLineCount()) return false; int bottomLastPixel= getLinePixel(widget, bottom + 1) - 1; return bottomLastPixel <= lastVisiblePixel; }
Source:
<code><START> public InvalidSecretFormatException () { } <END></code><technical_language>spaces ( in method names/calls</technical_language>

Target:
public InvalidSecretFormatException() { super(); }
Source:
<code>private void deleteRelationIfExists(@Nonnull final SQLiteConnection sqliteConnection, @Nonnull final RelationKey relation) throws CatalogException { try { SQLiteStatement statement = sqliteConnection <START> .prepare("DELETE FROM relations WHERE user_name=? AND program_name=? AND relation_name=? AND tombstone=1;"); <END> statement.bind(1, relation.getUserName()); statement.bind(2, relation.getProgramName()); statement.bind(3, relation.getRelationName()); statement.stepThrough(); statement.dispose(); statement = null; } catch (final SQLiteException e) { throw new CatalogException(e); } }</code><technical_language>do delete entries relation_schema table</technical_language>

Target:
private void deleteRelationIfExists(@Nonnull final SQLiteConnection sqliteConnection, @Nonnull final RelationKey relation) throws CatalogException { try { SQLiteStatement statement = sqliteConnection .prepare("DELETE FROM relations WHERE user_name=? AND program_name=? AND relation_name=? AND is_deleted=1;"); statement.bind(1, relation.getUserName()); statement.bind(2, relation.getProgramName()); statement.bind(3, relation.getRelationName()); statement.stepThrough(); statement.dispose(); statement = null; } catch (final SQLiteException e) { throw new CatalogException(e); } }
Source:
<code><START> protected String getCharset() { <END> return charset; }</code><technical_language>Ditto. suggestion String getCharset() { (or remove private field)</technical_language>

Target:
String getCharset() { return charset; }
Source:
<code>public boolean next() throws IOException { <START> while ( !exhausted() ) <END> { if ( currentChunkExhausted() ) { readNextChunk(); } chunkCursor++; assert chunkCursor <= chunkLength; return true; } return false; }</code><technical_language>if</technical_language>

Target:
public boolean next() throws IOException { if ( !exhausted() ) { if ( currentChunkExhausted() ) { readNextChunk(); } currentChunkTransaction = chunkTransactions.pop(); return true; } return false; }
Source:
<code>private List<ParquetFileReader> getReaders(List<InputFile> inputFiles) throws IOException { <START> List<ParquetFileReader> readers = new ArrayList<>(); <END> for (InputFile inputFile : inputFiles) { readers.add(ParquetFileReader.open(inputFile)); } return readers; }</code><technical_language>nit: ArrayList size is in advance, nice add constructor parameter avoid resize</technical_language>

Target:
private List<ParquetFileReader> getReaders(List<InputFile> inputFiles) throws IOException { List<ParquetFileReader> readers = new ArrayList<>(inputFiles.size()); for (InputFile inputFile : inputFiles) { readers.add(ParquetFileReader.open(inputFile)); } return readers; }
Source:
<code>public ActionResult execute() { <START> gateKeeper.verifyInstructorPrivileges(account); <END> InstructorCoursesPageData data = new InstructorCoursesPageData(account, sessionToken); try { List<InstructorAttributes> instructorList = logic.getInstructorsForGoogleId(data.account.googleId); logic.deleteAllCourses(instructorList); String statusMessage = Const.StatusMessages.COURSE_ALL_DELETED; statusToUser.add(new StatusMessage(statusMessage, StatusMessageColor.SUCCESS)); statusToAdmin = "All courses deleted"; } catch (Exception e) { setStatusForException(e); } if (isRedirectedToHomePage()) { return createRedirectResult(Const.ActionURIs.INSTRUCTOR_HOME_PAGE); } return createRedirectResult(Const.ActionURIs.INSTRUCTOR_COURSES_PAGE); }</code><technical_language>Instead of simply verifying if current user is instructor, follow format of instructorCourseDeleteAction.java check more strictly for instructor permission modify course? this is a soft delete, permission levels apply</technical_language>

Target:
public ActionResult execute() { InstructorCoursesPageData data = new InstructorCoursesPageData(account, sessionToken); List<InstructorAttributes> instructorList = logic.getInstructorsForGoogleId(data.account.googleId); for (InstructorAttributes instructor : instructorList) { CourseAttributes course = logic.getRecoveryCourseForInstructor(instructor); if (course != null) { gateKeeper.verifyAccessible(instructor, course, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_COURSE); } } try { logic.deleteAllCourses(instructorList); String statusMessage = Const.StatusMessages.COURSE_ALL_DELETED; statusToUser.add(new StatusMessage(statusMessage, StatusMessageColor.SUCCESS)); statusToAdmin = "All courses deleted"; } catch (Exception e) { setStatusForException(e); } return createRedirectResult(Const.ActionURIs.INSTRUCTOR_COURSES_PAGE); }
Source:
<code>public static void register(AggregationImplModule mod) { BinaryOperator<Long> add = Math::addExact; BinaryOperator<Long> sub = Math::subtractExact; mod.register( Signature.aggregate( NAME, DataTypes.FLOAT.getTypeSignature(), DataTypes.FLOAT.getTypeSignature()), args -> new SumAggregation<>(DataTypes.FLOAT, Float::sum, (n1, n2) -> n1 - n2) ); mod.register( Signature.aggregate( NAME, DataTypes.DOUBLE.getTypeSignature(), DataTypes.DOUBLE.getTypeSignature()), args -> new SumAggregation<>(DataTypes.DOUBLE, Double::sum, (n1, n2) -> n1 - n2) ); for (var supportedType : List.of(DataTypes.BYTE, DataTypes.SHORT, DataTypes.INTEGER, DataTypes.LONG)) { mod.register( Signature.aggregate( NAME, supportedType.getTypeSignature(), <START> supportedType.getTypeSignature()), <END> args -> new SumAggregation<>(supportedType, DataTypes.LONG, add, sub) ); } }</code><technical_language>return type is LONG</technical_language>

Target:
public static void register(AggregationImplModule mod) { BinaryOperator<Long> add = Math::addExact; BinaryOperator<Long> sub = Math::subtractExact; mod.register( Signature.aggregate( NAME, DataTypes.FLOAT.getTypeSignature(), DataTypes.FLOAT.getTypeSignature()), args -> new SumAggregation<>(DataTypes.FLOAT, Float::sum, (n1, n2) -> n1 - n2) ); mod.register( Signature.aggregate( NAME, DataTypes.DOUBLE.getTypeSignature(), DataTypes.DOUBLE.getTypeSignature()), args -> new SumAggregation<>(DataTypes.DOUBLE, Double::sum, (n1, n2) -> n1 - n2) ); for (var supportedType : List.of(DataTypes.BYTE, DataTypes.SHORT, DataTypes.INTEGER, DataTypes.LONG)) { mod.register( Signature.aggregate( NAME, supportedType.getTypeSignature(), DataTypes.LONG.getTypeSignature()), args -> new SumAggregation<>(supportedType, DataTypes.LONG, add, sub) ); } }
Source:
<code>public List<PluginWrapper> getPlugins() { <START> return plugins; <END> }</code><technical_language>Wrap Collections#unmodifyableList()? I assume read-only</technical_language>

Target:
public List<PluginWrapper> getPlugins() { return Collections.unmodifiableList(plugins); }
Source:
<code>public void validateNameUniqueness(Map<String, JobConfig> visitedConfigs) { <START> if (name() == null) return; <END> String currentJob = name().toLower(); if (visitedConfigs.containsKey(CaseInsensitiveString.str(name())) || visitedConfigs.containsKey(currentJob)) { JobConfig conflictingConfig = visitedConfigs.get(currentJob); conflictingConfig.addUniquenessViolationMessage(); this.addUniquenessViolationMessage(); } else { visitedConfigs.put(currentJob, this); } }</code><technical_language>StringUtil.isBlank instead. need rest of if name is empty string too</technical_language>

Target:
public void validateNameUniqueness(Map<String, JobConfig> visitedConfigs) { if (StringUtil.isBlank(CaseInsensitiveString.str(name()))) return; String currentJob = name().toLower(); if (visitedConfigs.containsKey(CaseInsensitiveString.str(name())) || visitedConfigs.containsKey(currentJob)) { JobConfig conflictingConfig = visitedConfigs.get(currentJob); conflictingConfig.addUniquenessViolationMessage(); this.addUniquenessViolationMessage(); } else { visitedConfigs.put(currentJob, this); } }
Source:
<code>public void should_pass_on_equal_files() throws Exception { File actual = createDeleteOnExitTempFileWithContent("assertJ"); <START> File expected = createDeleteOnExitTempFileWithContent("assertJ"); <END> assertThat(actual).hasSameBinaryContentAs(expected); }</code><technical_language>add WHEN/THEN sections shown in <LINK_0></technical_language>

Target:
public void should_pass_on_equal_files() throws Exception { File actual = createTempFileWithContent("assertJ"); File expected = createTempFileWithContent("assertJ"); assertThat(actual).hasSameBinaryContentAs(expected); }
Source:
<code>public boolean waitFor(LogOffset offset, String group, Duration timeout) throws InterruptedException { <START> boolean ret = false; <END> if (!name.equals(offset.partition().name())) { throw new IllegalArgumentException(name + " can not wait for an offset with a different Log: " + offset); } TopicPartition topicPartition = new TopicPartition(topic, offset.partition().partition()); try { ret = isProcessed(group, topicPartition, offset.offset()); if (ret) { return true; } final long timeoutMs = timeout.toMillis(); final long deadline = System.currentTimeMillis() + timeoutMs; final long delay = Math.min(100, timeoutMs); while (!ret && System.currentTimeMillis() < deadline) { Thread.sleep(delay); ret = isProcessed(group, topicPartition, offset.offset()); } return ret; } finally { if (log.isDebugEnabled()) { log.debug("waitFor " + offset + "/" + group + " returns: " + ret); } } }</code><technical_language>declare out in try</technical_language>

Target:
public boolean waitFor(LogOffset offset, String group, Duration timeout) throws InterruptedException { boolean ret = false; if (!name.equals(offset.partition().name())) { throw new IllegalArgumentException(name + " can not wait for an offset with a different Log: " + offset); } TopicPartition topicPartition = new TopicPartition(topic, offset.partition().partition()); try { ret = isProcessed(group, topicPartition, offset.offset()); if (ret) { return true; } long timeoutMs = timeout.toMillis(); long deadline = System.currentTimeMillis() + timeoutMs; long delay = Math.min(100, timeoutMs); while (!ret && System.currentTimeMillis() < deadline) { Thread.sleep(delay); ret = isProcessed(group, topicPartition, offset.offset()); } return ret; } finally { if (log.isDebugEnabled()) { log.debug("waitFor " + offset + "/" + group + " returns: " + ret); } } }
Source:
<code>public void setReadTimeout(final int readTimeout) { if (readTimeout < 1) { <START> throw new IllegalArgumentException("Read timeout must be positive."); <END> } this.readTimeout = readTimeout; }</code><technical_language>minor: if is for 0 passed throw IllegalArgumentException, error message "must greater 0" "must positive"</technical_language>

Target:
public void setReadTimeout(final int readTimeout) { if (readTimeout < 1) { throw new IllegalArgumentException("Read timeout must be greater than zero."); } this.readTimeout = readTimeout; }
Source:
<code>public SanctumOfCalmWaters(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{3}{U}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.SHRINE); <START> Ability ability = new BeginningOfPreCombatMainTriggeredAbility(new DrawCardSourceControllerEffect(new PermanentsOnBattlefieldCount(filter)), TargetController.YOU, true); <END> Effect effect = new DiscardControllerEffect(1); effect.setText("If you do, discard a card"); ability.addEffect(effect); this.addAbility(ability); }</code><technical_language>need set text auto generated correctly</technical_language>

Target:
public SanctumOfCalmWaters(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{3}{U}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.SHRINE); Ability ability = new BeginningOfPreCombatMainTriggeredAbility(new DrawCardSourceControllerEffect(new PermanentsOnBattlefieldCount(new FilterControlledPermanent(SubType.SHRINE))) .setText("At the beginning of your precombat main phase, you may draw X cards, where X is the number of Shrines you control"), TargetController.YOU, true); ability.addEffect(new DiscardControllerEffect(1).setText("If you do, discard a card")); this.addAbility(ability); }
Source:
<code>private void saveFile(Uri sourceUri, File externalFile) { final int chunkSize = 1024; byte[] imageData = new byte[chunkSize]; InputStream in = null; OutputStream out = null; try { in = getContentResolver().openInputStream(sourceUri); out = new FileOutputStream(externalFile); int bytesRead; while((bytesRead = in.read(imageData)) > 0) { <START> out.write(Arrays.copyOfRange(imageData, 0, Math.max(0, bytesRead))); <END> } } catch(IOException ex) { Toast.makeText(this, "Saving picture failed.", Toast.LENGTH_SHORT).show(); } finally { try { if(in != null) { in.close(); } if(out != null) { out.close(); } } catch(IOException e) { throw new RuntimeException(e); } } }</code><technical_language>copy temp file rename. get a temp file in dir naming "temp" + System.currentTimeMillis() + ".png" This is atomic operation saving files</technical_language>

Target:
private void saveFile(Uri sourceUri, File externalFile) { final int chunkSize = 1024; byte[] imageData = new byte[chunkSize]; InputStream in = null; OutputStream out = null; try { File temp = new File(getFilesDir(), "temp" + System.currentTimeMillis() +".jpg"); in = getContentResolver().openInputStream(sourceUri); out = new FileOutputStream(temp); int bytesRead; while((bytesRead = in.read(imageData)) > 0) { out.write(Arrays.copyOfRange(imageData, 0, Math.max(0, bytesRead))); } temp.renameTo(externalFile); } catch(IOException ex) { Log.e(TAG, ex.getMessage()); } finally { try { if(in != null) { in.close(); } if(out != null) { out.close(); } } catch(IOException e) { Log.e(TAG, "error closing input and output stream"); } } }
Source:
<code>private MetricManager(@Parameter(Parameters.DashboardHostAddress.class) final String hostAddress, @Parameter(Parameters.DashboardPort.class) final int port) { this.workerEvalParams = Collections.synchronizedMap(new HashMap<>()); this.serverEvalParams = Collections.synchronizedMap(new HashMap<>()); this.metricCollectionEnabled = false; this.numBlockByEvalIdForWorker = null; this.numBlockByEvalIdForServer = null; <START> boolean tempDashboardEnabled = !hostAddress.equals("INVALID"); <END> CloseableHttpAsyncClient tempReusableHttpClient = null; if (tempDashboardEnabled) { this.dashboardURL = "http://" + hostAddress + ":" + port + "/"; try { final PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor()); connectionManager.setMaxTotal(Integer.MAX_VALUE); tempReusableHttpClient = HttpAsyncClients.custom().setConnectionManager(connectionManager).build(); tempReusableHttpClient.start(); runMetricsSenderThread(); } catch (IOReactorException e) { LOG.log(Level.WARNING, "Dashboard: ", e); tempDashboardEnabled = false; tempReusableHttpClient = null; } } else { LOG.log(Level.INFO, "Dashboard is not in use"); this.dashboardURL = null; } this.reusableHttpClient = tempReusableHttpClient; this.dashboardEnabled = tempDashboardEnabled; }</code><technical_language>I think, good DashboardHostAddress judge dashboard is turned not. add a DashBoard boolean named parameter represent it. Setting default of DashboardHostAddress localhost better. please choose port number set default of DashboardPort</technical_language>

Target:
private MetricManager(@Parameter(Parameters.DashboardHostAddress.class) final String hostAddress, @Parameter(Parameters.DashboardPort.class) final int port) { this.workerEvalParams = Collections.synchronizedMap(new HashMap<>()); this.serverEvalParams = Collections.synchronizedMap(new HashMap<>()); this.metricCollectionEnabled = false; this.numBlockByEvalIdForWorker = null; this.numBlockByEvalIdForServer = null; this.dashboardSetupStatus = initDashboard(hostAddress, port); }
Source:
<code>private void goRunTest(Project project, String args, ArtifactoryBuildInfoClientBuilder clientBuilder, String repo) { Path projectDir = null; try { CommandExecutor goCommandExecutor = new CommandExecutor("go", null); List<String> goEnvArgs = new ArrayList<>(); goEnvArgs.add("env"); <START> goCommandExecutor.exeCommand(PROJECTS_ROOT.toFile(), goEnvArgs, log); <END> projectDir = createProjectDir(project); GoRun goRun = new GoRun(args, projectDir, clientBuilder, repo, getUsername(), getPassword(), getLog(), env); Build build = goRun.execute(); assertNotNull(build); assertEquals(build.getModules().size(), 1); Module module = build.getModules().get(0); assertEquals(module.getId(), project.getModuleId()); Set<String> moduleDependencies = module.getDependencies().stream().map(Dependency::getId).collect(Collectors.toSet()); assertEquals(moduleDependencies, project.dependencies); } catch (Exception e) { fail(ExceptionUtils.getStackTrace(e)); } finally { if (projectDir != null) { FileUtils.deleteQuietly(projectDir.toFile()); } } }</code><technical_language>remove env print</technical_language>

Target:
private void goRunTest(Project project, String args, ArtifactoryBuildInfoClientBuilder clientBuilder, String repo) { Path projectDir = null; try { projectDir = createProjectDir(project); GoRun goRun = new GoRun(args, projectDir, clientBuilder, repo, getUsername(), getPassword(), getLog(), env); Build build = goRun.execute(); assertNotNull(build); assertEquals(build.getModules().size(), 1); Module module = build.getModules().get(0); assertEquals(module.getId(), project.getModuleId()); Set<String> moduleDependencies = module.getDependencies().stream().map(Dependency::getId).collect(Collectors.toSet()); assertEquals(moduleDependencies, project.dependencies); } catch (Exception e) { fail(ExceptionUtils.getStackTrace(e)); } finally { if (projectDir != null) { FileUtils.deleteQuietly(projectDir.toFile()); } } }
Source:
<code>private boolean isClusterOverloaded() { int overloadedTaskNum = 0; for (final Map.Entry<String, TaskStats> entry : taskStatsMap.entrySet()) { if (entry.getValue().getTaskLoad() > overloadedTaskLoadThreshold) { overloadedTaskNum += 1; } } <START> final double overloadedTaskRate = overloadedTaskNum / taskStatsMap.getTaskList().size(); <END> return overloadedTaskRate > scaleOutOverloadedTaskRate; }</code><technical_language>rate -> ratio</technical_language>

Target:
private boolean isClusterOverloaded() { int overloadedTaskNum = 0; for (final Map.Entry<String, TaskStats> entry : taskStatsMap.entrySet()) { if (entry.getValue().getTaskLoad() > overloadedTaskLoadThreshold) { overloadedTaskNum += 1; } } final double overloadedTaskRatio = overloadedTaskNum / taskStatsMap.getTaskList().size(); return overloadedTaskRatio > scaleOutOverloadedTaskRatio; }
Source:
<code>public void onClick(View v) { mActivityHelper .getCurrentUser() .unlink(mProviderId) .addOnFailureListener( new TaskFailureLogger(TAG, "Failed to unlink " + mProviderId)) <START> .addOnSuccessListener(new OnSuccessListener<AuthResult>() { <END> @Override public void onSuccess(AuthResult result) { populateLinkedAccounts(); } }); }</code><technical_language>This OnSuccessListener activity scoped (addOnSuccessListener(activity, listener). want a step this class static hold a WeakReference Activity, is checks in onClick launching anything</technical_language>

Target:
public void onClick(View v) { mActivityHelper .getCurrentUser() .unlink(mProviderId) .addOnFailureListener( new TaskFailureLogger(TAG, "Failed to unlink " + mProviderId)) .addOnSuccessListener( AccountSettingsActivity.this, new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult result) { populateLinkedAccounts(); } }); }
Source:
<code>private String combineFlags(Iterable<Flag> flags) { List<String> flagNames = new ArrayList<String>(); for (Flag flag : flags) { <START> if( !flag.equals(Flag.RECENT) ) <END> flagNames.add(flag.realName()); } return combine(flagNames.toArray(new String[flagNames.size()]), ' '); }</code><technical_language>curly brackets avoid goto fail :-)</technical_language>

Target:
private String combineFlags(Iterable<Flag> flags) { List<String> flagNames = new ArrayList<String>(); for (Flag flag : flags) { if (!flag.equals(Flag.RECENT)) { flagNames.add(flag.realName()); } } return combine(flagNames.toArray(new String[flagNames.size()]), ' '); }
Source:
<code>public CacheResult get(FileReadRequest request, byte[] buffer, int offset, CacheQuota cacheQuota) { boolean result = read(request, buffer, offset); if (!result && ifExceedQuota(cacheQuota, request)) { stats.incrementQuotaExceed(); return CacheResult.CACHE_QUOTA_EXCEED; } <START> <END> try { cache.get(request.getPath(), cacheQuota::getIdentifier); } catch (ExecutionException e) { } if (result) { stats.incrementCacheHit(); return CacheResult.IN_CACHE; } stats.incrementCacheMiss(); return CacheResult.NOT_IN_CACHE; }</code><technical_language>I discussed this. if calculate put operation</technical_language>

Target:
public CacheResult get(FileReadRequest request, byte[] buffer, int offset, CacheQuota cacheQuota) { boolean result = read(request, buffer, offset); if (!result && ifExceedQuota(cacheQuota, request)) { stats.incrementQuotaExceed(); return CacheResult.CACHE_QUOTA_EXCEED; } try { cache.get(request.getPath(), cacheQuota::getIdentifier); } catch (ExecutionException e) { } if (result) { stats.incrementCacheHit(); return CacheResult.HIT; } stats.incrementCacheMiss(); return CacheResult.MISS; }