auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public BinaryContent transform( SourceResponse upstreamResponse, Map<String, Serializable> arguments) throws CatalogTransformerException { Set<String> hiddenFields = Optional.ofNullable((Set<String>) arguments.get(HIDDEN_FIELDS_KEY)) .orElse(Collections.emptySet()); List<String> attributeOrder = Optional.ofNullable((List<String>) arguments.get(COLUMN_ORDER_KEY)) .orElse(Collections.emptyList()); Map<String, String> columnAliasMap = Optional.ofNullable((Map<String, String>) arguments.get(COLUMN_ALIAS_KEY)) .orElse(Collections.emptyMap()); Set<AttributeDescriptor> allAttributeDescriptors = getAllRequestedAttributes( upstreamResponse.getResults(), hiddenFields, new HashSet<String>(attributeOrder)); <START> List<AttributeDescriptor> sortedAttributeDescriptors = <END> sortAttributes(allAttributeDescriptors, attributeOrder); Appendable csv = writeSearchResultsToCsv(upstreamResponse, columnAliasMap, sortedAttributeDescriptors); return createResponse(csv); }</code><technical_language>suggest creating a new variable called requestedFields instead of creating HashSet in-line. Set<String> requestedFields = new HashSet<String>(attributeOrder). result is same, helps code readable for others</technical_language>

Target:
public BinaryContent transform( SourceResponse upstreamResponse, Map<String, Serializable> arguments) throws CatalogTransformerException { Set<String> hiddenFields = Optional.ofNullable((Set<String>) arguments.get(HIDDEN_FIELDS_KEY)) .orElse(Collections.emptySet()); List<String> attributeOrder = Optional.ofNullable((List<String>) arguments.get(COLUMN_ORDER_KEY)) .orElse(Collections.emptyList()); Map<String, String> columnAliasMap = Optional.ofNullable((Map<String, String>) arguments.get(COLUMN_ALIAS_KEY)) .orElse(Collections.emptyMap()); Set<String> requestedFields = new HashSet<>(attributeOrder); Set<AttributeDescriptor> allAttributeDescriptors = getAllRequestedAttributes(upstreamResponse.getResults(), hiddenFields, requestedFields); List<AttributeDescriptor> sortedAttributeDescriptors = sortAttributes(allAttributeDescriptors, attributeOrder); Appendable csv = writeSearchResultsToCsv(upstreamResponse, columnAliasMap, sortedAttributeDescriptors); return createResponse(csv); }
Source:
<code>protected int getTestTimeoutMillis() { <START> return 3 * 180000; <END> }</code><technical_language>change? 9 * 60_000 for readability</technical_language>

Target:
protected int getTestTimeoutMillis() { return 3 * super.getTestTimeoutMillis(); }
Source:
<code>FileBlock getNextBlock( final FileBlock prevBlock, final FileMeta metadata) throws IOException { <START> synchronized ( InfinispanJFS.this ) <END> { UUID next = prevBlock.getNextBlockID(); FileBlock nextBlock = null; while ( nextBlock == null ) { nextBlock = blockCache.get( next ); if (nextBlock == null) { try { lockManager.reentrantSynchronous( metadata.getFilePath(), ( opLock ) -> { ClusterListener clusterListener = new ClusterListener( next, opLock ); clusterListener.listenToCache( blockCache ); opLock.await( WAIT_TIMEOUT ); return null; } ); } catch ( final InterruptedException e ) { return null; } } } return nextBlock; } }</code><technical_language>need careful this, lock file access of path. If necessary do (if confine lock a path...and synchronized for causing memory bloat!), need shrink scope of this synchronized block possible. a while loop of this a bit uneasy. a ReentrantOperation this ReentrantOperation locking anything, effectively...it's locked provider instance level for paths. rest of this commit, this synchronized block is needed. explain a bit more</technical_language>

Target:
FileBlock getNextBlock( final FileBlock prevBlock, final FileMeta metadata ) throws IOException { String next = prevBlock.getNextBlockID(); if ( next == null ) { return null; } try { lockManager.reentrantSynchronous( metadata.getFilePath(), ( opLock ) -> { FileBlock nextBlock = null; ClusterListener clusterListener = new ClusterListener( next, opLock ); while ( nextBlock == null ) { nextBlock = blockCache.get( next ); if ( nextBlock == null ) { clusterListener.listenToCache( blockCache ); } } return nextBlock; } ); } catch ( InterruptedException e ) { LoggerFactory.getLogger( getClass().getName() ) .error( "Interrupted while trying to get block with ID: " + next, e ); } return null; }
Source:
<code><START> public static Key buildPrivateKey(final String base64EncodedKeyContent) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { <END> final KeyFactory kf = KeyFactory.getInstance("RSA"); final PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(Base64.decodeBase64(base64EncodedKeyContent)); return kf.generatePrivate(keysp); }</code><technical_language>Please consider adding a Preconditions.checkArgument check base64EncodedKeyContent is blank</technical_language>

Target:
public static Key buildPrivateKey(final String base64EncodedKeyContent) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { Preconditions.checkNotNull(base64EncodedKeyContent); final KeyFactory kf = KeyFactory.getInstance("RSA"); final PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(Base64.decodeBase64(base64EncodedKeyContent)); return kf.generatePrivate(keysp); }
Source:
<code>public void setTitleText(final String title, final Serializable... args) { <START> String currTitle = getTitleText(); <END> if (!Objects.equals(title, currTitle)) { MessageModel model = getOrCreateComponentModel(); model.title = I18nUtilities.asMessage(title, args); } }</code><technical_language>before, this test response fromasMessage current value</technical_language>

Target:
public void setTitleText(final String title, final Serializable... args) { Serializable currTitle = getComponentModel().title; Serializable titleToBeSet = I18nUtilities.asMessage(title, args); if (!Objects.equals(titleToBeSet, currTitle)) { MessageModel model = getOrCreateComponentModel(); model.title = titleToBeSet; } }
Source:
<code>public void testConverter() throws Exception { String converterName = cs.getConverterName("text/plain", "application/pdf"); assertEquals("any2pdf", converterName); checkConverterAvailability(converterName); checkCommandAvailability("soffice"); BlobHolder result = convertTextBlob(converterName); checkPDFDocument(result); <START> checkPDFDocument(result); <END> }</code><technical_language>bad, needed :)</technical_language>

