auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private ListenableFuture<TransportChannel> getOrConnect(@CheckForNull InetSocketAddress address) { checkArgument(address != null); return Futures.transform(resolveSocketAddress(address), new Function<InetSocketAddress, TransportChannel>() { @Override public TransportChannel apply(final InetSocketAddress resolvedAddress) { return connectedChannels.get(resolvedAddress, new Computable<InetSocketAddress, TransportChannel>() { @Override public TransportChannel compute(final InetSocketAddress input) { final Channel channel = createConnectorChannel(); final TransportChannel transportChannel = createConnectorTransportChannel(channel, input); <START> Futures.addCallback(registerChannel(channel), new FutureCallback<Void>() { <END> @Override public void onSuccess(Void void0) { connect(channel, input, transportChannel); } @Override public void onFailure(Throwable throwable) { channel.unsafe().closeForcibly(); transportChannel.close(); } }); return transportChannel; } }); } }); }</code><technical_language>Lets return previous version of this code more compact; basically same</technical_language>

Target:
private ListenableFuture<TransportChannel> getOrConnect(@CheckForNull InetSocketAddress address) { checkArgument(address != null); return Futures.transform(resolveSocketAddress(address), new Function<InetSocketAddress, TransportChannel>() { @Override public TransportChannel apply(final InetSocketAddress resolvedAddress) { return connectedChannels.get(resolvedAddress, new Computable<InetSocketAddress, TransportChannel>() { @Override public TransportChannel compute(final InetSocketAddress input) { final Channel channel = createConnectorChannel(); final TransportChannel transportChannel = createConnectorTransportChannel(channel, input); eventLoop.register(channel).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { LOGGER.info("Registered connector: {}", transportChannel); connect(channel, input, transportChannel); } else { channel.unsafe().closeForcibly(); transportChannel.close(); } } }); return transportChannel; } }); } }); }
Source:
<code>public void testWrongSocket() { bot.view("Package Explorer").show(); bot.menu("File").click(); bot.menu("File").menu("Import...").click(); bot.shell("Import"); SWTBotTree tree = bot.tree(0); tree.expandNode("Git").select("Git Repository"); bot.button("Next >").click(); bot.shell("Import Git Repository"); bot.textWithLabel("URI:").setText("git://www.jgit.org:80/EGIT"); assertSourceParams(null, "www.jgit.org", "/EGIT", "git", "80", true, "", "", false, false); bot.button("Next >").click(); <START> assertEquals(" git://www.jgit.org:80/EGIT: not found.", bot.text(0) <END> .getText()); assertTrue(bot.button("Cancel").isEnabled()); assertTrue(bot.button("< Back").isEnabled()); assertFalse(bot.button("Next >").isEnabled()); assertFalse(bot.button("Finish").isEnabled()); bot.button("Cancel").click(); }</code><technical_language>EGit behaves differently this test expects, instead of displaying expected error message proceeds next wizard page ("Select branches clone remote repository."). msysgit CLI behaves similarily clone this URL, initializes empty repository hangs forever</technical_language>

Target:
public void testWrongSocket() { goToImportGitRepository(); bot.textWithLabel("URI:").setText("git://www.jgit.org:80/EGIT"); assertSourceParams(null, "www.jgit.org", "/EGIT", "git", "80", true, "", "", false, false); bot.button("Next >").click(); assertEquals(" git://www.jgit.org:80/EGIT: not found.", bot.text(0) .getText()); assertTrue(bot.button("Cancel").isEnabled()); assertTrue(bot.button("< Back").isEnabled()); assertFalse(bot.button("Next >").isEnabled()); assertFalse(bot.button("Finish").isEnabled()); bot.button("Cancel").click(); }
Source:
<code>public KieServerExtension scenarioSimulationServerExtension() { <START> return new ScenarioSimulationKieServerExtension(); <END> }</code><technical_language>Please replace this instance SpringBootScenarioSimulationKieServerExtension</technical_language>

Target:
public KieServerExtension scenarioSimulationServerExtension() { return new SpringBootScenarioSimulationKieServerExtension(); }
Source:
<code>public void marshal(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception { String filename; String filepath = exchange.getIn().getHeader(FILE_NAME, String.class); if (filepath == null) { filename = filepath = StringHelper.sanitize(exchange.getIn().getMessageId()); } else { filename = Paths.get(filepath).getFileName().toString(); } <START> <END> ZipOutputStream zos = new ZipOutputStream(stream); zos.putNextEntry(new ZipEntry(filepath)); InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, exchange, graph); try { IOHelper.copy(is, zos); } finally { IOHelper.close(is, zos); } String newFilename = filename + ".zip"; exchange.getOut().setHeader(FILE_NAME, newFilename); }</code><technical_language>Double assigment? Intentional</technical_language>

Target:
public void marshal(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception { String filename; String filepath = exchange.getIn().getHeader(FILE_NAME, String.class); if (filepath == null) { filename = filepath = StringHelper.sanitize(exchange.getIn().getMessageId()); } else { filename = Paths.get(filepath).getFileName().toString(); } ZipOutputStream zos = new ZipOutputStream(stream); if (preservePathElements) { createZipEntries(zos, filepath); } else { createZipEntries(zos, filename); } InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, exchange, graph); try { IOHelper.copy(is, zos); } finally { IOHelper.close(is, zos); } String newFilename = filename + ".zip"; exchange.getOut().setHeader(FILE_NAME, newFilename); }
Source:
<code>static int getExifRotation(int orientation) { switch (orientation) { case ORIENTATION_ROTATE_90: case ORIENTATION_TRANSPOSE: return 90; case ORIENTATION_ROTATE_180: <START> case ORIENTATION_FLIP_VERTICAL: <END> return 180; case ORIENTATION_ROTATE_270: case ORIENTATION_TRANSVERSE: return 270; default: return 0; } }</code><technical_language>A flip != 180 rotation</technical_language>

