auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void handlePost(ActionParameters params) throws ActionException { params.requireLoggedInUser(); JSONObject jsonObject = params.getHttpParamAsJSON("featureData"); OskariLayer layer = getLayer(jsonObject.optString("layerId")); if (!canEdit(layer, params.getUser())) { throw new ActionDeniedException("User doesn't have edit permission for layer: " + layer.getId()); } try { String payload = createPayload(jsonObject); String layerName = layer.getName(); <START> String url = layer.getUrl(); <END> url = movePrefixFromNameToURL(layerName,url); String responseString = postPayload(layer, payload, url); flushLayerTilesCache(layer.getId()); if (responseString.indexOf("Exception") > -1) { throw new ActionException("Cannot delete feature"); } else if (responseString.indexOf("<wfs:totalDeleted>1</wfs:totalDeleted>") > -1) { ResponseHelper.writeResponse(params, "Feature deleted"); } else { throw new ActionException("Unexpected response from service: " + responseString); } } catch (JSONException e) { LOG.error(e, "JSON processing error"); throw new ActionException("JSON processing error", e); } catch (XMLStreamException e) { LOG.error(e, "Failed to create WFS-T request"); throw new ActionException("Failed to create WFS-T request", e); } catch (FactoryException e) { LOG.error(e, "Failed to create WFS-T request (crs)"); throw new ActionException("Failed to create WFS-T request (crs)", e); } }</code><technical_language>out a lines with: String url = movePrefixFromNameToURL(layerName, layer.getUrl()); String responseString = postPayload(layer, payload, movePrefixFromNameToURL(layerName, layer.getUrl()));</technical_language>

Target:
public void handlePost(ActionParameters params) throws ActionException { params.requireLoggedInUser(); JSONObject jsonObject = params.getHttpParamAsJSON("featureData"); OskariLayer layer = getLayer(jsonObject.optString("layerId")); if (!canEdit(layer, params.getUser())) { throw new ActionDeniedException("User doesn't have edit permission for layer: " + layer.getId()); } try { String payload = createPayload(jsonObject); String responseString = postPayload(layer.getUsername(), layer.getPassword(), payload, getURLForNamespace(layer.getName(), layer.getUrl())); flushLayerTilesCache(layer.getId()); if (responseString.indexOf("Exception") > -1) { throw new ActionException("Cannot delete feature"); } else if (responseString.indexOf("<wfs:totalDeleted>1</wfs:totalDeleted>") > -1) { ResponseHelper.writeResponse(params, "Feature deleted"); } else { throw new ActionException("Unexpected response from service: " + responseString); } } catch (JSONException e) { LOG.error(e, "JSON processing error"); throw new ActionException("JSON processing error", e); } catch (XMLStreamException e) { LOG.error(e, "Failed to create WFS-T request"); throw new ActionException("Failed to create WFS-T request", e); } catch (FactoryException e) { LOG.error(e, "Failed to create WFS-T request (crs)"); throw new ActionException("Failed to create WFS-T request (crs)", e); } }
Source:
<code>public void testParseLongEmpty() throws EvaluationException { try { <START> PARSE_LONG.evaluate(s("")); <END> } catch (EvaluationException e){ assertThat("parse_Long(\"\") throws", true, instanceOf(Boolean.class)); } }</code><technical_language>This try-catch moved @Test annotation well</technical_language>

Target:
public void testParseLongEmpty() throws EvaluationException { PARSE_LONG.evaluate(s("")); }
Source:
<code>protected final List<IMergeViewerItem> createMergeViewerItemFrom(Collection<?> values) { List<IMergeViewerItem> ret = newArrayListWithCapacity(values.size()); for (EObject value : filter(values, EObject.class)) { <START> if (!value.eIsProxy()) { <END> IMergeViewerItem valueToAdd = createMergeViewerItemFrom(value); if (valueToAdd != null) { ret.add(valueToAdd); } } } return ret; }</code><technical_language>Remove this test, together</technical_language>

Target:
protected final List<IMergeViewerItem> createMergeViewerItemFrom(Collection<?> values) { List<IMergeViewerItem> ret = newArrayListWithCapacity(values.size()); for (EObject value : filter(values, EObject.class)) { IMergeViewerItem valueToAdd = createMergeViewerItemFrom(value); if (valueToAdd != null) { ret.add(valueToAdd); } } return ret; }
Source:
<code>public void shouldParsePushPayload() throws Exception { GitHubPushTrigger trigger = mock(GitHubPushTrigger.class); FreeStyleProject prj = jenkins.createFreeStyleProject(); prj.addTrigger(trigger); prj.setScm(GIT_SCM_FROM_RESOURCE); GHSubscriberEvent subscriberEvent = new GHSubscriberEvent("shouldParsePushPayload", GHEvent.PUSH, classpath("payloads/push.json")); new DefaultPushGHEventSubscriber().onEvent(subscriberEvent); <START> verify(trigger).onPost(GitHubTriggerEvent.create() <END> .withTimestamp(subscriberEvent.getTimestamp()) .withOrigin("shouldParsePushPayload") .withTriggeredByUser(TRIGGERED_BY_USER_FROM_RESOURCE) .build() ); }</code><technical_language>is verify(trigger).onPost(same(...)) (with matcher?)</technical_language>