Target:
public void testConverter() throws Exception { String converterName = cs.getConverterName("text/plain", "application/pdf"); assertEquals("any2pdf", converterName); checkConverterAvailability(converterName); checkCommandAvailability("soffice"); BlobHolder result = convertTextBlob(converterName); checkPDFDocument(result); }
Source:
<code>public void create() { setPreviousScreen(Screens.PROJECT_MENU); super.root = new Group(); root.setVisible(false); toolBar = new ToolBar(skin); toolBar.right(); Button move = new TextButton("Mover", skin); <START> paint = new DrawComponent(skin, "Pintar", "Herramienta de pincel", Color.BLACK, 350, 550); <END> delete = new DrawComponent(skin, "Borrar", "Herramienta de goma", 350, 250); text = new DrawComponent(skin, "Texto", "Herramienta de escribir", Color.BLACK, 350, 550); Button inter = new TextButton("Zonas Int.", skin); Button add = new TextButton("Añadir", skin); Button effect = new TextButton("Efectos", skin); effect.setDisabled(true); Button more = new TextButton("...", skin); ImageButton frames = new ImageButton(skin); frames.setX(AbstractScreen.stagew - frames.getWidth()); toolBar.add(move); toolBar.add(paint.getButton()); toolBar.add(delete.getButton()); toolBar.add(text.getButton()); toolBar.add(inter); toolBar.add(add); toolBar.add(effect); toolBar.add(more); toolBar.invalidate(); toolBar.validate(); root.addActor(toolBar); root.addActor(frames); root.addActor(paint.getPanel()); delete.actCoordinates(); root.addActor(delete.getPanel()); paint.actCoordinates(); root.addActor(text.getPanel()); text.actCoordinates(); stage.addActor(root); }</code><technical_language>I18N</technical_language>

Target:
public void create() { setPreviousScreen(Screens.PROJECT_MENU); super.root = new Group(); root.setVisible(false); toolBar = new ToolBar(skin); toolBar.right(); Button move = new TextButton("Mover", skin); paint = new DrawComponent(skin, "Pintar", "Herramienta de pincel", Type.BRUSH, 350, 550); delete = new DrawComponent(skin, "Borrar", "Herramienta de goma", Type.RUBBER, 350, 250); text = new DrawComponent(skin, "Texto", "Herramienta de escribir", Type.TEXT, 350, 550); Button inter = new TextButton("Zonas Int.", skin); Button add = new TextButton("Añadir", skin); Button effect = new TextButton("Efectos", skin); effect.setDisabled(true); Button more = new TextButton("...", skin); ImageButton frames = new ImageButton(skin); frames.setX(AbstractScreen.stagew - frames.getWidth()); toolBar.add(move); toolBar.add(paint.getButton()); toolBar.add(delete.getButton()); toolBar.add(text.getButton()); toolBar.add(inter); toolBar.add(add); toolBar.add(effect); toolBar.add(more); toolBar.invalidate(); toolBar.validate(); root.addActor(toolBar); root.addActor(frames); root.addActor(paint.getPanel()); delete.actCoordinates(); root.addActor(delete.getPanel()); paint.actCoordinates(); root.addActor(text.getPanel()); text.actCoordinates(); stage.addActor(root); }
Source:
<code>public CopyObjectException(String sourcePath, String destinationPath, String message) { <START> super(String.format("Either the source path %s or the destination path %s was not found. " + <END> "(message: %s)", sourcePath, destinationPath, message)); this.sourcePath = sourcePath; this.destinationPath = destinationPath; }</code><technical_language>change %s '%s' nasty leading trailing spaces more obvious</technical_language>

Target:
public CopyObjectException(String sourcePath, String destinationPath, String message) { super(String.format("Either the source path '%s' or the destination path '%s' was not found. " + "(message: %s)", sourcePath, destinationPath, message)); this.sourcePath = sourcePath; this.destinationPath = destinationPath; }
Source:
<code>public static void main(String[] args) throws Exception { Args searchArgs = new Args(); CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90)); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.err.println("Example command: "+ SearchRDF.class.getSimpleName() + parser.printExample(OptionHandlerFilter.REQUIRED)); return; } new SearchRDF(searchArgs.index).search(searchArgs.subject, searchArgs.property); <START> } <END></code><technical_language>Put main end for consistency other code</technical_language>

Target:
public static void main(String[] args) throws Exception { Args searchArgs = new Args(); CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90)); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.err.println("Example command: "+ SearchRDF.class.getSimpleName() + parser.printExample(OptionHandlerFilter.REQUIRED)); return; } new SearchRDF(searchArgs.index).search(searchArgs.subject, searchArgs.predicate); }
Source:
<code>public void visitAssignmentExpression(AssignmentExpressionTree tree) { <START> if (tree.variable() instanceof BracketMemberExpressionTreeImpl) { <END> if (((BracketMemberExpressionTreeImpl) tree.variable()).object().types().contains(Kind.ARRAY)) { if (((BracketMemberExpressionTreeImpl) tree.variable()).property() instanceof LiteralTreeImpl) { LiteralTreeImpl al = (LiteralTreeImpl) ((BracketMemberExpressionTreeImpl) tree.variable()).property(); if (!NumberUtils.isNumber(al.token().text())) { addLineIssue(tree, MESSAGE); } } else if (((BracketMemberExpressionTreeImpl) tree.variable()).property() instanceof IdentifierTreeImpl) { IdentifierTreeImpl idt= (IdentifierTreeImpl)((BracketMemberExpressionTreeImpl) tree.variable()).property(); if (!NumberUtils.isNumber(idt.name())) { addLineIssue(tree, MESSAGE); } } } } super.visitAssignmentExpression(tree); }</code><technical_language>@laftanza Please tree.variable().is(Kind.BRACKET_MEMBER_EXPRESSION) instead</technical_language>