Target:
static int getExifRotation(int orientation) { int rotation; switch (orientation) { case ORIENTATION_ROTATE_90: case ORIENTATION_TRANSPOSE: rotation = 90; break; case ORIENTATION_ROTATE_180: case ORIENTATION_FLIP_VERTICAL: rotation = 180; break; case ORIENTATION_ROTATE_270: case ORIENTATION_TRANSVERSE: rotation = 270; break; default: rotation = 0; } return rotation; }
Source:
<code>public void deleteDraft() { JCUser user = userService.getCurrentUser(); TopicDraft topicDraft = topicDraftDao.getForUser(user); <START> if (topicDraft != null) { <END> topicDraftDao.delete(topicDraft); } }</code><technical_language>If add method deleteDraft(User user) DAO itself, allow delete HQL delete instead of loading first. 2x faster :)</technical_language>

Target:
public void deleteDraft() { JCUser user = userService.getCurrentUser(); topicDraftDao.deleteByUser(user); }
Source:
<code>private static Type getPrestoType(String elasticsearchType) { switch (elasticsearchType) { case "double": case "float": return DOUBLE; case "integer": return INTEGER; case "long": return BIGINT; case "string": case "text": case "keyword": return VARCHAR; case "boolean": return BOOLEAN; case "binary": return VARBINARY; default: <START> throw new IllegalArgumentException("Not supported Elasticsearch type: " + elasticsearchType); <END> } }</code><technical_language>Unsupported type:</technical_language>

Target:
private static Type getPrestoType(String elasticsearchType) { switch (elasticsearchType) { case "double": case "float": return DOUBLE; case "integer": return INTEGER; case "long": return BIGINT; case "string": case "text": case "keyword": return VARCHAR; case "boolean": return BOOLEAN; case "binary": return VARBINARY; default: throw new IllegalArgumentException("Unsupported type: " + elasticsearchType); } }
Source:
<code>public String getName() { <START> return this.modeName; <END> }</code><technical_language>a differentiation of name id</technical_language>

Target:
public String getName() { return this.friendlyName; }
Source:
<code>public static SdtFile getSdtFile(String archiveFilename) { <START> for (String part : new String[] {"HD.sdt", "HD.SDT", "HW.sdt", "HW.SDT"}) { <END> File f = new File(PathUtils.getDKIIFolder() + PathUtils.DKII_SFX_FOLDER + archiveFilename + part); if (f.exists()) { return new SdtFile(f); } } return null; }</code><technical_language>ConversionUtils.getRealFileName instead of duplicate entries</technical_language>

Target:
public static SdtFile getSdtFile(String archiveFilename) { for (String part : new String[] {"HD.sdt", "HW.sdt"}) { try { File f = new File(ConversionUtils.getRealFileName(PathUtils.getDKIIFolder(), PathUtils.DKII_SFX_FOLDER + archiveFilename + part)); if (f.exists()) { return new SdtFile(f); } } catch (Exception ex) { } } LOGGER.log(Level.WARNING, "SDT File archive {0} not found", archiveFilename); return null; }
Source:
<code>public AvroUser() { <START> this(AvroUserSchemaLoader.load(), "", 0, "") ; <END> }</code><technical_language>default for **name** **favouriteColor** recognisable "defaultName" "defaultColor" instead of empty strings... easier debug tests later..</technical_language>

Target:
public AvroUser() { this(AvroUserSchemaLoader.load(), "defaultName", 0, "defaultColor") ; }
Source:
<code>public Collection<PluginFQN> parsePlugins(Map<String, String> attributes) throws InfrastructureException { if (attributes == null) { return emptyList(); } String pluginsAttribute = attributes.getOrDefault(Constants.WORKSPACE_TOOLING_PLUGINS_ATTRIBUTE, null); <START> String editorAttribute = <END> attributes.getOrDefault(Constants.WORKSPACE_TOOLING_EDITOR_ATTRIBUTE, null); List<PluginFQN> metaFQNs = new ArrayList<>(); if (!isNullOrEmpty(pluginsAttribute)) { String[] plugins = pluginsAttribute.split(" *, *"); if (plugins.length != 0) { metaFQNs.addAll(parsePluginFQNs(plugins)); } } if (!isNullOrEmpty(editorAttribute)) { String[] editor = editorAttribute.split(" *, *"); if (editor.length > 1) { throw new InfrastructureException( "Multiple editors found in workspace config attributes. " + "Only one editor is supported per workspace."); } metaFQNs.addAll(parsePluginFQNs(editor)); } return metaFQNs; }</code><technical_language>a public method good lines java doc</technical_language>

Target:
public Collection<PluginFQN> parsePlugins(Map<String, String> attributes) throws InfrastructureException { if (attributes == null) { return emptyList(); } String pluginsAttribute = attributes.getOrDefault(Constants.WORKSPACE_TOOLING_PLUGINS_ATTRIBUTE, null); String editorAttribute = attributes.getOrDefault(Constants.WORKSPACE_TOOLING_EDITOR_ATTRIBUTE, null); List<PluginFQN> metaFQNs = new ArrayList<>(); if (!isNullOrEmpty(pluginsAttribute)) { String[] plugins = splitAttribute(pluginsAttribute); if (plugins.length != 0) { metaFQNs.addAll(parsePluginFQNs(plugins)); } } if (!isNullOrEmpty(editorAttribute)) { String[] editor = splitAttribute(editorAttribute); if (editor.length > 1) { throw new InfrastructureException( "Multiple editors found in workspace config attributes. " + "Only one editor is supported per workspace."); } metaFQNs.addAll(parsePluginFQNs(editor)); } return metaFQNs; }
Source:
<code>public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); if (aggregate.getGroupSets().size() != 1) { return; } List<AggregateCall> newAggCalls = new ArrayList<AggregateCall>(); <START> AggregateFactory f = HiveRelFactories.HIVE_AGGREGATE_FACTORY; <END> VBuilder vb = new VBuilder(aggregate); ProjectFactory projectFactory = HiveRelFactories.HIVE_PROJECT_FACTORY; if (aggregate.getAggCallList().equals(vb.newAggCalls)) { return; } newAggCalls = vb.newAggCalls; RelNode newAgg = aggregate.copy(aggregate.getTraitSet(), aggregate.getInput(), aggregate.getGroupSet(), aggregate.getGroupSets(), newAggCalls); RelNode newProject = projectFactory.createProject(newAgg, vb.newProjects, aggregate.getRowType().getFieldNames()); call.transformTo(newProject); return; }</code><technical_language>I guess passing builder incur a penalty rule instantiation? is perfect set factories in constructor rest remains generic? Additionally, pass sketchClass enum instead of full HiveConf</technical_language>

