auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public <I, F extends ScanFormatFactory<I>> ScanFormat<I> discoverScanFormat( Class<F> formatFactoryClass, ConfigOption<String> formatOption, String formatPrefix) { return discoverOptionalScanFormat(formatFactoryClass, formatOption, formatPrefix) .orElseThrow(() -> new ValidationException( <START> String.format("Could not find required scan format option '%s'.", formatOption.key()))); <END> }</code><technical_language>nit: drop option. I sound nicer if simply find format</technical_language>

Target:
public <I, F extends ScanFormatFactory<I>> ScanFormat<I> discoverScanFormat( Class<F> formatFactoryClass, ConfigOption<String> formatOption, String formatPrefix) { return discoverOptionalScanFormat(formatFactoryClass, formatOption, formatPrefix) .orElseThrow(() -> new ValidationException( String.format("Could not find required scan format '%s'.", formatOption.key()))); }
Source:
<code>private boolean isDefaultGiven(String swaggerContent) throws APIManagementException { Swagger swagger = getSwagger(swaggerContent); boolean isDefaultIsGiven = true; Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions(); OAuth2Definition checkDefault = (OAuth2Definition) securityDefinitions.get(SWAGGER_SECURITY_SCHEMA_KEY); if (checkDefault == null) { isDefaultIsGiven = false; <START> } <END> return isDefaultIsGiven; }</code><technical_language>do a null check for securityDefinitions. Otherwise, this break if swagger security definitions</technical_language>

Target:
private boolean isDefaultGiven(String swaggerContent) throws APIManagementException { Swagger swagger = getSwagger(swaggerContent); boolean isDefaultIsGiven = true; Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions(); if (securityDefinitions == null) { securityDefinitions = new HashMap<>(); } OAuth2Definition checkDefault = (OAuth2Definition) securityDefinitions.get(SWAGGER_SECURITY_SCHEMA_KEY); if (checkDefault == null) { isDefaultIsGiven = false; } return isDefaultIsGiven; }
Source:
<code>public PathComponent build() { if (this.path.length() == 0) { return null; } <START> String path = UrlPathHelper.getSanitizedPath(this.path); <END> return new HierarchicalUriComponents.FullPathComponent(path); }</code><technical_language>I prefer avoid dependency UriComponentsBuilder UrlPathHelper. is more of a Servlet API specific component while is more general. if re-use in this case touch Servlet specific, minor worth gain</technical_language>

Target:
public PathComponent build() { if (this.path.length() == 0) { return null; } String sanitized = getSanitizedPath(this.path); return new HierarchicalUriComponents.FullPathComponent(sanitized); }
Source:
<code>private void createDoubleClickListener(TreeViewer treeViewer) { <START> treeViewer.addDoubleClickListener(new IDoubleClickListener() { <END> @Override public void doubleClick(DoubleClickEvent event) { if (event.getSelection() instanceof TreeSelection) { TreeSelection selection = (TreeSelection) event.getSelection(); if (selection.getFirstElement() instanceof ITimeGraphEntry) { ITimeGraphEntry entry = (ITimeGraphEntry) selection.getFirstElement(); if (entry.hasChildren()) { fTimeGraphWrapper.setExpandedState(entry, !fTimeGraphWrapper.getExpandedState(entry)); } } } } }); }</code><technical_language>this a lambda</technical_language>

Target:
private void createDoubleClickListener(TreeViewer treeViewer) { treeViewer.addDoubleClickListener(event -> { if (event.getSelection() instanceof TreeSelection) { TreeSelection selection = (TreeSelection) event.getSelection(); if (selection.getFirstElement() instanceof ITimeGraphEntry) { ITimeGraphEntry entry = (ITimeGraphEntry) selection.getFirstElement(); if (entry.hasChildren()) { fTimeGraphWrapper.setExpandedState(entry, !fTimeGraphWrapper.getExpandedState(entry)); } } } }); }
Source:
<code>public void serialize() { byte[] result = serializer.serialize("someKey", value); <START> System.out.println(Arrays.toString(result)); <END> assertArrayEquals(expectedResult, result); }</code><technical_language>a log print standard out please</technical_language>

Target:
public void serialize() { byte[] result = serializer.serialize("someKey", value); assertArrayEquals(expectedResult, result); }
Source:
<code>void handleFinished() { int ret = doUnmountVolume(path, true, removeEncryption); Slog.i(TAG, "Unmount completed: " + path + ", result code: " + ret); <START> this.mountShutdownLatch.countDown(); <END> }</code><technical_language>suggest: synchronized (this) { if (mLatch != null) { mLatch.countDown(); } mLatch = null; } this prevents accidental double-handleFinished() invocations counting times. (it defensively forces 1:1 mapping.)</technical_language>

Target:
void handleFinished() { int ret = doUnmountVolume(path, true, removeEncryption); Slog.i(TAG, "Unmount completed: " + path + ", result code: " + ret); mMountShutdownLatch.countDown(); }
Source:
<code>static void assertAccountInAccountService(Account account, AccountService accountService) { Account accountFoundById = accountService.getAccountById(account.getId()); Account accountFoundByName = accountService.getAccountByName(account.getName()); assertEquals("Account got by id from accountService does not match account got by name.", accountFoundById, accountFoundByName); try { <START> System.out.println(accountFoundById.toJson()); <END> System.out.println(account.toJson()); } catch (JSONException e) { e.printStackTrace(); } assertEquals("Account got by id from accountService does not match the account to assert", accountFoundById, account); assertEquals("The number of containers in the account is wrong.", accountFoundById.getAllContainers().size(), account.getAllContainers().size()); for (Container container : account.getAllContainers()) { assertContainerInAccountService(container, accountService); } }</code><technical_language>code deleted</technical_language>