Target:
public void visitAssignmentExpression(AssignmentExpressionTree tree) { if (tree.variable().is(Tree.Kind.BRACKET_MEMBER_EXPRESSION)) { BracketMemberExpressionTree memberExpression = (BracketMemberExpressionTree) tree.variable(); if (memberExpression.object().types().containsOnly(Kind.ARRAY)) { ExpressionTree arrayIndex = memberExpression.property(); if (arrayIndex.types().containsOnly(Kind.STRING)) { addIssue(arrayIndex, String.format(MESSAGE, CheckUtils.asString(memberExpression.object()))); } } } super.visitAssignmentExpression(tree); }
Source:
<code>private Object convertStringToInternal(String value, TypeInformation type) { if (type.equals(Types.INT)) { return Integer.parseInt(value); } else if (type.equals(Types.LONG)) { return Long.parseLong(value); } else if (type.equals(Types.STRING)) { return BinaryString.fromString(value); } else { <START> throw new UnsupportedOperationException("Unsupported type: " + type); <END> } }</code><technical_language>partition column, Unsupported partition type clear</technical_language>

Target:
private Object convertStringToInternal(String value, TypeInformation type) { if (type.equals(Types.INT)) { return Integer.parseInt(value); } else if (type.equals(Types.LONG)) { return Long.parseLong(value); } else if (type.equals(Types.STRING)) { return BinaryString.fromString(value); } else { throw new UnsupportedOperationException("Unsupported partition type: " + type); } }
Source:
<code>public void copyToWithPermission(FilePath target) throws IOException, InterruptedException { if (this.channel == target.channel) { act(new SecureFileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { try { File targetFile = new File(target.remote).getAbsoluteFile(); <START> mkdirs(targetFile.getParentFile()); <END> Files.copy(reading(f).toPath(), writing(targetFile).toPath(), StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } catch (InvalidPathException e) { throw new IOException(e); } return null; } }); return; } copyTo(target); target.chmod(mode()); target.setLastModifiedIfPossible(lastModified()); }</code><technical_language>Files.createDirectory(), miss directory creation failure event</technical_language>

Target:
public void copyToWithPermission(FilePath target) throws IOException, InterruptedException { if (this.channel == target.channel) { act(new SecureFileCallable<Void>() { public Void invoke(File f, VirtualChannel channel) throws IOException { File targetFile = new File(target.remote); File targetDir = targetFile.getParentFile(); filterNonNull().mkdirs(targetDir); Files.createDirectories(Util.fileToPath(targetDir)); Files.copy(Util.fileToPath(reading(f)), Util.fileToPath(writing(targetFile)), StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); return null; } }); return; } copyTo(target); target.chmod(mode()); target.setLastModifiedIfPossible(lastModified()); }
Source:
<code>private static AddPartitionDesc getBaseAddPartitionDescFromPartition( Path fromPath, String dbName, ImportTableDesc tblDesc, Partition partition, ReplicationSpec replicationSpec, HiveConf conf) throws MetaException, SemanticException { AddPartitionDesc partsDesc = new AddPartitionDesc(dbName, tblDesc.getTableName(), EximUtil.makePartSpec(tblDesc.getPartCols(), partition.getValues()), partition.getSd().getLocation(), partition.getParameters()); AddPartitionDesc.OnePartitionDesc partDesc = partsDesc.getPartition(0); partDesc.setInputFormat(partition.getSd().getInputFormat()); partDesc.setOutputFormat(partition.getSd().getOutputFormat()); partDesc.setNumBuckets(partition.getSd().getNumBuckets()); partDesc.setCols(partition.getSd().getCols()); partDesc.setSerializationLib(partition.getSd().getSerdeInfo().getSerializationLib()); partDesc.setSerdeParams(partition.getSd().getSerdeInfo().getParameters()); partDesc.setBucketCols(partition.getSd().getBucketCols()); partDesc.setSortCols(partition.getSd().getSortCols()); if (replicationSpec.isInReplicationScope() && tblDesc.isExternal()) { <START> if (replicationSpec.isInReplicationScope()) { <END> String newLocation = ReplExternalTables .externalTableLocation(conf, partition.getSd().getLocation()); LOG.debug("partition has data location: {}", partition, newLocation); partDesc.setLocation(newLocation); } return partsDesc; } else { partDesc.setLocation(new Path(fromPath, Warehouse.makePartName(tblDesc.getPartCols(), partition.getValues())).toString()); return partsDesc; } }</code><technical_language>Redundant replicationSpec.isInReplicationScope()</technical_language>

Target:
private static AddPartitionDesc getBaseAddPartitionDescFromPartition( Path fromPath, String dbName, ImportTableDesc tblDesc, Partition partition, ReplicationSpec replicationSpec, HiveConf conf) throws MetaException, SemanticException { AddPartitionDesc partsDesc = new AddPartitionDesc(dbName, tblDesc.getTableName(), EximUtil.makePartSpec(tblDesc.getPartCols(), partition.getValues()), partition.getSd().getLocation(), partition.getParameters()); AddPartitionDesc.OnePartitionDesc partDesc = partsDesc.getPartition(0); partDesc.setInputFormat(partition.getSd().getInputFormat()); partDesc.setOutputFormat(partition.getSd().getOutputFormat()); partDesc.setNumBuckets(partition.getSd().getNumBuckets()); partDesc.setCols(partition.getSd().getCols()); partDesc.setSerializationLib(partition.getSd().getSerdeInfo().getSerializationLib()); partDesc.setSerdeParams(partition.getSd().getSerdeInfo().getParameters()); partDesc.setBucketCols(partition.getSd().getBucketCols()); partDesc.setSortCols(partition.getSd().getSortCols()); if (replicationSpec.isInReplicationScope() && tblDesc.isExternal() && !replicationSpec.isMigratingToExternalTable()) { String newLocation = ReplExternalTables .externalTableLocation(conf, partition.getSd().getLocation()); LOG.debug("partition has data location: {}", partition, newLocation); partDesc.setLocation(newLocation); } else { partDesc.setLocation(new Path(fromPath, Warehouse.makePartName(tblDesc.getPartCols(), partition.getValues())).toString()); } return partsDesc; }
Source:
<code>public void setAway(final boolean onOrOff, final String... deviceNames) { <START> neoHubConnector.sendMessage("{\"AWAY_" + (onOrOff ? "ON" : "OFF") <END> + "\":[\"" + StringUtils.join(deviceNames, "\",\"") + "\"]}", null); }</code><technical_language>i prefer String.format() in order write message placeholders (%s) refactor commands static constants</technical_language>