Target:
public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); if (aggregate.getGroupSets().size() != 1) { return; } List<AggregateCall> newAggCalls = new ArrayList<AggregateCall>(); VBuilder vb = new VBuilder(aggregate); if (aggregate.getAggCallList().equals(vb.newAggCalls)) { return; } newAggCalls = vb.newAggCalls; RelNode newAgg = aggregate.copy(aggregate.getTraitSet(), aggregate.getInput(), aggregate.getGroupSet(), aggregate.getGroupSets(), newAggCalls); RelNode newProject = projectFactory.createProject(newAgg, vb.newProjects, aggregate.getRowType().getFieldNames()); call.transformTo(newProject); return; }
Source:
<code>public Object fromAvro(Schema schema, Object input) { switch (schema.getType()) { case NULL: if (input == null) { return null; } throw new NonNullValueException(); case UNION: for (Schema sub : schema.getTypes()) { try { return service.fromAvro(sub, BlobProperty.class, input); } catch (NonNullValueException e) { } } throw new RuntimeServiceException(CANNOT_MAP_FROM + schema.getType()); case RECORD: try { GenericRecord record = (GenericRecord) input; <START> String mimeType = (String) record.get(service.encodeName(Constants.MIME_TYPE)); <END> String encoding = (String) record.get(Constants.ENCODING); byte[] bytes = ((ByteBuffer) record.get(Constants.DATA)).array(); Blob b = Blobs.createBlob(bytes, mimeType, encoding); b.setFilename((String) record.get(Constants.NAME)); b.setDigest((String) record.get(Constants.DIGEST)); return b; } catch (IOException e) { throw new RuntimeServiceException(CANNOT_MAP_FROM + schema.getType(), e); } default: throw new RuntimeServiceException(CANNOT_MAP_FROM + schema.getType()); } }</code><technical_language>import in a static constants use, especially Constants is pacakge protected</technical_language>

Target:
public Object fromAvro(Schema schema, Object input) { switch (schema.getType()) { case NULL: if (input == null) { return null; } throw new NonNullValueException(); case UNION: for (Schema sub : schema.getTypes()) { try { return service.fromAvro(sub, BlobProperty.class, input); } catch (NonNullValueException e) { } } throw new RuntimeServiceException(CANNOT_MAP_FROM + schema.getType()); case RECORD: try { GenericRecord record = (GenericRecord) input; String mimeType = (String) record.get(service.encodeName(AvroConstants.MIME_TYPE)); String encoding = (String) record.get(AvroConstants.ENCODING); byte[] bytes = ((ByteBuffer) record.get(AvroConstants.DATA)).array(); Blob b = Blobs.createBlob(bytes, mimeType, encoding); b.setFilename((String) record.get(AvroConstants.CONTENT_NAME)); b.setDigest((String) record.get(AvroConstants.DIGEST)); return b; } catch (IOException e) { throw new RuntimeServiceException(CANNOT_MAP_FROM + schema.getType(), e); } default: throw new RuntimeServiceException(CANNOT_MAP_FROM + schema.getType()); } }
Source:
<code>private static String extractScriptStackTrace(RhinoException e) { <START> String st = e.getScriptStackTrace(); <END> if (st.equals("")) return null; return st; }</code><technical_language>return (e.getScriptStackTrace().isEmpty() ? null : e.getScriptStackTrace();</technical_language>

Target:
private static String extractScriptStackTrace(RhinoException e) { String st = e.getScriptStackTrace(); if (st.isEmpty()) return null; return st; }
Source:
<code>protected final void init() { eventBus.init(this); <START> tenantIndex.init(this); <END> }</code><technical_language>This reads if TenantIndex initializes BoundedContext</technical_language>

Target:
protected final void init() { eventBus.registerWith(this); tenantIndex.registerWith(this); }
Source:
<code>private void searchForDefault() { long start = System.currentTimeMillis(); ArrayList<File> roots = new ArrayList<>(); ArrayList<File> folders = new ArrayList<>(); if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState())) { <START> Logger.log(LogTypes.SOFT_ASSERT, "Access outside scoped storage in searching zip file"); <END> roots.add(Environment.getExternalStorageDirectory()); } for (String s : FileUtil.getExternalMounts()) { roots.add(new File(s)); } for (File r : roots) { folders.add(r); for (File f : r.listFiles()) { if (f.isDirectory()) { folders.add(f); } } } File bestMatch = null; for (File folder : folders) { for (File f : folder.listFiles()) { String name = f.getName().toLowerCase(); if (name.startsWith("commcare") && name.endsWith(".zip")) { if (bestMatch == null) { bestMatch = f; } else { if (bestMatch.lastModified() < f.lastModified()) { bestMatch = f; } } } } if (bestMatch != null) { break; } if (System.currentTimeMillis() - start > MAX_TIME_TO_TRY) { Log.i(LOG_TAG, "Had to bail on looking for a default file, was taking too long"); break; } } if (bestMatch != null) { editFileLocation.setText(bestMatch.getAbsolutePath()); } }</code><technical_language>this path get hit if is this functionality. is point in adding soft assert need disable this functionality in Android 11 if is other alternate provided in Android 11 for file searching</technical_language>