Target:
static void assertAccountInAccountService(Account account, AccountService accountService) { Account accountFoundById = accountService.getAccountById(account.getId()); Account accountFoundByName = accountService.getAccountByName(account.getName()); assertEquals("Account got by id from accountService does not match account got by name.", accountFoundById, accountFoundByName); assertEquals("Account got by id from accountService does not match the account to assert", accountFoundById, account); assertEquals("The number of containers in the account is wrong.", accountFoundById.getAllContainers().size(), account.getAllContainers().size()); for (Container container : account.getAllContainers()) { assertContainerInAccountService(container, accountService); } }
Source:
<code>public void testBasic() { ExpectedValueProvider<FunctionCall> aggregationPattern = PlanMatchPattern.functionCall("count", false, ImmutableList.of(anySymbol())); tester().assertThat(new AddIntermediateAggregations()) .setSystemProperty(ENABLE_INTERMEDIATE_AGGREGATIONS, "true") .setSystemProperty(TASK_CONCURRENCY, "4") .on(p -> p.aggregation(af -> { p.variable("a", BIGINT); p.variable("b", BIGINT); p.variable("c", BIGINT); af.globalGrouping() .step(AggregationNode.Step.FINAL) <START> .addAggregation(p.variable(p.symbol("c")), p.rowExpression("count(b)")) <END> .source( p.gatheringExchange( ExchangeNode.Scope.REMOTE_STREAMING, p.aggregation(ap -> ap.globalGrouping() .step(AggregationNode.Step.PARTIAL) .addAggregation(p.variable(p.symbol("b")), p.rowExpression("count(a)")) .source( p.values(p.variable("a")))))); })) .matches( aggregation( globalAggregation(), ImmutableMap.of(Optional.empty(), aggregationPattern), ImmutableMap.of(), Optional.empty(), FINAL, exchange(LOCAL, GATHER, aggregation( globalAggregation(), ImmutableMap.of(Optional.empty(), aggregationPattern), ImmutableMap.of(), Optional.empty(), INTERMEDIATE, exchange(LOCAL, REPARTITION, exchange(REMOTE_STREAMING, GATHER, aggregation( globalAggregation(), ImmutableMap.of(Optional.empty(), aggregationPattern), ImmutableMap.of(), Optional.empty(), INTERMEDIATE, exchange(LOCAL, GATHER, aggregation( globalAggregation(), ImmutableMap.of(Optional.empty(), aggregationPattern), ImmutableMap.of(), Optional.empty(), PARTIAL, values(ImmutableMap.of("a", 0))))))))))); }</code><technical_language>changes commit adds rowExpression</technical_language>

Target:
public void testBasic() { ExpectedValueProvider<FunctionCall> aggregationPattern = PlanMatchPattern.functionCall("count", false, ImmutableList.of(anySymbol())); tester().assertThat(new AddIntermediateAggregations()) .setSystemProperty(ENABLE_INTERMEDIATE_AGGREGATIONS, "true") .setSystemProperty(TASK_CONCURRENCY, "4") .on(p -> p.aggregation(af -> { p.variable("a", BIGINT); p.variable("b", BIGINT); p.variable("c", BIGINT); af.globalGrouping() .step(AggregationNode.Step.FINAL) .addAggregation(p.variable("c"), p.rowExpression("count(b)")) .source( p.gatheringExchange( ExchangeNode.Scope.REMOTE_STREAMING, p.aggregation(ap -> ap.globalGrouping() .step(AggregationNode.Step.PARTIAL) .addAggregation(p.variable("b"), p.rowExpression("count(a)")) .source( p.values(p.variable("a")))))); })) .matches( aggregation( globalAggregation(), ImmutableMap.of(Optional.empty(), aggregationPattern), ImmutableMap.of(), Optional.empty(), FINAL, exchange(LOCAL, GATHER, aggregation( globalAggregation(), ImmutableMap.of(Optional.empty(), aggregationPattern), ImmutableMap.of(), Optional.empty(), INTERMEDIATE, exchange(LOCAL, REPARTITION, exchange(REMOTE_STREAMING, GATHER, aggregation( globalAggregation(), ImmutableMap.of(Optional.empty(), aggregationPattern), ImmutableMap.of(), Optional.empty(), INTERMEDIATE, exchange(LOCAL, GATHER, aggregation( globalAggregation(), ImmutableMap.of(Optional.empty(), aggregationPattern), ImmutableMap.of(), Optional.empty(), PARTIAL, values(ImmutableMap.of("a", 0))))))))))); }
Source:
<code>public void testAtomFeed() { Map<String, Object> metadata = (Map<String, Object>)expectedFeed.get("metadata"); <START> AtomFeed found = AtomFeed.parseStream(this.xmlStream); <END> assertEquals(metadata.get("itemsPerPage"), found.itemsPerPage); assertEquals(metadata.get("startIndex"), found.startIndex); assertEquals(metadata.get("totalResults"), found.totalResults); List<Map<String, Object>> expectedEntries = (List<Map<String, Object>>)expectedFeed.get("entries"); List<AtomEntry> foundEntries = (List<AtomEntry>)found.entries; for (int i = 0; i < foundEntries.size(); i++) { AtomEntry foundEntry = foundEntries.get(i); Map<String, Object> expectedEntry = expectedEntries.get(i); assertEquals(expectedEntry.get("id"), foundEntry.id); assertEquals(expectedEntry.get("title"), foundEntry.title); assertEquals(expectedEntry.get("updated"), foundEntry.updated); Map<String, String> expectedLinks = (Map<String, String>)expectedEntry.get("links"); for (String linkName : foundEntry.links.keySet()) { assertEquals(expectedLinks.get(linkName), foundEntry.links.get(linkName)); } if (expectedEntry.containsKey("content")) { Map<String, Object> expectedContent = (Map<String, Object>)expectedEntry.get("content"); for (String key : foundEntry.content.keySet()) { if (!key.startsWith("eai:")) { assertEquals("Mismatch on " + key, expectedContent.get(key), foundEntry.content.get(key)); } } } else { assertNull(foundEntry.content); } } }</code><technical_language>Easier read renames: - metadata -> expectedMetadata - -> actualFeed Ditto for some subsequent uses: - foundEntries -> actualEntries - foundEntry -> actualEntry</technical_language>

