auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private CertificateInfo createCertificateInfo(X509Certificate cert) throws GeneralSecurityException { MessageDigest sha1 = MessageDigest.getInstance("SHA1"); sha1.update(cert.getEncoded()); boolean selfSigned = false; try { cert.verify(cert.getPublicKey()); selfSigned = true; } catch (GeneralSecurityException e) { } StringBuilder sb = new StringBuilder(); if (selfSigned) { sb.append("Self signed certificate, "); } sb.append("subject name: "); sb.append(cert.getSubjectX500Principal()); if (!selfSigned) { sb.append(", issued by: "); sb.append(cert.getIssuerX500Principal()); } sb.append(". SHA1 hash: "); sb.append(Hex.encodeHexString(sha1.digest())); sb.append("."); return new CertificateInfo(new Base64(0).encodeToString(cert.getEncoded()), <START> cert.getSubjectX500Principal().toString(), "desc"); <END> }</code><technical_language>"desc" -> sb.toString()</technical_language>

Target:
private CertificateInfo createCertificateInfo(X509Certificate cert) throws GeneralSecurityException { MessageDigest sha1 = MessageDigest.getInstance("SHA1"); sha1.update(cert.getEncoded()); boolean selfSigned = false; try { cert.verify(cert.getPublicKey()); selfSigned = true; } catch (GeneralSecurityException e) { } StringBuilder sb = new StringBuilder(); if (selfSigned) { sb.append("Self signed certificate, "); } sb.append("subject name: "); sb.append(cert.getSubjectX500Principal()); if (!selfSigned) { sb.append(", issued by: "); sb.append(cert.getIssuerX500Principal()); } sb.append(". SHA1 hash: "); sb.append(Hex.encodeHexString(sha1.digest())); sb.append("."); return new CertificateInfo(new Base64(0).encodeToString(cert.getEncoded()), cert.getSubjectX500Principal().toString(), sb.toString()); }
Source:
<code>public void testBooleanAliasesInvalidValues() { column.setFactField(FIELD_NAME); column.setFieldType(DataType.TYPE_BOOLEAN); column.setValueList("yes=Yes, no=No"); <START> assertEquals(0, utilities.getValueList(column).length); <END> }</code><technical_language>rewritten Assertions.assertThat(utilities.getValueList(column)).isEmpty()</technical_language>

Target:
public void testBooleanAliasesInvalidValues() { column.setFactField(FIELD_NAME); column.setFieldType(DataType.TYPE_BOOLEAN); column.setValueList("yes=Yes, no=No"); Assertions.assertThat(utilities.getValueList(column)).isEmpty(); }
Source:
<code>private boolean usesUnwrapping(AnnotationMirror annotationMirror, TypeMirror typeMirror) { if ( constraintHelper.isSupportedForUnwrappingByDefault( getQualifiedName( typeMirror ) ) ) { <START> return true; <END> } return annotationApiHelper.getAnnotationArrayValue( annotationMirror, "payload" ).stream() .map( AnnotationValue::getValue ) .map( type -> (TypeMirror) type ) .map( typeUtils::asElement ) .map( elem -> ( (TypeElement) elem ).getQualifiedName() ) .filter( name -> name.toString().equals( "javax.validation.valueextraction.Unwrapping.Unwrap" ) ) .findAny().isPresent(); }</code><technical_language>account case unwrapped default Skip payload. In this case, unwrapping</technical_language>

Target:
private boolean usesUnwrapping(AnnotationMirror annotationMirror, TypeMirror typeMirror) { UnwrapMode mode = annotationApiHelper.determineUnwrapMode( annotationMirror ); if ( UnwrapMode.SKIP.equals( mode ) ) { return false; } if ( constraintHelper.isSupportedForUnwrappingByDefault( getQualifiedName( typeMirror ) ) ) { return true; } return UnwrapMode.UNWRAP.equals( mode ); }
Source:
<code><START> public String getSubtitle() { <END> SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()); return dateFormat.format(date); }</code><technical_language>this change here</technical_language>

Target:
public String getSubtitle() { SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATE_FORMAT, Locale.getDefault()); return dateFormat.format(date); }
Source:
<code>private ICompletionProposal[] getAttributeValueProposals(String taskName, String attributeName, String prefix) { List<ICompletionProposal> proposals = new ArrayList<>(); IElement taskElement = getDtd().getElement(taskName); if (taskElement != null) { IAttribute attribute = taskElement.getAttributes().get(attributeName); if (attribute != null) { String[] items = attribute.getEnum(); if (items != null) { String item; for (String item2 : items) { <START> item = item2; <END> if (prefix.length() == 0 || item.toLowerCase().startsWith(prefix)) { proposals.add(new AntCompletionProposal(item, cursorPosition - prefix.length(), prefix.length(), item.length(), null, item, null, AntCompletionProposal.TASK_PROPOSAL)); } } } } } else { AntTypeDefinition taskClass = getTaskClass(taskName); if (taskClass != null) { IntrospectionHelper helper = getIntrospectionHelper(taskClass); if (helper != null) { addAttributeValueProposals(helper, attributeName, prefix, proposals); } } else { AntTypeDefinition nestedType = getNestedType(); if (nestedType != null) { IntrospectionHelper helper = getIntrospectionHelper(nestedType); if (helper != null) { addAttributeValueProposals(helper, attributeName, prefix, proposals); } } } } return proposals.toArray(new ICompletionProposal[proposals.size()]); }</code><technical_language>loop var; declaration of 'item' neccessary loop</technical_language>