Target:
public void setAway(final boolean onOrOff, final String... deviceNames) { neoHubConnector.sendMessage( String.format("{\"AWAY_%s\":[\"%s\"]}", onOrOff ? "ON" : "OFF", StringUtils.join(deviceNames, "\",\"")), null); }
Source:
<code>public void validateDebitCreditField(String debitCredit) throws ValidationException { if(!StringUtils.equalsIgnoreCase(debitCredit, ConcurConstants.ConcurPdpConstants.CREDIT) && !StringUtils.equalsIgnoreCase(debitCredit, ConcurConstants.ConcurPdpConstants.DEBIT)) { LOG.debug("validateDebitCreditField, invalid debit or credit: " + debitCredit); throw new ValidationException(debitCredit + " is not a valid valuee for the debit or credit field."); } else { <START> LOG.debug("validateDebitCreditField, found a valid debit/credit."); <END> } }</code><technical_language>I more sense log failure. I necessarily interested in knowing this a valid value</technical_language>

Target:
public boolean validateDebitCreditField(String debitCredit) { boolean valid = StringUtils.equalsIgnoreCase(debitCredit, ConcurConstants.ConcurPdpConstants.CREDIT) || StringUtils.equalsIgnoreCase(debitCredit, ConcurConstants.ConcurPdpConstants.DEBIT); if (valid) { LOG.debug("validateDebitCreditField, found a valid debit/credit."); } else { LOG.error("validateDebitCreditField, invalid debit or credit: " + debitCredit); } return valid; }
Source:
<code>boolean dispose() throws IOException { <START> try { <END> _out.close(); } finally { } return true; }</code><technical_language>I exception swallowed</technical_language>

Target:
boolean dispose() throws IOException { _out.close(); return true; }
Source:
<code>public CompletableFuture<Boolean> replaceIssueLabels(TurboIssue issue, List<String> newLabels) { List<String> originalLabels = issue.getLabels(); logger.info("Changing labels for " + issue + " on UI"); Optional<TurboIssue> replaceResult = models.replaceIssueLabels(issue.getRepoId(), issue.getId(), newLabels); if (!replaceResult.isPresent()) { return CompletableFuture.completedFuture(false); } refreshUI(); return updateIssueLabelsOnRepo(issue, newLabels) .thenApply((isUpdateSuccessful) -> { if (isUpdateSuccessful) { return true; } logger.error("Unable to update model on server"); revertLocalLabelsReplace(replaceResult.get(), originalLabels); return false; <START> }); <END> }</code><technical_language>if improve SLAP lines 210-219. if though</technical_language>

Target:
public CompletableFuture<Boolean> replaceIssueLabels(TurboIssue issue, List<String> newLabels) { List<String> originalLabels = issue.getLabels(); logger.info("Changing labels for " + issue + " on UI"); Optional<TurboIssue> localReplaceResult = models.replaceIssueLabels(issue.getRepoId(), issue.getId(), newLabels); if (!localReplaceResult.isPresent()) { return CompletableFuture.completedFuture(false); } refreshUI(); return updateIssueLabelsOnServer(issue, newLabels) .thenApply((isUpdateSuccessful) -> handleIssueLabelsUpdateOnServerResult( isUpdateSuccessful, localReplaceResult.get(), originalLabels)); }
Source:
<code>private void disableWatchdog() { if (this.isEnabled) { writeWatchdogDevice("V"); <START> this.isEnabled = false; <END> } }</code><technical_language>remove WD_FILE</technical_language>

Target:
private void disableWatchdog() { if (this.enabled) { writeWatchdogDevice("V"); this.enabled = false; } }
Source:
<code><START> public void createCommitStatus(GHCommitState state, String message) { <END> GHRepository ghRepository = repo.getGitHubRepo(); GhprbTrigger trigger = helper.getTrigger(); Job<?, ?> actualProject = trigger.getActualProject(); for (GhprbExtension ext : Ghprb.getJobExtensions(trigger, GhprbCommitStatus.class)) { if (ext instanceof GhprbCommitStatus) { try { ((GhprbCommitStatus) ext).createCommitStatus(actualProject, id, head, state, ghRepository, message); } catch (GhprbCommitStatusException e) { repo.commentOnFailure(null, null, e); } } } }</code><technical_language>hm, shouldnt method exist else</technical_language>

Target:
public void createCommitStatus(GHCommitState state, String message) { GHRepository ghRepository = repo.getGitHubRepo(); GhprbTrigger trigger = helper.getTrigger(); Job<?, ?> actualProject = trigger.getActualProject(); for (GhprbExtension ext : Ghprb.getJobExtensions(trigger, GhprbSimpleStatus.class)) { if (ext instanceof GhprbSimpleStatus) { try { ((GhprbSimpleStatus) ext).createCommitStatus(actualProject, id, head, state, ghRepository, message); } catch (GhprbCommitStatusException e) { repo.commentOnFailure(null, null, e); } } } }
Source:
<code>public int save(SqlStorage<FormDefRecord> formDefRecordStorage) { <START> if (StringUtils.isEmpty(mFormFilePath)) { <END> throw new SQLException("Can't save a form def with an empty form file path"); } File form = new File(mFormFilePath); if (StringUtils.isEmpty(mDisplayName)) { mDisplayName = form.getName(); } if (StringUtils.isEmpty(mFormMediaPath)) { mFormMediaPath = getMediaPath(mFormFilePath); } formDefRecordStorage.write(this); if (recordId == -1) { throw new SQLException("Failed to save the FormDefRecord " + toString()); } return recordId; }</code><technical_language>This a bit of odd time fail this me. validate this path empty is set, is used</technical_language>