Target:
public void testAtomFeed() { Map<String, Object> expectedMetadata = (Map<String, Object>)expectedFeed.get("metadata"); AtomFeed actualFeed = AtomFeed.parseStream(this.xmlStream); assertEquals(expectedMetadata.get("itemsPerPage"), actualFeed.itemsPerPage); assertEquals(expectedMetadata.get("startIndex"), actualFeed.startIndex); assertEquals(expectedMetadata.get("totalResults"), actualFeed.totalResults); List<Map<String, Object>> expectedEntries = (List<Map<String, Object>>)expectedFeed.get("entries"); List<AtomEntry> actualEntries = (List<AtomEntry>)actualFeed.entries; for (int i = 0; i < actualEntries.size(); i++) { AtomEntry actualEntry = actualEntries.get(i); Map<String, Object> expectedEntry = expectedEntries.get(i); assertEquals(expectedEntry.get("id"), actualEntry.id); assertEquals(expectedEntry.get("title"), actualEntry.title); assertEquals(expectedEntry.get("updated"), actualEntry.updated); Map<String, String> expectedLinks = (Map<String, String>)expectedEntry.get("links"); for (String linkName : actualEntry.links.keySet()) { assertEquals(expectedLinks.get(linkName), actualEntry.links.get(linkName)); } if (expectedEntry.containsKey("content")) { Map<String, Object> expectedContent = (Map<String, Object>)expectedEntry.get("content"); for (String key : actualEntry.content.keySet()) { if (!key.startsWith("eai:")) { assertEquals("Mismatch on " + key, expectedContent.get(key), actualEntry.content.get(key)); } } } else { assertNull(actualEntry.content); } } }
Source:
<code>public LabelType(String name, List<LabelValue> valueList) { this.name = checkName(name); canOverride = true; <START> branch = Arrays.asList("project"); <END> values = sortValues(valueList); abbreviation = defaultAbbreviation(name); functionName = "MaxWithBlock"; maxNegative = Short.MIN_VALUE; maxPositive = Short.MAX_VALUE; if (values.size() > 0) { if (values.get(0).getValue() < 0) { maxNegative = values.get(0).getValue(); } if (values.get(values.size() - 1).getValue() > 0) { maxPositive = values.get(values.size() - 1).getValue(); } } }</code><technical_language>I if label applies complete project, branch list empty 'refs/*' entry</technical_language>

Target:
public LabelType(String name, List<LabelValue> valueList) { this.name = checkName(name); canOverride = true; values = sortValues(valueList); abbreviation = defaultAbbreviation(name); functionName = "MaxWithBlock"; maxNegative = Short.MIN_VALUE; maxPositive = Short.MAX_VALUE; if (values.size() > 0) { if (values.get(0).getValue() < 0) { maxNegative = values.get(0).getValue(); } if (values.get(values.size() - 1).getValue() > 0) { maxPositive = values.get(values.size() - 1).getValue(); } } }
Source:
<code>public static CallNotPermittedException getCallNotPermittedException(CircuitBreaker circuitBreaker) { boolean disableStackTraces = circuitBreaker.getCircuitBreakerConfig().isDisableStackTraces(); String message = String.format("CircuitBreaker '%s' is %s and does not permit further calls", circuitBreaker.getName(), circuitBreaker.getState()); <START> if (disableStackTraces) { <END> return new CallNotPermittedException(message, false); } else { return new CallNotPermittedException(message, true); } }</code><technical_language>return new CallNotPermittedException(message, writableStackTraceEnabled); instead</technical_language>

Target:
public static CallNotPermittedException getCallNotPermittedException(CircuitBreaker circuitBreaker) { boolean writableStackTraceEnabled = circuitBreaker.getCircuitBreakerConfig().isWritableStackTraceEnabled(); String message = String.format("CircuitBreaker '%s' is %s and does not permit further calls", circuitBreaker.getName(), circuitBreaker.getState()); return new CallNotPermittedException(message, writableStackTraceEnabled); }
Source:
<code>public void close() { releaseCurrentSortBuffer(); if (fileWriter != null) { fileWriter.releaseQuietly(); <START> } <END> super.close(); }</code><technical_language>#close called canceller thread if I remembered correctly, race condition here. release fileWriter interrupt task thread while writing data. For other resource cleanup put #releaseInternal() task exits</technical_language>

Target:
public void close() { releaseCurrentSortBuffer(); super.close(); IOUtils.closeQuietly(fileWriter); }
Source:
<code>void initializeSystemColors () { COLOR_WIDGET_DARK_SHADOW_RGBA = new GdkRGBA (); COLOR_WIDGET_DARK_SHADOW_RGBA.alpha = 1.0; initializeColorList(); byte buffer = OS.GTK_THEME_SET ? Converter.wcsToMbcs (OS.GTK_THEME_NAME, true) : OS.getThemeNameBytes(); byte darkBuffer = OS.GTK_THEME_DARK ? darkBuffer = Converter.wcsToMbcs ("dark", true) : null; long themeProvider = GTK.gtk_css_provider_get_named(buffer, darkBuffer); String cssOutput = gtk_css_provider_to_string(themeProvider); initializeSystemColorsWidget(cssOutput); initializeSystemColorsList(cssOutput); initializeSystemColorsTitle(cssOutput); initializeSystemColorsLink(cssOutput); <START> if (GTK.GTK_VERSION >= OS.VERSION(3, 20, 0)) { initializeSystemColorsTooltip_3_20(); } else { initializeSystemColorsTooltip_old(cssOutput); } <END> COLOR_TITLE_FOREGROUND_RGBA = COLOR_LIST_SELECTION_TEXT_RGBA; COLOR_TITLE_BACKGROUND_RGBA = COLOR_LIST_SELECTION_RGBA; COLOR_TITLE_BACKGROUND_GRADIENT_RGBA = toGdkRGBA (COLOR_LIST_SELECTION_RGBA, 1.3); COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT_RGBA = toGdkRGBA (COLOR_TITLE_INACTIVE_BACKGROUND_RGBA, 1.3); }</code><technical_language>combine this function "initializeSystemColorsTooltip" do version guards in function</technical_language>