Target:
private void searchForDefault() { long start = System.currentTimeMillis(); ArrayList<File> roots = new ArrayList<>(); ArrayList<File> folders = new ArrayList<>(); if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState())) { roots.add(Environment.getExternalStorageDirectory()); } for (String s : FileUtil.getExternalMounts()) { roots.add(new File(s)); } for (File r : roots) { folders.add(r); for (File f : r.listFiles()) { if (f.isDirectory()) { folders.add(f); } } } File bestMatch = null; for (File folder : folders) { for (File f : folder.listFiles()) { String name = f.getName().toLowerCase(); if (name.startsWith("commcare") && name.endsWith(".zip")) { if (bestMatch == null) { bestMatch = f; } else { if (bestMatch.lastModified() < f.lastModified()) { bestMatch = f; } } } } if (bestMatch != null) { break; } if (System.currentTimeMillis() - start > MAX_TIME_TO_TRY) { Log.i(LOG_TAG, "Had to bail on looking for a default file, was taking too long"); break; } } if (bestMatch != null) { editFileLocation.setText(bestMatch.getAbsolutePath()); } }
Source:
<code><START> public void handleToken(Token<GcodeTokenId> token, int line) { <END> if (GcodeTokenId.MOVEMENT.equals(token.id())) { if ((StringUtils.equalsIgnoreCase(token.text(), Code.G1.name()) || StringUtils.equalsIgnoreCase(token.text(), Code.G3.name())) && firstMovementToken == null) { firstMovementToken = token; firstMovementLine = line; } } else if (GcodeTokenId.PARAMETER.equals(token.id())) { if (StringUtils.startsWithIgnoreCase(token.text(), "F") && firstFeedRateToken == null) { firstFeedRateToken = token; firstFeedRateLine = line; } } }</code><technical_language>Move firstMovementToken == null firstFeedRateToken == null front of outer if/else short circuit string comparisons for of program</technical_language>

Target:
public void handleToken(Token<GcodeTokenId> token, int line) { if (GcodeTokenId.MOVEMENT.equals(token.id())) { if (isMovementCommand(token) && firstMovementToken == null) { firstMovementToken = token; firstMovementLine = line; } } else if (GcodeTokenId.PARAMETER.equals(token.id())) { if (StringUtils.startsWithIgnoreCase(token.text(), "F") && firstFeedRateToken == null) { firstFeedRateToken = token; firstFeedRateLine = line; } } }
Source:
<code>public void testCodeActionsQuickAssist() throws CoreException { MockLanguageServer.reset(); IProject p = TestUtils.createProject(getClass().getSimpleName() + System.currentTimeMillis()); IFile f = TestUtils.createUniqueTestFile(p, "error"); TextEdit tEdit = new TextEdit(new Range(new Position(0, 0), new Position(0, 5)), "fixed"); WorkspaceEdit wEdit = new WorkspaceEdit(Collections.singletonMap(f.getLocationURI().toString(), Collections.singletonList(tEdit))); MockLanguageServer.INSTANCE.setCodeActions(Collections .singletonList(Either.forLeft(new Command( "fixme", "edit", Collections.singletonList(wEdit)) ) )); AbstractTextEditor editor = (AbstractTextEditor)TestUtils.openEditor(f); final Set<Shell> beforeShells = Arrays.stream(editor.getSite().getShell().getDisplay().getShells()).filter(Shell::isVisible).collect(Collectors.toSet()); editor.selectAndReveal(3, 0); TextOperationAction action = (TextOperationAction) editor.getAction(ITextEditorActionConstants.QUICK_ASSIST); action.update(); action.run(); this.completionShell= TestUtils.findNewShell(beforeShells, editor.getSite().getShell().getDisplay()); final Table completionProposalList = TestUtils.findCompletionSelectionControl(completionShell); checkCompletionContent(completionProposalList); editor.close(false); <START> p.delete(true, new NullProgressMonitor()); <END> }</code><technical_language>AllCleanRule do work of lines 158..159, skip this code</technical_language>

Target:
public void testCodeActionsQuickAssist() throws CoreException { MockLanguageServer.reset(); IProject p = TestUtils.createProject(getClass().getSimpleName() + System.currentTimeMillis()); IFile f = TestUtils.createUniqueTestFile(p, "error"); TextEdit tEdit = new TextEdit(new Range(new Position(0, 0), new Position(0, 5)), "fixed"); WorkspaceEdit wEdit = new WorkspaceEdit(Collections.singletonMap(f.getLocationURI().toString(), Collections.singletonList(tEdit))); MockLanguageServer.INSTANCE.setCodeActions(Collections .singletonList(Either.forLeft(new Command( "fixme", "edit", Collections.singletonList(wEdit)) ) )); AbstractTextEditor editor = (AbstractTextEditor)TestUtils.openEditor(f); final Set<Shell> beforeShells = Arrays.stream(editor.getSite().getShell().getDisplay().getShells()).filter(Shell::isVisible).collect(Collectors.toSet()); editor.selectAndReveal(3, 0); TextOperationAction action = (TextOperationAction) editor.getAction(ITextEditorActionConstants.QUICK_ASSIST); action.update(); action.run(); Shell completionShell= TestUtils.findNewShell(beforeShells, editor.getSite().getShell().getDisplay()); final Table completionProposalList = TestUtils.findCompletionSelectionControl(completionShell); checkCompletionContent(completionProposalList); }
Source:
<code>boolean validateCommitMsg(Job job) { String ignoreCommitMsg = job.getIgnoreCommitMsg(); if(ignoreCommitMsg.isEmpty()){ return true; } else{ CommitRequest commitRequest = new CommitRequest.Builder( repository, refChange.getToHash()).build(); String actualCommitMsg = commitService.getCommit(commitRequest).getMessage(); boolean hasIgnoreMsg = actualCommitMsg != null && <START> actualCommitMsg.toLowerCase().contains(ignoreCommitMsg.toLowerCase()); <END> return !hasIgnoreMsg; } }</code><technical_language>I treat ignoreCommitMsg a regex instead of a substring. This give users more power check for multiple strings a commit message check a portion of string (beginning end typically)</technical_language>

Target:
boolean validateCommitMsg(Job job) { String ignoreCommitMsg = job.getIgnoreCommitMsg(); if(ignoreCommitMsg.isEmpty()){ return true; } else{ CommitRequest commitRequest = new CommitRequest.Builder( repository, refChange.getToHash()).build(); String actualCommitMsg = commitService.getCommit(commitRequest).getMessage(); boolean hasIgnoreMsg = actualCommitMsg != null && actualCommitMsg.matches(ignoreCommitMsg); return !hasIgnoreMsg; } }
Source:
<code>private Collection<T> getHierarchyMapperExpandedItems() { HierarchyMapper<T, ?> hierarchyMapper = getHierarchyMapper(); if (!hierarchyMapper.hasExpandedItems()) { <START> return Collections.unmodifiableCollection(Collections.emptySet()); <END> } Collection<T> expandedItems = new HashSet<>(); getHierarchyMapper().fetchRootItems(null) .forEach(root -> expandedItems.addAll(getExpandedItems(root))); return Collections.unmodifiableCollection(expandedItems); }</code><technical_language>Collections.emptySet() produces empty unmodifiable set, I recall, do wrap again</technical_language>