Target:
private ICompletionProposal[] getAttributeValueProposals(String taskName, String attributeName, String prefix) { List<ICompletionProposal> proposals = new ArrayList<>(); IElement taskElement = getDtd().getElement(taskName); if (taskElement != null) { IAttribute attribute = taskElement.getAttributes().get(attributeName); if (attribute != null) { String[] items = attribute.getEnum(); if (items != null) { for (String item : items) { if (prefix.length() == 0 || item.toLowerCase().startsWith(prefix)) { proposals.add(new AntCompletionProposal(item, cursorPosition - prefix.length(), prefix.length(), item.length(), null, item, null, AntCompletionProposal.TASK_PROPOSAL)); } } } } } else { AntTypeDefinition taskClass = getTaskClass(taskName); if (taskClass != null) { IntrospectionHelper helper = getIntrospectionHelper(taskClass); if (helper != null) { addAttributeValueProposals(helper, attributeName, prefix, proposals); } } else { AntTypeDefinition nestedType = getNestedType(); if (nestedType != null) { IntrospectionHelper helper = getIntrospectionHelper(nestedType); if (helper != null) { addAttributeValueProposals(helper, attributeName, prefix, proposals); } } } } return proposals.toArray(new ICompletionProposal[proposals.size()]); }
Source:
<code>private void checkIfFilesAreTheSame(List<String> generatedTestTables) { generatedTestTables.forEach(tableName -> { String generatedFilePath = String.format("com/palantir/atlasdb/table/description/generated/%s.java", tableName); File expectedFile = new File(EXPECTED_FILES_FOLDER_PATH, generatedFilePath); File actualFile = new File(testFolder.getRoot(), generatedFilePath); assertThat(expectedFile.length()).isEqualTo(actualFile.length()); try (Stream<String> expectedFileStream = java.nio.file.Files .lines(Paths.get(EXPECTED_FILES_FOLDER_PATH, generatedFilePath)); Stream<String> actualFileStream = java.nio.file.Files <START> .lines(Paths.get(testFolder.getRoot().getPath(), generatedFilePath)); <END> Stream<Boolean> zipped = Streams.zip( expectedFileStream, actualFileStream, (first, second) -> { if (first.equals(second)) return true; return first.contains("__CLASS_HASH") && second.contains("__CLASS_HASH"); })) { assertThat(zipped .anyMatch(elem -> !elem)) .isFalse(); } catch (IOException e) { Assertions.fail("Exception on stream creation", e); } }); }</code><technical_language>a bit of duplication paths in Files above. I call File.toPath() files created lines 217/218</technical_language>

Target:
private void checkIfFilesAreTheSame(List<String> generatedTestTables) { generatedTestTables.forEach(tableName -> { String generatedFilePath = String.format("com/palantir/atlasdb/table/description/generated/%s.java", tableName); File expectedFile = new File(EXPECTED_FILES_FOLDER_PATH, generatedFilePath); File actualFile = new File(testFolder.getRoot(), generatedFilePath); assertThat(expectedFile.length()).isEqualTo(actualFile.length()); try (Stream<String> expectedFileStream = java.nio.file.Files.lines(expectedFile.toPath()); Stream<String> actualFileStream = java.nio.file.Files.lines(actualFile.toPath()); Stream<Boolean> zipped = correspondingLinesMatchOrAreHashes(expectedFileStream, actualFileStream)) { assertThat(zipped).allMatch(elem -> elem); } catch (IOException e) { Assertions.fail("Exception on stream creation", e); } }); }
Source:
<code>public void testLegoEv3MotorMove() { <START> <END> checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(brickPosition, R.string.ev3_motor_move); enterValueInFormulaTextFieldOnBrickAtPosition(newValue, R.id.ev3_motor_move_speed_edit_text, brickPosition); }</code><technical_language>please remove newline</technical_language>