Target:
void initializeSystemColors () { COLOR_WIDGET_DARK_SHADOW_RGBA = new GdkRGBA (); COLOR_WIDGET_DARK_SHADOW_RGBA.alpha = 1.0; initializeColorList(); byte buffer = OS.GTK_THEME_SET ? Converter.wcsToMbcs (OS.GTK_THEME_NAME, true) : OS.getThemeNameBytes(); byte darkBuffer = OS.GTK_THEME_DARK ? darkBuffer = Converter.wcsToMbcs ("dark", true) : null; long themeProvider = GTK.gtk_css_provider_get_named(buffer, darkBuffer); String cssOutput = gtk_css_provider_to_string(themeProvider); initializeSystemColorsWidget(cssOutput); initializeSystemColorsList(cssOutput); initializeSystemColorsTitle(cssOutput); initializeSystemColorsLink(cssOutput); initializeSystemColorsTooltip(cssOutput); COLOR_TITLE_FOREGROUND_RGBA = COLOR_LIST_SELECTION_TEXT_RGBA; COLOR_TITLE_BACKGROUND_RGBA = COLOR_LIST_SELECTION_RGBA; COLOR_TITLE_BACKGROUND_GRADIENT_RGBA = toGdkRGBA (COLOR_LIST_SELECTION_RGBA, 1.3); COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT_RGBA = toGdkRGBA (COLOR_TITLE_INACTIVE_BACKGROUND_RGBA, 1.3); }
Source:
<code><START> public void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, <END> List<SignalFxProtocolBuffers.PointValue> datumPoints) throws SignalFxMetricsException { if (datumPoints.isEmpty()) { return; } List<NameValuePair> params = Lists.newArrayList(); params.add(new BasicNameValuePair("orgid", orgId)); params.add(new BasicNameValuePair("metric_type", metricType)); params.add(new BasicNameValuePair("metric", metric)); for(Map.Entry<String,String> entry : dimensions.entrySet()) { params.add(new BasicNameValuePair("sfxdim_" + entry.getKey(), entry.getValue())); } try { CloseableHttpResponse resp = null; try { resp = postToEndpoint(auth, new InputStreamEntity( new ProtocolBufferStreamingInputStream<SignalFxProtocolBuffers.PointValue>( datumPoints.iterator()), PROTO_TYPE), "/v1/backfill?" + URLEncodedUtils.format(params, "UTF-8"), false); int code = resp.getStatusLine().getStatusCode(); if (code != HttpStatus.SC_OK) { throw new SignalFxMetricsException("Invalid status code " + code); } } finally { if (resp != null) { resp.close(); } } } catch (IOException e) { throw new SignalFxMetricsException("Exception posting to backfillDataPoints", e); } }</code><technical_language>is orgId required is this API? reason backend derive auth token do for normal ingest</technical_language>

Target:
public void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, List<SignalFxProtocolBuffers.PointValue> datumPoints) throws SignalFxMetricsException { if (datumPoints.isEmpty()) { return; } List<NameValuePair> params = Lists.newArrayList(); params.add(new BasicNameValuePair("orgid", orgId)); params.add(new BasicNameValuePair("metric_type", metricType)); params.add(new BasicNameValuePair("metric", metric)); for (Map.Entry<String,String> entry : dimensions.entrySet()) { params.add(new BasicNameValuePair("sfxdim_" + entry.getKey(), entry.getValue())); } try { CloseableHttpResponse resp = null; try { resp = postToEndpoint(auth, new InputStreamEntity( new ProtocolBufferStreamingInputStream<SignalFxProtocolBuffers.PointValue>( datumPoints.iterator()), PROTO_TYPE), "/v1/backfill?" + URLEncodedUtils.format(params, StandardCharsets.UTF_8), false); int code = resp.getStatusLine().getStatusCode(); if (code != HttpStatus.SC_OK) { throw new SignalFxMetricsException("Invalid status code " + code); } } finally { if (resp != null) { resp.close(); } } } catch (IOException e) { throw new SignalFxMetricsException("Exception posting to backfillDataPoints", e); } }
Source:
<code><START> public ClueWeb09Collection.FileSegment createFileSegment(Path p) throws IOException { <END> return new FileSegment(p); }</code><technical_language>FileSegment instead of ClueWeb09Collection.FileSegment</technical_language>

