auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void deleteReleaseWebHook(final ReleaseWebHookResource resource) { if (resource == null) { throw new InvalidParameterException("event parameter is null"); } final TeamPluginGlobalConfig config = TeamPluginGlobalConfig.get(); if (config == null) { throw new InternalError("Cannot load TFS global configuration"); } String webHookNameToDelete = resource.getWebHookName(); ReleaseWebHook webHook = validateAndGetReleaseWebHookByName(webHookNameToDelete); for (final Item projectItem : Jenkins.getActiveInstance().getAllItems()) { if (projectItem instanceof AbstractProject) { AbstractProject project = (AbstractProject) projectItem; ReleaseWebHookAction action = getReleaseWebHookActionFromProject(project); if (action != null) { for (ReleaseWebHookName webHookName : action.getWebHookNames()) { <START> if (webHookName.getWebHookName().equalsIgnoreCase(webHookNameToDelete)) { <END> logger.fine(String.format("WebHook %s is referenced in project %s. Cannot delete until all the references are removed.", webHookNameToDelete, project.getName())); return; } } } } } List<ReleaseWebHook> releaseWebHooks = ReleaseWebHookHelper.getReleaseWebHookConfigurations(); releaseWebHooks.remove(webHook); ReleaseWebHookHelper.saveReleaseWebHookConfigurations(releaseWebHooks); }</code><technical_language>getWebHookName ReleaseWebHookName</technical_language>

Target:
private void deleteReleaseWebHook(final ReleaseWebHookResource resource) { if (resource == null) { throw new InvalidParameterException("resource is null"); } final TeamPluginGlobalConfig config = TeamPluginGlobalConfig.get(); if (config == null) { throw new InternalError("Cannot load TFS global configuration"); } String webHookNameToDelete = resource.getWebHookName(); ReleaseWebHook webHook = validateAndGetReleaseWebHookByName(webHookNameToDelete); for (final Item projectItem : Jenkins.getActiveInstance().getAllItems()) { if (projectItem instanceof AbstractProject) { AbstractProject project = (AbstractProject) projectItem; ReleaseWebHookAction action = getReleaseWebHookActionFromProject(project); if (action != null) { for (ReleaseWebHookReference webHookReference : action.getWebHookReferences()) { if (webHookReference.getWebHookName().equalsIgnoreCase(webHookNameToDelete)) { throw new UnsupportedOperationException(String.format("WebHook %s is referenced in project %s. Cannot delete until all the references are removed.", webHookNameToDelete, project.getName())); } } } } } List<ReleaseWebHook> releaseWebHooks = ReleaseWebHookHelper.getReleaseWebHookConfigurations(); releaseWebHooks.remove(webHook); ReleaseWebHookHelper.saveReleaseWebHookConfigurations(releaseWebHooks); }
Source:
<code>public void update(CruiseConfig cruiseConfig) { cruiseConfig.update(getPipelineGroup(), pipelineConfig.name().toString(), pipelineConfig); if (!StringUtils.equalsIgnoreCase(group, updatedGroupName)) { PipelineConfigs group = cruiseConfig.findGroup(this.group); group.remove(pipelineConfig); <START> cruiseConfig.getGroups().addPipeline(updatedGroupName, pipelineConfig); <END> } }</code><technical_language>is a case I missed. adding a group existence check in canContinue handle I need add a check itself? Update: is a check of canEditPipeline in UpdatePipelineConfigCommand#canContinue blow if pipeline group exist. I suggest moving this block update method in UpdatePipelineConfigCommand.java. updates cruise config is added in entity command's update method. Similar CreatePipelineConfigCommand#update it</technical_language>

Target:
public void update(CruiseConfig cruiseConfig) { cruiseConfig.update(getExistingPipelineGroupName(), pipelineConfig.name().toString(), pipelineConfig); if (!existingGroupName.equalsIgnoreCase(newGroupName)) { PipelineConfigs group = cruiseConfig.findGroup(this.existingGroupName); group.remove(pipelineConfig); cruiseConfig.getGroups().addPipeline(newGroupName, pipelineConfig); } }
Source:
<code>private String buildSignedHeaders(Multimap<String, String> canonicalizedHeadersMap) { StringBuilder signedHeadersBuffer = new StringBuilder(); for (Entry<String, String> header : canonicalizedHeadersMap.entries()) { String key = header.getKey(); signedHeadersBuffer.append(key.toLowerCase()).append(";"); } if(signedHeadersBuffer.length() > 0) { signedHeadersBuffer.deleteCharAt(signedHeadersBuffer.length()-1); <START> } <END> return signedHeadersBuffer.toString(); }</code><technical_language>Instead of manually building string removing trailing ';', do like: java return Joiner.on(';').join(Iterables.transform(canonicalizedHeadersMap.keySet(), new Function<String, String>() { @Override public String apply(String input) { return input.toLowerCase(); } }));</technical_language>

Target:
private static String buildSignedHeaders(Multimap<String, String> canonicalizedHeadersMap) { return Joiner.on(';').join(Iterables.transform(canonicalizedHeadersMap.keySet(), new Function<String, String>() { @Override public String apply(String input) { return input.toLowerCase(); } })); }
Source:
<code>public static int getHeaderBlockEndColumnIndex(final List<GridColumn<?>> allColumns, final GridColumn.HeaderMetaData headerMetaData, final int headerRowIndex, final int headerColumnIndex) { int candidateHeaderColumnIndex = headerColumnIndex; if (candidateHeaderColumnIndex == allColumns.size() - 1) { return candidateHeaderColumnIndex; } while (candidateHeaderColumnIndex < allColumns.size() - 1) { final GridColumn candidateColumn = allColumns.get(candidateHeaderColumnIndex + 1); final List<GridColumn.HeaderMetaData> candidateHeaderMetaData = candidateColumn.getHeaderMetaData(); if (candidateHeaderMetaData.size() - 1 < headerRowIndex) { break; } <START> if (!candidateHeaderMetaData.get(headerRowIndex).equals(headerMetaData)) { <END> break; } candidateHeaderColumnIndex++; } return candidateHeaderColumnIndex; }</code><technical_language>assume Objects.equals</technical_language>