Target:
private Collection<T> getHierarchyMapperExpandedItems() { HierarchyMapper<T, ?> hierarchyMapper = getHierarchyMapper(); if (!hierarchyMapper.hasExpandedItems()) { return Collections.emptySet(); } Collection<T> expandedItems = new HashSet<>(); getHierarchyMapper().fetchRootItems(null) .forEach(root -> expandedItems.addAll(getExpandedItems(root))); return Collections.unmodifiableCollection(expandedItems); }
Source:
<code>public Response setEndOffsets( Map<Integer, Long> offsets, @QueryParam("resume") @DefaultValue("false") final boolean resume ) throws InterruptedException { if (offsets == null) { return Response.status(Response.Status.BAD_REQUEST) .entity("Request body must contain a map of { partition:endOffset }") .build(); } else if (!endOffsets.keySet().containsAll(offsets.keySet())) { return Response.status(Response.Status.BAD_REQUEST) .entity( String.format( "Request contains partitions not being handled by this task, my partitions: %s", endOffsets.keySet() ) ) .build(); } <START> for (Integer partition : offsets.keySet()) { <END> if (offsets.get(partition).compareTo(nextOffsets.get(partition)) < 0) { return Response.status(Response.Status.BAD_REQUEST) .entity( String.format( "End offset must be >= current offset for partition [%s] (current: %s)", partition, nextOffsets.get(partition) ) ) .build(); } } pauseLock.lockInterruptibly(); try { if (!paused) { return Response.status(Response.Status.BAD_REQUEST) .entity("Task must be paused before changing the end offsets") .build(); } endOffsets.putAll(offsets); log.info("endOffsets changed to %s", endOffsets); } finally { pauseLock.unlock(); } if (resume) { resume(); } return Response.ok(endOffsets).build(); }</code><technical_language>nit: is more desired in java land if wanted iterate keys values in a map for (Map.Entry<Integer, Long> entry : offsets.entrySet())</technical_language>

Target:
public Response setEndOffsets( Map<Integer, Long> offsets, @QueryParam("resume") @DefaultValue("false") final boolean resume ) throws InterruptedException { if (offsets == null) { return Response.status(Response.Status.BAD_REQUEST) .entity("Request body must contain a map of { partition:endOffset }") .build(); } else if (!endOffsets.keySet().containsAll(offsets.keySet())) { return Response.status(Response.Status.BAD_REQUEST) .entity( String.format( "Request contains partitions not being handled by this task, my partitions: %s", endOffsets.keySet() ) ) .build(); } pauseLock.lockInterruptibly(); try { if (!isPaused()) { return Response.status(Response.Status.BAD_REQUEST) .entity("Task must be paused before changing the end offsets") .build(); } for (Map.Entry<Integer, Long> entry : offsets.entrySet()) { if (entry.getValue().compareTo(nextOffsets.get(entry.getKey())) < 0) { return Response.status(Response.Status.BAD_REQUEST) .entity( String.format( "End offset must be >= current offset for partition [%s] (current: %s)", entry.getKey(), nextOffsets.get(entry.getKey()) ) ) .build(); } } endOffsets.putAll(offsets); log.info("endOffsets changed to %s", endOffsets); } finally { pauseLock.unlock(); } if (resume) { resume(); } return Response.ok(endOffsets).build(); }
Source:
<code>public String computeHmac(byte[] data) { SecretKey hmacKey = deriveKey(32, "hmackey"); try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(hmacKey); return BaseEncoding.base16().encode(mac.doFinal(data)); } catch (NoSuchAlgorithmException | InvalidKeyException e) { logger.warn("Error computing HMAC: ", e); <START> return ""; <END> } }</code><technical_language>this null</technical_language>

Target:
public String computeHmac(byte[] data) { SecretKey hmacKey = deriveKey(32, "hmackey"); try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(hmacKey); return BaseEncoding.base16().encode(mac.doFinal(data)); } catch (NoSuchAlgorithmException | InvalidKeyException e) { logger.warn("Error computing HMAC: ", e); return null; } }
Source:
<code><START> public static Long srem(Region<ByteArrayWrapper, RedisSet> region, <END> ByteArrayWrapper key, ArrayList<ByteArrayWrapper> membersToRemove, AtomicBoolean setWasDeleted) { RedisSet redisSet = region.get(key); long numRemoved; if (redisSet == null) { numRemoved = 0; } else { numRemoved = redisSet.doSrem(membersToRemove, region, key, setWasDeleted); } return numRemoved; }</code><technical_language>code returned "long" it? reason change this Long</technical_language>

Target:
public static long srem(Region<ByteArrayWrapper, RedisSet> region, ByteArrayWrapper key, ArrayList<ByteArrayWrapper> membersToRemove, AtomicBoolean setWasDeleted) { RedisSet redisSet = region.get(key); long numRemoved; if (redisSet == null) { numRemoved = 0; } else { numRemoved = redisSet.doSrem(membersToRemove, region, key, setWasDeleted); } return numRemoved; }
Source:
<code>public byte[] getCacheKey() { <START> byte[] dimBytes = this.dimension.getBytes(Charsets.UTF_8); <END> byte[] valBytes = this.value.getBytes(Charsets.UTF_8); return ByteBuffer.allocate(2 + dimBytes.length + valBytes.length) .put(CACHE_KEY) .put(dimBytes) .put(STRING_SEPARATOR) .put(valBytes) .array(); }</code><technical_language>StringUtils.toUtf8</technical_language>

Target:
public byte[] getCacheKey() { byte[] dimBytes = StringUtils.toUtf8(this.dimension); byte[] valBytes = StringUtils.toUtf8(this.value); return ByteBuffer.allocate(2 + dimBytes.length + valBytes.length) .put(CACHE_KEY) .put(dimBytes) .put(STRING_SEPARATOR) .put(valBytes) .array(); }
Source:
<code>protected int tryAcquireShared(int ignore) { <START> return getState() >= STARTED ? 1 : -1; <END> }</code><technical_language>this getState() > STARTED? >=, awaitStarted able proceed state check state is some kind of START_EXITED_*, fail succeeded</technical_language>