Target:
public FileSegment createFileSegment(Path p) throws IOException { return new FileSegment(p); }
Source:
<code>public static void disableVersioning_test() throws Exception { if (!mintEnv) { System.out.println("Test: disableVersioning(DisableVersioningArgs args)"); } long startTime = System.currentTimeMillis(); try { String name = getRandomName(); client.makeBucket(MakeBucketArgs.builder().bucket(name).build()); <START> client.disableVersioning(DisableVersioningArgs.builder().bucket(name).build()); <END> client.removeBucket(RemoveBucketArgs.builder().bucket(name).build()); mintSuccessLog("disableVersioning(DisableVersioningArgs args)", null, startTime); } catch (Exception e) { ErrorResponse errorResponse = null; if (e instanceof ErrorResponseException) { ErrorResponseException exp = (ErrorResponseException) e; errorResponse = exp.errorResponse(); } if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) { mintIgnoredLog("disableVersioning(DisableVersioningArgs args)", null, startTime); } else { mintFailedLog( "disableVersioning(DisableVersioningArgs args)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } }</code><technical_language>add more check this java client.enableVersioning(EnableVersioningArgs.builder().bucket(name).build()); client.disableVersioning(DisableVersioningArgs.builder().bucket(name).build());</technical_language>

Target:
public static void disableVersioning_test() throws Exception { if (!mintEnv) { System.out.println("Test: disableVersioning(DisableVersioningArgs args)"); } long startTime = System.currentTimeMillis(); try { String name = getRandomName(); client.makeBucket(MakeBucketArgs.builder().bucket(name).build()); client.disableVersioning(DisableVersioningArgs.builder().bucket(name).build()); client.enableVersioning(EnableVersioningArgs.builder().bucket(name).build()); client.disableVersioning(DisableVersioningArgs.builder().bucket(name).build()); client.removeBucket(RemoveBucketArgs.builder().bucket(name).build()); mintSuccessLog("disableVersioning(DisableVersioningArgs args)", null, startTime); } catch (Exception e) { ErrorResponse errorResponse = null; if (e instanceof ErrorResponseException) { ErrorResponseException exp = (ErrorResponseException) e; errorResponse = exp.errorResponse(); } if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) { mintIgnoredLog("disableVersioning(DisableVersioningArgs args)", null, startTime); } else { mintFailedLog( "disableVersioning(DisableVersioningArgs args)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } }
Source:
<code>public void testGetResultListSizeWithTypedQuery() throws Exception { <START> List<Helicopter> helicopters = em.createQuery( "FROM Helicopter", Helicopter.class ) <END> .getResultList(); Assertions.assertThat( helicopters.size() ).isEqualTo( 2 ); }</code><technical_language>Is a test for passing wrong type creating a typed query</technical_language>

Target:
public void testGetResultListSizeWithTypedQuery() throws Exception { List<Helicopter> helicopters = em.createQuery( "FROM Helicopter", Helicopter.class ) .getResultList(); assertThat( helicopters.size() ).isEqualTo( 2 ); }
Source:
<code>protected void refreshVisuals() { super.refreshVisuals(); <START> DSemanticDiagram dSemanticDiagram = getDSemanticDiagram(); if (dSemanticDiagram != null) { ColorDescription backgroundColor = dSemanticDiagram.getDescription().getBackgroundColor(); if (backgroundColor != null && getFigure() != null) { RGBValues rgbBackgroundValues = new AbstractColorUpdater().getRGBValuesFromColorDescription(dSemanticDiagram.getTarget(), backgroundColor); Color colorUpdate = new Color(null, rgbBackgroundValues.getRed(), rgbBackgroundValues.getGreen(), rgbBackgroundValues.getBlue()); if (getFigure().getBackgroundColor() != colorUpdate) { if (isWhiteColor(rgbBackgroundValues)) { getFigure().setBackgroundColor(null); getFigure().setOpaque(false); } else { getFigure().setBackgroundColor(colorUpdate); getFigure().setOpaque(true); } } } } <END> }</code><technical_language>This duplicate code in createFigure(). extracted a common method, for example "private void configureBackground(IFigure fig)"</technical_language>

Target:
protected void refreshVisuals() { super.refreshVisuals(); configureBackground(getFigure()); }
Source:
<code>public void valueMapShouldReturnAProperDeserializedJsonList() { String json = "[\"red\",\"green\",\"blue\"]"; List<String> expected = new ArrayList<String>(asList("red","green","blue")); ValueMap valueMap = new ValueMap().withJSON(KEY, json); List<String> actual = (List<String>)valueMap.get(KEY); assertThat(actual.size(), is(expected.size())); <START> for (int counter = 0; counter < actual.size(); counter++) { <END> assertThat(actual.get(counter), is(expected.get(counter))); } }</code><technical_language>Similarly get rid of loop expected object do like: assertThat(actual.size(), is(3)); assertThat(actual, hasItems("red","green","blue"));</technical_language>

Target:
public void valueMapShouldReturnAProperDeserializedJsonList() { String json = "[\"red\",\"green\",\"blue\"]"; ValueMap valueMap = new ValueMap().withJSON(KEY, json); List<String> actual = (List<String>)valueMap.get(KEY); assertThat(actual.size(), is(3)); assertThat(actual, hasItems("red", "green", "blue")); }
Source:
<code><START> public static boolean isTabListEmpty() { <END> List<Tab> tabs = getTabs(); return !tabs.isEmpty() && !tabs.get(0).getBackStack().isEmpty(); }</code><technical_language>code right name of this method is misleading. of name implies</technical_language>

Target:
public static boolean isTabListEmpty() { List<Tab> tabs = getTabs(); return tabs.isEmpty() || (tabs.size() == 1 && tabs.get(0).getBackStack().isEmpty()); }
Source:
<code>public HighPassNode(Context context) { <START> RenderingConfig renderingConfig = context.get(Config.class).getRendering(); <END> DisplayResolutionDependentFBOs displayResolutionDependentFBOs = context.get(DisplayResolutionDependentFBOs.class); renderingConfig.subscribe(RenderingConfig.BLOOM, this); requiresCondition(renderingConfig::isBloom); requiresFBO(HIGH_PASS_FBO_CONFIG, displayResolutionDependentFBOs); addDesiredStateChange(new BindFBO(HIGH_PASS_FBO, displayResolutionDependentFBOs)); addDesiredStateChange(new SetViewportToSizeOf(HIGH_PASS_FBO, displayResolutionDependentFBOs)); highPass = getMaterial(HIGH_PASS_MATERIAL); addDesiredStateChange(new EnableMaterial(HIGH_PASS_MATERIAL)); int textureSlot = 0; addDesiredStateChange(new SetInputTextureFromFBO(textureSlot, READONLY_GBUFFER, ColorTexture, displayResolutionDependentFBOs, HIGH_PASS_MATERIAL, "tex")); }</code><technical_language>This line moved below, renderingConfig.subscribe line</technical_language>

Target:
public HighPassNode(Context context) { super(context); RenderingConfig renderingConfig = context.get(Config.class).getRendering(); renderingConfig.subscribe(RenderingConfig.BLOOM, this); requiresCondition(renderingConfig::isBloom); DisplayResolutionDependentFBOs displayResolutionDependentFBOs = context.get(DisplayResolutionDependentFBOs.class); requiresFBO(HIGH_PASS_FBO_CONFIG, displayResolutionDependentFBOs); addDesiredStateChange(new BindFBO(HIGH_PASS_FBO, displayResolutionDependentFBOs)); addDesiredStateChange(new SetViewportToSizeOf(HIGH_PASS_FBO, displayResolutionDependentFBOs)); highPass = getMaterial(HIGH_PASS_MATERIAL); addDesiredStateChange(new EnableMaterial(HIGH_PASS_MATERIAL)); int textureSlot = 0; addDesiredStateChange(new SetInputTextureFromFBO(textureSlot, READONLY_GBUFFER, ColorTexture, displayResolutionDependentFBOs, HIGH_PASS_MATERIAL, "tex")); }
Source:
<code>public Signature createSignature(final X509Certificate certificate, final PrivateKey privateKey, final PublicKey publicKey) throws SAMLAssertionBuilderException { final BasicX509Credential credential = new BasicX509Credential(certificate, privateKey); credential.setEntityCertificate(certificate); credential.setPrivateKey(privateKey); final Signature signature = OpenSAMLUtil.buildSignature(); signature.setSigningCredential(credential); signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1); signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); try { signature.setKeyInfo(getKeyInfo(publicKey)); } catch (final Exception ex) { <START> LOG.error("Get HL7 Prefix Property exception: {}", ex.getLocalizedMessage(), ex); <END> throw new SAMLAssertionBuilderException(ex.getLocalizedMessage(), ex); } return signature; }</code><technical_language>Consider logging full exception here, passed stack, reduce log verbosity</technical_language>

Target:
public Signature createSignature(final X509Certificate certificate, final PrivateKey privateKey, final PublicKey publicKey) throws SAMLAssertionBuilderException { final BasicX509Credential credential = new BasicX509Credential(certificate, privateKey); credential.setEntityCertificate(certificate); credential.setPrivateKey(privateKey); final Signature signature = OpenSAMLUtil.buildSignature(); signature.setSigningCredential(credential); signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1); signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); try { signature.setKeyInfo(getKeyInfo(publicKey)); } catch (final Exception ex) { throw new SAMLAssertionBuilderException(ex.getLocalizedMessage(), ex); } return signature; }
Source:
<code>public void doJobInFuture(String username, String password, String insightURL, String[] participantLabels, String fullPath, String reportId, JobDetail jobDetail, String fileName) { <START> String response = insightReportService.runReport(username, password, insightURL, participantLabels, fullPath,reportId); <END> if (response != null) { CompletableFuture<Object> future = CompletableFuture.supplyAsync(() -> { try { insightReportService.saveToFile(response.toString(), fullPath); userService.persistJobCompleted(jobDetail, fileName); }catch(Exception e) { logger.error("Exeception is thrown while creating file : " + e); } return null; }); } }</code><technical_language>report needs run part of future. line needs move try block</technical_language>

Target:
public void doJobInFuture(String username, String password, String insightURL, String[] participantLabels, String fullPath, String reportId, JobDetail jobDetail, String fileName) { CompletableFuture<Object> future = CompletableFuture.supplyAsync(() -> { try { String response = insightReportService.runReport(username, password, insightURL, participantLabels, fullPath, reportId); insightReportService.saveToFile(response.toString(), fullPath); userService.persistJobCompleted(jobDetail, fileName); }catch(Exception e) { logger.error("Exception is thrown while creating file : " + e); userService.persistJobFailed(jobDetail, fileName); } return null; }); }
Source:
<code>public void rewriteResourceZip(@NonNull File source, @NonNull File dest) throws IOException { if (dest.exists()) { boolean deleted = dest.delete(); if (!deleted) { throw new IOException("Could not delete " + dest); } } JarInputStream zis = null; try { FileInputStream fis = new FileInputStream(source); try { FileOutputStream fos = new FileOutputStream(dest); zis = new JarInputStream(fis); JarOutputStream zos = new JarOutputStream(fos); try { zos.setLevel(Deflater.DEFAULT_COMPRESSION); ZipEntry entry = zis.getNextEntry(); while (entry != null) { String name = entry.getName(); boolean directory = entry.isDirectory(); Resource resource = getResourceByJarPath(name); if (resource == null || resource.reachable) { JarEntry outEntry = new <START> JarEntry(entry.getName()); <END> if (entry.getTime() != -1L) { outEntry.setTime(entry.getTime()); } int method = entry.getMethod(); outEntry.setMethod(method); if (method == ZipEntry.STORED) { outEntry.setCompressedSize(entry.getCompressedSize()); outEntry.setSize(entry.getSize()); outEntry.setCrc(entry.getCrc()); } zos.putNextEntry(outEntry); if (!directory) { byte[] bytes = ByteStreams.toByteArray(zis); if (bytes != null) { zos.write(bytes); } } zos.closeEntry(); } else if (isVerbose()) { System.out.println("Skipped unused resource " + name + ": " + entry.getSize() + " bytes"); } entry = zis.getNextEntry(); } zos.flush(); } finally { Closeables.close(zos, false); } } finally { Closeables.close(fis, true); } } finally { Closeables.close(zis, false); } }</code><technical_language>copy constructor</technical_language>

Target:
public void rewriteResourceZip(@NonNull File source, @NonNull File dest) throws IOException { if (dest.exists()) { boolean deleted = dest.delete(); if (!deleted) { throw new IOException("Could not delete " + dest); } } JarInputStream zis = null; try { FileInputStream fis = new FileInputStream(source); try { FileOutputStream fos = new FileOutputStream(dest); zis = new JarInputStream(fis); JarOutputStream zos = new JarOutputStream(fos); try { zos.setLevel(Deflater.DEFAULT_COMPRESSION); ZipEntry entry = zis.getNextEntry(); while (entry != null) { String name = entry.getName(); boolean directory = entry.isDirectory(); Resource resource = getResourceByJarPath(name); if (resource == null || resource.reachable) { JarEntry outEntry = new JarEntry(entry); zos.putNextEntry(outEntry); if (!directory) { byte[] bytes = ByteStreams.toByteArray(zis); if (bytes != null) { zos.write(bytes); } } zos.closeEntry(); } else if (isVerbose()) { System.out.println("Skipped unused resource " + name + ": " + entry.getSize() + " bytes"); } entry = zis.getNextEntry(); } zos.flush(); } finally { Closeables.close(zos, false); } } finally { Closeables.close(fis, true); } } finally { Closeables.close(zis, false); } }
Source:
<code>public void testAddStandardVariable() throws Exception { String propertyName = "property name " + new Random().nextInt(10000); this.ontologyDataManager.addProperty(propertyName, "test property", 1087); StandardVariable stdVariable = new StandardVariable(); stdVariable.setName("variable name " + new Random().nextInt(10000)); stdVariable.setDescription("variable description"); stdVariable.setProperty(this.ontologyDataManager.findTermByName(propertyName, CvId.PROPERTIES)); stdVariable.setMethod(new Term(4030, "Assigned", "Term, name or id assigned")); stdVariable.setScale(new Term(6000, "DBCV", "Controlled vocabulary from a database")); stdVariable.setDataType(new Term(1120, "Character variable", "variable with char values")); stdVariable.setIsA(new Term(1050, "Study condition", "Study condition class")); stdVariable.setEnumerations(new ArrayList<Enumeration>()); <START> stdVariable.getEnumerations().add(new Enumeration(10001, "HB", "Hybridization nursery", 2)); <END> stdVariable.getEnumerations().add(new Enumeration(10002, "PN", "Pedigree nursery", 3)); stdVariable.setConstraints(new VariableConstraints(100.0, 999.0)); stdVariable.setCropOntologyId("CROP-TEST"); try { this.ontologyDataManager.addStandardVariable(stdVariable, PROGRAM_UUID); } catch (MiddlewareQueryException e) { if (e.getMessage().contains("already exists")) { } } Debug.println(IntegrationTestBase.INDENT, "Standard variable saved: " + stdVariable.getId()); }</code><technical_language>@vmaletta, please remove types of Nursery</technical_language>

Target:
public void testAddStandardVariable() throws Exception { String propertyName = "property name " + new Random().nextInt(10000); this.ontologyDataManager.addProperty(propertyName, "test property", 1087); StandardVariable stdVariable = new StandardVariable(); stdVariable.setName("variable name " + new Random().nextInt(10000)); stdVariable.setDescription("variable description"); stdVariable.setProperty(this.ontologyDataManager.findTermByName(propertyName, CvId.PROPERTIES)); stdVariable.setMethod(new Term(4030, "Assigned", "Term, name or id assigned")); stdVariable.setScale(new Term(6000, "DBCV", "Controlled vocabulary from a database")); stdVariable.setDataType(new Term(1120, "Character variable", "variable with char values")); stdVariable.setIsA(new Term(1050, "Study condition", "Study condition class")); stdVariable.setEnumerations(new ArrayList<Enumeration>()); stdVariable.getEnumerations().add(new Enumeration(StudyType.N.getId(), StudyType.N.getName(), StudyType.N.getLabel(), 1)); stdVariable.getEnumerations().add(new Enumeration(StudyType.HB.getId(), StudyType.HB.getName(), StudyType.HB.getLabel(), 2)); stdVariable.getEnumerations().add(new Enumeration(StudyType.PN.getId(), StudyType.PN.getName(), StudyType.PN.getLabel(), 3)); stdVariable.setConstraints(new VariableConstraints(100.0, 999.0)); stdVariable.setCropOntologyId("CROP-TEST"); try { this.ontologyDataManager.addStandardVariable(stdVariable, PROGRAM_UUID); } catch (MiddlewareQueryException e) { if (e.getMessage().contains("already exists")) { } } Debug.println(IntegrationTestBase.INDENT, "Standard variable saved: " + stdVariable.getId()); }
Source:
<code>public Principal getUser(final HttpServletRequest request, final HttpServletResponse response) { final HttpSession session = request.getSession(); if (session.getAttribute(LOGGED_IN_KEY) != null) { LOGGER.debug("Session found; user already logged in."); return (Principal) session.getAttribute(LOGGED_IN_KEY); } final Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION); if (assertion != null) { final Principal p = getUser(assertion.getPrincipal().getName()); if (p == null) { <START> LOGGER.error("Principal is null for " + assertion.getPrincipal().getName()); <END> } LOGGER.debug("Logging in from CAS.", p.getName()); session.setAttribute(LOGGED_IN_KEY, p); session.setAttribute(LOGGED_OUT_KEY, null); return p; } return super.getUser(request, response); }</code><technical_language>parameterized log statements. right this</technical_language>

Target:
public Principal getUser(final HttpServletRequest request, final HttpServletResponse response) { final HttpSession session = request.getSession(); if (session.getAttribute(LOGGED_IN_KEY) != null) { LOGGER.debug("Session found; user already logged in."); return (Principal) session.getAttribute(LOGGED_IN_KEY); } final Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION); if (assertion != null) { final Principal p = getUser(assertion.getPrincipal().getName()); if (p == null) { LOGGER.error("Principal is null for ", assertion.getPrincipal().getName()); } LOGGER.debug("Logging in from CAS.", p.getName()); session.setAttribute(LOGGED_IN_KEY, p); session.setAttribute(LOGGED_OUT_KEY, null); return p; } return super.getUser(request, response); }
Source:
<code>protected IndexValue findKey(StoreKey key) throws StoreException { final Timer.Context context = metrics.findTime.time(); try { <START> ConcurrentNavigableMap<Long, IndexSegment> segmentsMapsToFind = indexes.descendingMap(); <END> for (Map.Entry<Long, IndexSegment> entry : segmentsMapsToFind.entrySet()) { logger.trace("Index : searching index with start offset {}", dataDir, entry.getKey()); IndexValue value = entry.getValue().find(key); if (value != null) { logger.trace("Index : found value offset size ttl {}", dataDir, value.getOffset(), value.getSize(), value.getTimeToLiveInMs()); return value; } } } finally { context.stop(); } return null; }</code><technical_language>isnt segmentsMapToFind? (not Maps)</technical_language>