Target:
public void shouldParsePushPayload() throws Exception { GitHubPushTrigger trigger = mock(GitHubPushTrigger.class); FreeStyleProject prj = jenkins.createFreeStyleProject(); prj.addTrigger(trigger); prj.setScm(GIT_SCM_FROM_RESOURCE); GHSubscriberEvent subscriberEvent = new GHSubscriberEvent("shouldParsePushPayload", GHEvent.PUSH, classpath("payloads/push.json")); new DefaultPushGHEventSubscriber().onEvent(subscriberEvent); verify(trigger).onPost(eq(GitHubTriggerEvent.create() .withTimestamp(subscriberEvent.getTimestamp()) .withOrigin("shouldParsePushPayload") .withTriggeredByUser(TRIGGERED_BY_USER_FROM_RESOURCE) .build() )); }
Source:
<code>public String tSnePlotWithMetadata( @PathVariable String experimentAccession, @PathVariable int perplexity, @PathVariable String metadata, @RequestParam(defaultValue = "") String accessKey) { Experiment experiment = experimentTrader.getExperiment(experimentAccession, accessKey); <START> if(getTSnePlotMetadata(experiment.getAccession()).equalsIgnoreCase("[]")) { <END> return GSON.toJson(ImmutableMap.of( "series", new ArrayList<Map<String, Object>>() )); } else { return GSON.toJson( ImmutableMap.of( "series", modelForHighcharts( "", new TreeMap<>( tSnePlotService.fetchTSnePlotWithMetadata( experiment.getAccession(), perplexity, metadata))))); } }</code><technical_language>Is returning empty series a requirement for widget? In current implementation, [added support for missing metadata](<LINK_0>, get t-SNE points belong a "Not available" series. If want implement some support for requesting non-existent metadata types, I making of HTTP error code more informative for user</technical_language>

Target:
public String tSnePlotWithMetadata( @PathVariable String experimentAccession, @PathVariable int perplexity, @PathVariable String metadata, @RequestParam(defaultValue = "") String accessKey) { Experiment experiment = experimentTrader.getExperiment(experimentAccession, accessKey); if(isNullOrEmpty(getTSnePlotMetadata(experiment.getAccession()))) { return GSON.toJson(ImmutableMap.of( "series", new ArrayList<Map<String, Object>>() )); } else { return GSON.toJson( ImmutableMap.of( "series", modelForHighcharts( "", new TreeMap<>( tSnePlotService.fetchTSnePlotWithMetadata( experiment.getAccession(), perplexity, metadata))))); } }
Source:
<code>public void serverLeavingAndJoiningWhilePutAndClear() throws Exception { int locatorPort = ClusterStartupRule.getDUnitLocatorPort(); Future<Void> startStopServer = executor.submit(() -> { for (int i = 0; i < 3; i++) { MemberVM server3 = cluster.startServerVM(3, s -> s.withConnectionToLocator(locatorPort) .withProperty(SERIALIZABLE_OBJECT_FILTER, "org.apache.geode.cache.query.data.*") .withRegion(RegionShortcut.PARTITION, "cities")); server3.stop(false); } }); Future<Void> putAndClear = executor.submit(() -> { for (int i = 0; i < 30; i++) { IntStream.range(0, 100).forEach(j -> cities.put(j, new City(j))); try { cities.clear(); } catch (ServerOperationException e) { assertThat(e.getCause().getMessage()) .contains("Unable to clear all the buckets from the partitioned region cities") .contains("either data (buckets) moved or member departed"); } QueryService queryService = clientCache.getQueryService(); Query query = queryService.newQuery(MUMBAI_QUERY); Query query2 = queryService.newQuery(ID_10_QUERY); assertThat(((SelectResults) query.execute()).size()).isEqualTo(0); <START> assertThat(((SelectResults) query2.execute()).size()).isEqualTo(0); <END> } }); startStopServer.get(60, TimeUnit.SECONDS); putAndClear.get(60, TimeUnit.SECONDS); }</code><technical_language>asserts await.untilAsserted's. Judging DUnit failure</technical_language>

Target:
public void serverLeavingAndJoiningWhilePutAndClear() throws Exception { int locatorPort = ClusterStartupRule.getDUnitLocatorPort(); Future<Void> startStopServer = executor.submit(() -> { for (int i = 0; i < 3; i++) { MemberVM server3 = cluster.startServerVM(3, s -> s.withConnectionToLocator(locatorPort) .withProperty(SERIALIZABLE_OBJECT_FILTER, "org.apache.geode.cache.query.data.*") .withRegion(RegionShortcut.PARTITION, "cities")); server3.stop(false); } }); Future<Void> putAndClear = executor.submit(() -> { for (int i = 0; i < 30; i++) { IntStream.range(0, 100).forEach(j -> cities.put(j, new City(j))); try { cities.clear(); QueryService queryService = clientCache.getQueryService(); Query query = queryService.newQuery(MUMBAI_QUERY); Query query2 = queryService.newQuery(ID_10_QUERY); assertThat(((SelectResults) query.execute()).size()).isEqualTo(0); assertThat(((SelectResults) query2.execute()).size()).isEqualTo(0); } catch (ServerOperationException e) { assertThat(e.getCause().getMessage()) .contains("Unable to clear all the buckets from the partitioned region cities") .contains("either data (buckets) moved or member departed"); } } }); startStopServer.get(60, TimeUnit.SECONDS); putAndClear.get(60, TimeUnit.SECONDS); }
Source:
<code>public void testGenerateClass() throws CarbonToolsIntegrationTestException, XPathExpressionException { boolean fileCreated = false; Process process = null; String commandDirectory; try { <START> serviceUrl = automationContext.getContextUrls().getServiceUrl() + "/Version?wsdl"; <END> log.info("Service URL -" + serviceUrl); String[] cmdArrayToWsdl2Java; if (CarbonCommandToolsUtil.isCurrentOSWindows()) { throw new SkipException("Issue with wsdl2java.bat"); } else { cmdArrayToWsdl2Java = new String[]{"sh", "wsdl2java.sh", "-uri", serviceUrl}; commandDirectory = System.getProperty(ServerConstants.CARBON_HOME) + "/bin"; } process = CarbonCommandToolsUtil.runScript(commandDirectory, cmdArrayToWsdl2Java); fileCreated = CarbonCommandToolsUtil.waitForFileCreation( System.getProperty(ServerConstants.CARBON_HOME) + File.separator + "bin" + File.separator + "src/org/wso2/carbon/core/services/version/VersionStub.java"); } finally { if (process != null) { process.destroy(); } } Assert.assertTrue(fileCreated, "Java file not created successfully"); }</code><technical_language>Rename variable wsdlURL</technical_language>

Target:
public void testGenerateClass() throws CarbonToolsIntegrationTestException, XPathExpressionException { boolean fileCreated = false; Process process = null; String commandDirectory; try { serviceUrl = automationContext.getContextUrls().getServiceUrl() + "/Version?wsdl"; log.info("Service URL -" + serviceUrl); String[] cmdArrayToWsdl2Java; if ((CarbonCommandToolsUtil.getCurrentOperatingSystem(). contains(OperatingSystems.WINDOWS.name().toLowerCase())) ) { throw new SkipException("Issue with wsdl2java.bat"); } else { cmdArrayToWsdl2Java = new String[]{"sh", "wsdl2java.sh", "-uri", serviceUrl}; commandDirectory = System.getProperty(ServerConstants.CARBON_HOME) + "/bin"; } process = CarbonCommandToolsUtil.runScript(commandDirectory, cmdArrayToWsdl2Java); fileCreated = CarbonCommandToolsUtil.waitForFileCreation( System.getProperty(ServerConstants.CARBON_HOME) + File.separator + "bin" + File.separator + "src/org/wso2/carbon/core/services/version/VersionStub.java"); } finally { if (process != null) { process.destroy(); } } Assert.assertTrue(fileCreated, "Java file not created successfully"); }
Source:
<code>public long getQueueSize() { return executorQueue.size() * batchSize <START> + (openBatch == null ? 0 : openBatch.size()); <END> }</code><technical_language>discussed in chat, openBatch reference change accesses it, create a local var for it</technical_language>

Target:
public long getQueueSize() { Batch snapshot = openBatch; return executorQueue.size() * batchSize + (snapshot == null ? 0 : snapshot.size()); }
Source:
<code>protected AndroidDriver createBrowser() { try { return new AndroidDriver(new URL(getAndroidDriverUrl()), createCapabilities()); <START> } catch (MalformedURLException e) { <END> throw new RuntimeException(e); } }</code><technical_language>throw a RuntimeException, return null instead. superclass handling case returned object is null handle accordingly</technical_language>

Target:
protected AndroidDriver createBrowser() { try { return new AndroidDriver(new URL(getAndroidDriverUrl()), createCapabilities()); } catch (MalformedURLException e) { LOGGER.error("Invalid URL: " + getAndroidDriverUrl(), e); return null; } }
Source:
<code>private void assertTetherStatesNotNullButEmpty(final TetherStatesParcel parcel) { assertFalse(parcel == null); assertEquals(0, parcel.availableList.length); assertEquals(0, parcel.tetheredList.length); assertEquals(0, parcel.localOnlyList.length); assertEquals(0, parcel.erroredIfaceList.length); assertEquals(0, parcel.lastErrorList.length); <START> } <END></code><technical_language>use: MiscAssertsKt.assertFieldCountEquals(5, TetherStatesParcel.class) this is missed if a field is added</technical_language>

Target:
private void assertTetherStatesNotNullButEmpty(final TetherStatesParcel parcel) { assertFalse(parcel == null); assertEquals(0, parcel.availableList.length); assertEquals(0, parcel.tetheredList.length); assertEquals(0, parcel.localOnlyList.length); assertEquals(0, parcel.erroredIfaceList.length); assertEquals(0, parcel.lastErrorList.length); MiscAssertsKt.assertFieldCountEquals(5, TetherStatesParcel.class); }
Source:
<code>public void fireUpdated(RegistrationUpdate update, Registration registration) { for (RegistrationListener l : listeners) { l.updated(update, registration); } clientStatusTracker.setClientOnline(registration); <START> } <END></code><technical_language>I create a clientStatusTracker attribute in LeshanServer add a RegistrationListener call this clientStatusTracker.setClientOnline(registration)</technical_language>

Target:
public void fireUpdated(RegistrationUpdate update, Registration registration) { for (RegistrationListener l : listeners) { l.updated(update, registration); } }
Source:
<code>public void shouldBuildProperTriggerEventRequests() { List<TriggerEventRequest> triggerEventRequests = triggerBuilder.buildTriggers(); assertFalse(triggerEventRequests.isEmpty()); <START> assertEquals(3, triggerEventRequests.get(0).getEventParameters().size()); <END> assertEquals(DisplayNameHelper.buildDisplayName(DisplayNames.COHORT_GOTMEMBER, CONFIG_NAME), triggerEventRequests.get(0).getDisplayName()); assertEquals(EventKeys.BASE_SUBJECT + "Cohort.GotMember", triggerEventRequests.get(0).getSubject()); }</code><technical_language>verify if event parameters added trigger</technical_language>

Target:
public void shouldBuildProperTriggerEventRequests() { List<TriggerEventRequest> triggerEventRequests = triggerBuilder.buildTriggers(); assertFalse(triggerEventRequests.isEmpty()); assertEquals(3, triggerEventRequests.get(0).getEventParameters().size()); assertEquals(Keys.PATIENT_UUID, triggerEventRequests.get(0).getEventParameters().get(0).getEventKey()); assertEquals(Keys.PATIENT_DISPLAY, triggerEventRequests.get(0).getEventParameters().get(1).getEventKey()); assertEquals(Keys.COHORT_QUERY_UUID, triggerEventRequests.get(0).getEventParameters().get(2).getEventKey()); assertEquals(DisplayNameHelper.buildDisplayName(DisplayNames.COHORT_QUERY_REPORTMEMBER, CONFIG_NAME), triggerEventRequests.get(0).getDisplayName()); assertEquals(EventSubjects.GET_COHORT_QUERY_MEMBER_EVENT, triggerEventRequests.get(0).getSubject()); }
Source:
<code>private Xpp3Dom stripConfigElements(Xpp3Dom config, ArrayList<String> goalParams) { for (int i=0; i<config.getChildCount(); i++) { if (!goalParams.contains(config.getChild(i).getName().trim())) { <START> config.removeChild(i); <END> stripConfigElements(config, goalParams); } } return config; }</code><technical_language>Removing a child config while iterating children problems. operate a copy of config remove copy, return copy</technical_language>

Target:
private Xpp3Dom stripConfigElements(Xpp3Dom config, ArrayList<String> goalParams) { List<Integer> removeChildren = new ArrayList<Integer>(); for (int i=0; i<config.getChildCount(); i++) { if (!goalParams.contains(config.getChild(i).getName().trim())) { removeChildren.add(i); } } Collections.reverse(removeChildren); for (int child : removeChildren) { config.removeChild(child); } return config; }
Source:
<code>private Method getRequestMethod(RequestMethod req) { <START> Map<RequestMethod, Method> map = new HashMap<>(8); <END> map.put(RequestMethod.GET, Method.GET); map.put(RequestMethod.POST, Method.POST); map.put(RequestMethod.PUT, Method.PUT); map.put(RequestMethod.DELETE, Method.DELETE); map.put(RequestMethod.PATCH, Method.PATCH); map.put(RequestMethod.OPTIONS, Method.OPTIONS); map.put(RequestMethod.HEAD, Method.HEAD); map.put(RequestMethod.TRACE, Method.TRACE); return map.get(req); }</code><technical_language>suggestion Map<RequestMethod, Method> map = new HashMap<>();</technical_language>

Target:
private Method getRequestMethod(RequestMethod req) { Map<RequestMethod, Method> map = new HashMap<>(); map.put(RequestMethod.GET, Method.GET); map.put(RequestMethod.POST, Method.POST); map.put(RequestMethod.PUT, Method.PUT); map.put(RequestMethod.DELETE, Method.DELETE); map.put(RequestMethod.PATCH, Method.PATCH); map.put(RequestMethod.OPTIONS, Method.OPTIONS); map.put(RequestMethod.HEAD, Method.HEAD); map.put(RequestMethod.TRACE, Method.TRACE); return map.get(req); }
Source:
<code>public List<String> values(String name) { <START> return headers == null ? null : headers.get("Request-Id"); <END> }</code><technical_language>I this headers.get(name)</technical_language>

Target:
public List<String> values(String name) { return headers == null ? null : headers.get(name); }
Source:
<code>private ExternalParamCollection createExternalParamCollection(DataEntry dataEntry, InternalParamCollection queryParams) { ExternalParamCollection pc = new ExternalParamCollection(); <START> if(!dataService.getConfig(configId).isCaseSensitive()) { <END> for (String name : dataEntry.getNames()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(name.toLowerCase(), dataEntry.getValue(name), DBSFields.COLUMN)); } for (InternalParam iParam : queryParams.getParams()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(iParam.getName().toLowerCase(), iParam.getValue(), DBSFields.QUERY_PARAM)); } } else { for (String name : dataEntry.getNames()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(name, dataEntry.getValue(name), DBSFields.COLUMN)); } for (InternalParam iParam : queryParams.getParams()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(iParam.getName(), iParam.getValue(), DBSFields.QUERY_PARAM)); } } return pc; }</code><technical_language>Fix code formatting</technical_language>