Target:
protected int tryAcquireShared(int ignore) { return getState() > STARTED ? 1 : -1; }
Source:
<code>public void checkSamplefn5NaN(){ final String expression = "fn:arrayNaN(\"x\", 5)"; boolean success = true; StringBuffer sb = new StringBuffer(""); try{ double[] result = performExpression(expression); for (double value: result){ sb.append(value+","); } success = Double.isNaN(result[0]) && Double.isNaN(result[1]) && Double.isNaN(result[2]) && Double.isNaN(result[3]) && Double.isNaN(result[4]) && (result[5] == 5) && (result[6] == 6); <START> } catch (Exception e){ <END> e.printStackTrace(); success = false; } System.out.println("JEXLExpressionEngineEnhancedTest: expression="+expression +"\n result "+sb.toString()); assertTrue(success); }</code><technical_language>re-throw exception instead of catching here? test fail stack printed automatically</technical_language>

Target:
public void checkSamplefn5NaN() { final String expression = "fn:arrayNaN(\"x\", 5)"; StringBuffer sb = new StringBuffer(""); try{ double[] result = performExpression(expression); for (double value: result){ sb.append(value+","); } System.out.println("JEXLExpressionEngineEnhancedTest: expression="+expression +"\n result "+sb.toString()); assertEquals(Double.NaN, result[0], DELTA); assertEquals(Double.NaN, result[1], DELTA); assertEquals(Double.NaN, result[2], DELTA); assertEquals(Double.NaN, result[3], DELTA); assertEquals(Double.NaN, result[4], DELTA); assertEquals(5, result[5], DELTA); assertEquals(6, result[6], DELTA); } catch (Exception e){ throw new RuntimeException(e); } }
Source:
<code>public synchronized InetAddress getResolvedDestinationAddress() throws UnknownHostException { this.resolvedDestinationAddress = InetAddress.getByName(this.unresolvedDestinationAddress); return this.resolvedDestinationAddress; <START> } <END></code><technical_language>This resolvedDestinationAddress passed in constructor</technical_language>

Target:
public synchronized InetAddress getResolvedDestinationAddress() throws UnknownHostException { if (this.resolvedDestinationAddress != null) { return this.resolvedDestinationAddress; } return InetAddress.getByName(this.unresolvedDestinationAddress); }
Source:
<code>private Map<String, ResourceAssignment> calculateAssignment(ClusterModel clusterModel, RebalanceAlgorithm algorithm) throws HelixRebalanceException { long startTime = System.currentTimeMillis(); LOG.info("Start calculating for an assignment"); OptimalAssignment optimalAssignment = algorithm.calculate(clusterModel); Map<String, ResourceAssignment> newAssignment = optimalAssignment.getOptimalResourceAssignment(); <START> LOG.info("Finish calculating an assignment. Took: ms.", <END> System.currentTimeMillis() - startTime); return newAssignment; }</code><technical_language>Print algorithm algorithm using</technical_language>

Target:
private Map<String, ResourceAssignment> calculateAssignment(ClusterModel clusterModel, RebalanceAlgorithm algorithm) throws HelixRebalanceException { long startTime = System.currentTimeMillis(); LOG.info("Start calculating for an assignment with algorithm {}", algorithm.getClass().getSimpleName()); OptimalAssignment optimalAssignment = algorithm.calculate(clusterModel); Map<String, ResourceAssignment> newAssignment = optimalAssignment.getOptimalResourceAssignment(); LOG.info("Finish calculating an assignment with algorithm {}. Took: ms.", algorithm.getClass().getSimpleName(), System.currentTimeMillis() - startTime); return newAssignment; }
Source:
<code>public void dispose() throws Exception { <START> latch.awaitFinished(); <END> if (controller.isConnected()) controller.disconnect(); }</code><technical_language>fix here, condition sequence is causing issue? concerned tests get a state blocks forever, specifically, SpecificationStatement evaluate a lot of catching of exceptions latch trigger a finally calls this. hard reason if in cases scriptFuture Thread in a good state latch finished eventually triggered</technical_language>