Target:
public void testLegoEv3MotorMove() { final int testMoveSpeedValue = 40; checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(brickPosition, R.string.ev3_motor_move); enterValueInFormulaTextFieldOnBrickAtPosition(testMoveSpeedValue, R.id.ev3_motor_move_speed_edit_text, brickPosition); }
Source:
<code>public static ElixirCompilerError create(String rootPath, String elixircMessage){ Matcher matcher = COMPILER_MESSAGE_PATTERN.matcher(StringUtil.trimTrailing(elixircMessage)); if(!matcher.matches()) return null; String relativeFilePath = FileUtil.toSystemIndependentName(matcher.group(1)); String line = matcher.group(2); String warning = matcher.group(3); String details = matcher.group(4); String path = StringUtil.isEmpty(rootPath) ? relativeFilePath : new File(FileUtil.toSystemIndependentName(rootPath), relativeFilePath).getPath(); <START> int lineNumber = StringUtil.parseInt(line, -1); <END> CompilerMessageCategory category = warning != null ? CompilerMessageCategory.WARNING : CompilerMessageCategory.ERROR; assert path != null; return new ElixirCompilerError(details, VfsUtilCore.pathToUrl(path), lineNumber, category); }</code><technical_language>[x] VfsUtilCore.pathToUrl -1 if line number is unknown? If case, prefer a named constant a magic number, UNKNOWN_LINE_NUMBER = -1 StringUtil.parseInt(line, UNKNOWN_LINE_NUMBER</technical_language>

Target:
public static ElixirCompilerError create(String rootPath, String elixircMessage){ Matcher matcher = COMPILER_MESSAGE_PATTERN.matcher(StringUtil.trimTrailing(elixircMessage)); if(!matcher.matches()) return null; String relativeFilePath = FileUtil.toSystemIndependentName(matcher.group(1)); String line = matcher.group(2); String warning = matcher.group(3); String details = matcher.group(4); String path = StringUtil.isEmpty(rootPath) ? relativeFilePath : new File(FileUtil.toSystemIndependentName(rootPath), relativeFilePath).getPath(); int lineNumber = StringUtil.parseInt(line, UNKNOWN_LINE_NUMBER); CompilerMessageCategory category = warning != null ? CompilerMessageCategory.WARNING : CompilerMessageCategory.ERROR; assert path != null; return new ElixirCompilerError(details, VfsUtilCore.pathToUrl(path), lineNumber, category); }
Source:
<code>private static MultiPath create(final MultiPath path, final double w, final double h) { LienzoPaths.rectangle(path, w, h, 0.0); return path <START> .setFillColor("#F9FAD2") <END> .setStrokeColor(ColorName.BLACK); }</code><technical_language>This color is close Light Goldenrod Yellow, fafad2 instead of string literal</technical_language>

Target:
private static MultiPath create(final MultiPath path, final double w, final double h) { LienzoPaths.rectangle(path, w, h, 0.0); return path .setFillColor(ColorName.LIGHTGOLDENRODYELLOW) .setStrokeColor(ColorName.BLACK); }
Source:
<code>private String getPreviousVcsRevision(ArtifactoryBuildInfoClientBuilder clientBuilder, String buildName) throws IOException { <START> ArtifactoryBuildInfoClient client = clientBuilder.build(); <END> Build previousBuildInfo = client.getBuildInfo(buildName, LATEST); if (previousBuildInfo == null) { return ""; } if (StringUtils.isNotEmpty(previousBuildInfo.getVcsRevision())) { return previousBuildInfo.getVcsRevision(); } List<Vcs> vcsList = previousBuildInfo.getVcs(); if (vcsList != null && vcsList.size() > 0) { for (Vcs curVcs : previousBuildInfo.getVcs()) { if (StringUtils.isNotEmpty(curVcs.getRevision())) { return curVcs.getRevision(); } } } return ""; }</code><technical_language>Please close client: suggestion try (ArtifactoryBuildInfoClient client = clientBuilder.build()) {</technical_language>

Target:
private String getPreviousVcsRevision(ArtifactoryBuildInfoClientBuilder clientBuilder, String buildName) throws IOException { try (ArtifactoryBuildInfoClient client = clientBuilder.build()) { Build previousBuildInfo = client.getBuildInfo(buildName, LATEST); if (previousBuildInfo == null) { return ""; } if (StringUtils.isNotEmpty(previousBuildInfo.getVcsRevision())) { return previousBuildInfo.getVcsRevision(); } List<Vcs> vcsList = previousBuildInfo.getVcs(); if (vcsList != null && vcsList.size() > 0) { for (Vcs curVcs : previousBuildInfo.getVcs()) { if (StringUtils.isNotEmpty(curVcs.getRevision())) { return curVcs.getRevision(); } } } return ""; } }
Source:
<code>public LinkedList<FirmwareInfo> getFirmwareDeviceList(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("firmware_version") final Long firmwareVersion) { if(firmwareVersion == null) { LOGGER.error("Missing firmwareVersion parameter"); throw new WebApplicationException(Response.Status.BAD_REQUEST); } final Jedis jedis = jedisPool.getResource(); final String fwVersion = firmwareVersion.toString(); LinkedList<FirmwareInfo> deviceInfo = new LinkedList<>(); try { final Set<Tuple> allFWDevices = jedis.zrevrangeWithScores(fwVersion, 0, -1); <START> for(Tuple device: allFWDevices){ <END> deviceInfo.add(new FirmwareInfo(fwVersion, device.getElement(), (long)device.getScore())); } } catch (Exception e) { LOGGER.error("Failed retrieving firmware device list.", e.getMessage()); } finally { jedisPool.returnResource(jedis); } return deviceInfo; }</code><technical_language>final</technical_language>

Target:
public List<FirmwareInfo> getFirmwareDeviceList(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("firmware_version") final Long firmwareVersion) { if(firmwareVersion == null) { LOGGER.error("Missing firmwareVersion parameter"); throw new WebApplicationException(Response.Status.BAD_REQUEST); } final Jedis jedis = jedisPool.getResource(); final String fwVersion = firmwareVersion.toString(); List<FirmwareInfo> deviceInfo = new ArrayList<>(); try { final Set<Tuple> allFWDevices = jedis.zrevrangeWithScores(fwVersion, 0, -1); for(final Tuple device: allFWDevices){ deviceInfo.add(new FirmwareInfo(fwVersion, device.getElement(), (long)device.getScore())); } } catch (Exception e) { LOGGER.error("Failed retrieving firmware device list.", e.getMessage()); } finally { jedisPool.returnResource(jedis); } return deviceInfo; }
Source:
<code>public boolean handleRequest(MessageContext messageContext) { X509Certificate certificateFromMessageContext = null; org.apache.axis2.context.MessageContext axis2MsgContext = ((Axis2MessageContext) messageContext).getAxis2MessageContext(); Map headers = (Map) (axis2MsgContext) .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); Object sslCertObject = axis2MsgContext.getProperty(NhttpConstants.SSL_CLIENT_AUTH_CERT_X509); if (sslCertObject != null) { X509Certificate[] x509Certificates = (X509Certificate[]) sslCertObject; if (x509Certificates.length > 0) { certificateFromMessageContext = x509Certificates[0]; } } if (certificateFromMessageContext != null) { if (!headers.containsKey(Utils.getClientCertificateHeader())) { try { byte[] base64Encoded = Base64.encodeBase64(certificateFromMessageContext.getEncoded()); String base64EncodedString = <START> APIMgtGatewayConstants.BEGIN_CERTIFICATE_STRING.concat(new String(base64Encoded)).concat( <END> "\n").concat(APIMgtGatewayConstants.END_CERTIFICATE_STRING); base64EncodedString = Base64.encodeBase64URLSafeString(base64EncodedString.getBytes()); headers.put(Utils.getClientCertificateHeader(), base64EncodedString); } catch (javax.security.cert.CertificateEncodingException e) { log.error("Error while encoding certificate", e); } } } return true; }</code><technical_language>need "\n" BEGIN_CERTIFICATE_STRING</technical_language>

Target:
public boolean handleRequest(MessageContext messageContext) { org.apache.axis2.context.MessageContext axis2MsgContext = ((Axis2MessageContext) messageContext).getAxis2MessageContext(); Map headers = (Map) axis2MsgContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); try { X509Certificate clientCertificate = Utils.getClientCertificate(axis2MsgContext); headers.remove(Utils.getClientCertificateHeader()); if (clientCertificate != null) { byte[] encoded = Base64.encodeBase64(clientCertificate.getEncoded()); String base64EncodedString = APIMgtGatewayConstants.BEGIN_CERTIFICATE_STRING .concat(new String(encoded)).concat("\n") .concat(APIMgtGatewayConstants.END_CERTIFICATE_STRING); base64EncodedString = Base64.encodeBase64URLSafeString(base64EncodedString.getBytes()); headers.put(Utils.getClientCertificateHeader(), base64EncodedString); } } catch (APIManagementException | CertificateEncodingException e) { log.error("Error while converting client certificate", e); } return true; }
Source:
<code><START> public void closeWithJS() { <END> new JavascriptActions(driver).execute( "arguments[0].click();", driver.findElement(closeButtonSelector) ); }</code><technical_language>explain do need function</technical_language>