Target:
protected IndexValue findKey(StoreKey key) throws StoreException { final Timer.Context context = metrics.findTime.time(); try { ConcurrentNavigableMap<Long, IndexSegment> segmentsMapToFind = indexes.descendingMap(); for (Map.Entry<Long, IndexSegment> entry : segmentsMapToFind.entrySet()) { logger.trace("Index : searching index with start offset {}", dataDir, entry.getKey()); IndexValue value = entry.getValue().find(key); if (value != null) { logger.trace("Index : found value offset size ttl {}", dataDir, value.getOffset(), value.getSize(), value.getTimeToLiveInMs()); return value; } } } finally { context.stop(); } return null; }
Source:
<code>void initialize() throws IOException { if ( !writerTaken.compareAndSet( false, true ) ) { throw new IllegalStateException( "Writer in " + this + " is already acquired by someone else. " + "Only a single writer is allowed. The writer will become available as soon as " + "acquired writer is closed" ); } boolean success = false; try { readLock = writerCheckpointMutex.readLock(); readLock.lock(); cursor = openRootCursor( PagedFile.PF_SHARED_WRITE_LOCK ); stableGeneration = stableGeneration( generation ); unstableGeneration = unstableGeneration( generation ); PointerChecking.assertNoSuccessor( cursor, stableGeneration, unstableGeneration ); treeLogic.initialize( cursor ); success = true; } catch ( TreeInconsistencyException e ) { throw appendTreeInformation( e ); } finally { if ( !success ) { <START> closeCursor(); <END> writerTaken.set( false ); releaseLock(); } } }</code><technical_language>call close here</technical_language>