Target:
public int save(SqlStorage<FormDefRecord> formDefRecordStorage) { if (StringUtils.isEmpty(mFormFilePath)) { Logger.log(LogTypes.SOFT_ASSERT, "Empty value for mFormFilePath while saving FormDefRecord"); } File form = new File(mFormFilePath); if (StringUtils.isEmpty(mDisplayName)) { mDisplayName = form.getName(); } if (StringUtils.isEmpty(mFormMediaPath)) { mFormMediaPath = getMediaPath(mFormFilePath); } formDefRecordStorage.write(this); if (recordId == -1) { throw new SQLException("Failed to save the FormDefRecord " + toString()); } return recordId; }
Source:
<code>JSONArray getTurnServers(Client c, final boolean test) { JSONArray arr = new JSONArray(); if (!Strings.isEmpty(turnUrl)) { try { JSONObject turn = new JSONObject(); if ("rest".equalsIgnoreCase(turnMode)) { Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(new SecretKeySpec(turnSecret.getBytes(), HMAC_SHA1_ALGORITHM)); StringBuilder user = new StringBuilder() .append((test ? 60 : turnTtl * 60) + System.currentTimeMillis() / 1000L); final String uid = c.getUid(); <START> if (uid != null && !Strings.isEmpty(uid)) { <END> user.append(':').append(uid); } else if (!Strings.isEmpty(turnUser)) { user.append(':').append(turnUser); } turn.put("username", user) .put("credential", Base64.getEncoder().encodeToString(mac.doFinal(user.toString().getBytes()))); } else { turn.put("username", turnUser) .put("credential", turnSecret); } JSONArray urls = new JSONArray(); final String[] turnUrls = turnUrl.split(","); for (int i = 0; i < turnUrls.length; i++) { final String url = turnUrls[i]; if (!url.startsWith("stun:") && !url.startsWith("stuns:") && !url.startsWith("turn:") && !url.startsWith("turns:")) { urls.put("turn:" + url); } else { urls.put(url); } } turn.put("urls", urls); arr.put(turn); } catch (NoSuchAlgorithmException|InvalidKeyException e) { log.error("Unexpected error while creating turn", e); } } return arr; }</code><technical_language>this null check is redundant Strings.isEmpty check for null</technical_language>

Target:
JSONArray getTurnServers(Client c, final boolean test) { JSONArray arr = new JSONArray(); if (!Strings.isEmpty(turnUrl)) { try { JSONObject turn = new JSONObject(); if ("rest".equalsIgnoreCase(turnMode)) { Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(new SecretKeySpec(turnSecret.getBytes(), HMAC_SHA1_ALGORITHM)); StringBuilder user = new StringBuilder() .append((test ? 60 : turnTtl * 60) + System.currentTimeMillis() / 1000L); final String uid = c == null ? null : c.getUid(); if (!Strings.isEmpty(uid)) { user.append(':').append(uid); } else if (!Strings.isEmpty(turnUser)) { user.append(':').append(turnUser); } turn.put("username", user) .put("credential", Base64.getEncoder().encodeToString(mac.doFinal(user.toString().getBytes()))); } else { turn.put("username", turnUser) .put("credential", turnSecret); } JSONArray urls = new JSONArray(); final String[] turnUrls = turnUrl.split(","); for (String url : turnUrls) { if (url.startsWith("stun:") || url.startsWith("stuns:") || url.startsWith("turn:") || url.startsWith("turns:")) { urls.put(url); } else { urls.put("turn:" + url); } } turn.put("urls", urls); arr.put(turn); } catch (NoSuchAlgorithmException|InvalidKeyException e) { log.error("Unexpected error while creating turn", e); } } return arr; }
Source:
<code>public Optional<List> metacardValueToJsonValue( WorkspaceTransformer transformer, List metacardXMLStrings, Metacard workspaceMetacard) { final List<Map<String, Object>> listActions = getListActions(workspaceMetacard); <START> final Optional<List> listMetacardOptional = <END> super.metacardValueToJsonValue(transformer, metacardXMLStrings, workspaceMetacard); listMetacardOptional.ifPresent( listMetacards -> ((List<Object>) listMetacards) .stream() .filter(Map.class::isInstance) .map(Map.class::cast) .forEach(listMetacardMap -> listMetacardMap.put(ACTIONS_KEY, listActions))); return listMetacardOptional; }</code><technical_language>This called listMetacardsOptional</technical_language>

Target:
public Optional<List> metacardValueToJsonValue( WorkspaceTransformer transformer, List metacardXMLStrings, Metacard workspaceMetacard) { final List<Map<String, Object>> listActions = getListActions(workspaceMetacard); final Optional<List> listMetacardsOptional = super.metacardValueToJsonValue(transformer, metacardXMLStrings, workspaceMetacard); listMetacardsOptional.ifPresent( listMetacards -> ((List<Object>) listMetacards) .stream() .filter(Map.class::isInstance) .map(Map.class::cast) .forEach(listMetacardMap -> listMetacardMap.put(ACTIONS_KEY, listActions))); return listMetacardsOptional; }
Source:
<code>public ScalarFunctionImplementation(List<ScalarImplementationChoice> choices, boolean deterministic) { <START> this.choices = choices; <END> this.deterministic = deterministic; }</code><technical_language>a defensive copy of choices: this.choices = ImmutableList.copyOf(choices); In addition, check choices is empty</technical_language>

Target:
public ScalarFunctionImplementation(List<ScalarImplementationChoice> choices, boolean deterministic) { checkArgument(!choices.isEmpty(), "choices is an empty list"); this.choices = ImmutableList.copyOf(choices); this.deterministic = deterministic; }
Source:
<code>private void checkEbsVolumeStatus(AuthenticatedContext ac, AmazonEC2Client client, String volumeId) { Waiter<DescribeVolumesRequest> volumeChecker = client.waiters().volumeAvailable(); DescribeVolumesRequest describeVolumesRequest = new DescribeVolumesRequest().withVolumeIds(volumeId); StackCancellationCheck stackCancellationCheck = new StackCancellationCheck(ac.getCloudContext().getId()); <START> run(volumeChecker, describeVolumesRequest, stackCancellationCheck, "Volume creation failed"); <END> }</code><technical_language>mention volume id relevant info</technical_language>