Target:
private ExternalParamCollection createExternalParamCollection(DataEntry dataEntry, InternalParamCollection queryParams) { ExternalParamCollection pc = new ExternalParamCollection(); if (!dataService.getConfig(configId).isResultSetFieldsCaseSensitive()) { for (String name : dataEntry.getNames()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(name.toLowerCase(), dataEntry.getValue(name), DBSFields.COLUMN)); } for (InternalParam iParam : queryParams.getParams()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(iParam.getName().toLowerCase(), iParam.getValue(), DBSFields.QUERY_PARAM)); } } else { for (String name : dataEntry.getNames()) { pc.addParam(new org.wso2.carbon.dataservices.core.engine.ExternalParam(name, dataEntry.getValue(name), DBSFields.COLUMN)); } for (InternalParam iParam : queryParams.getParams()) { pc.addParam( new org.wso2.carbon.dataservices.core.engine.ExternalParam(iParam.getName(), iParam.getValue(), DBSFields.QUERY_PARAM)); } } return pc; }
Source:
<code>public String maskSensitiveElements( final Message message, final String originalLogString) { <START> if (sensitiveElementNames.isEmpty() || message == null) { return originalLogString; } <END> final String contentType = (String) message.get(Message.CONTENT_TYPE); if (contentType.toLowerCase().contains(XML_CONTENT) || contentType.toLowerCase().contains(HTML_CONTENT)) { return applyMasks(originalLogString, MATCH_PATTERN_XML, REPLACEMENT_PATTERN_XML); } else if (contentType.toLowerCase().contains(JSON_CONTENT)) { return applyMasks(originalLogString, MATCH_PATTERN_JSON, REPLACEMENT_PATTERN_JSON); } return originalLogString; }</code><technical_language>return if originalLogString is null + remove Optional.ofNullable in applyMasks below</technical_language>