Target:
public void closeWithJS() { clickByJS(closeButtonSelector); }
Source:
<code>public void reportAction(Player reporter, Player reported, String report) { for (Player player : server.getOnlinePlayers()) { if (plugin.al.isAdmin(player)) { playerMsg(player, ChatColor.RED + "[REPORTS] " + ChatColor.GOLD + reporter.getName() + " has reported " + reported.getName() + " for " + report); } } <START> public void adminHelp(Player sender, String message) { <END> for (Player player : server.getOnlinePlayers()) { if (plugin.al.isAdmin(player)) { playerMsg(player, ChatColor.RED + "[ADMINHELP] " + ChatColor.GOLD + sender.getName() + ": " + message); } } } }</code><technical_language>Formatting</technical_language>

Target:
public void reportAction(Player reporter, Player reported, String report) { for (Player player : server.getOnlinePlayers()) { if (plugin.al.isAdmin(player)) { playerMsg(player, ChatColor.RED + "[REPORTS] " + ChatColor.GOLD + reporter.getName() + " has reported " + reported.getName() + " for " + report); } } }
Source:
<code>void checkTier(Configured configuration, PluginExceptionConditionAccumulator accumulator, LocalizationContext localizationContext) { GoogleCredentials credentials = provider.getCredentials(); SQLAdmin sqlAdmin = credentials.getSQLAdmin(); String projectId = credentials.getProjectId(); String tierName = configuration.getConfigurationValue(TIER, localizationContext); <START> try { <END> List<Tier> tierList = sqlAdmin.tiers().list(projectId).execute().getItems(); if (tierList != null) { for (Tier tier : tierList) { if (tier.getTier().equals(tierName)) { return; } } } addError(accumulator, TIER, localizationContext, null, INVALID_TIER_MSG, tierName); } catch (IOException e) { throw new TransientProviderException(e); } }</code><technical_language>Add logging for consistency other validation methods</technical_language>

Target:
void checkTier(Configured configuration, PluginExceptionConditionAccumulator accumulator, LocalizationContext localizationContext) { String tierName = configuration.getConfigurationValue(TIER, localizationContext); LOG.info(">> Querying tier'{}'", tierName); GoogleCredentials credentials = provider.getCredentials(); SQLAdmin sqlAdmin = credentials.getSQLAdmin(); String projectId = credentials.getProjectId(); try { List<Tier> tierList = sqlAdmin.tiers().list(projectId).execute().getItems(); if (tierList != null) { for (Tier tier : tierList) { if (tier.getTier().equals(tierName)) { return; } } } addError(accumulator, TIER, localizationContext, null, INVALID_TIER_MSG, tierName); } catch (IOException e) { throw new TransientProviderException(e); } }
Source:
<code>public void run() { state = State.RUNNING; try { <START> applicationProcess.pauseApplier( CoreStateDownloaderService.OPERATION_NAME ); <END> while ( true ) { if ( Thread.interrupted() ) { break; } try { downloader.downloadSnapshot( leaderLocator.getLeader() ); applicationProcess.resumeApplier( CoreStateDownloaderService.OPERATION_NAME ); break; } catch ( StoreCopyFailedException e ) { log.error( "Failed to download snapshot. Retrying in ms.", timeout.getMillis(), e ); } catch ( NoLeaderFoundException e ) { log.warn( "No leader found. Retrying in ms.", timeout.getMillis() ); } LockSupport.parkNanos( TimeUnit.MILLISECONDS.toNanos( timeout.getMillis() ) ); timeout.increment(); } } finally { state = State.COMPLETED; } }</code><technical_language>This work correctly subsequent attempts failure pause times, resume successful attempt. pause/resume functionality is reference counting left a reference count > 0. need object a lifetime of attempts pause resume, each</technical_language>

Target:
public void run() { if ( !moveToRunningState() ) { return; } try { applicationProcess.pauseApplier( OPERATION_NAME ); while ( keepRunning ) { try { downloader.downloadSnapshot( leaderLocator.getLeader() ); break; } catch ( StoreCopyFailedException e ) { log.error( "Failed to download snapshot. Retrying in ms.", timeout.getMillis(), e ); } catch ( NoLeaderFoundException e ) { log.warn( "No leader found. Retrying in ms.", timeout.getMillis() ); } Thread.sleep( timeout.getMillis() ); timeout.increment(); } } catch ( InterruptedException e ) { log.error( "Persistent snapshot downloader was interrupted" ); } finally { applicationProcess.resumeApplier( OPERATION_NAME ); state = State.COMPLETED; } }
Source:
<code>protected void setDefaultLocale(Locale locale) throws Exception { assertThat(locale, is(notNullValue())); ConfigurationAdmin configAdmin = (ConfigurationAdmin) getService( Class.forName("org.osgi.service.cm.ConfigurationAdmin")); assertThat(configAdmin, is(notNullValue())); LocaleProvider localeProvider = (LocaleProvider) getService( Class.forName("org.eclipse.smarthome.core.i18n.LocaleProvider")); assertThat(localeProvider, is(notNullValue())); Configuration config = configAdmin.getConfiguration("org.eclipse.smarthome.core.i18nprovider", null); assertThat(config, is(notNullValue())); Dictionary<String, Object> properties = config.getProperties(); if (properties == null) { properties = new Hashtable<String, Object>(); } properties.put("language", locale.getLanguage()); properties.put("script", locale.getScript()); properties.put("region", locale.getCountry()); properties.put("variant", locale.getVariant()); config.update(properties); waitForAssert(new Closure<Object>(null) { <START> private static final long serialVersionUID = -5083904877474902686L; <END> public Object doCall() { assertThat(localeProvider.getLocale(), is(locale)); return null; } }); }</code><technical_language>I fix warnings added a @SuppressWarnings("serial"). Works both</technical_language>