Target:
private void checkEbsVolumeStatus(AuthenticatedContext ac, AmazonEC2Client client, String volumeId) { Waiter<DescribeVolumesRequest> volumeChecker = client.waiters().volumeAvailable(); DescribeVolumesRequest describeVolumesRequest = new DescribeVolumesRequest().withVolumeIds(volumeId); StackCancellationCheck stackCancellationCheck = new StackCancellationCheck(ac.getCloudContext().getId()); run(volumeChecker, describeVolumesRequest, stackCancellationCheck, String.format("Volume creation failed (volume id: %s)", volumeId)); }
Source:
<code>public void addModifiedColumns( GlobalConfiguration globalCfg, Value value, Element parent, PropertyAuditingData propertyAuditingData) { boolean basicType = value.getType() instanceof BasicType; boolean toOneType = value.getType() instanceof ManyToOneType || value.getType() instanceof OneToOneType; if ( basicType || toOneType ) { if ( value.getColumnSpan() == 1 ) { Selectable selectable = value.getColumnIterator().next(); if ( selectable instanceof Column ) { <START> String columnName = propertyAuditingData.getModifiedFlagName(); <END> if ( !propertyAuditingData.isModifiedFlagNameExplicitlySpecified() ) { columnName = ( (Column) selectable ).getName() + globalCfg.getModifiedFlagSuffix(); } else { columnName = propertyAuditingData.getExplicitModifiedFlagName(); } MetadataTools.addModifiedFlagPropertyWithColumn( parent, propertyAuditingData.getName(), globalCfg.getModifiedFlagSuffix(), propertyAuditingData.getModifiedFlagName(), columnName ); return; } } } MetadataTools.addModifiedFlagProperty( parent, propertyAuditingData.getName(), globalCfg.getModifiedFlagSuffix(), propertyAuditingData.getModifiedFlagName() ); }</code><technical_language>String columnName;</technical_language>

Target:
public void addModifiedColumns( GlobalConfiguration globalCfg, Value value, Element parent, PropertyAuditingData propertyAuditingData) { boolean basicType = value.getType() instanceof BasicType; boolean toOneType = value.getType() instanceof ManyToOneType || value.getType() instanceof OneToOneType; if ( basicType || toOneType ) { if ( value.getColumnSpan() == 1 ) { Selectable selectable = value.getColumnIterator().next(); if ( selectable instanceof Column ) { final String columnName; if ( !propertyAuditingData.isModifiedFlagNameExplicitlySpecified() ) { columnName = ( (Column) selectable ).getName() + globalCfg.getModifiedFlagSuffix(); } else { columnName = propertyAuditingData.getExplicitModifiedFlagName(); } MetadataTools.addModifiedFlagPropertyWithColumn( parent, propertyAuditingData.getName(), globalCfg.getModifiedFlagSuffix(), propertyAuditingData.getModifiedFlagName(), columnName ); return; } } } super.addModifiedColumns( globalCfg, value, parent, propertyAuditingData ); }
Source:
<code>public List<SingleColumn> generateChecksumColumns(Column column) { checkArgument(column.getType() instanceof ArrayType, "Expect ArrayType, found %s", column.getType().getDisplayName()); Type elementType = ((ArrayType) column.getType()).getElementType(); Expression checksum; if (elementType.isOrderable()) { FunctionCall arraySort = new FunctionCall(QualifiedName.of("array_sort"), ImmutableList.of(column.getIdentifier())); if (elementType instanceof ArrayType || elementType instanceof RowType) { checksum = new CoalesceExpression( new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(new TryExpression(arraySort))), new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(column.getIdentifier()))); } else { checksum = new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(arraySort)); } } else { checksum = new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(column.getIdentifier())); } FunctionCall arrayCardinality = new FunctionCall(QualifiedName.of("sum"), ImmutableList.of(new FunctionCall(QualifiedName.of("cardinality"), ImmutableList.of(column.getIdentifier())))); <START> return ImmutableList.of(new SingleColumn(checksum, Optional.of(delimitedIdentifier(getChecksumColumnAlias(column)))), new SingleColumn(arrayCardinality, Optional.of(delimitedIdentifier(getCardinalityColumnAlias(column))))); <END> }</code><technical_language>parameter a separate line</technical_language>

Target:
public List<SingleColumn> generateChecksumColumns(Column column) { checkArgument(column.getType() instanceof ArrayType, "Expect ArrayType, found %s", column.getType().getDisplayName()); Type elementType = ((ArrayType) column.getType()).getElementType(); Expression checksum; if (elementType.isOrderable()) { FunctionCall arraySort = new FunctionCall(QualifiedName.of("array_sort"), ImmutableList.of(column.getIdentifier())); if (elementType instanceof ArrayType || elementType instanceof RowType) { checksum = new CoalesceExpression( new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(new TryExpression(arraySort))), new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(column.getIdentifier()))); } else { checksum = new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(arraySort)); } } else { checksum = new FunctionCall(QualifiedName.of("checksum"), ImmutableList.of(column.getIdentifier())); } Expression arrayCardinalitySum = new CoalesceExpression( new FunctionCall( QualifiedName.of("sum"), ImmutableList.of(new FunctionCall(QualifiedName.of("cardinality"), ImmutableList.of(column.getIdentifier())))), new LongLiteral("0")); return ImmutableList.of( new SingleColumn(checksum, Optional.of(delimitedIdentifier(getChecksumColumnAlias(column)))), new SingleColumn(arrayCardinalitySum, Optional.of(delimitedIdentifier(getCardinalitySumColumnAlias(column))))); }
Source:
<code>private void rename( final boolean saveCurrentChanges ) { final DataObject[] modifiedDataObject = new DataObject[ 1 ]; if ( saveCurrentChanges ) { if ( isDirty() ) { if ( context.isEditorChanged() ) { modifiedDataObject[ 0 ] = context.getDataObject(); } else { modifiedDataObject[ 0 ] = null; } } } renamePopUpPresenter.show( versionRecordManager.getPathToLatest(), javaFileNameValidator, new CommandWithFileNameAndCommitMessage() { @Override public void execute( final FileNameAndCommitMessage details ) { view.showBusyIndicator( org.kie.workbench.common.widgets.client.resources.i18n.CommonConstants.INSTANCE.Renaming() ); <START> modelerService.call( getRenameSuccessCallback( renamePopUpPresenter.getView(), context.getDataObject().getPackageName(), details.getNewFileName() ), <END> getRenameErrorCallback( renamePopUpPresenter.getView() ) ).rename( versionRecordManager.getPathToLatest(), details.getNewFileName(), details.getCommitMessage(), true, saveCurrentChanges, getSource(), modifiedDataObject[ 0 ], metadata ); } } ); }</code><technical_language>This invocation context.getDataObject().getPackageName() introduces a NPE in cases a file parsed properly is edited</technical_language>