Target:
public void dispose() throws Exception { if (controller.isConnected()) controller.disconnect(); }
Source:
<code>public void enforceRequiredVariables() { VariableScope variableScope = getVariableScope(); for (Variable variable : variableScope.getVariables()) { String name = variable.getName(); if (variableScope.isRequired(name)) { if (name.startsWith(VariableScope.CASE_FILE_PREFIX)) { <START> if (!findCaseData(variable.getName())) { <END> throw new VariableViolationException(getProcessInstance().getId(), name, "Case file item '" + name + "' is required but not set"); } } else if (!variables.containsKey(name)) { throw new VariableViolationException(getProcessInstance().getId(), variable.getName(), "Variable '" + variable.getName() + "' is required but not set"); } } } }</code><technical_language>variable.getName() is retrieved name suggestion if (!findCaseData(name)) {</technical_language>

Target:
public void enforceRequiredVariables() { VariableScope variableScope = getVariableScope(); for (Variable variable : variableScope.getVariables()) { String name = variable.getName(); if (variableScope.isRequired(name)) { if (name.startsWith(VariableScope.CASE_FILE_PREFIX)) { if (!findCaseData(name)) { throw new VariableViolationException(getProcessInstance().getId(), name, "Case file item '" + name + "' is required but not set"); } } else if (!variables.containsKey(name)) { throw new VariableViolationException(getProcessInstance().getId(), name, "Variable '" + name + "' is required but not set"); } } } }
Source:
<code>public int hashCode() { int result = taskName != null ? taskName.hashCode() : 0; result = 31 * result + (description != null ? description.hashCode() : 0); <START> result = 31 * result + hashCode; <END> return result; }</code><technical_language>hashCode depend taskName, description, hashCode</technical_language>

Target:
public int hashCode() { int result = taskName != null ? taskName.hashCode() : 0; result = 31 * result + (description != null ? description.hashCode() : 0); result = 31 * result + uniqueId; return result; }
Source:
<code>private static XeSource source(final Doc doc, final String name, final Request req) throws IOException { final Href home = new RqHref.Base(req).href() .path("doc").with("file", name); final Attributes attrs = doc.attributes(); return new XeAppend( "doc", new XeChain( new XeDirectives( new Directives() .add("name").set(name).up() .add("size").set(Long.toString(attrs.size())).up() .add("created") .set(Long.toString(attrs.created().getTime())).up() .add("type").set(attrs.type()).up() .add("name").set(name) ), new XeLink("read", home.path("read")), <START> new XeLink("shortlink", new Href(doc.shortUrl())), <END> new XeLink("delete", home.path("delete")), new XeLink("add-friend", home.path("add-friend")), new XeAppend( "friends", new XeTransform<>( doc.friends().names(), new XeTransform.Func<String>() { @Override public XeSource transform(final String friend) { return TkDocs.source(friend, home); } } ) ) ) ); }</code><technical_language>"short"</technical_language>

Target:
private static XeSource source(final Doc doc, final String name, final Request req) throws IOException { final Href home = new RqHref.Base(req).href() .path("doc").with("file", name); final Attributes attrs = doc.attributes(); return new XeAppend( "doc", new XeChain( new XeDirectives( new Directives() .add("name").set(name).up() .add("size").set(Long.toString(attrs.size())).up() .add("created") .set(Long.toString(attrs.created().getTime())).up() .add("type").set(attrs.type()).up() .add("name").set(name) ), new XeLink("read", home.path("read")), new XeLink("short", new Href(doc.shortUrl())), new XeLink("delete", home.path("delete")), new XeLink("add-friend", home.path("add-friend")), new XeAppend( "friends", new XeTransform<>( doc.friends().names(), new XeTransform.Func<String>() { @Override public XeSource transform(final String friend) { return TkDocs.source(friend, home); } } ) ) ) ); }
Source:
<code>private void migrate(ItemDAO<Pipeline> dao, Pipeline pipeline, String type) { getStages(pipeline) .stream() .filter(stage -> stage.containsKey("stageTimeoutMs")) <START> .forEach(stage -> stage.put("timeoutMs", stage.get("stageTimeoutMs"))); <END> dao.update(pipeline.getId(), pipeline); log.info("Migrated stage timeouts", type, pipeline.getId()); }</code><technical_language>interest in removing stageTimeoutMs value</technical_language>

Target:
private void migrate(ItemDAO<Pipeline> dao, Pipeline pipeline, String type) { getStages(pipeline) .stream() .filter(stage -> stage.containsKey("stageTimeoutMs")) .forEach(stage -> stage.put("timeoutMs", stage.remove("stageTimeoutMs"))); dao.update(pipeline.getId(), pipeline); log.info("Migrated stage timeouts", type, pipeline.getId()); }
Source:
<code>public void testShowPopulatedScreenAssets() { when(libraryService.hasAssets(any(WorkspaceProject.class))).thenReturn(true); this.assetsScreen.init(); verify(emptyAssetsScreen, never()).getView(); verify(populatedAssetsScreen, times(1)).getView(); verify(view).setContent(populatedAssetsScreen.getView().getElement()); assertThat(assetsScreen.isEmpty(), <START> CoreMatchers.is(false)); <END> }</code><technical_language>this instead of assertThat(...).isTrue() assertj assertTrue(...) junit in other parts of this repo</technical_language>

Target:
public void testShowPopulatedScreenAssets() { when(libraryService.hasAssets(any(WorkspaceProject.class))).thenReturn(true); this.assetsScreen.init(); verify(emptyAssetsScreen, never()).getView(); verify(populatedAssetsScreen, times(1)).getView(); verify(view).setContent(populatedAssetsScreen.getView().getElement()); assertFalse(assetsScreen.isEmpty()); }
Source:
<code>public IMarkerResolution[] getResolutions(IMarker marker) { ArrayList resolutions = new ArrayList(); for (Object resolutionQueryEntry : resolutionQueries.entrySet()) { Map.Entry entry = (Entry) resolutionQueryEntry; MarkerQuery query = (MarkerQuery) entry.getKey(); MarkerQueryResult result = query.performQuery(marker); if (result != null) { Map resultsTable = (Map) entry.getValue(); if (resultsTable.containsKey(result)) { Iterator elements = ((Collection) resultsTable.get(result)).iterator(); while (elements.hasNext()) { IConfigurationElement element = (IConfigurationElement) elements.next(); IMarkerResolutionGenerator generator = null; try { generator = (IMarkerResolutionGenerator) element.createExecutableExtension(ATT_CLASS); IMarkerResolution[] res = generator.getResolutions(marker); if (res <START> == null) <END> { for (IMarkerResolution generatedResolution : res) { resolutions.add(generatedResolution); } } else { StatusManager.getManager() .handle(new Status(IStatus.ERROR, IDEWorkbenchPlugin.IDE_WORKBENCH, IStatus.ERROR, "Failure in " + generator.getClass().getName() + " from plugin " + element.getContributor().getName() + ": getResolutions(IMarker) must not return null", null), StatusManager.LOG); } } catch (CoreException e) { Policy.handle(e); } } } } } return (IMarkerResolution[]) resolutions.toArray(new IMarkerResolution[resolutions.size()]); }</code><technical_language>accidentally inverted condition wrongly</technical_language>

Target:
public IMarkerResolution[] getResolutions(IMarker marker) { ArrayList resolutions = new ArrayList(); for (Object resolutionQueryEntry : resolutionQueries.entrySet()) { Map.Entry entry = (Entry) resolutionQueryEntry; MarkerQuery query = (MarkerQuery) entry.getKey(); MarkerQueryResult result = query.performQuery(marker); if (result != null) { Map resultsTable = (Map) entry.getValue(); if (resultsTable.containsKey(result)) { Iterator elements = ((Collection) resultsTable.get(result)).iterator(); while (elements.hasNext()) { IConfigurationElement element = (IConfigurationElement) elements.next(); IMarkerResolutionGenerator generator = null; try { generator = (IMarkerResolutionGenerator) element.createExecutableExtension(ATT_CLASS); IMarkerResolution[] res = generator.getResolutions(marker); if (res != null) { for (IMarkerResolution generatedResolution : res) { resolutions.add(generatedResolution); } } else { StatusManager.getManager() .handle(new Status(IStatus.ERROR, IDEWorkbenchPlugin.IDE_WORKBENCH, IStatus.ERROR, "Failure in " + generator.getClass().getName() + " from plugin " + element.getContributor().getName() + ": getResolutions(IMarker) must not return null", null), StatusManager.LOG); } } catch (CoreException e) { Policy.handle(e); } } } } } return (IMarkerResolution[]) resolutions.toArray(new IMarkerResolution[resolutions.size()]); }
Source:
<code>private void addNetworkPostData() { if (nics == null) { return; } VmInterfaceModel model = <START> NewVmInterfaceModel.createInstance(getEntity().getStaticData(), getEntity().getStatus(), getEntity().getStoragePoolId(), <END> getEntity().getVdsGroupCompatibilityVersion(), nics, this); setWindow(model); stopProgress(); }</code><technical_language>I this formatted well</technical_language>

Target:
private void addNetworkPostData() { if (nics == null) { return; } VmInterfaceModel model = NewGuideVmInterfaceModel.createInstance(getEntity().getStaticData(), getEntity().getStoragePoolId(), getEntity().getVdsGroupCompatibilityVersion(), nics, this); setWindow(model); stopProgress(); }
Source:
<code>protected String prepareJsonPayload(Position position) { Map<String, Object> data = new HashMap<>(); if (position != null) { data.put(KEY_POSITION, position); } <START> if (position.getDeviceId() != 0) { <END> Device device = Context.getIdentityManager().getById(position.getDeviceId()); if (device != null) { data.put(KEY_DEVICE, device); } } try { return Context.getObjectMapper().writeValueAsString(data); } catch (JsonProcessingException e) { Log.warning(e); return null; } }</code><technical_language>I this check if necessary next check device for null enough</technical_language>

Target:
protected String prepareJsonPayload(Position position) { Map<String, Object> data = new HashMap<>(); Device device = Context.getIdentityManager().getById(position.getDeviceId()); if (position != null) { data.put(KEY_POSITION, position); } if (device != null) { data.put(KEY_DEVICE, device); } try { return Context.getObjectMapper().writeValueAsString(data); } catch (JsonProcessingException e) { Log.warning(e); return null; } }
Source:
<code>public void decompress(ByteBuffer input, int compressedSize, ByteBuffer output, int uncompressedSize) throws IOException { output.clear(); try { DirectCodecPool.DECOMPRESS_METHOD.invoke(decompressor, (ByteBuffer) input.limit(compressedSize), (ByteBuffer) output.limit(uncompressedSize)); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); <START> } <END> output.position(uncompressedSize); }</code><technical_language>I assume printStackTrace() is want here</technical_language>