Target:
void initialize() throws IOException { if ( !writerTaken.compareAndSet( false, true ) ) { throw new IllegalStateException( "Writer in " + this + " is already acquired by someone else. " + "Only a single writer is allowed. The writer will become available as soon as " + "acquired writer is closed" ); } boolean success = false; try { readLock = writerCheckpointMutex.readLock(); readLock.lock(); cursor = openRootCursor( PagedFile.PF_SHARED_WRITE_LOCK ); stableGeneration = stableGeneration( generation ); unstableGeneration = unstableGeneration( generation ); PointerChecking.assertNoSuccessor( cursor, stableGeneration, unstableGeneration ); treeLogic.initialize( cursor ); success = true; } catch ( TreeInconsistencyException e ) { throw appendTreeInformation( e ); } finally { if ( !success ) { close(); } } }
Source:
<code><START> public boolean setLocation(final Vector3d position, final UUID world) { <END> final WorldProperties prop = Sponge.getServer().getWorldManager().getProperties(world).orElseThrow(() -> new IllegalArgumentException("Invalid World: No world found for UUID")); final World loaded; try { loaded = Sponge.getServer().getWorldManager().loadWorld(prop).orElseThrow(() -> new IllegalArgumentException("Invalid World: Could not load world for UUID")); } catch (IOException ex) { throw new IllegalArgumentException("Invalid World: ", ex); } return this.setLocation(Location.of(loaded, position)); }</code><technical_language>funny enough, this is implemented correctly in API 7... <LINK_0> is supposed load a world. queries if World is online bombs if isn't</technical_language>