Target:
private void rename( final boolean saveCurrentChanges ) { final DataObject[] modifiedDataObject = new DataObject[ 1 ]; if ( saveCurrentChanges ) { if ( isDirty() ) { if ( context.isEditorChanged() ) { modifiedDataObject[ 0 ] = context.getDataObject(); } else { modifiedDataObject[ 0 ] = null; } } } renamePopUpPresenter.show( versionRecordManager.getPathToLatest(), javaFileNameValidator, new CommandWithFileNameAndCommitMessage() { @Override public void execute( final FileNameAndCommitMessage details ) { view.showBusyIndicator( org.kie.workbench.common.widgets.client.resources.i18n.CommonConstants.INSTANCE.Renaming() ); modelerService.call( getRenameSuccessCallback( renamePopUpPresenter.getView() ), getRenameErrorCallback( renamePopUpPresenter.getView() ) ).rename( versionRecordManager.getPathToLatest(), details.getNewFileName(), details.getCommitMessage(), true, saveCurrentChanges, getSource(), modifiedDataObject[ 0 ], metadata ); } } ); }
Source:
<code>public void testUseMeta() throws IOException { DataFileWriter<?> w = new DataFileWriter<>(new GenericDatumWriter<>()); File f = new File(DIR.getRoot().getPath(), "testDataFileMeta.avro"); w.setMeta("hello", "bar"); w.create(Schema.create(Type.NULL), f); w.close(); DataFileStream<Void> r = new DataFileStream<>(new FileInputStream(f), new GenericDatumReader<>()); assertTrue(r.getMetaKeys().contains("hello")); assertEquals("bar", r.getMetaString("hello")); <START> r.close(); <END> }</code><technical_language>a try-with-resource pattern here</technical_language>

Target:
public void testUseMeta() throws IOException { File f = new File(DIR.getRoot().getPath(), "testDataFileMeta.avro"); try (DataFileWriter<?> w = new DataFileWriter<>(new GenericDatumWriter<>())) { w.setMeta("hello", "bar"); w.create(Schema.create(Type.NULL), f); } try (DataFileStream<Void> r = new DataFileStream<>(new FileInputStream(f), new GenericDatumReader<>())) { assertTrue(r.getMetaKeys().contains("hello")); assertEquals("bar", r.getMetaString("hello")); } }
Source:
<code>public void test() throws Exception { startDefaultMaster(); final HeliosClient client = defaultClient(); final CreateJobResponse createIdMismatch = client.createJob( new Job(JobId.fromString("bad:job:deadbeef"), "busyBox", IDLE_COMMAND, EMPTY_ENV, <START> EMPTY_PORTS, EMPTY_REGISTRATION, EMPTY_VOLUMES, "")).get(); <END> assertEquals(CreateJobResponse.Status.INVALID_JOB_DEFINITION, createIdMismatch.getStatus()); }</code><technical_language>EMPTY_REGISTRATION_DOMAIN</technical_language>

Target:
public void test() throws Exception { startDefaultMaster(); final HeliosClient client = defaultClient(); final CreateJobResponse createIdMismatch = client.createJob( new Job(JobId.fromString("bad:job:deadbeef"), "busyBox", IDLE_COMMAND, EMPTY_ENV, EMPTY_PORTS, EMPTY_REGISTRATION, EMPTY_VOLUMES, EMPTY_EXPIRES, EMPTY_REGISTRATION_DOMAIN)).get(); assertEquals(CreateJobResponse.Status.INVALID_JOB_DEFINITION, createIdMismatch.getStatus()); }
Source:
<code>public void testUnhandledExceptionStoredOnNoPreviousExceptionStored() { assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); CrashReporter.storeUnhandledException(exception); <START> assertTrue(!sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); <END> }</code><technical_language>assertFalse(...);</technical_language>

Target:
public void testUnhandledExceptionStoredOnNoPreviousExceptionStored() { assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); CrashReporter.storeUnhandledException(exception); assertFalse(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); }
Source:
<code>public void removeSchemaObject(Session session, SchemaObject obj) { int type = obj.getType(); if (type == DbObject.TABLE_OR_VIEW) { Table table = (Table) obj; if (table.isTemporary() && !table.isGlobalTemporary()) { session.removeLocalTempTable(table); return; } } else if (type == DbObject.INDEX) { Index index = (Index) obj; Table table = index.getTable(); if (table.isTemporary() && !table.isGlobalTemporary()) { session.removeLocalTempTableIndex(index); return; } } else if (type == DbObject.CONSTRAINT) { Constraint constraint = (Constraint) obj; Table table = constraint.getTable(); if (table.isTemporary() && !table.isGlobalTemporary()) { session.removeLocalTempTableConstraint(constraint); return; } } checkWritingAllowed(); lockMeta(session); synchronized (this) { Comment comment = findComment(obj); if (comment != null) { removeDatabaseObject(session, comment); } obj.getSchema().remove(obj); int id = obj.getId(); if (!starting) { Table t = getDependentTable(obj, null); if (t != null) { obj.getSchema().add(obj); throw DbException.get(ErrorCode.CANNOT_DROP_2, obj.getSQL(), t.getSQL()); } obj.removeChildrenAndResources(session); } removeMeta(session, id); <START> return; <END> } }</code><technical_language>unnecessary return</technical_language>