Target:
public static int getHeaderBlockEndColumnIndex(final List<GridColumn<?>> allColumns, final GridColumn.HeaderMetaData headerMetaData, final int headerRowIndex, final int headerColumnIndex) { int candidateHeaderColumnIndex = headerColumnIndex; if (candidateHeaderColumnIndex == allColumns.size() - 1) { return candidateHeaderColumnIndex; } while (candidateHeaderColumnIndex < allColumns.size() - 1) { final GridColumn candidateColumn = allColumns.get(candidateHeaderColumnIndex + 1); final List<GridColumn.HeaderMetaData> candidateHeaderMetaData = candidateColumn.getHeaderMetaData(); if (candidateHeaderMetaData.size() - 1 < headerRowIndex) { break; } if (!Objects.equals(candidateHeaderMetaData.get(headerRowIndex), headerMetaData)) { break; } candidateHeaderColumnIndex++; } return candidateHeaderColumnIndex; }
Source:
<code>public void onFrob(ActivateEvent event, EntityRef entity) { DoorComponent door = entity.getComponent(DoorComponent.class); <START> if (door.isOpen) { <END> entity.send(new CloseDoorEvent(event.getInstigator())); } else { entity.send(new CloseDoorEvent(event.getInstigator())); } }</code><technical_language>mentioned in Slack, send CloseDoorEvent in logic branches, I assume open</technical_language>

Target:
public void onFrob(ActivateEvent event, EntityRef entity) { DoorComponent door = entity.getComponent(DoorComponent.class); if (door.isOpen) { event.getInstigator().send(new CloseDoorEvent(entity)); } else { event.getInstigator().send(new OpenDoorEvent(entity)); } }
Source:
<code>public void destroyGameObject(int id) { <START> gameObjects.get(id).destroy(); <END> }</code><technical_language>want remove object observable do</technical_language>

Target:
public void destroyGameObject(int id) { gameObjects.remove(id); gameObjects.get(id).destroy(); }
Source:
<code>public String getSearchTitle() { String title = new String(); if (req.getParameter("q") != null && !req.getParameter("q").isEmpty()) { title += req.getParameter("q") + " (full)"; } if (req.getParameter(QueryBuilder.DEFS) != null && !req.getParameter(QueryBuilder.DEFS).isEmpty()) { title = addTitleDelimiter(title); title += req.getParameter(QueryBuilder.DEFS) + " (definition)"; } if (req.getParameter(QueryBuilder.REFS) != null && !req.getParameter(QueryBuilder.REFS).isEmpty()) { title = addTitleDelimiter(title); title += req.getParameter(QueryBuilder.REFS) + " (reference)"; } if (req.getParameter(QueryBuilder.PATH) != null && !req.getParameter(QueryBuilder.PATH).isEmpty()) { title = addTitleDelimiter(title); title += req.getParameter(QueryBuilder.PATH) + " (path)"; } if (req.getParameter(QueryBuilder.HIST) != null && !req.getParameter(QueryBuilder.HIST).isEmpty()) { title = addTitleDelimiter(title); title += req.getParameter(QueryBuilder.HIST) + " (history)"; } if (req.getParameterValues(QueryBuilder.PROJECT) != null && req.getParameterValues(QueryBuilder.PROJECT).length != 0) { if (!title.isEmpty()) { title += " "; } title += "in projects: "; String projects[] = req.getParameterValues(QueryBuilder.PROJECT); <START> for (int i = 0; i < projects.length; i++) { <END> title += projects[i]; if (i < projects.length - 1) { title += ", "; } } } return Util.htmlize(title + " - OpenGrok search results"); }</code><technical_language>I this review. In Java8 I is a possibility this shorter. like: java Arrays.asList(a).stream().collect(Collectors.joining(","))</technical_language>