Target:
public boolean setLocation(final Vector3d position, final UUID world) { final Optional<ServerWorld> targetWorld = Sponge.getServer().getWorldManager().getWorld(world); return targetWorld.isPresent() && this.setLocation(Location.of(targetWorld.get(), position)); }
Source:
<code>public void run() { LOGGER.info("Run {}: {}", getClass().getName(), Thread.currentThread().getName()); LOGGER.info("Queue={}", queue); while (active.get()) { final MailQueueItem queueItem; try { queueItem = queue.deQueue(); workerService.execute(() -> { TimeMetric timeMetric = metricFactory.timer(SPOOL_PROCESSING); try { numActive.incrementAndGet(); processingActive.incrementAndGet(); Mail mail = queueItem.getMail(); LOGGER.debug("==== Begin processing mail ====", mail.getName()); try { mailProcessor.service(mail); queueItem.done(true); } catch (Exception e) { if (active.get()) { <START> LOGGER.error("Exception processing mail while spooling {}", e.getMessage(), e); <END> } queueItem.done(false); } finally { LifecycleUtil.dispose(mail); mail = null; } } catch (Throwable e) { if (active.get()) { LOGGER.error("Exception processing mail while spooling {}", e.getMessage(), e); } } finally { processingActive.decrementAndGet(); numActive.decrementAndGet(); timeMetric.stopAndPublish(); } }); } catch (MailQueueException e1) { if (active.get()) { LOGGER.error("Exception dequeue mail", e1); } } catch (InterruptedException interrupted) { } } LOGGER.info("Stop : {}", getClass().getName(), Thread.currentThread().getName()); }</code><technical_language>getMessage</technical_language>

Target:
public void run() { LOGGER.info("Run {}: {}", getClass().getName(), Thread.currentThread().getName()); LOGGER.info("Queue={}", queue); while (active.get()) { final MailQueueItem queueItem; try { queueItem = queue.deQueue(); workerService.execute(() -> { TimeMetric timeMetric = metricFactory.timer(SPOOL_PROCESSING); try { numActive.incrementAndGet(); processingActive.incrementAndGet(); Mail mail = queueItem.getMail(); LOGGER.debug("==== Begin processing mail ====", mail.getName()); try { mailProcessor.service(mail); queueItem.done(true); } catch (Exception e) { if (active.get()) { LOGGER.error("Exception processing mail while spooling", e); } queueItem.done(false); } finally { LifecycleUtil.dispose(mail); mail = null; } } catch (Throwable e) { if (active.get()) { LOGGER.error("Exception processing mail while spooling", e); } } finally { processingActive.decrementAndGet(); numActive.decrementAndGet(); timeMetric.stopAndPublish(); } }); } catch (MailQueueException e1) { if (active.get()) { LOGGER.error("Exception dequeue mail", e1); } } catch (InterruptedException interrupted) { } } LOGGER.info("Stop : {}", getClass().getName(), Thread.currentThread().getName()); }
Source:
<code>public StageInfo getStageInfo() { return stateMachine.getStageInfo( () -> getAllTasks().stream() .map(RemoteTask::getTaskInfo) <START> .collect(toImmutableList())); <END> }</code><technical_language>I getBasicStageStats/getStageInfo a bit hard read, update as: public BasicStageStats getBasicStageStats() { return stateMachine.getBasicStageStats(this::getAllTaskInfo); } public StageInfo getStageInfo() { return stateMachine.getStageInfo(this::getAllTaskInfo); } private Iterable<TaskInfo> getAllTaskInfo() { return getAllTasks().stream() .map(RemoteTask::getTaskInfo) .collect(toImmutableList()); }</technical_language>

Target:
public StageInfo getStageInfo() { return stateMachine.getStageInfo(this::getAllTaskInfo); }
Source:
<code><START> public JavaPackageSource(Package javaPackage) { <END> this.packageName = javaPackage.getName(); }</code><technical_language>I introduce a JavaPackageSource(String) constructor well</technical_language>

Target:
public JavaPackageSource(Package javaPackage) { this(Preconditions.notNull(javaPackage, "java package must not be null").getName()); }
Source:
<code>private static long sleep(long millis) { long startTime = System.nanoTime(); try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } <START> long sleepTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); <END> if (sleepTimeMs < 0) { sleepTimeMs = 0; } return sleepTimeMs; }</code><technical_language>Nano time is prone for overflows. Millis fine</technical_language>

Target:
private static long sleep(long millis) throws InterruptedException { long startTime = System.nanoTime(); Thread.sleep(millis); long sleepTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); if (sleepTimeMs < 0) { sleepTimeMs = 0; } return sleepTimeMs; }
Source:
<code>public static Collection<Object[]> data() throws Exception { return Arrays.asList(new Object[][] { { getDetectorRequest(), "<?xml version=\"1.0\"?>\n" + "<detector-request location=\"MINION\" serviceName=\"ICMP\" address=\"localhost\">\n"+ <START> "<attributes>port=8980</attributes> \n"+ <END> "<attributes>timeout=5000</attributes> \n" + "<attributes>retries=10</attributes> \n" + "</detector-request>" } }); }</code><technical_language>encode attributes key pairs instead of concatenated strings i.e. <attribute name="port">8980</attribute></technical_language>

Target:
public static Collection<Object[]> data() throws Exception { return Arrays.asList(new Object[][] { { getDetectorRequest(), "<?xml version=\"1.0\"?>\n" + "<detector-request location=\"MINION\" serviceName=\"ICMP\" address=\"localhost\">\n"+ "<attributes><entry> <key>port</key> <value>8980</value> </entry> </attributes> \n" + "</detector-request>" } }); }