Target:
protected void setDefaultLocale(Locale locale) throws Exception { assertThat(locale, is(notNullValue())); ConfigurationAdmin configAdmin = (ConfigurationAdmin) getService( Class.forName("org.osgi.service.cm.ConfigurationAdmin")); assertThat(configAdmin, is(notNullValue())); LocaleProvider localeProvider = (LocaleProvider) getService( Class.forName("org.eclipse.smarthome.core.i18n.LocaleProvider")); assertThat(localeProvider, is(notNullValue())); Configuration config = configAdmin.getConfiguration("org.eclipse.smarthome.core.i18nprovider", null); assertThat(config, is(notNullValue())); Dictionary<String, Object> properties = config.getProperties(); if (properties == null) { properties = new Hashtable<>(); } properties.put("language", locale.getLanguage()); properties.put("script", locale.getScript()); properties.put("region", locale.getCountry()); properties.put("variant", locale.getVariant()); config.update(properties); waitForAssert(new Closure<Object>(null) { private static final long serialVersionUID = -5083904877474902686L; public Object doCall() { assertThat(localeProvider.getLocale(), is(locale)); return null; } }); }
Source:
<code>public void encode(OutputStream stream, Map<String, String> headers) throws IOException { <START> if (headers.isEmpty()) { <END> return; } writeInt(stream, headers.size()); for (Entry<String, String> header : headers.entrySet()) { byte[] nameBytes = header.getKey().getBytes(UTF_8); byte[] valueBytes = header.getValue().getBytes(UTF_8); writeInt(stream, nameBytes.length); writeInt(stream, valueBytes.length); for (byte nameByte : nameBytes) { stream.write(nameByte); } for (byte valueByte : valueBytes) { stream.write(valueByte); } } }</code><technical_language>Im in doubt do need conditions: [32](<LINK_2>: if (headers.isEmpty()) { ... } [52](<LINK_0> if (stream.available() < 1) { ... } If headers empty u write [32](<LINK_2> size 0. [55](<LINK_1> u return hashmap size 0</technical_language>

Target:
public void encode(OutputStream stream, Map<String, String> headers) throws IOException { if (headers.isEmpty()) { return; } writeInt(stream, headers.size()); for (Entry<String, String> header : headers.entrySet()) { byte[] nameBytes = header.getKey().getBytes(UTF_8); writeInt(stream, nameBytes.length); stream.write(nameBytes); byte[] valueBytes = header.getValue().getBytes(UTF_8); writeInt(stream, valueBytes.length); stream.write(valueBytes); } }
Source:
<code>public static void toJSON(OutputWriter outputWriter, Material material) { <START> outputWriter.add("id", material.getId()) <END> .add("name", material.getDisplayName()) .add("fingerprint", material.getFingerprint()) .add("type", material.getTypeForDisplay()) .add("description", material.getLongDescription()); }</code><technical_language>Current representation of material config is: json { "id": 1, "name": "test-repo", "fingerprint": "de08b060ebfc1fb988b6683bf21", "type": "Git", "description": "URL: <LINK_0>, Branch: master" } sense representation json { "name": "test-repo", "fingerprint": "fksdhfksdg", "type": "git", "url": "https://******@github.com/gocd/gocd" "branch": "master" }</technical_language>

Target:
public static void toJSON(OutputWriter outputWriter, Material material) { outputWriter .add("name", material.getDisplayName()) .add("fingerprint", material.getFingerprint()) .add("type", material.getTypeForDisplay()) .add("description", material.getLongDescription()); }
Source:
<code><START> private Map<String, String> getVmMapDetails(UserVm userVm) { <END> List<UserVmDetailVO> userVmDetails = _userVmDetailsDao.listDetails(userVm.getId()); Map<String, String> details = new HashMap<String, String>(); for (UserVmDetailVO detail : userVmDetails) { details.put(detail.getName(), detail.getValue()); } return details; }</code><technical_language>Is this anywhere</technical_language>

Target:
protected Map<String, String> getVmMapDetails(UserVm userVm) { List<UserVmDetailVO> userVmDetails = _userVmDetailsDao.listDetails(userVm.getId()); Map<String, String> details = new HashMap<String, String>(); for (UserVmDetailVO detail : userVmDetails) { details.put(detail.getName(), detail.getValue()); } return details; }
Source:
<code>public QueryControlResult delete(final String queryId) { final QueryControlResult queryControlResult = new QueryControlResult(); queryControlResult.setQueryId(queryId); try { planStore.delete(queryId); } catch (final IOException e) { e.printStackTrace(); queryControlResult.setIsSuccess(false); <START> queryControlResult.setMsg("Fail: cannot delete " + queryId + "'s logical plan."); <END> return queryControlResult; } if (deleteQueryFromManager(queryId)) { queryControlResult.setIsSuccess(true); queryControlResult.setMsg("Success: " + queryId + " is deleted."); } else { queryControlResult.setIsSuccess(false); queryControlResult.setMsg("Fail: There is no " + queryId); } return queryControlResult; }</code><technical_language>good create a utility class for client messages</technical_language>

Target:
public QueryControlResult delete(final String queryId) { final QueryControlResult queryControlResult = new QueryControlResult(); queryControlResult.setQueryId(queryId); try { planStore.delete(queryId); } catch (final IOException e) { e.printStackTrace(); queryControlResult.setIsSuccess(false); queryControlResult.setMsg(ResultMessage.planDeletionFail(queryId)); return queryControlResult; } if (deleteQueryFromManager(queryId)) { queryControlResult.setIsSuccess(true); queryControlResult.setMsg(ResultMessage.deleteSuccess(queryId)); } else { queryControlResult.setIsSuccess(false); queryControlResult.setMsg(ResultMessage.noQueryId(queryId)); } return queryControlResult; }
Source:
<code>private OnHeapValueHolder<V> newUpdateValueHolder(K key, V oldValue, V newValue, long now, long oldExpirationTime, StoreEventSink<K, V> eventSink) { if (newValue == null) { throw new NullPointerException(); } Duration duration = Duration.ZERO; try { duration = expiry.getExpiryForUpdate(key, oldValue, newValue); } catch (RuntimeException re) { LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); } if (Duration.ZERO.equals(duration)) { eventSink.removed(key, oldValue); return null; } long expirationTime; if (duration == null) { expirationTime = oldExpirationTime; } else { if (duration.isForever()) { expirationTime = ValueHolder.NO_EXPIRE; } else { expirationTime = safeExpireTime(now, duration); } } OnHeapValueHolder<V> holder = null; try { holder = makeValue(key, newValue, now, expirationTime, this.valueCopier); eventSink.updated(key, oldValue, newValue); } catch (LimitExceededException e) { <START> LOG.warn(e.getMessage()); <END> } return holder; }</code><technical_language>is a missing removed event here. expiry result is a duration of zero</technical_language>

Target:
private OnHeapValueHolder<V> newUpdateValueHolder(K key, V oldValue, V newValue, long now, long oldExpirationTime, StoreEventSink<K, V> eventSink) { if (newValue == null) { throw new NullPointerException(); } Duration duration = Duration.ZERO; try { duration = expiry.getExpiryForUpdate(key, oldValue, newValue); } catch (RuntimeException re) { LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); } if (Duration.ZERO.equals(duration)) { eventSink.removed(key, oldValue); return null; } long expirationTime; if (duration == null) { expirationTime = oldExpirationTime; } else { if (duration.isForever()) { expirationTime = ValueHolder.NO_EXPIRE; } else { expirationTime = safeExpireTime(now, duration); } } OnHeapValueHolder<V> holder = null; try { holder = makeValue(key, newValue, now, expirationTime, this.valueCopier); eventSink.updated(key, oldValue, newValue); } catch (LimitExceededException e) { LOG.warn(e.getMessage()); eventSink.removed(key, oldValue); } return holder; }
Source:
<code>public Object getAdapter(Class required) { if (IContentOutlinePage.class.equals(required)) { return getOutlinePage(); } else if (required == IShowInTargetList.class) { return new IShowInTargetList() { @Override @SuppressWarnings("deprecation") public String[] getShowInTargetIds() { return new String[] { IPageLayout.ID_PROJECT_EXPLORER, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV }; } }; } else if (required == IShowInSource.class) { ICElement ce= null; ce= getElementAt(getSourceViewer().getSelectedRange().x, false); if (ce instanceof ITranslationUnit) { ce = null; } final ISelection selection= ce != null ? new StructuredSelection(ce) : null; return new IShowInSource() { @Override public ShowInContext getShowInContext() { return new ShowInContext(getEditorInput(), selection); } }; } else if (ProjectionAnnotationModel.class.equals(required)) { if (fProjectionSupport != null) { Object adapter = fProjectionSupport.getAdapter(getSourceViewer(), required); if (adapter != null) return adapter; } } else if (IContextProvider.class.equals(required)) { return new CUIHelp.CUIHelpContextProvider(this); } else if (IGotoMarker.class.equals(required)) { IGotoMarker gotoMarker= new GotoMarkerAdapter(); return gotoMarker; } else if (ITemplatesPage.class.equals(required)) { if (fTemplatesPage == null) { fTemplatesPage = new CTemplatesPage(this); } return fTemplatesPage; <START> } else if (ITranslationUnitProvider.class == required) <END> return this; return super.getAdapter(required); }</code><technical_language>isAssignableFrom is correct one. fixed other two</technical_language>

Target:
public Object getAdapter(Class required) { if (IContentOutlinePage.class.equals(required)) { return getOutlinePage(); } else if (required == IShowInTargetList.class) { return new IShowInTargetList() { @Override @SuppressWarnings("deprecation") public String[] getShowInTargetIds() { return new String[] { IPageLayout.ID_PROJECT_EXPLORER, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV }; } }; } else if (required == IShowInSource.class) { ICElement ce= null; ce= getElementAt(getSourceViewer().getSelectedRange().x, false); if (ce instanceof ITranslationUnit) { ce = null; } final ISelection selection= ce != null ? new StructuredSelection(ce) : null; return new IShowInSource() { @Override public ShowInContext getShowInContext() { return new ShowInContext(getEditorInput(), selection); } }; } else if (ProjectionAnnotationModel.class.equals(required)) { if (fProjectionSupport != null) { Object adapter = fProjectionSupport.getAdapter(getSourceViewer(), required); if (adapter != null) return adapter; } } else if (IContextProvider.class.equals(required)) { return new CUIHelp.CUIHelpContextProvider(this); } else if (IGotoMarker.class.equals(required)) { IGotoMarker gotoMarker= new GotoMarkerAdapter(); return gotoMarker; } else if (ITemplatesPage.class.equals(required)) { if (fTemplatesPage == null) { fTemplatesPage = new CTemplatesPage(this); } return fTemplatesPage; } else if (ITranslationUnitHolder.class == required) return this; return super.getAdapter(required); }
Source:
<code>DatanodeCommand cacheReport() throws IOException { if (dn.getFSDataset().getCacheCapacity() == 0) { return null; } DatanodeCommand cmd = null; final long startTime = monotonicNow(); if (startTime - lastCacheReport > dnConf.cacheReportInterval) { if (LOG.isDebugEnabled()) { LOG.debug("Sending cacheReport from service actor: " + this); } lastCacheReport = startTime; String bpid = bpos.getBlockPoolId(); List<Long> blockIds = dn.getFSDataset().getCacheReport(bpid); long createTime = monotonicNow(); cmd = bpNamenode.cacheReport(bpRegistration, bpid, blockIds); long sendTime = monotonicNow(); long sendCost = sendTime - createTime; dn.getMetrics().addCacheReport(sendCost); if (LOG.isDebugEnabled()) { LOG.debug("CacheReport of " + blockIds.size() <START> + " block(s) took " + (createTime - startTime) + " msecs to generate and " <END> + sendCost + " msecs for RPC and NN processing"); } } return cmd; }</code><technical_language>cost of a subtraction is marginal. Moving monotonicNow() more significant, if is x86 RDSTC call, a barrier function blocks speculative execution complete</technical_language>

Target:
DatanodeCommand cacheReport() throws IOException { if (dn.getFSDataset().getCacheCapacity() == 0) { return null; } DatanodeCommand cmd = null; final long startTime = monotonicNow(); if (startTime - lastCacheReport > dnConf.cacheReportInterval) { if (LOG.isDebugEnabled()) { LOG.debug("Sending cacheReport from service actor: " + this); } lastCacheReport = startTime; String bpid = bpos.getBlockPoolId(); List<Long> blockIds = dn.getFSDataset().getCacheReport(bpid); long createTime = monotonicNow(); cmd = bpNamenode.cacheReport(bpRegistration, bpid, blockIds); long sendTime = monotonicNow(); long createCost = createTime - startTime; long sendCost = sendTime - createTime; dn.getMetrics().addCacheReport(sendCost); if (LOG.isDebugEnabled()) { LOG.debug("CacheReport of " + blockIds.size() + " block(s) took " + createCost + " msecs to generate and " + sendCost + " msecs for RPC and NN processing"); } } return cmd; }
Source:
<code>public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); listener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override <START> public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { if(s.equals(getString(R.string.minimize_on_exit_key))){ String newSetting = sharedPreferences.getString(s,null); if(newSetting != null){ if(newSetting.equals(getString(R.string.minimize_on_exit_popup_key))){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(getContext())){ Snackbar.make(getListView(),R.string.permission_display_over_apps,Snackbar.LENGTH_INDEFINITE) .setAction(R.string.settings, new View.OnClickListener() { @Override public void onClick(View view) { PermissionHelper.checkSystemAlertWindowPermission(getContext()); } }) .show(); } } } } } <END> }; }</code><technical_language>Suggestion: java public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { // M above, if user chooses minimise popup player exit app // display other apps permission, show a snackbar user give permission if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && s.equals(getString(R.string.minimize_on_exit_key))) { String newSetting = sharedPreferences.getString(s,null); if(newSetting != null && newSetting.equals(getString(R.string.minimize_on_exit_popup_key)) && !Settings.canDrawOverlays(getContext())) { Snackbar.make(getListView(),R.string.permission_display_over_apps,Snackbar.LENGTH_INDEFINITE) .setAction(R.string.settings, new View.OnClickListener() { @Override public void onClick(View view) { PermissionHelper.checkSystemAlertWindowPermission(getContext()); } }) .show(); } } }</technical_language>

Target:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); listener = (sharedPreferences, s) -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && s.equals(getString(R.string.minimize_on_exit_key))) { String newSetting = sharedPreferences.getString(s, null); if (newSetting != null && newSetting.equals(getString(R.string.minimize_on_exit_popup_key)) && !Settings.canDrawOverlays(getContext())) { Snackbar.make(getListView(), R.string.permission_display_over_apps, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.settings, view -> PermissionHelper.checkSystemAlertWindowPermission(getContext())) .show(); } } }; }
Source:
<code>private void assertTagExists(TableName table) throws IOException { List<Cell> values = new ArrayList<>(); for (HRegion region : UTIL.getHBaseCluster().getRegions(table)) { <START> values.clear(); <END> Scan scan = new Scan(); scan.setRaw(true); scan.readAllVersions(); scan.withStartRow(ROW1); RegionScanner scanner = region.getScanner(scan); scanner.next(values); if (!values.isEmpty()) { break; } } boolean deleteFound = false; for (Cell cell: values) { if (PrivateCellUtil.isDelete(cell.getType().getCode())) { deleteFound = true; List<Tag> tags = PrivateCellUtil.getTags(cell); Assert.assertEquals(1, tags.size()); for (Tag tag : tags) { Assert.assertEquals(TEST_TAG, Tag.getValueAsString(tag)); } } } Assert.assertTrue(deleteFound); }</code><technical_language>nit: redundant</technical_language>