Target:
public String getSearchTitle() { String title = new String(); if (req.getParameter("q") != null && !req.getParameter("q").isEmpty()) { title += req.getParameter("q") + " (full)"; } if (req.getParameter(QueryBuilder.DEFS) != null && !req.getParameter(QueryBuilder.DEFS).isEmpty()) { title = addTitleDelimiter(title); title += req.getParameter(QueryBuilder.DEFS) + " (definition)"; } if (req.getParameter(QueryBuilder.REFS) != null && !req.getParameter(QueryBuilder.REFS).isEmpty()) { title = addTitleDelimiter(title); title += req.getParameter(QueryBuilder.REFS) + " (reference)"; } if (req.getParameter(QueryBuilder.PATH) != null && !req.getParameter(QueryBuilder.PATH).isEmpty()) { title = addTitleDelimiter(title); title += req.getParameter(QueryBuilder.PATH) + " (path)"; } if (req.getParameter(QueryBuilder.HIST) != null && !req.getParameter(QueryBuilder.HIST).isEmpty()) { title = addTitleDelimiter(title); title += req.getParameter(QueryBuilder.HIST) + " (history)"; } if (req.getParameterValues(QueryBuilder.PROJECT) != null && req.getParameterValues(QueryBuilder.PROJECT).length != 0) { if (!title.isEmpty()) { title += " "; } title += "in projects: "; String projects[] = req.getParameterValues(QueryBuilder.PROJECT); title += Arrays.asList(projects).stream().collect(Collectors.joining(",")); } return Util.htmlize(title + " - OpenGrok search results"); }
Source:
<code>private void setVmToNonHeadlessMode() { VmStatic vmStatic = vmStaticDao.get(getParameters().getDev().getVmId()); if <START> (vmStatic != null && <END> vmStatic.getDefaultDisplayType() == DisplayType.none) { vmStatic.setDefaultDisplayType(DisplayType.qxl); vmStaticDao.update(vmStatic); } if (getVmDeviceUtils().getVideoDevices(getParameters().getDev().getVmId()).isEmpty()) { getVmDeviceUtils().addVideoDevices(vmStatic, getVmDeviceUtils().getNeededNumberOfVideoDevices(vmStatic)); } }</code><technical_language>I guess check for vmStatic != null is overcome scenario in VM is removed this operation, right? if happen (let's device persisted database), continue declare operation succeeded. REST-API do returned ID - display device? in this case I device</technical_language>

Target:
private void setVmToNonHeadlessMode() { VmStatic vmStatic = vmStaticDao.get(getParameters().getDev().getVmId()); if (vmStatic != null && vmStatic.getDefaultDisplayType() == DisplayType.none) { vmStatic.setDefaultDisplayType(DisplayType.qxl); resourceManager.getVmManager(getParameters().getDev().getVmId()).update(vmStatic); } if (getVmDeviceUtils().getVideoDevices(getParameters().getDev().getVmId()).isEmpty()) { getVmDeviceUtils().addVideoDevices(vmStatic, getVmDeviceUtils().getNeededNumberOfVideoDevices(vmStatic)); } }
Source:
<code>private void getBookmarks(IngestJobContext context, AbstractFile file) throws TskCoreException, IOException, SAXException, PropertyListFormatException, ParseException, ParserConfigurationException { if (file.getSize() == 0) { return; } File tempFile = createTemporaryFile(context, file); try { <START> postArtifact( getBookmarkArtifacts(file, tempFile, context)); <END> } finally { tempFile.delete(); } }</code><technical_language>check for postArtifact postArtifacts</technical_language>

Target:
private void getBookmarks(IngestJobContext context, AbstractFile file) throws TskCoreException, IOException, SAXException, PropertyListFormatException, ParseException, ParserConfigurationException { if (file.getSize() == 0) { return; } File tempFile = createTemporaryFile(context, file); try { postArtifacts(getBookmarkArtifacts(file, tempFile, context)); } finally { tempFile.delete(); } }
Source:
<code>protected ExprEval eval(final double x, final double y) { <START> return ExprEval.of((long) x / (long) y); <END> }</code><technical_language>divide in double</technical_language>

Target:
protected ExprEval eval(final double x, final double y) { return ExprEval.of((long) (x / y)); }
Source:
<code>public String toString() { String versionString = componentVersion; if (this.wineryVersion > 0) { <START> versionString += ((Objects.nonNull(versionString) && versionString.length() > 0) ? WINERY_VERSION_SEPARATOR : "") <END> + WINERY_VERSION_PREFIX + wineryVersion; if (this.workInProgressVersion > 0) { versionString += WINERY_VERSION_SEPARATOR + WINERY_WIP_VERSION_PREFIX + this.workInProgressVersion; } } return versionString; }</code><technical_language>[!StringUtils.isBlank(versionSTring)](<LINK_0> increase readability</technical_language>

Target:
public String toString() { String versionString = componentVersion; if (this.wineryVersion > 0) { versionString += (StringUtils.isEmpty(versionString) ? "" : WINERY_VERSION_SEPARATOR) + WINERY_VERSION_PREFIX + wineryVersion; if (this.workInProgressVersion > 0) { versionString += WINERY_VERSION_SEPARATOR + WINERY_WIP_VERSION_PREFIX + this.workInProgressVersion; } } return versionString; }
Source:
<code>public void testPublishDocument() throws OperationException { <START> OperationContext ctx = new OperationContext(session); <END> ctx.setInput(fileToPublish); DocumentModel publishedDoc = (DocumentModel) service.run(ctx, PublishDocument.ID, Collections.singletonMap("target", section)); assertEquals(section.getId(), session.getDocument(publishedDoc.getParentRef()).getId()); assertEquals(1, session.getChildren(section.getRef()).size()); }</code><technical_language>Please try-with-resource for OperationContext creation</technical_language>

Target:
public void testPublishDocument() throws OperationException { try (OperationContext ctx = new OperationContext(session); CapturingEventListener listener = new CapturingEventListener(DocumentEventTypes.DOCUMENT_PUBLISHED)) { ctx.setInput(fileToPublish); DocumentModel publishedDoc = (DocumentModel) service.run(ctx, PublishDocument.ID, Collections.singletonMap("target", section)); assertEquals(section.getId(), session.getDocument(publishedDoc.getParentRef()).getId()); assertEquals(1, session.getChildren(section.getRef()).size()); assertTrue(listener.hasBeenFired(DocumentEventTypes.DOCUMENT_PUBLISHED)); } }
Source:
<code>private void validateModel(BpmnModel model) throws Exception { FlowElement flowElement = model.getMainProcess().getFlowElement("ManualTask_0ej3luy"); <START> assertNotNull(flowElement); <END> assertTrue(flowElement instanceof ManualTask); checkXml(model); }</code><technical_language>Please, AssertJ assertions. for next line</technical_language>

Target:
private void validateModel(BpmnModel model) throws Exception { FlowElement flowElement = model.getMainProcess().getFlowElement("ManualTask_0ej3luy"); assertThat(flowElement).isNotNull(); assertThat(flowElement instanceof ManualTask).isTrue(); checkXml(model); }
Source:
<code>public void onConnect() { <START> logger.info("Connected to my.openHAB service"); <END> mIsConnected = true; }</code><technical_language>"pimp" log statement some more details (e.g. url, uuid)</technical_language>

Target:
public void onConnect() { logger.info("Connected to my.openHAB service (UUID = {}, base URL = {})", this.mUUID, this.mOHBaseUrl); mIsConnected = true; }
Source:
<code>public static void setVelocity(Ability ability, Entity entity, Vector vector) { final AbilityVelocityAffectEntityEvent event = new AbilityVelocityAffectEntityEvent(ability, entity, vector); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) return; Vector velocity = event.getNewVector(); if (entity instanceof TNTPrimed) { if (ConfigManager.defaultConfig.get().getBoolean("Properties.BendingAffectFallingSand.TNT")) { velocity.multiply(ConfigManager.defaultConfig.get().getDouble("Properties.BendingAffectFallingSand.TNTStrengthMultiplier")); } } else if (entity instanceof FallingBlock) { if (ConfigManager.defaultConfig.get().getBoolean("Properties.BendingAffectFallingSand.Normal")) { velocity.multiply(ConfigManager.defaultConfig.get().getDouble("Properties.BendingAffectFallingSand.NormalStrengthMultiplier")); } } if (velocity.getX() > 4) { velocity.setX(4); } else if (velocity.getX() < -4) { velocity.setX(-4); } if (velocity.getY() > 4) { velocity.setY(4); } else if (velocity.getY() < -4) { velocity.setY(-4); } if (velocity.getZ() > 4) { velocity.setZ(4); } else if (velocity.getZ() < -4) { velocity.setZ(-4); <START> } <END> event.getAffected().setVelocity(velocity); }</code><technical_language>For future reference, good add a velocity != NaN null check</technical_language>

Target:
public static void setVelocity(Ability ability, Entity entity, Vector vector) { final AbilityVelocityAffectEntityEvent event = new AbilityVelocityAffectEntityEvent(ability, entity, vector); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) return; Vector velocity = event.getVelocity(); if(velocity == null || Double.isNaN(velocity.length())) return; if (entity instanceof TNTPrimed) { if (ConfigManager.defaultConfig.get().getBoolean("Properties.BendingAffectFallingSand.TNT")) { velocity.multiply(ConfigManager.defaultConfig.get().getDouble("Properties.BendingAffectFallingSand.TNTStrengthMultiplier")); } } else if (entity instanceof FallingBlock) { if (ConfigManager.defaultConfig.get().getBoolean("Properties.BendingAffectFallingSand.Normal")) { velocity.multiply(ConfigManager.defaultConfig.get().getDouble("Properties.BendingAffectFallingSand.NormalStrengthMultiplier")); } } if (velocity.getX() > 4) { velocity.setX(4); } else if (velocity.getX() < -4) { velocity.setX(-4); } if (velocity.getY() > 4) { velocity.setY(4); } else if (velocity.getY() < -4) { velocity.setY(-4); } if (velocity.getZ() > 4) { velocity.setZ(4); } else if (velocity.getZ() < -4) { velocity.setZ(-4); } event.getAffected().setVelocity(velocity); }
Source:
<code><START> public Long get() { <END> return supplier.get(); }</code><technical_language>pass existing ImmutableTimestampSupplier Scrubber - feels awkward for this class implement Supplier</technical_language>