Target:
public void removeSchemaObject(Session session, SchemaObject obj) { int type = obj.getType(); if (type == DbObject.TABLE_OR_VIEW) { Table table = (Table) obj; if (table.isTemporary() && !table.isGlobalTemporary()) { session.removeLocalTempTable(table); return; } } else if (type == DbObject.INDEX) { Index index = (Index) obj; Table table = index.getTable(); if (table.isTemporary() && !table.isGlobalTemporary()) { session.removeLocalTempTableIndex(index); return; } } else if (type == DbObject.CONSTRAINT) { Constraint constraint = (Constraint) obj; Table table = constraint.getTable(); if (table.isTemporary() && !table.isGlobalTemporary()) { session.removeLocalTempTableConstraint(constraint); return; } } checkWritingAllowed(); lockMeta(session); synchronized (this) { Comment comment = findComment(obj); if (comment != null) { removeDatabaseObject(session, comment); } obj.getSchema().remove(obj); int id = obj.getId(); if (!starting) { Table t = getDependentTable(obj, null); if (t != null) { obj.getSchema().add(obj); throw DbException.get(ErrorCode.CANNOT_DROP_2, obj.getSQL(), t.getSQL()); } obj.removeChildrenAndResources(session); } removeMeta(session, id); } }
Source:
<code>public List<StackImpl> searchStacks(List<String> tags, int skipCount, int maxItems) { lock.readLock().lock(); try { <START> return FluentIterable.from(stacks.values()) <END> .skip(skipCount) .filter(new Predicate<DecoratedStack>() { @Override public boolean apply(DecoratedStack decoratedStack) { return tags == null || decoratedStack.getTags().containsAll(tags); } }) .limit(maxItems) .toList(); } finally { lock.readLock().unlock(); } }</code><technical_language>stream API instead of FluentIterable</technical_language>

Target:
public List<DecoratedStackImpl> searchStacks(List<String> tags, int skipCount, int maxItems) { lock.readLock().lock(); try { return stacks.values().stream() .skip(skipCount) .filter(decoratedStack -> tags == null || decoratedStack.getTags().containsAll(tags)) .limit(maxItems) .collect(toList()); } finally { lock.readLock().unlock(); } }
Source:
<code><START> public TileEntity createNewTileEntity(World worldIn, int meta) <END> { return createNewTileEntityDefault(worldIn, meta); }</code><technical_language>this final</technical_language>

Target:
public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileCoverable(); }
Source:
<code>public void setAcl(AlluxioURI path, SetAclAction action, List<AclEntry> entries, SetAclContext context) throws FileDoesNotExistException, AccessControlException, InvalidPathException, IOException { Metrics.SET_ACL_OPS.inc(); <START> addFileSystemMasterCallTrackers(context); <END> try (RpcContext rpcContext = createRpcContext(); FileSystemMasterAuditContext auditContext = createAuditContext("setAcl", path, null, null)) { syncMetadata(rpcContext, path, context.getOptions().getCommonOptions(), context.getOptions().getRecursive() ? DescendantType.ALL : DescendantType.NONE, auditContext, LockedInodePath::getInodeOrNull, (inodePath, permChecker) -> permChecker.checkSetAttributePermission(inodePath, false, true, false) ); LockingScheme lockingScheme = createLockingScheme(path, context.getOptions().getCommonOptions(), LockPattern.WRITE_INODE); try (LockedInodePath inodePath = mInodeTree.lockInodePath(lockingScheme)) { mPermissionChecker.checkSetAttributePermission(inodePath, false, true, false); if (context.getOptions().getRecursive()) { try (LockedInodePathList descendants = mInodeTree.getDescendants(inodePath)) { for (LockedInodePath child : descendants) { mPermissionChecker.checkSetAttributePermission(child, false, true, false); } } catch (AccessControlException e) { auditContext.setAllowed(false); throw e; } } if (!inodePath.fullPathExists()) { throw new FileDoesNotExistException(ExceptionMessage .PATH_DOES_NOT_EXIST.getMessage(path)); } setAclInternal(rpcContext, action, inodePath, entries, context); auditContext.setSucceeded(true); } } }</code><technical_language>do this for recursive delete</technical_language>

Target:
public void setAcl(AlluxioURI path, SetAclAction action, List<AclEntry> entries, SetAclContext context) throws FileDoesNotExistException, AccessControlException, InvalidPathException, IOException { Metrics.SET_ACL_OPS.inc(); try (RpcContext rpcContext = createRpcContext(); FileSystemMasterAuditContext auditContext = createAuditContext("setAcl", path, null, null)) { syncMetadata(rpcContext, path, context.getOptions().getCommonOptions(), context.getOptions().getRecursive() ? DescendantType.ALL : DescendantType.NONE, auditContext, LockedInodePath::getInodeOrNull, (inodePath, permChecker) -> permChecker.checkSetAttributePermission(inodePath, false, true, false) ); LockingScheme lockingScheme = createLockingScheme(path, context.getOptions().getCommonOptions(), LockPattern.WRITE_INODE); try (LockedInodePath inodePath = mInodeTree.lockInodePath(lockingScheme)) { mPermissionChecker.checkSetAttributePermission(inodePath, false, true, false); if (context.getOptions().getRecursive()) { try (LockedInodePathList descendants = mInodeTree.getDescendants(inodePath)) { for (LockedInodePath child : descendants) { mPermissionChecker.checkSetAttributePermission(child, false, true, false); } } catch (AccessControlException e) { auditContext.setAllowed(false); throw e; } } if (!inodePath.fullPathExists()) { throw new FileDoesNotExistException(ExceptionMessage .PATH_DOES_NOT_EXIST.getMessage(path)); } setAclInternal(rpcContext, action, inodePath, entries, context); auditContext.setSucceeded(true); } } }