Target:
public String maskSensitiveElements( final Message message, final String originalLogString) { if (replacementsXML.isEmpty() && replacementsJSON.isEmpty() || message == null || originalLogString == null) { return originalLogString; } final String contentType = (String) message.get(Message.CONTENT_TYPE); if (contentType.toLowerCase().contains(XML_CONTENT) || contentType.toLowerCase().contains(HTML_CONTENT)) { return applyMasks(originalLogString, replacementsXML); } else if (contentType.toLowerCase().contains(JSON_CONTENT)) { return applyMasks(originalLogString, replacementsJSON); } return originalLogString; }
Source:
<code>public void beginTree(DetailAST rootAST) { final Map<Integer, TextBlock> cppComments = getFileContents() .getSingleLineComments(); final Map<Integer, List<TextBlock>> cComments = getFileContents() .getBlockComments(); final Set<Integer> lines = new HashSet<>(); lines.addAll(cppComments.keySet()); lines.addAll(cComments.keySet()); for (Integer lineNo : lines) { final String line = getLines()[lineNo - 1]; final String lineBefore; final TextBlock comment; final int commentColNo; if (cppComments.containsKey(lineNo)) { comment = cppComments.get(lineNo); lineBefore = line.substring(0, comment.getStartColNo()); commentColNo = comment.getStartColNo(); } else { final List<TextBlock> commentList = cComments.get(lineNo); comment = commentList.get(commentList.size() - 1); lineBefore = line.substring(0, comment.getStartColNo()); <START> commentColNo = comment.getStartColNo(); <END> if (comment.getText().length == 1 && !CommonUtil.isBlank(line .substring(comment.getEndColNo() + 1))) { continue; } } if (!format.matcher(lineBefore).find() && !isLegalComment(comment)) { illegalLines.put(lineNo, commentColNo); } } }</code><technical_language>awesome feedback, fixed</technical_language>