Target:
public Long get() { Long ts = supplier.get(); for (ImmutableTimestampMonitor monitor : monitors) { monitor.update(ts); } return ts; }
Source:
<code>public void checkUserIsNotAssigneeForRepo() throws Exception { MatcherAssert.assertThat( <START> RtAssigneesITCase.repo().assignees().check("octocat"), <END> Matchers.is(false) ); }</code><technical_language>I more random here, RandomStringUtils.randomAlpha(Tv.TEN), for example</technical_language>

Target:
public void checkUserIsNotAssigneeForRepo() throws Exception { MatcherAssert.assertThat( RtAssigneesITCase.repo() .assignees() .check(RandomStringUtils.randomAlphabetic(Tv.TEN)), Matchers.is(false) ); }
Source:
<code>public static SnomedIdentifierValidator getIdentifierValidator(ComponentCategory category) { switch (category) { case CONCEPT: case DESCRIPTION: case RELATIONSHIP: return new SnomedComponentIdentifierValidator(category); <START> default: throw new UnsupportedOperationException(""+category); <END> } }</code><technical_language>"Can't create validator for category: "</technical_language>

Target:
public static SnomedIdentifierValidator getIdentifierValidator(ComponentCategory category) { switch (category) { case CONCEPT: case DESCRIPTION: case RELATIONSHIP: return new SnomedComponentIdentifierValidator(category); default: throw new UnsupportedOperationException("Can't create validator for category: " + category); } }
Source:
<code>public void testInPackageScan() { <START> DefaultClasspathScanner scanner = new DefaultClasspathScanner("com.canoo.impl.server.classpathscan"); <END> assertForAnnotation(scanner); }</code><technical_language>add final</technical_language>

Target:
public void testInPackageScan() { final DefaultClasspathScanner scanner = new DefaultClasspathScanner(CLASSPATH_SCAN); assertNotNull(scanner); assertForAnnotation(scanner); }
Source:
<code>Page() throws IOException { Document hostDoc = HtmlDomUtil.clone(template); css = injectCssFile(hostDoc, "gerrit_sitecss", site.site_css); header = injectXmlFile(hostDoc, "gerrit_header", site.site_header); footer = injectXmlFile(hostDoc, "gerrit_footer", site.site_footer); final HostPageData pageData = new HostPageData(); <START> pageData.pluginUrls = getPluginUrls(); <END> pageData.config = config; final StringWriter w = new StringWriter(); w.write("var " + HPD_ID + "="); json(pageData, w); w.write(";"); final Element data = HtmlDomUtil.find(hostDoc, HPD_ID); asScript(data); data.appendChild(hostDoc.createTextNode(w.toString())); data.appendChild(hostDoc.createComment(HPD_ID)); permutations = new HashMap<Permutation, Content>(); for (Permutation p : selector.getPermutations()) { final Document d = HtmlDomUtil.clone(hostDoc); Element nocache = HtmlDomUtil.find(d, "gerrit_module"); nocache.getParentNode().removeChild(nocache); p.inject(d); permutations.put(p, new Content(d)); } Element nocache = HtmlDomUtil.find(hostDoc, "gerrit_module"); asScript(nocache); nocache.setAttribute("src", noCacheName); permutations.put(null, new Content(hostDoc)); }</code><technical_language>Drop this assignment. formatted in output twice</technical_language>

Target:
Page() throws IOException { Document hostDoc = HtmlDomUtil.clone(template); css = injectCssFile(hostDoc, "gerrit_sitecss", site.site_css); header = injectXmlFile(hostDoc, "gerrit_header", site.site_header); footer = injectXmlFile(hostDoc, "gerrit_footer", site.site_footer); final HostPageData pageData = new HostPageData(); pageData.config = config; final StringWriter w = new StringWriter(); w.write("var " + HPD_ID + "="); json(pageData, w); w.write(";"); final Element data = HtmlDomUtil.find(hostDoc, HPD_ID); asScript(data); data.appendChild(hostDoc.createTextNode(w.toString())); data.appendChild(hostDoc.createComment(HPD_ID)); permutations = new HashMap<Permutation, Content>(); for (Permutation p : selector.getPermutations()) { final Document d = HtmlDomUtil.clone(hostDoc); Element nocache = HtmlDomUtil.find(d, "gerrit_module"); nocache.getParentNode().removeChild(nocache); p.inject(d); permutations.put(p, new Content(d)); } Element nocache = HtmlDomUtil.find(hostDoc, "gerrit_module"); asScript(nocache); nocache.setAttribute("src", noCacheName); permutations.put(null, new Content(hostDoc)); }
Source:
<code><START> Object getValue(Object obj) throws Exception { <END> throw new HazelcastException("Path agnostic value extraction is not supported"); }</code><technical_language>Minor: remove throws</technical_language>