Target:
private void assertTagExists(TableName table) throws IOException { List<Cell> values = new ArrayList<>(); for (HRegion region : UTIL.getHBaseCluster().getRegions(table)) { Scan scan = new Scan(); scan.setRaw(true); scan.readAllVersions(); scan.withStartRow(ROW1); RegionScanner scanner = region.getScanner(scan); scanner.next(values); if (!values.isEmpty()) { break; } } boolean deleteFound = false; for (Cell cell: values) { if (PrivateCellUtil.isDelete(cell.getType().getCode())) { deleteFound = true; List<Tag> tags = PrivateCellUtil.getTags(cell); Assert.assertEquals(1, tags.size()); for (Tag tag : tags) { Assert.assertEquals(TEST_TAG, Tag.getValueAsString(tag)); } } } Assert.assertTrue(deleteFound); }
Source:
<code>private String getLongleafScript(String outputPath) throws Exception { String scriptContent = "#!/usr/bin/env bash\necho $@ >> " + outputPath; File longleafScript = File.createTempFile("longleaf", ".sh"); FileUtils.write(longleafScript, scriptContent, "UTF-8"); longleafScript.deleteOnExit(); <START> Runtime.getRuntime().exec("chmod u+x " + longleafScript.getAbsolutePath()); <END> return longleafScript.getAbsolutePath(); }</code><technical_language>some built in java utilities for setting file permissions days: <LINK_0></technical_language>