Target:
public void decompress(ByteBuffer input, int compressedSize, ByteBuffer output, int uncompressedSize) throws IOException { output.clear(); try { DECOMPRESS_METHOD.invoke(decompressor, (ByteBuffer) input.limit(compressedSize), (ByteBuffer) output.limit(uncompressedSize)); } catch (IllegalAccessException e) { throw new DirectCodecPool.ParquetCompressionCodecException(e); } catch (InvocationTargetException e) { throw new DirectCodecPool.ParquetCompressionCodecException(e); } output.position(uncompressedSize); }
Source:
<code>public boolean postProcess(ClassCollection modelClasses) { for (Map.Entry<String, Set<String>> module : classesInModule.entrySet()) { Set<ClassMetaData> classData = new LinkedHashSet<>(); for (String qualifiedClassName : module.getValue()) { if (!modelClasses.containsQualifiedClass(qualifiedClassName)) { Utils.error(Utils.stripPackage(qualifiedClassName) + " could not be added to the module. " + <START> "Only classes extending RealmObject, which are part of this project, can be added."); <END> return false; } classData.add(modelClasses.getClassFromQualifiedName(qualifiedClassName)); } String qualifiedModuleClassName = module.getKey(); if (moduleAnnotations.get(qualifiedModuleClassName).library()) { libraryModules.put(qualifiedModuleClassName, classData); } else { modules.put(qualifiedModuleClassName, classData); } } if (modules.size() > 0 && libraryModules.size() > 0) { Utils.error("Normal modules and library modules cannot be mixed in the same project"); return false; } if (libraryModules.size() == 0 && modelClasses.size() > 0) { shouldCreateDefaultModule = true; String defaultModuleName = Constants.REALM_PACKAGE_NAME + "." + Constants.DEFAULT_MODULE_CLASS_NAME; modules.put(defaultModuleName, modelClasses.getClasses()); } return true; }</code><technical_language>RealmModel classes ... include inheritance interface + annotation approach</technical_language>

Target:
public boolean postProcess(ClassCollection modelClasses) { for (String qualifiedModuleClassName : globalModules) { Set<ClassMetaData> classData = new LinkedHashSet<>(); classData.addAll(modelClasses.getClasses()); defineModule(qualifiedModuleClassName, classData); } for (Map.Entry<String, Set<String>> module : specificClassesModules.entrySet()) { String qualifiedModuleClassName = module.getKey(); Set<ClassMetaData> classData = new LinkedHashSet<>(); for (String qualifiedModelClassName : module.getValue()) { if (!modelClasses.containsQualifiedClass(qualifiedModelClassName)) { Utils.error(Utils.stripPackage(qualifiedModelClassName) + " could not be added to the module. " + "Only classes extending RealmObject or implementing RealmModel, which are part of this project, can be added."); return false; } classData.add(modelClasses.getClassFromQualifiedName(qualifiedModelClassName)); } defineModule(qualifiedModuleClassName, classData); } if (modules.size() > 0 && libraryModules.size() > 0) { Utils.error("Normal modules and library modules cannot be mixed in the same project"); return false; } if (libraryModules.size() == 0 && modelClasses.size() > 0) { shouldCreateDefaultModule = true; String defaultModuleName = Constants.REALM_PACKAGE_NAME + "." + Constants.DEFAULT_MODULE_CLASS_NAME; modules.put(defaultModuleName, modelClasses.getClasses()); } return true; }