Target:
Object getValue(Object obj) { throw new HazelcastException("Path agnostic value extraction is not supported"); }
Source:
<code>public Response setClusterStateModelDefinition( @PathParam("clusterId") String clusterId, @PathParam("statemodel") String statemodel, String content ) { ZNRecord record; try { record = toZNRecord(content); } catch (IOException e) { _logger.error("Failed to deserialize user's input " + content + ", Exception: " + e); return badRequest("Input is not a valid ZNRecord!"); } StateModelDefinition stateModelDefinition = new StateModelDefinition(record); HelixDataAccessor dataAccessor = getDataAccssor(clusterId); PropertyKey key = dataAccessor.keyBuilder().stateModelDef(stateModelDefinition.getId()); boolean retcode = true; try { retcode = dataAccessor.setProperty(key, stateModelDefinition); } catch (Exception e) { _logger.error("Failed to set StateModelDefinition key:" + key + ", Exception: " + e); retcode = false; } <START> if (!retcode) { <END> return badRequest("Failed to set the content " + content); } return OK(); }</code><technical_language>is need retcode? If exception is caught, return badRequest</technical_language>

Target:
public Response setClusterStateModelDefinition(@PathParam("clusterId") String clusterId, @PathParam("statemodel") String statemodel, String content) { ZNRecord record; try { record = toZNRecord(content); } catch (IOException e) { _logger.error("Failed to deserialize user's input " + content + ", Exception: " + e); return badRequest("Input is not a valid ZNRecord!"); } StateModelDefinition stateModelDefinition = new StateModelDefinition(record); HelixDataAccessor dataAccessor = getDataAccssor(clusterId); PropertyKey key = dataAccessor.keyBuilder().stateModelDef(stateModelDefinition.getId()); boolean retcode = true; try { retcode = dataAccessor.setProperty(key, stateModelDefinition); } catch (Exception e) { _logger.error("Failed to set StateModelDefinition key:" + key + ", Exception: " + e); return badRequest("Failed to set the content " + content); } return OK(); }
Source:
<code>public ExcelConfiguration(int columnNameLineNumber, boolean skipEmptyLines, boolean skipEmptyColumns) { <START> this(columnNameLineNumber, null, skipEmptyLines, skipEmptyColumns, false, 1000); <END> }</code><technical_language>nice if default of a "1000" in a constant, want set default zero in case pass "false" argument for detectColumnTypes property</technical_language>

Target:
public ExcelConfiguration(int columnNameLineNumber, boolean skipEmptyLines, boolean skipEmptyColumns) { this(columnNameLineNumber, null, skipEmptyLines, skipEmptyColumns, false, NUMBERS_OF_LINES_TO_SCAN); }
Source:
<code>public final Message<?> postReceive(Message<?> message, MessageChannel channel) { if (message instanceof MessageWithSpan) { MessageWithSpan messageWithSpan = (MessageWithSpan) message; Message<?> messageToHandle = messageWithSpan.message; populatePropagatedContext(messageWithSpan.span, messageToHandle, channel); publish(new ClientReceivedEvent(this, messageWithSpan.span)); <START> return message; <END> } return message; }</code><technical_language>I prior art much, more idiomatic Message for rely headers convey correlation data. a custom implementation of MessageHeaders better? a helper specific sleuthy header names</technical_language>

Target:
public final Message<?> postReceive(Message<?> message, MessageChannel channel) { if (message instanceof MessageWithSpan) { MessageWithSpan messageWithSpan = (MessageWithSpan) message; Message<?> messageToHandle = messageWithSpan.message; populatePropagatedContext(messageWithSpan.span, messageToHandle, channel); return message; } return message; }
Source:
<code>public void notification_onCommitRealmResults() { final Realm looperThreadRealm = looperThread.realm; looperThreadRealm.beginTransaction(); <START> AllJavaTypes child = looperThreadRealm.createObject(AllJavaTypes.class, 10); <END> looperThreadRealm.commitTransaction(); final AtomicInteger counter = new AtomicInteger(0); RealmChangeListener<RealmResults<AllJavaTypes>> listener = new RealmChangeListener<RealmResults<AllJavaTypes>>() { @Override public void onChange(RealmResults<AllJavaTypes> object) { counter.incrementAndGet(); } }; child.getObjectParents().addChangeListener(listener); looperThreadRealm.beginTransaction(); AllJavaTypes parent = looperThreadRealm.createObject(AllJavaTypes.class, 1); parent.setFieldObject(child); looperThreadRealm.commitTransaction(); looperThread.postRunnable( new Runnable() { @Override public void run() { assertEquals(2, looperThreadRealm.where(AllJavaTypes.class).findAll().size()); assertEquals(1, counter.get()); looperThread.testComplete(); } } ); }</code><technical_language>need add this looperThread.strongReferences this object risk GC'ed waiting for callbacks cached backlink RealmResults it</technical_language>

Target:
public void notification_onCommitRealmResults() { final Realm looperThreadRealm = looperThread.realm; looperThreadRealm.beginTransaction(); AllJavaTypes child = looperThreadRealm.createObject(AllJavaTypes.class, 10); looperThreadRealm.commitTransaction(); final AtomicInteger counter = new AtomicInteger(0); RealmChangeListener<RealmResults<AllJavaTypes>> listener = new RealmChangeListener<RealmResults<AllJavaTypes>>() { @Override public void onChange(RealmResults<AllJavaTypes> object) { counter.incrementAndGet(); } }; child.getObjectParents().addChangeListener(listener); looperThreadRealm.beginTransaction(); AllJavaTypes parent = looperThreadRealm.createObject(AllJavaTypes.class, 1); parent.setFieldObject(child); looperThreadRealm.commitTransaction(); verifyPostConditions( looperThreadRealm, new PostConditions() { public void run(Realm realm) { assertEquals(2, looperThreadRealm.where(AllJavaTypes.class).findAll().size()); assertEquals(1, counter.get()); } }, child, parent); }
Source:
<code>public String getIdentitySelectString(String table, String column, int type) { <START> return "select currval('" + table + '_' + column + "_seq')"; <END> }</code><technical_language>Do need some escaping mechanism guard possibility 'table', 'column' names special characters (like "(", ")", "'", etc.)</technical_language>