Target:
public void beginTree(DetailAST rootAST) { final Map<Integer, TextBlock> cppComments = getFileContents() .getSingleLineComments(); final Map<Integer, List<TextBlock>> cComments = getFileContents() .getBlockComments(); final Set<Integer> lines = new HashSet<>(); lines.addAll(cppComments.keySet()); lines.addAll(cComments.keySet()); for (Integer lineNo : lines) { final String line = getLines()[lineNo - 1]; final String lineBefore; final TextBlock comment; if (cppComments.containsKey(lineNo)) { comment = cppComments.get(lineNo); lineBefore = line.substring(0, comment.getStartColNo()); } else { final List<TextBlock> commentList = cComments.get(lineNo); comment = commentList.get(commentList.size() - 1); lineBefore = line.substring(0, comment.getStartColNo()); if (comment.getText().length == 1 && !CommonUtil.isBlank(line .substring(comment.getEndColNo() + 1))) { continue; } } if (!format.matcher(lineBefore).find() && !isLegalComment(comment)) { illegalLines.put(lineNo, comment.getStartColNo()); } } }
Source:
<code>private List<Header> getPropagatedHeaders(Exchange exchange, HeaderFilterStrategy headerFilterStrategy) { return exchange.getIn().getHeaders().entrySet().stream() <START> .filter(entry -> !headerFilterStrategy.applyFilterToExternalHeaders(entry.getKey(), entry.getValue(), exchange)) <END> .map(entry -> new RecordHeader(entry.getKey(), getHeaderValue(entry.getValue()))) .collect(Collectors.toList()); }</code><technical_language>filter(includedHeaders)</technical_language>

Target:
private List<Header> getPropagatedHeaders(Exchange exchange, HeaderFilterStrategy headerFilterStrategy) { return exchange.getIn().getHeaders().entrySet().stream() .filter(entry -> shouldBeFiltered(entry, exchange, headerFilterStrategy)) .map(this::getRecordHeader) .filter(Objects::nonNull) .collect(Collectors.toList()); }
Source:
<code><START> public boolean equals(Object that) { <END> return (that instanceof NumberRange) ? equals((NumberRange) that) : super.equals(that); }</code><technical_language>@Override</technical_language>

Target:
public boolean equals(Object that) { return super.equals(that); }
Source:
<code>public T get() { Provider<T> p = item.get(); T t = null; <START> if( p != null ) { <END> t = p.get(); } return t; }</code><technical_language>nit: if (p != null)</technical_language>

Target:
public T get() { ItemAndPluginName myItem = item.get(); return myItem != null ? myItem.provider.get() : null; }
Source:
<code>public JsonConverter() { final Set<DeserializationFeature> deserializationFeatures = new HashSet<>(); deserializationFeatures.add(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); <START> deserializer = new JsonDeserializer(deserializationFeatures, true); <END> }</code><technical_language>Passing in a JsonNodeFactory instance here, JsonConverter instances JsonDeserializer in converter JsonNodeFactory. currently stands, JsonDeserializer instance of JsonNodeFactory, set differently in future caught</technical_language>

Target:
public JsonConverter() { serializer = new JsonSerializer( mkSet(), JSON_NODE_FACTORY ); deserializer = new JsonDeserializer( mkSet( DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS ), JSON_NODE_FACTORY ); }
Source:
<code>public String toString() { return "WorkspaceServiceImpl{" + "securityService=" + securityService + ", catalogFramework=" + catalogFramework + ", workspaceTransformer=" + workspaceTransformer + ", maxSubscriptions=" <START> + maxSubscriptions.get() <END> + '}'; }</code><technical_language>mighty fine clean this a string format if feeling</technical_language>

Target:
public String toString() { return String.format( "WorkspaceServiceImpl{securityService=%s, catalogFramework=%s, workspaceTransformer=%s, maxSubscriptions=%d}", securityService, catalogFramework, workspaceTransformer, maxSubscriptions); }
Source:
<code>public <T> Mono<FeedResponse<T>> readMany( List<Pair<String, PartitionKey>> itemKeyList, <START> String sessionToken, <END> Class<T> classType) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (!StringUtils.isNotBlank(sessionToken)) { options = options.setSessionToken(sessionToken); } options.setMaxDegreeOfParallelism(-1); return CosmosBridgeInternal .getAsyncDocumentClient(this.getDatabase()) .readMany(itemKeyList, BridgeInternal.getLink(this), options, classType); }</code><technical_language>Is Itemizing (or promoting parts of) request option, limit applicable ones</technical_language>