Target:
private String getLongleafScript(String outputPath) throws Exception { String scriptContent = "#!/usr/bin/env bash\necho $@ >> " + outputPath; File longleafScript = File.createTempFile("longleaf", ".sh"); FileUtils.write(longleafScript, scriptContent, "UTF-8"); longleafScript.deleteOnExit(); Set<PosixFilePermission> ownerExecutable = PosixFilePermissions.fromString("r-x------"); Files.setPosixFilePermissions(longleafScript.toPath(), ownerExecutable); return longleafScript.getAbsolutePath(); }
Source:
<code>public URI getWorkingDirectoryURI() { <START> if (!fDirectoryStack.isEmpty()) <END> return fDirectoryStack.lastElement(); return fBaseDirectoryURI; }</code><technical_language>Please bring braces back</technical_language>

Target:
public URI getWorkingDirectoryURI() { if (!fDirectoryStack.isEmpty()) { return fDirectoryStack.lastElement(); } return fBaseDirectoryURI; }
Source:
<code>public static Person toPerson(OpenMRSPerson person, boolean includeNames) { Person converted = new Person(); converted.setUuid(person.getPersonId()); if (person.getDateOfBirth() != null) { converted.setBirthdate(person.getDateOfBirth().toDate()); } if (person.getDeathDate() != null) { converted.setDeathDate(person.getDeathDate().toDate()); } converted.setBirthdateEstimated((Boolean) ObjectUtils.defaultIfNull(person.getBirthDateEstimated(), false)); converted.setDead((Boolean) ObjectUtils.defaultIfNull(person.getDead(), false)); <START> converted.setCauseOfDeath(toConcept(person.getCauseOfDeath())); <END> converted.setGender(person.getGender()); if (includeNames) { PreferredName name = new PreferredName(); name.setGivenName(person.getFirstName()); name.setMiddleName(person.getMiddleName()); name.setFamilyName(person.getLastName()); List<PreferredName> names = new ArrayList<PreferredName>(); names.add(name); converted.setNames(names); PreferredAddress address = new PreferredAddress(); address.setAddress1(person.getAddress()); List<PreferredAddress> addresses = new ArrayList<PreferredAddress>(); addresses.add(address); converted.setAddresses(addresses); } return converted; }</code><technical_language>do remove this</technical_language>