Target:
public String getIdentitySelectString(String table, String column, int type) { return "select 1"; }
Source:
<code>public String evaluate(Run<?, ?> run, FilePath workspace, TaskListener listener, String macroName) { StringBuilder buffer = new StringBuilder(); AbstractTestResultAction<?> testResult = run.getAction(AbstractTestResultAction.class); if (null == testResult) { return "No tests ran."; } List<TestResult> failedTests = testResult.getFailedTests().stream().collect(Collectors.toList()); <START> failedTests = testSuiteName.length() == 0 ? failedTests : failedTests.stream().filter(t -> t.getFullName().contains(testSuiteName)).collect(Collectors.toList()); <END> int failCount = failedTests.size(); if (failCount == 0) { buffer.append("All tests passed"); } else { String lineBreak = getLineBreak(); buffer.append(failCount).append(" tests failed.").append(lineBreak); boolean showOldFailures = !onlyRegressions; if(maxLength < Integer.MAX_VALUE) { maxLength *= 1024; } if (maxTests > 0) { int printedTests = 0; int printedLength = 0; for (TestResult failedTest : failedTests) { if (showOldFailures || getTestAge(failedTest) == 1) { if (printedTests < maxTests && printedLength <= maxLength) { printedLength += outputTest(buffer, failedTest, showStack, showMessage, maxLength-printedLength); printedTests++; } } } if (failCount > printedTests) { buffer.append("... and ").append(failCount - printedTests).append(" other failed tests.") .append(lineBreak); } if (printedLength >= maxLength) { buffer.append(lineBreak).append("... output truncated.").append(lineBreak); } } } return buffer.toString(); }</code><technical_language>I if a regular expression filter instead of a single name. Also, people want filter multiple names</technical_language>