Target:
public <T> Mono<FeedResponse<T>> readMany( List<Pair<String, PartitionKey>> itemKeyList, String sessionToken, Class<T> classType) { CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); if (!StringUtils.isNotEmpty(sessionToken)) { options = options.setSessionToken(sessionToken); } options.setMaxDegreeOfParallelism(-1); return CosmosBridgeInternal .getAsyncDocumentClient(this.getDatabase()) .readMany(itemKeyList, BridgeInternal.getLink(this), options, classType); }
Source:
<code>public List<String> getParameters() { <START> return new ArrayList<>(parameters); <END> }</code><technical_language>return [unmodifiable list](<LINK_0> here</technical_language>

Target:
public List<String> getParameters() { return unmodifiableList(parameters); }
Source:
<code>public boolean sourceStatus(String servicePID) { try { <START> List<ServiceReference<? extends Source>> sourceReferences = getServiceReferences(); <END> for (ServiceReference<? extends Source> ref : sourceReferences) { Source service = bundleContext.getService(ref); if (service instanceof ConfiguredService) { ConfiguredService cs = (ConfiguredService) service; try { Configuration config = configurationAdmin .getConfiguration(cs.getConfigurationPid()); if (config.getProperties().get("service.pid").equals(servicePID)) { return service.isAvailable(); } } catch (IOException e) { LOGGER.warn("Couldn't find configuration for source '{}'", service.getId()); } } else { LOGGER.warn("Source '{}' not a configured service", service.getId()); } } } catch (InvalidSyntaxException e) { LOGGER.error("Could not get service reference list"); } return false; }</code><technical_language>If add a LDAP filter a parameter, get a list filtered service.pid. remove a lot of this code</technical_language>

Target:
public boolean sourceStatus(String servicePID) { try { List<Source> sources = helper.getSources(); for (Source source : sources) { if (source instanceof ConfiguredService) { ConfiguredService cs = (ConfiguredService) source; try { Configuration config = helper.getConfiguration(cs); if (config != null && config.getProperties().get("service.pid") .equals(servicePID)) { try { return source.isAvailable(); } catch (Exception e) { LOGGER.warn("Couldn't get availability on source {}: {}", servicePID, e); } } } catch (IOException e) { LOGGER.warn("Couldn't find configuration for source '{}'", source.getId()); } } else { LOGGER.warn("Source '{}' not a configured service", source.getId()); } } } catch (InvalidSyntaxException e) { LOGGER.error("Could not get service reference list"); } return false; }
Source:
<code>public void testAnswerCard(){ Collection col; col = getCol(); long deckId = mTestDeckIds[0]; col.getDecks().select(deckId); <START> col.getSched().reset(); <END> Card card = col.getSched().getCard(); long cardId = card.getId(); assertEquals("card is initial new", Consts.CARD_TYPE_NEW, card.getQueue()); ContentResolver cr = InstrumentationRegistry.getInstrumentation().getTargetContext().getContentResolver(); Uri reviewInfoUri = FlashCardsContract.ReviewInfo.CONTENT_URI; ContentValues values = new ContentValues(); long noteId = card.note().getId(); int cardOrd = card.getOrd(); int ease = AbstractFlashcardViewer.EASE_3; long timeTaken = 5000; values.put(FlashCardsContract.ReviewInfo.NOTE_ID, noteId); values.put(FlashCardsContract.ReviewInfo.CARD_ORD, cardOrd); values.put(FlashCardsContract.ReviewInfo.EASE, ease); values.put(FlashCardsContract.ReviewInfo.TIME_TAKEN, timeTaken); int updateCount = cr.update(reviewInfoUri, values, null, null); assertEquals("Check if update returns 1", 1, updateCount); try { Thread.currentThread().wait(500); } catch (Exception e) { } col.getSched().reset(); Card newCard = col.getSched().getCard(); if(newCard != null){ if(newCard.note().getId() == card.note().getId() && newCard.getOrd() == card.getOrd()){ fail("Next scheduled card has not changed"); } } Card cardAfterReview = col.getCard(cardId); assertEquals("card is now type rev", Card.TYPE_REV, cardAfterReview.getQueue()); }</code><technical_language>Agreed this change is necessary a change test. useful "Extract Method" 3 lines reduce code duplication</technical_language>

Target:
public void testAnswerCard(){ Collection col = getCol(); Card card = getFirstCardFromScheduler(col); long cardId = card.getId(); assertEquals("card is initial new", Consts.CARD_TYPE_NEW, card.getQueue()); ContentResolver cr = InstrumentationRegistry.getInstrumentation().getTargetContext().getContentResolver(); Uri reviewInfoUri = FlashCardsContract.ReviewInfo.CONTENT_URI; ContentValues values = new ContentValues(); long noteId = card.note().getId(); int cardOrd = card.getOrd(); int ease = AbstractFlashcardViewer.EASE_3; long timeTaken = 5000; values.put(FlashCardsContract.ReviewInfo.NOTE_ID, noteId); values.put(FlashCardsContract.ReviewInfo.CARD_ORD, cardOrd); values.put(FlashCardsContract.ReviewInfo.EASE, ease); values.put(FlashCardsContract.ReviewInfo.TIME_TAKEN, timeTaken); int updateCount = cr.update(reviewInfoUri, values, null, null); assertEquals("Check if update returns 1", 1, updateCount); try { Thread.currentThread().wait(500); } catch (Exception e) { } col.getSched().reset(); Card newCard = col.getSched().getCard(); if(newCard != null){ if(newCard.note().getId() == card.note().getId() && newCard.getOrd() == card.getOrd()){ fail("Next scheduled card has not changed"); } } Card cardAfterReview = col.getCard(cardId); assertEquals("card is now type rev", Card.TYPE_REV, cardAfterReview.getQueue()); }
Source:
<code>public void partOpened(IWorkbenchPart part) { IDragAndDropService dndService = part.getSite() .getService(IDragAndDropService.class); if (dndService == null) { return; } if (part instanceof BndEditor) { <START> part = ((BndEditor) part).getSourcePage(); <END> } Control control = part.getAdapter(Control.class); if ((control == null) || !(control instanceof StyledText)) { return; } IPath file = null; if (part instanceof EditorPart) { EditorPart editorPart = (EditorPart) part; IEditorInput editorInput = editorPart.getEditorInput(); if (editorInput instanceof IFileEditorInput) { IFileEditorInput input = (IFileEditorInput) editorInput; file = input.getFile() .getFullPath(); } else if (editorInput instanceof IStorageEditorInput) { IStorageEditorInput input = (IStorageEditorInput) editorInput; try { file = input.getStorage() .getFullPath(); } catch (CoreException e) { throw Exceptions.duck(e); } } } if (file != null) { String fileName = file.lastSegment(); String fileExtension = file.getFileExtension(); if ("pom.xml".equals(fileName)) { dndService.addMergedDropTarget(control, DROP_COPY, transfers, new MavenDropTargetListener((StyledText) control)); } else if ("gradle".equalsIgnoreCase(fileExtension)) { dndService.addMergedDropTarget(control, DROP_COPY, transfers, new GradleDropTargetListener((StyledText) control)); } else if ("bnd".equalsIgnoreCase(fileExtension) || "bndrun".equalsIgnoreCase(fileExtension)) { dndService.addMergedDropTarget(control, DROP_COPY, transfers, new BndDropTargetListener((StyledText) control)); } } }</code><technical_language>modify BndEditor do this. BndEditor override getAdapter method return styledText queries for Control.class</technical_language>

Target:
public void partOpened(IWorkbenchPart part) { IDragAndDropService dndService = part.getSite() .getService(IDragAndDropService.class); if (dndService == null) { return; } Control control = part.getAdapter(Control.class); if ((control == null) || !(control instanceof StyledText)) { return; } IPath file = null; if (part instanceof EditorPart) { EditorPart editorPart = (EditorPart) part; IEditorInput editorInput = editorPart.getEditorInput(); if (editorInput instanceof IFileEditorInput) { IFileEditorInput input = (IFileEditorInput) editorInput; file = input.getFile() .getFullPath(); } else if (editorInput instanceof IStorageEditorInput) { IStorageEditorInput input = (IStorageEditorInput) editorInput; try { file = input.getStorage() .getFullPath(); } catch (CoreException e) { throw Exceptions.duck(e); } } } if (file != null) { String fileName = file.lastSegment(); String fileExtension = file.getFileExtension(); if ("pom.xml".equals(fileName)) { dndService.addMergedDropTarget(control, DROP_COPY, transfers, new MavenDropTargetListener((StyledText) control)); } else if ("gradle".equalsIgnoreCase(fileExtension)) { dndService.addMergedDropTarget(control, DROP_COPY, transfers, new GradleDropTargetListener((StyledText) control)); } else if ("bnd".equalsIgnoreCase(fileExtension) || "bndrun".equalsIgnoreCase(fileExtension)) { dndService.addMergedDropTarget(control, DROP_COPY, transfers, new BndDropTargetListener((StyledText) control)); } } }
Source:
<code>public CleanerThread() { this.setName("Reportal-Cleaner-Thread"); <START> CLEAN_INTERVAL_MS = props.getInt("reportal.clean.interval.ms", 24 * 60 * 60 * 1000); <END> OUTPUT_DIR_RETENTION_MS = props.getInt("reportal.output.dir.retention.ms", 7 * 24 * 60 * 60 * 1000); MAIL_TEMP_DIR_RETENTION_MS = props.getInt("reportal.mail.temp.dir.retention.ms", 1 * 24 * 60 * 60 * 1000); }</code><technical_language>replace 24_60_60*1000 static variable. DEFAULT_REPORTAL_CLEAN_INTERVAL_MS. easier find. defaults</technical_language>

Target:
public CleanerThread() { this.setName("Reportal-Cleaner-Thread"); CLEAN_INTERVAL_MS = props.getLong("reportal.clean.interval.ms", DEFAULT_CLEAN_INTERVAL_MS); OUTPUT_DIR_RETENTION_MS = props.getLong("reportal.output.dir.retention.ms", DEFAULT_OUTPUT_DIR_RETENTION_MS); MAIL_TEMP_DIR_RETENTION_MS = props.getLong("reportal.mail.temp.dir.retention.ms", DEFAULT_MAIL_TEMP_DIR_RETENTION_MS); }
Source:
<code>public static ClientSelector labelSelector(final String labelMask) { return new ClientSelector() { @Override public boolean select(Client client) { <START> return client.getAttributes().values().iterator().next().matches(labelMask); <END> } @Override public String toString() { return "ClientSelector{labelMask:" + labelMask + " }"; } }; }</code><technical_language>this selector check client labels, one</technical_language>

Target:
public static ClientSelector labelSelector(final String labelMask) { return new ClientSelector() { @Override public boolean select(Client client) { Set<String> labels = client.getLabels(); for (String label : labels) { if (label.matches(labelMask)) { return true; } } return false; } @Override public String toString() { return "ClientSelector{labelMask:" + labelMask + " }"; } }; }
Source:
<code>private void setNeedsMoreUsersIfAppropriate(final Page page, final Project project, final Session session) { boolean hasEnoughUsersGroups = project.getUsersWithPermission(Type.ADMIN).size() > 1 || project.getGroupsWithPermission(Type.ADMIN).size() > 0 || !hasPermission(session.getUser(), Type.ADMIN) <START> || !this.forceMultipleUsers; <END> page.add("hasEnoughUsersGroups", hasEnoughUsersGroups); }</code><technical_language>nitpick : move this.forceMultipleUsers front, if config is off, fallback existing logic</technical_language>

Target:
private void setNeedsMoreUsersIfAppropriate(final Page page, final Project project, final Session session) { boolean hasEnoughUsersGroups = !this.forceMultipleUsers || project.getUsersWithPermission(Type.ADMIN).size() > 1 || project.getGroupsWithPermission(Type.ADMIN).size() > 0 || !hasPermission(session.getUser(), Type.ADMIN); page.add("hasEnoughUsersGroups", hasEnoughUsersGroups); }
Source:
<code>private void broadcastUDPForCoapDeviceDiscover() { logger.debug(TAG + ": Broadcasting udp"); DatagramSocket mClientSock; try { mClientSock = new DatagramSocket(); InetAddress hostAddress = InetAddress.getByName("255.255.255.255"); logger.info(hostAddress.getHostAddress()); logger.info(hostAddress.getHostName()); logger.info(hostAddress.getCanonicalHostName()); logger.debug(hostAddress.getHostAddress()); logger.debug(hostAddress.getHostName()); <START> logger.debug(hostAddress.getCanonicalHostName()); <END> String mMsg = "mchp_coap"; DatagramPacket out = new DatagramPacket(mMsg.getBytes(), mMsg.length(), hostAddress, 65525); mClientSock.send(out); mClientSock.setSoTimeout(5000); while (true) { try { byte[] buf = new byte[1000]; DatagramPacket in = new DatagramPacket(buf, buf.length); mClientSock.receive(in); String payload = new String(in.getData()); logger.debug(TAG + ": Get reply from bcast from:" + in.getAddress().getHostAddress()); if (payload.substring(0, 9).equals("mchp_coap")) { discoverCoAP(in.getAddress()); } } catch (SocketTimeoutException e) { mClientSock.close(); break; } } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>please condense logging line debug trace level. logger.trace("address: {}, name: {}, canonicalName: {}", hostAddress.getHostAddress(), hostAddress.getHostName(), hostAddress.getCanonicalHostName());</technical_language>

Target:
private void broadcastUDPForCoapDeviceDiscover() { logger.debug(TAG + ": Broadcasting udp"); DatagramSocket mClientSock; try { mClientSock = new DatagramSocket(); InetAddress hostAddress = InetAddress.getByName("255.255.255.255"); logger.debug("address: {}, name: {}, canonicalName: {}", hostAddress.getHostAddress(), hostAddress.getHostName(), hostAddress.getCanonicalHostName()); DatagramPacket out = new DatagramPacket(serverIdentifier.getBytes(), serverIdentifier.length(), hostAddress, 65525); mClientSock.send(out); mClientSock.setSoTimeout(5000); while (true) { try { byte[] buf = new byte[1000]; DatagramPacket in = new DatagramPacket(buf, buf.length); mClientSock.receive(in); String payload = new String(in.getData()); logger.debug(TAG + ": Get reply from bcast from:" + in.getAddress().getHostAddress()); if (payload.substring(0, 9).equals(serverIdentifier)) { discoverCoAP(in.getAddress()); } } catch (SocketTimeoutException e) { mClientSock.close(); break; } } } catch (SocketException e) { logger.debug("UDP error on the socket", e); } catch (IOException e) { logger.debug("IO error on the socket", e); } }
Source:
<code>public void endWindow() { if (windowId <= windowDataManager.getLargestCompletedWindow()) { return; } <START> <END> if (!partialWindowTuples.isEmpty() && windowId > windowDataManager.getLargestCompletedWindow()) { throw new RuntimeException("Violates Exactly once. Not all the tuples received after operator reset."); } getProducer().flush(); try { this.windowDataManager.save(getPartitionsAndOffsets(true), windowId); } catch (IOException | InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }</code><technical_language>check for "windowId > windowDataManager.getLargestCompletedWindow()" in next line is redundant</technical_language>

Target:
public void endWindow() { if (windowId <= windowDataManager.getLargestCompletedWindow()) { return; } if (!partialWindowTuples.isEmpty()) { throw new RuntimeException("Violates Exactly once. Not all the tuples received after operator reset."); } getProducer().flush(); try { this.windowDataManager.save(getPartitionsAndOffsets(true), windowId); } catch (IOException | InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }
Source:
<code>public void testResolveTipSha1() throws IOException { ObjectId masterId = db.resolve("refs/heads/master"); Set<Ref> resolved = db.getRefDatabase().resolveTipSha1(masterId); <START> assertEquals(resolved.size(), 2); <END> checkContainsRef(resolved, db.exactRef("refs/heads/master")); checkContainsRef(resolved, db.exactRef("HEAD")); assertEquals(db.getRefDatabase() .resolveTipSha1(ObjectId.zeroId()).size(), 0); }</code><technical_language>arguments in order previous uses, for example L347. order is correct? If this one, do a cleanup of others</technical_language>

Target:
public void testResolveTipSha1() throws IOException { ObjectId masterId = db.resolve("refs/heads/master"); Set<Ref> resolved = db.getRefDatabase().resolveTipSha1(masterId); assertEquals(2, resolved.size()); checkContainsRef(resolved, db.exactRef("refs/heads/master")); checkContainsRef(resolved, db.exactRef("HEAD")); assertEquals(db.getRefDatabase() .resolveTipSha1(ObjectId.zeroId()).size(), 0); }
Source:
<code>protected boolean set(Entity entity, Boolean value) { if (!entity.worldObj.isRemote) { if (value) { ((WorldServer) entity.worldObj).getEntityTracker().untrackEntity(entity); } else { <START> ((WorldServer) entity.worldObj).getEntityTracker().trackEntity(entity); <END> } ((WorldServer) entity.worldObj).getEntityTracker().updateTrackedEntities(); entity.setInvisible(value); return true; } else { return false; } }</code><technical_language>Need check if entity is tracked here, explode</technical_language>

Target:
protected boolean set(Entity entity, Boolean value) { if (!entity.worldObj.isRemote) { EntityTracker entityTracker = ((WorldServer) entity.worldObj).getEntityTracker(); if (value) { entityTracker.untrackEntity(entity); } else { if (!entityTracker.trackedEntityHashTable.containsItem(entity.getEntityId())) { entityTracker.trackEntity(entity); } } entityTracker.updateTrackedEntities(); entity.setInvisible(value); return true; } else { return false; } }
Source:
<code>public boolean onScale(ScaleGestureDetector detector) { mScaleFactor *= detector.getScaleFactor(); mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f)); <START> Iterator<Paint> iter = mTextStyle.iterator(); <END> while (iter.hasNext()) { iter.next().setTextSize(DEFAULT_TEXT_SIZE * mScaleFactor); } invalidate(); return true; }</code><technical_language>a for</technical_language>

Target:
public boolean onScale(ScaleGestureDetector detector) { mScaleFactor *= detector.getScaleFactor(); mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f)); for (Paint p : mTextStyle) { p.setTextSize(DEFAULT_TEXT_SIZE * mScaleFactor); } invalidate(); return true; }
Source:
<code>public void testListMultipartUploads() throws Exception { String uploadId = api.initiateMultipartUpload(VAULT_NAME1, 8); try { PaginatedMultipartUploadCollection uploads = api.listMultipartUploads(VAULT_NAME1); <START> ImmutableList.Builder<String> list = ImmutableList.<String>builder(); <END> for(MultipartUploadMetadata upload : uploads) { list.add(upload.getMultipartUploadId()); } assertTrue(list.build().contains(uploadId)); assertTrue(api.abortMultipartUpload(VAULT_NAME1, uploadId)); } finally { api.abortMultipartUpload(VAULT_NAME1, uploadId); } }</code><technical_language>infer type with: ImmutableList.Builder<String> list = ImmutableList.builder();</technical_language>

Target:
public void testListMultipartUploads() throws Exception { long partSizeInMb = 1; String uploadId = api.initiateMultipartUpload(VAULT_NAME1, partSizeInMb); try { assertNotNull(api.uploadPart(VAULT_NAME1, uploadId, ContentRange.fromPartNumber(0, partSizeInMb), buildPayload(partSizeInMb * MiB))); PaginatedMultipartUploadCollection uploads = api.listMultipartUploads(VAULT_NAME1); ImmutableList.Builder<String> list = ImmutableList.builder(); for (MultipartUploadMetadata upload : uploads) { list.add(upload.getMultipartUploadId()); } assertTrue(list.build().contains(uploadId)); assertTrue(api.abortMultipartUpload(VAULT_NAME1, uploadId)); } finally { api.abortMultipartUpload(VAULT_NAME1, uploadId); } }
Source:
<code>private String endOfMonthManipulation(String value) { DateTime dateTime = new DateTime(value); <START> return dateTime.dayOfMonth().withMaximumValue().toString(); <END> }</code><technical_language>set time 23:59:59</technical_language>

Target:
private String endOfMonthManipulation(String value) { DateTime dateTime = new DateTime(value); return dateTime.dayOfMonth().withMaximumValue().withTime(23, 59, 59, 999).toString(); }