Target:
public static Person toPerson(OpenMRSPerson person, boolean includeNames) { Person converted = new Person(); converted.setUuid(person.getPersonId()); if (person.getDateOfBirth() != null) { converted.setBirthdate(person.getDateOfBirth().toDate()); } if (person.getDeathDate() != null) { converted.setDeathDate(person.getDeathDate().toDate()); } converted.setBirthdateEstimated((Boolean) ObjectUtils.defaultIfNull(person.getBirthDateEstimated(), false)); converted.setDead((Boolean) ObjectUtils.defaultIfNull(person.getDead(), false)); if (person.getCauseOfDeath() != null) { converted.setCauseOfDeath(toConcept(person.getCauseOfDeath())); } converted.setGender(person.getGender()); if (includeNames) { PreferredName name = new PreferredName(); name.setGivenName(person.getFirstName()); name.setMiddleName(person.getMiddleName()); name.setFamilyName(person.getLastName()); List<PreferredName> names = new ArrayList<PreferredName>(); names.add(name); converted.setNames(names); PreferredAddress address = new PreferredAddress(); address.setAddress1(person.getAddress()); List<PreferredAddress> addresses = new ArrayList<PreferredAddress>(); addresses.add(address); converted.setAddresses(addresses); } return converted; }
Source:
<code><START> protected void setCallbackManager(final CallbackManager manager) { <END> if (manager == null) { return; } callbackManager.shutdown(); callbackManager = manager; }</code><technical_language>Icky. pass in ctor instead</technical_language>

Target:
protected void setCallbackManager(final CallbackManager manager) { if (manager == null) { throw new NullPointerException("setCallbackManager can not be called with a null parameter."); } else if (callbackManager != null) { throw new IllegalStateException("setCallbackManager can only be called once."); } callbackManager = manager; }
Source:
<code>@Override public final void start(GridCacheSharedContext<K, V> cctx) throws IgniteCheckedException { if (!starting.compareAndSet(false, true)) assert false : "Method start is called more than once for manager: " + this; assert cctx != null; this.cctx = cctx; log = cctx.logger(getClass()); diagnosticLog = cctx.logger(DIAGNOSTIC_LOG_CATEGORY); MetricRegistry sysreg = cctx.kernalContext().metric().registry(CACHE_METRICS); <START> lastDataVer = sysreg.longMetric("LastDataVersion", "Node start time."); <END> start0(); if (log.isDebugEnabled()) log.debug(startInfo()); }</code><technical_language>Please, add empty line</technical_language>

Target:
@Override public final void start(GridCacheSharedContext<K, V> cctx) throws IgniteCheckedException { if (!starting.compareAndSet(false, true)) assert false : "Method start is called more than once for manager: " + this; assert cctx != null; this.cctx = cctx; log = cctx.logger(getClass()); diagnosticLog = cctx.logger(DIAGNOSTIC_LOG_CATEGORY); start0(); if (log.isDebugEnabled()) log.debug(startInfo()); }
Source:
<code><START> public void setSymbolResolver(SymbolResolver symbolResolver) { <END> this.symbolResolver = symbolResolver; }</code><technical_language>return this; for chaining</technical_language>

Target:
public ParserConfiguration setSymbolResolver(SymbolResolver symbolResolver) { this.symbolResolver = symbolResolver; return this; }
Source:
<code>public synchronized void onJobFinish(final int numReleasedResources) { numAvailableResources += numReleasedResources; while (!jobWaitingQueue.isEmpty()) { final JobEntity jobEntity = jobWaitingQueue.peek(); final int numResourcesToUse = jobEntity.getNumWorkers() + jobEntity.getNumServers(); if (numAvailableResources >= numResourcesToUse) { LOG.log(Level.INFO, "Start job {0} with {1} resources. Remaining free resources: {2}", new Object[]{jobEntity.getJobId(), numAvailableResources, numAvailableResources - numResourcesToUse}); numAvailableResources -= numResourcesToUse; jobServerDriverFuture.get().executeJob(jobEntity); jobWaitingQueue.poll(); } else { <START> break; END> } } }</code><technical_language>helpful add a description, for example: break// FIFO; jobs in queue wait necessary resources</technical_language>

Target:
public synchronized void onJobFinish(final int numReleasedResources) { numAvailableResources += numReleasedResources; while (!jobWaitingQueue.isEmpty()) { final JobEntity jobEntity = jobWaitingQueue.peek(); if (tryExecute(jobEntity)) { jobWaitingQueue.poll(); } else { break; } } }
Source:
<code>public String getLinkAt(int offset) { for (int i = 0; i < linkRanges.size(); i++) { if (linkRanges.get(i).isOffsetInRange(offset)) { return hrefs.get(i); } } <START> return null; <END> }</code><technical_language>avoid null rework empty string</technical_language>

Target:
public Optional<String> getLinkAt(int offset) { for (int i = 0; i < linkRanges.size(); i++) { if (linkRanges.get(i).contains(offset)) { return Optional.of(hrefs.get(i)); } } return Optional.empty(); }