Target:
public String evaluate(Run<?, ?> run, FilePath workspace, TaskListener listener, String macroName) { StringBuilder buffer = new StringBuilder(); AbstractTestResultAction<?> testResult = run.getAction(AbstractTestResultAction.class); if (null == testResult) { return "No tests ran."; } int failCount = testResult.getFailCount(); List<? extends TestResult> failedAndFilteredTests = filterTests(testResult.getFailedTests(), testNamePattern); failCount = testNamePattern.length() == 0 ? failCount : failedAndFilteredTests.size(); if (failCount == 0) { buffer.append("All tests passed"); } else { String lineBreak = getLineBreak(); buffer.append(failCount).append(" tests failed.").append(lineBreak); boolean showOldFailures = !onlyRegressions; if(maxLength < Integer.MAX_VALUE) { maxLength *= 1024; } if (maxTests > 0) { int printedTests = 0; int printedLength = 0; for (TestResult failedTest : failedAndFilteredTests) { if (showOldFailures || getTestAge(failedTest) == 1) { if (printedTests < maxTests && printedLength <= maxLength) { printedLength += outputTest(buffer, failedTest, showStack, showMessage, maxLength-printedLength); printedTests++; } } } if (failCount > printedTests) { buffer.append("... and ").append(failCount - printedTests).append(" other failed tests.") .append(lineBreak); } if (printedLength >= maxLength) { buffer.append(lineBreak).append("... output truncated.").append(lineBreak); } } } return buffer.toString(); }
Source:
<code>public void testExcelReporter() { XmlSuite suite = new XmlSuite(); suite.setName("ExcelReporterSuite"); XmlTest test = new XmlTest(suite); test.setName("ExcelReporterTest"); List<XmlClass> classes = new ArrayList<>(); classes.add(new XmlClass(ConfigTest.class)); test.setXmlClasses(classes); List<XmlSuite> xmlSuites = new ArrayList<>(); xmlSuites.add(suite); Configuration config = new Configuration(); SuiteRunner iSuite = new SuiteRunner(config, suite, SUREFIRE_DEFAULT_REPORTS_DIR); iSuite.getXmlSuite().setParentSuite(suite); List<ISuite> iSuites = new ArrayList<>(); iSuites.add(iSuite); ExcelReport excelReport = new ExcelReport(); excelReport.setExcelFileName(excelReportFileName); excelReport.generateReport(xmlSuites, iSuites, SUREFIRE_DEFAULT_REPORTS_DIR); assertTrue(Files.exists(p), "Verify path of Excel Report file."); assertTrue(Files.isRegularFile(p), "Verify that Excel_Report.xls is a file."); if (Files.exists(p) && Files.isRegularFile(p)) { FileInputStream fileInputStream = null; HSSFWorkbook workbook = null; try { fileInputStream = new FileInputStream(p.toFile()); workbook = new HSSFWorkbook(fileInputStream); assertEquals(ReportSheetNames.values().length, workbook.getNumberOfSheets(), "Verify number of worksheets in ExcelReport"); } catch (FileNotFoundException e) { fail("Test excel-report-test failed due to FileNotFoundException."); } catch (IOException e) { fail("Test excel-report-test failed due to IOException."); } finally { <START> if (fileInputStream != null) { <END> try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }</code><technical_language>Please IOUtils.closeQuietyly(fileInputStream);</technical_language>

Target:
public void testExcelReporter() throws IOException { XmlSuite suite = new XmlSuite(); suite.setName("ExcelReporterSuite"); XmlTest test = new XmlTest(suite); test.setName("ExcelReporterTest"); List<XmlClass> classes = new ArrayList<>(); classes.add(new XmlClass(ConfigTest.class)); test.setXmlClasses(classes); List<XmlSuite> xmlSuites = new ArrayList<>(); xmlSuites.add(suite); Configuration config = new Configuration(); SuiteRunner iSuite = new SuiteRunner(config, suite, strReportsDirectory); iSuite.getXmlSuite().setParentSuite(suite); List<ISuite> iSuites = new ArrayList<>(); iSuites.add(iSuite); ExcelReport excelReport = new ExcelReport(); excelReport.setExcelFileName(excelReportFileName); excelReport.generateReport(xmlSuites, iSuites, strReportsDirectory); assertTrue(Files.exists(excelFile), "Verify path of Excel Report file."); assertTrue(Files.isRegularFile(excelFile), "Verify that Excel Report is a file."); FileInputStream fileInputStream = new FileInputStream(excelFile.toFile()); HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream); assertEquals(ReportSheetNames.values().length, workbook.getNumberOfSheets(), "Verify number of worksheets in ExcelReport"); IOUtils.closeQuietly(fileInputStream); }
Source:
<code>public MapReactiveUserDetailsService(Collection<UserDetails> users) { Assert.notEmpty(users, "users cannot be null or empty"); final ConcurrentHashMap<String, UserDetails> map = new ConcurrentHashMap<>(); for (UserDetails user: users) { <START> map.put(user.getUsername(), user); <END> } this.users = map; }</code><technical_language>This line needs call getKey: suggestion map.put(getKey(user.getUsername()), user);</technical_language>

Target:
public MapReactiveUserDetailsService(Collection<UserDetails> users) { Assert.notEmpty(users, "users cannot be null or empty"); this.users = new ConcurrentHashMap<>(); for (UserDetails user : users) { this.users.put(getKey(user.getUsername()), user); } }
Source:
<code>public boolean equals(Object o) { if ( this == o ) { return true; } <START> if ( o == null || o.getClass() != BeanGroupProcessedUnit.class ) { <END> return false; } BeanGroupProcessedUnit that = (BeanGroupProcessedUnit) o; if ( bean != that.bean ) { return false; } if ( !group.equals( that.group ) ) { return false; } return true; }</code><technical_language>Annoying one... Please a separate JIRA commit</technical_language>

Target:
public boolean equals(Object o) { if ( this == o ) { return true; } BeanGroupProcessedUnit that = (BeanGroupProcessedUnit) o; if ( bean != that.bean ) { return false; } if ( !group.equals( that.group ) ) { return false; } return true; }
Source:
<code><START> public boolean areCursorsValid(final String topic, final List<Cursor> cursors) { <END> final List<TopicPartition> partitions = listPartitions(topic); return cursors .stream() .allMatch(cursor -> partitions .stream() .filter(tp -> tp.getPartitionId().equals(cursor.getPartition())) .findFirst() .map(pInfo -> { final long newestOffset = Long.parseLong(pInfo.getNewestAvailableOffset()); final long oldestOffset = Long.parseLong(pInfo.getOldestAvailableOffset()); final long offset = Long.parseLong(cursor.getOffset()); return offset >= oldestOffset && offset <= newestOffset; }) .orElse(false)); }</code><technical_language>final String topicName</technical_language>

Target:
public boolean areCursorsValid(final String topic, final List<Cursor> cursors) { final List<TopicPartition> partitions = listPartitions(topic); return cursors .stream() .allMatch(cursor -> partitions .stream() .filter(tp -> tp.getPartitionId().equals(cursor.getPartition())) .findFirst() .map(pInfo -> { final long newestOffset = toKafkaOffset(pInfo.getNewestAvailableOffset()); final long oldestOffset = toKafkaOffset(pInfo.getOldestAvailableOffset()); try { final long offset = fromNakadiCursor(cursor).getOffset(); return offset >= oldestOffset && offset <= newestOffset; } catch (NumberFormatException e) { return false; } }) .orElse(false)); }
Source:
<code>private Iterable<Review> reviews(final Publisher contentPublisher, Set<org.atlasapi.media.entity.simple.Review> simpleReviews) { return Iterables.transform(simpleReviews, <START> new Function<org.atlasapi.media.entity.simple.Review, Review>() { <END> @Override public Review apply(org.atlasapi.media.entity.simple.Review simpleReview) { if (simpleReview.getPublisherDetails() != null && !getPublisher(simpleReview.getPublisherDetails()) .equals(contentPublisher)) { throw new IllegalArgumentException("Review publisher must match content publisher"); } Review review = new Review(Locale.forLanguageTag( simpleReview.getLanguage()), simpleReview.getReview() ); review.setType(simpleReview.getType()); review.setPeople(simpleReview.getPeople()); return review; } }); }</code><technical_language>change this lambda, intellij do for you. a bunch more of Function<things> easily a lot nicer</technical_language>

Target:
private Iterable<Review> reviews(final Publisher contentPublisher, Set<org.atlasapi.media.entity.simple.Review> simpleReviews) { return Iterables.transform(simpleReviews, simpleReview -> { if (simpleReview.getPublisherDetails() != null && !getPublisher(simpleReview.getPublisherDetails()) .equals(contentPublisher)) { throw new IllegalArgumentException( "Review publisher must match content publisher" ); } Review review = new Review(Locale.forLanguageTag( simpleReview.getLanguage()), simpleReview.getReview() ); review.setType(simpleReview.getType()); Author author = Author.builder() .withAuthorName(simpleReview.getAuthor().getAuthorName()) .withAuthorInitials(simpleReview.getAuthor().getAuthorInitials()) .build(); review.setAuthor(author); return review; } ); }
Source:
<code>private boolean postLog(){ try{ <START> final byte[] bytes = getByteLog(); <END> if(bytes.length >= MAX_LOG_SIZE){ LOGGER.warn("Log message too large, size {}", bytes.length); return false; } this.dataLogger.put(this.senseId, bytes); return true; } catch (ProvisionedThroughputExceededException ptEx){ LOGGER.error("Provisioned Throughput Exceeded."); } catch (AmazonClientException awsEx){ LOGGER.error("Post log message for sense failed: {}", this.senseId, awsEx.getMessage()); } catch (Exception ex){ LOGGER.error("Post log message for sense failed, generic error: {}", this.senseId, ex.getMessage()); } return false; }</code><technical_language>rename this toByteArray()</technical_language>

Target:
private boolean postLog(){ try{ final byte[] bytes = toByteArray(); if(bytes.length >= MAX_LOG_SIZE){ LOGGER.warn("Log message too large, size {}", bytes.length); return false; } this.dataLogger.put(this.senseId, bytes); return true; } catch (ProvisionedThroughputExceededException ptEx){ LOGGER.error("Provisioned Throughput Exceeded."); } catch (AmazonClientException awsEx){ LOGGER.error("Post log message for sense failed: {}", this.senseId, awsEx.getMessage()); } catch (Exception ex){ LOGGER.error("Post log message for sense failed, generic error: {}", this.senseId, ex.getMessage()); } return false; }
Source:
<code>public File getResource(String providerName, String resourcePath) { if (resourcePath == null || !resourcePath.equals(FilenameUtils.normalize(resourcePath)) || new File(resourcePath) .isAbsolute()) { return null; } if (providerName == null) { for (ResourceProvider provider : resourceProviders.values()) { File ret = provider.getResource(resourcePath); <START> if (ret != null) <END> return ret; } return null; } else { ResourceProvider provider = resourceProviders.get(providerName); return provider.getResource(resourcePath); } }</code><technical_language>I understand this fix supportive of it, confirm prevent behaviors currently relied working? main I thinking of is "development mode" allows for hot reloading of pages UI framework "watching" modules. this affect that? @mogoodrich do know</technical_language>

Target:
public File getResource(String providerName, String resourcePath) { if (resourcePath == null) { return null; } if (!resourcePath.equals(FilenameUtils.normalize(resourcePath))) { log.warn("Attempted to load file via directory traversal using path: {}", resourcePath); return null; } if (providerName == null) { for (ResourceProvider provider : resourceProviders.values()) { File ret = provider.getResource(resourcePath); if (ret != null) return ret; } return null; } else { ResourceProvider provider = resourceProviders.get(providerName); return provider.getResource(resourcePath); } }
Source:
<code>public void configure(Binder binder) { binder.bind(ThriftConnector.class).in(Scopes.SINGLETON); thriftClientBinder(binder).bindThriftClient(PrestoThriftService.class); binder.bind(ThriftMetadata.class).in(Scopes.SINGLETON); binder.bind(ThriftSplitManager.class).in(Scopes.SINGLETON); binder.bind(ThriftPageSourceProvider.class).in(Scopes.SINGLETON); binder.bind(PrestoThriftServiceProvider.class).to(RetryingPrestoThriftServiceProvider.class).in(Scopes.SINGLETON); binder.bind(PrestoThriftServiceProvider.class).annotatedWith(NonRetrying.class).to(DefaultPrestoThriftServiceProvider.class).in(Scopes.SINGLETON); configBinder(binder).bindConfig(ThriftConnectorConfig.class); binder.bind(ThriftSessionProperties.class).in(Scopes.SINGLETON); binder.bind(ThriftIndexProvider.class).in(Scopes.SINGLETON); <START> newExporter(binder).export(PrestoThriftServiceProvider.class).as(generatedNameOf(RetryingPrestoThriftServiceProvider.class, connectorId)); <END> }</code><technical_language>Unrelated formatting change</technical_language>

Target:
public void configure(Binder binder) { binder.bind(ThriftConnector.class).in(Scopes.SINGLETON); thriftClientBinder(binder).bindThriftClient(PrestoThriftService.class); binder.bind(ThriftMetadata.class).in(Scopes.SINGLETON); binder.bind(ThriftSplitManager.class).in(Scopes.SINGLETON); binder.bind(ThriftPageSourceProvider.class).in(Scopes.SINGLETON); binder.bind(PrestoThriftServiceProvider.class).to(RetryingPrestoThriftServiceProvider.class).in(Scopes.SINGLETON); binder.bind(PrestoThriftServiceProvider.class).annotatedWith(NonRetrying.class).to(DefaultPrestoThriftServiceProvider.class).in(Scopes.SINGLETON); configBinder(binder).bindConfig(ThriftConnectorConfig.class); binder.bind(ThriftSessionProperties.class).in(Scopes.SINGLETON); binder.bind(ThriftIndexProvider.class).in(Scopes.SINGLETON); binder.bind(ThriftConnectorStats.class).in(Scopes.SINGLETON); newExporter(binder).export(PrestoThriftServiceProvider.class) .as(generatedNameOf(RetryingPrestoThriftServiceProvider.class, connectorId)); newExporter(binder).export(ThriftConnectorStats.class) .as(generatedNameOf(ThriftConnectorStats.class, connectorId)); }
Source:
<code>public final void contextDestroyed(final ServletContextEvent sce) { val logger = Logger.getLogger("org.apereo.cas"); <START> logger.info("Unregistering JdbcServletContextListener"); <END> val cl = Thread.currentThread().getContextClassLoader(); val drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { val driver = drivers.nextElement(); if (driver.getClass().getClassLoader() == cl) { try { DriverManager.deregisterDriver(driver); } catch (final SQLException ex) { logger.warning("Error deregistering JDBC driver " + ex); } } else { logger.info("Not deregistering JDBC driver as it does not belong to this webapp's ClassLoader: " + driver); } } }</code><technical_language>Review logger statements, choose levels correctly</technical_language>

Target:
public final void contextDestroyed(final ServletContextEvent sce) { val logger = Logger.getLogger("org.apereo.cas"); logger.fine("Unregistering JdbcServletContextListener"); val cl = Thread.currentThread().getContextClassLoader(); val drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { val driver = drivers.nextElement(); if (driver.getClass().getClassLoader() == cl) { try { DriverManager.deregisterDriver(driver); } catch (final SQLException ex) { logger.warning("Error deregistering JDBC driver " + ex); } } else { logger.fine("Not deregistering JDBC driver as it does not belong to this webapp's ClassLoader: " + driver); } } }
Source:
<code>public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { <START> super.channelRead(ctx, msg); <END> }</code><technical_language>replace ReferenceCountUtil.release(msg)</technical_language>

Target:
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ReferenceCountUtil.release(msg); }