auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public User(int id, String name, String preferred_language, String country, int age, String gender, int dType, String pUnit, String a1cUnit, String weightUnit, String pRange, double minRange, double maxRange) { <END> this.id = id; this.name = name; this.preferred_language = preferred_language; this.country = country; this.age = age; this.gender = gender; this.d_type = dType; this.preferred_unit = pUnit; this.preferred_unit_a1c = a1cUnit; this.preferred_unit_weight = weightUnit; this.preferred_range = pRange; this.custom_range_max = maxRange; this.custom_range_min = minRange; }</code><technical_language>this private implement a builder</technical_language>

Target:
User(int id, String name, String preferred_language, String country, int age, String gender, int dType, String pUnit, String a1cUnit, String weightUnit, String pRange, double minRange, double maxRange) { this.id = id; this.name = name; this.preferred_language = preferred_language; this.country = country; this.age = age; this.gender = gender; this.d_type = dType; this.preferred_unit = pUnit; this.preferred_unit_a1c = a1cUnit; this.preferred_unit_weight = weightUnit; this.preferred_range = pRange; this.custom_range_max = maxRange; this.custom_range_min = minRange; }
Source:
<code>public String getAccumuloUser(){ <START> return get("sc.cloudbase.username"); <END> }</code><technical_language>strings in public constants enum anywhere</technical_language>

Target:
public String getAccumuloUser(){ return get(CLOUDBASE_USER); }
Source:
<code>public static boolean preValidate(String path) throws CTFException { String metadataPath = path + Utils.SEPARATOR + METADATA_FILENAME; File metadataFile = new File(metadataPath); if (metadataFile.exists() && metadataFile.length() > PREVALIDATION_SIZE) { try (FileChannel fc = FileChannel.open(metadataFile.toPath(), StandardOpenOption.READ)) { ByteBuffer bb = ByteBuffer.allocate(PREVALIDATION_SIZE); fc.read(bb); if (bb.getInt(0) == Utils.TSDL_MAGIC) { return true; } bb.order(ByteOrder.LITTLE_ENDIAN); if (bb.getInt(0) == Utils.TSDL_MAGIC) { return true; } <START> Charset forName = Charset.forName("ASCII"); END> byte bytes[] = new byte[PREVALIDATION_SIZE]; bb.get(bytes); String text = new String(bytes, forName); return text.startsWith("/* CTF"); } catch (IOException e) { throw new CTFException(e.getMessage(), e); } } return false; }</code><technical_language>set position 0 here</technical_language>

Target:
public static boolean preValidate(String path) throws CTFException { String metadataPath = path + Utils.SEPARATOR + METADATA_FILENAME; File metadataFile = new File(metadataPath); if (metadataFile.exists() && metadataFile.length() > PREVALIDATION_SIZE) { try (FileChannel fc = FileChannel.open(metadataFile.toPath(), StandardOpenOption.READ)) { ByteBuffer bb = ByteBuffer.allocate(PREVALIDATION_SIZE); fc.read(bb); if (bb.getInt(0) == Utils.TSDL_MAGIC) { return true; } bb.order(ByteOrder.LITTLE_ENDIAN); if (bb.getInt(0) == Utils.TSDL_MAGIC) { return true; } bb.position(0); Charset forName = Charset.forName("ASCII"); byte bytes[] = new byte[PREVALIDATION_SIZE]; bb.get(bytes); String text = new String(bytes, forName); return text.startsWith(TEXT_ONLY_METADATA_HEADER_PREFIX); } catch (IOException e) { throw new CTFException(e.getMessage(), e); } } return false; }
Source:
<code><START> protected URL getCompleteResourceUrl() throws MalformedURLException { <END> URL requestUrl = null; if (item != null) { requestUrl = getNamespacedUrl(item); } else { requestUrl = getNamespacedUrl(); } if (name != null) { requestUrl = new URL(URLUtils.join(requestUrl.toString(), name)); } else if (item != null && reloadingFromServer) { requestUrl = new URL(URLUtils.join(requestUrl.toString(), checkName(item))); } return requestUrl; }</code><technical_language>I this private</technical_language>

Target:
private URL getCompleteResourceUrl() throws MalformedURLException { URL requestUrl = null; if (item != null) { requestUrl = getNamespacedUrl(item); } else { requestUrl = getNamespacedUrl(); } if (name != null) { requestUrl = new URL(URLUtils.join(requestUrl.toString(), name)); } else if (item != null && reloadingFromServer) { requestUrl = new URL(URLUtils.join(requestUrl.toString(), checkName(item))); } return requestUrl; }
Source:
<code>public static void sendMail(String host, String port, String from, String to, String cc, String subject, String mailMessage, int mailSmtpTimeout, int mailSmtpConnectionTimeout) { Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.timeout", mailSmtpTimeout); props.put("mail.smtp.connectiontimeout", mailSmtpConnectionTimeout); Session session = Session.getDefaultInstance(props, null); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipient(Message.RecipientType.TO, new InternetAddress( to)); message.setRecipient(Message.RecipientType.CC, new InternetAddress( cc)); message.setSubject(subject); message.setSentDate(new Date()); MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setText(mailMessage); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messagePart); message.setContent(multipart); Transport.send(message); } catch (Exception e) { <START> LOG.error("Error sending query end email", e); <END> } }</code><technical_language>add query ID log statement</technical_language>

Target:
public static void sendMail(String host, String port, String from, String to, String cc, String subject, String mailMessage, int mailSmtpTimeout, int mailSmtpConnectionTimeout) { Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.timeout", mailSmtpTimeout); props.put("mail.smtp.connectiontimeout", mailSmtpConnectionTimeout); Session session = Session.getDefaultInstance(props, null); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipient(Message.RecipientType.TO, new InternetAddress( to)); if(cc != null && cc.length() > 0){ message.setRecipient(Message.RecipientType.CC, new InternetAddress( cc)); } message.setSubject(subject); message.setSentDate(new Date()); MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setText(mailMessage); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messagePart); message.setContent(multipart); Transport.send(message); } catch (Exception e) { LOG.error("Error sending query end email", e); } }
Source:
<code><START> public NormalizeTableFilterParams( <END> final List<TableName> tableNames, final String regex, final String namespace ) { this.tableNames = tableNames; this.regex = regex; this.namespace = namespace; }</code><technical_language>This constructor public a IA marker public</technical_language>

Target:
private NormalizeTableFilterParams(final List<TableName> tableNames, final String regex, final String namespace) { this.tableNames = tableNames; this.regex = regex; this.namespace = namespace; }
Source:
<code>private static void testStateSystemExplorer() { SWTWorkbenchBot bot = new SWTWorkbenchBot(); List<String> expectedAnalyses = new ArrayList<>(); expectedAnalyses.addAll(EXPECTED_ANALYSES); <START> expectedAnalyses.sort(null); <END> SWTBotUtils.openView(TmfStateSystemExplorer.ID); SWTBotView sseBot = bot.viewByTitle("State System Explorer"); sseBot.show(); SWTBotTree tree = sseBot.bot().tree(); bot.waitWhile(treeHasRows(tree, 0)); tree.getAllItems()[0].expand(); List<String> actual = sseBot.bot().tree().getAllItems()[0].getNodes(); assertTrue("State systems are not what expected : " + EXPECTED_ANALYSES + " instead " + actual, actual.containsAll(EXPECTED_ANALYSES)); sseBot.close(); SWTBotUtils.openView(TmfStateSystemExplorer.ID); sseBot = bot.viewByTitle("State System Explorer"); sseBot.show(); tree = sseBot.bot().tree(); bot.waitWhile(treeHasRows(tree, 0)); tree.getAllItems()[0].expand(); actual.clear(); actual.addAll(sseBot.bot().tree().getAllItems()[0].getNodes()); assertTrue("State systems are not what expected : " + EXPECTED_ANALYSES + " instead " + actual, actual.containsAll(EXPECTED_ANALYSES)); }</code><technical_language>Is sort necessary</technical_language>

Target:
private void testStateSystemExplorer() { SWTWorkbenchBot bot = new SWTWorkbenchBot(); List<String> expectedAnalyses = new ArrayList<>(); expectedAnalyses.addAll(EXPECTED_ANALYSES); SWTBotUtils.openView(TmfStateSystemExplorer.ID); SWTBotView sseBot = bot.viewByTitle("State System Explorer"); sseBot.show(); List<String> actual = getSSNames(sseBot); assertTrue("State systems are not what expected : " + EXPECTED_ANALYSES + " instead " + actual, actual.containsAll(EXPECTED_ANALYSES)); sseBot.close(); SWTBotUtils.openView(TmfStateSystemExplorer.ID); sseBot = bot.viewByTitle("State System Explorer"); sseBot.show(); List<String> secondOpen = getSSNames(sseBot); assertEquals("Test reopen view", actual, secondOpen); bot.closeAllEditors(); bot.waitUntil(treeHasRows(sseBot.bot().tree(), 0)); before(); secondOpen = getSSNames(sseBot); assertEquals("Test reopen trace", actual, secondOpen); sseBot.close(); }
Source:
<code>private void populateIdpList(List<IdpConfig> providers) { mProviders = new ArrayList<>(); for (IdpConfig idpConfig : providers) { switch (idpConfig.getProviderId()) { case AuthUI.GOOGLE_PROVIDER: mProviders.add(new GoogleProvider(this, idpConfig)); break; case AuthUI.FACEBOOK_PROVIDER: mProviders.add(new FacebookProvider( idpConfig, getFlowParams().themeId)); break; case AuthUI.TWITTER_PROVIDER: mProviders.add(new TwitterProvider(this)); break; case AuthUI.EMAIL_PROVIDER: mProviders.add(new EmailProvider(this, getFlowParams())); break; case AuthUI.PHONE_VERIFICATION_PROVIDER: <START> PhoneIdpConfig phoneIdpConfig = (PhoneIdpConfig) idpConfig; <END> mProviders.add(new PhoneProvider(this, getFlowParams(), phoneIdpConfig)); break; default: Log.e(TAG, "Encountered unknown provider parcel with type: " + idpConfig.getProviderId()); } } ViewGroup btnHolder = findViewById(R.id.btn_holder); for (final Provider provider : mProviders) { View loginButton = getLayoutInflater() .inflate(provider.getButtonLayout(), btnHolder, false); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (provider instanceof IdpProvider) { getDialogHolder().showLoadingDialog(R.string.fui_progress_dialog_loading); } provider.startLogin(AuthMethodPickerActivity.this); } }); if (provider instanceof IdpProvider) { ((IdpProvider) provider).setAuthenticationCallback(this); } btnHolder.addView(loginButton); } }</code><technical_language>this break older clients, breaking compatibility</technical_language>

Target:
private void populateIdpList(List<IdpConfig> providers) { mProviders = new ArrayList<>(); for (IdpConfig idpConfig : providers) { switch (idpConfig.getProviderId()) { case AuthUI.GOOGLE_PROVIDER: mProviders.add(new GoogleProvider(this, idpConfig)); break; case AuthUI.FACEBOOK_PROVIDER: mProviders.add(new FacebookProvider( idpConfig, getFlowParams().themeId)); break; case AuthUI.TWITTER_PROVIDER: mProviders.add(new TwitterProvider(this)); break; case AuthUI.EMAIL_PROVIDER: mProviders.add(new EmailProvider(this, getFlowParams())); break; case AuthUI.PHONE_VERIFICATION_PROVIDER: mProviders.add(new PhoneProvider(this, getFlowParams())); break; default: Log.e(TAG, "Encountered unknown provider parcel with type: " + idpConfig.getProviderId()); } } ViewGroup btnHolder = findViewById(R.id.btn_holder); for (final Provider provider : mProviders) { View loginButton = getLayoutInflater() .inflate(provider.getButtonLayout(), btnHolder, false); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (provider instanceof IdpProvider) { getDialogHolder().showLoadingDialog(R.string.fui_progress_dialog_loading); } provider.startLogin(AuthMethodPickerActivity.this); } }); if (provider instanceof IdpProvider) { ((IdpProvider) provider).setAuthenticationCallback(this); } btnHolder.addView(loginButton); } }
Source:
<code>public void onReloadPlugin(Plugin oldPlugin, Plugin newPlugin) { if (hasAvatarProvider(newPlugin)) { avatarSupport = true; <START> } else { if (avatarSupport <END> && hasAvatarProvider(oldPlugin)) { avatarSupport = false; } } }</code><technical_language>else if line</technical_language>

Target:
public void onReloadPlugin(Plugin oldPlugin, Plugin newPlugin) { update(); }
Source:
<code>public String getId() { if (!isNullOrEmpty(id)) { return id; } else if (!isNullOrEmpty(publisher) && !isNullOrEmpty(name) && !isNullOrEmpty(version)) { <START> return String.format("%s/%s/%s", publisher, name, version); <END> } else { return null; } }</code><technical_language>String.format is of effective ways concatenate strings together</technical_language>

Target:
public String getId() { return id; }
Source:
<code>public void setup() { commonOptions = PipelineOptionsFactory.as(HBaseImportOptions.class); String projectId = <START> checkNotNull(System.getProperty(BigtableOptionsFactory.PROJECT_ID_KEY), "Project Id"); <END> commonOptions.setBigtableProjectId(projectId); commonOptions.setBigtableClusterId( checkNotNull(System.getProperty(BigtableOptionsFactory.CLUSTER_KEY), "Cluster Id")); commonOptions.setBigtableZoneId( checkNotNull(System.getProperty(BigtableOptionsFactory.ZONE_KEY), "Zone Id")); commonOptions.setStagingLocation( checkNotNull(System.getProperty("google.dataflow.stagingLocation"), "Staging Location")); cloudTestDataFolder = checkNotNull(System.getProperty(CLOUD_TEST_DATA_FOLDER), CLOUD_TEST_DATA_FOLDER); if (!cloudTestDataFolder.endsWith(File.separator)) { cloudTestDataFolder = cloudTestDataFolder + File.separator; } }</code><technical_language>nit: "Project ID" is a error message. "Project ID is required" ? is a nit</technical_language>

Target:
public void setup() throws Exception { commonOptions = PipelineOptionsFactory.as(HBaseImportOptions.class); commonOptions.setBigtableProjectId( checkNotNull(System.getProperty(BigtableOptionsFactory.PROJECT_ID_KEY), "Required property missing: " + BigtableOptionsFactory.PROJECT_ID_KEY)); commonOptions.setBigtableClusterId( checkNotNull(System.getProperty(BigtableOptionsFactory.CLUSTER_KEY), "Required property missing: " + BigtableOptionsFactory.CLUSTER_KEY)); commonOptions.setBigtableZoneId( checkNotNull(System.getProperty(BigtableOptionsFactory.ZONE_KEY), "Required property missing: " + BigtableOptionsFactory.ZONE_KEY)); commonOptions.setStagingLocation( checkNotNull(System.getProperty(GOOGLE_DATAFLOW_STAGING_LOCATION), "Required property missing: " + GOOGLE_DATAFLOW_STAGING_LOCATION)); commonOptions.setMaxNumWorkers(1); cloudTestDataFolder = checkNotNull(System.getProperty(CLOUD_TEST_DATA_FOLDER), CLOUD_TEST_DATA_FOLDER); if (!cloudTestDataFolder.endsWith(File.separator)) { cloudTestDataFolder = cloudTestDataFolder + File.separator; } tableUtilsFactory = BigtableTableUtilsFactory.from(commonOptions); }
Source:
<code>public Object createModule(String name) throws CheckstyleException { Object instance = null; if (!name.contains(PACKAGE_SEPARATOR)) { instance = createFromExistingName(name); if (instance == null) { if (thirdPartyNameToFullModuleNames == null) { thirdPartyNameToFullModuleNames = generateThirdPartyNameToFullModuleName(moduleClassLoader); } instance = createObjectFromMap(name, thirdPartyNameToFullModuleNames); } } if (instance == null) { instance = createObject(name); } if (instance == null && useBruteForceModuleLoading) { <START> instance = createModuleByBruteForce(name); <END> } if (instance == null) { String attemptedNames = null; if (!name.contains(PACKAGE_SEPARATOR)) { final String nameCheck = name + CHECK_SUFFIX; attemptedNames = joinPackageNamesWithClassName(name, packages) + STRING_SEPARATOR + nameCheck + STRING_SEPARATOR + joinPackageNamesWithClassName(nameCheck, packages); } final LocalizedMessage exceptionMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, UNABLE_TO_INSTANTIATE_EXCEPTION_MESSAGE, new String[] {name, attemptedNames}, null, getClass(), null); throw new CheckstyleException(exceptionMessage.getMessage()); } return instance; }</code><technical_language>I read this code .... I do understand is brute force here.... is naming desing problem. searchModuleInAllPackages ... createModuleByTryInEachPackage(packages, name)</technical_language>

Target:
public Object createModule(String name) throws CheckstyleException { Object instance = null; if (!name.contains(PACKAGE_SEPARATOR)) { instance = createFromStandardCheckSet(name); if (instance == null) { if (thirdPartyNameToFullModuleNames == null) { thirdPartyNameToFullModuleNames = generateThirdPartyNameToFullModuleName(moduleClassLoader); } instance = createObjectFromMap(name, thirdPartyNameToFullModuleNames); } } if (instance == null) { instance = createObject(name); } if (instance == null && moduleLoadOption == ModuleLoadOption.TRY_IN_ALL_REGISTERED_PACKAGES) { instance = createModuleByTryInEachPackage(name); } if (instance == null) { String attemptedNames = null; if (!name.contains(PACKAGE_SEPARATOR)) { final String nameCheck = name + CHECK_SUFFIX; attemptedNames = joinPackageNamesWithClassName(name, packages) + STRING_SEPARATOR + nameCheck + STRING_SEPARATOR + joinPackageNamesWithClassName(nameCheck, packages); } final LocalizedMessage exceptionMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, UNABLE_TO_INSTANTIATE_EXCEPTION_MESSAGE, new String[] {name, attemptedNames}, null, getClass(), null); throw new CheckstyleException(exceptionMessage.getMessage()); } return instance; }
Source:
<code>public void testGetProducerConfigs() { final Map<String, Object> returnedProps = streamsConfig.getProducerConfigs(clientId); assertThat(returnedProps.get(ProducerConfig.CLIENT_ID_CONFIG), equalTo(clientId)); assertThat(returnedProps.get(ProducerConfig.LINGER_MS_CONFIG), equalTo("100")); <START> assertThat(returnedProps.get(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG), equalTo("10000")); <END> }</code><technical_language>a String a long</technical_language>

Target:
public void testGetProducerConfigs() { final Map<String, Object> returnedProps = streamsConfig.getProducerConfigs(clientId); assertThat(returnedProps.get(ProducerConfig.CLIENT_ID_CONFIG), equalTo(clientId)); assertThat(returnedProps.get(ProducerConfig.LINGER_MS_CONFIG), equalTo("100")); assertThat(returnedProps.get(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG), equalTo(10000)); }
Source:
<code>public void testCanvasCommandExecuteInsertBelow() { final DecisionRule existingRule = new DecisionRule(); final DMNGridRow existingUiRow = new DMNGridRow(); dtable.getRule().add(existingRule); uiModel.appendRow(existingUiRow); makeCommand(1); uiModel.appendColumn(uiInputClauseColumn); uiModel.appendColumn(uiOutputClauseColumn); uiModel.appendColumn(uiDescriptionColumn); final Command<GraphCommandExecutionContext, RuleViolation> graphCommand = command.newGraphCommand(canvasHandler); final Command<AbstractCanvasHandler, CanvasViolation> canvasCommand = command.newCanvasCommand(canvasHandler); graphCommand.execute(graphCommandExecutionContext); canvasCommand.execute(canvasHandler); assertEquals(2, uiModel.getRowCount()); assertEquals(existingUiRow, uiModel.getRow(0)); assertEquals(uiModelRow, <START> uiModel.getRow(1)); <END> verify(command).updateRowNumbers(); verify(command).updateParentInformation(); }</code><technical_language>check cell values of uiModel.getRow()</technical_language>

Target:
public void testCanvasCommandExecuteInsertBelow() { final DecisionRule existingRule = new DecisionRule(); final DMNGridRow existingUiRow = new DMNGridRow(); dtable.getRule().add(existingRule); uiModel.appendRow(existingUiRow); dtable.getInput().add(new InputClause()); dtable.getOutput().add(new OutputClause()); makeCommand(1); uiModel.appendColumn(uiInputClauseColumn); uiModel.appendColumn(uiOutputClauseColumn); uiModel.appendColumn(uiDescriptionColumn); final Command<GraphCommandExecutionContext, RuleViolation> graphCommand = command.newGraphCommand(canvasHandler); final Command<AbstractCanvasHandler, CanvasViolation> canvasCommand = command.newCanvasCommand(canvasHandler); graphCommand.execute(graphCommandExecutionContext); canvasCommand.execute(canvasHandler); assertEquals(2, uiModel.getRowCount()); assertEquals(existingUiRow, uiModel.getRow(0)); assertEquals(uiModelRow, uiModel.getRow(1)); assertDefaultUiRowValues(1); verify(command).updateRowNumbers(); verify(command).updateParentInformation(); }
Source:
<code>static ClientConfigFactory findDefaultConfigFactory() { return StreamSupport.stream(ServiceLoader.load(ClientConfigFactory.class).spliterator(), false) .sorted(Comparator .comparingInt(ClientConfigFactory::getPriority) .thenComparing(Comparator.comparing(f -> f.getClass().getCanonicalName()))) .findFirst() .orElseGet(() -> { <START> throw new IllegalStateException("Expecting on implementation of ClientConfigFactory discoverable via the ServiceLoader"); <END> }); }</code><technical_language>Typo: "one" (or "single")</technical_language>

Target:
static ClientConfigFactory findDefaultConfigFactory() { return StreamSupport.stream(ServiceLoader.load(ClientConfigFactory.class).spliterator(), false) .sorted(Comparator .comparingInt(ClientConfigFactory::getPriority) .thenComparing(Comparator.comparing(f -> f.getClass().getCanonicalName()))) .findFirst() .orElseGet(() -> { throw new IllegalStateException("Expecting at least one implementation of ClientConfigFactory discoverable via the ServiceLoader"); }); }
Source:
<code>public Response listContainers(@Context HttpHeaders headers, @QueryParam("groupId") String groupId, @QueryParam("artifactId") String artifactId, @QueryParam("version") String version, @QueryParam("status") String status) { ReleaseIdFilter releaseIdFilter = new ReleaseIdFilter.Builder() .groupId(groupId) .artifactId(artifactId) .version(version) .build(); KieContainerStatusFilter statusFilter; if (status == null) { statusFilter = KieContainerStatusFilter.ACCEPT_ALL; } else { statusFilter = KieContainerStatusFilter.parseFromString(status); <START> } <END> KieContainerResourceFilter containerFilter = new KieContainerResourceFilter(releaseIdFilter, statusFilter); return createCorrectVariant(server.listContainers(containerFilter), headers); }</code><technical_language>instead of this if else parseFromString return ACCEPT_ALL if argument is null empty, wdyt</technical_language>

Target:
public Response listContainers(@Context HttpHeaders headers, @QueryParam("groupId") String groupId, @QueryParam("artifactId") String artifactId, @QueryParam("version") String version, @QueryParam("status") String status) { ReleaseIdFilter releaseIdFilter = new ReleaseIdFilter.Builder() .groupId(groupId) .artifactId(artifactId) .version(version) .build(); KieContainerStatusFilter statusFilter = KieContainerStatusFilter.parseFromNullableString(status); KieContainerResourceFilter containerFilter = new KieContainerResourceFilter(releaseIdFilter, statusFilter); return createCorrectVariant(server.listContainers(containerFilter), headers); }
Source:
<code>private void doGetAttachmentForDisplay(ResourceRequest request, ResourceResponse response) throws IOException, PortletException { final String attachmentId = request.getParameter(PortalConstants.ATTACHMENT_ID); final User user = UserCacheHolder.getUserFromRequest(request); <START> final TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory()); <END> Attachment attachment = attachmentPortletUtils.getAttachmentForDisplay(user, attachmentId); if(attachment==null) { response.setProperty(ResourceResponse.HTTP_STATUS_CODE, "500"); } else { try { writeJSON(request, response, serializer.toString(attachment)); } catch (TException exception) { LOGGER.error("Cannot serialize attachment", exception); response.setProperty(ResourceResponse.HTTP_STATUS_CODE, "500"); } } }</code><technical_language>sense serializer a static field</technical_language>

Target:
private void doGetAttachmentForDisplay(ResourceRequest request, ResourceResponse response) throws IOException, PortletException { final String attachmentId = request.getParameter(PortalConstants.ATTACHMENT_ID); final User user = UserCacheHolder.getUserFromRequest(request); Attachment attachment = attachmentPortletUtils.getAttachmentForDisplay(user, attachmentId); if (attachment == null) { response.setProperty(ResourceResponse.HTTP_STATUS_CODE, "500"); } else { writeJSON(request, response, OBJECT_MAPPER.writeValueAsString(attachment)); } }
Source:
<code>private String retrieveSubjectTokenFromCredentialFile() throws IOException { IdentityPoolCredentialSource identityPoolCredentialSource = (IdentityPoolCredentialSource) credentialSource; String credentialFilePath = identityPoolCredentialSource.credentialLocation; if (!Files.exists(Paths.get(credentialFilePath), LinkOption.NOFOLLOW_LINKS)) { <START> throw new IOException("Invalid credential location. The file does not exist."); <END> } try { return new String(Files.readAllBytes(Paths.get(credentialFilePath))); } catch (IOException e) { throw new IOException( "Error when attempting to read the subject token from the credential file.", e); } }</code><technical_language>useful include non-existent path in exception message aid in debugging</technical_language>

Target:
private String retrieveSubjectTokenFromCredentialFile() throws IOException { IdentityPoolCredentialSource identityPoolCredentialSource = (IdentityPoolCredentialSource) credentialSource; String credentialFilePath = identityPoolCredentialSource.credentialLocation; if (!Files.exists(Paths.get(credentialFilePath), LinkOption.NOFOLLOW_LINKS)) { throw new IOException( String.format( "Invalid credential location. The file at %s does not exist.", credentialFilePath)); } try { return new String(Files.readAllBytes(Paths.get(credentialFilePath))); } catch (IOException e) { throw new IOException( "Error when attempting to read the subject token from the credential file.", e); } }
Source:
<code>protected long getContentLength(HttpServletRequest request) { if(useServlet31){ return request.getContentLengthLong(); } <START> String contentLengthHeader = request.getHeader(HttpHeaders.CONTENT_LENGTH); <END> if (contentLengthHeader != null) { return Long.parseLong(contentLengthHeader); } return request.getContentLength(); }</code><technical_language>add this change here? This part of original issue it</technical_language>

Target:
protected long getContentLength(HttpServletRequest request) { if(useServlet31){ return request.getContentLengthLong(); } String contentLengthHeader = request.getHeader(HttpHeaders.CONTENT_LENGTH); if (contentLengthHeader != null) { try { return Long.parseLong(contentLengthHeader); } catch (NumberFormatException e){} } return request.getContentLength(); }
Source:
<code>private synchronized Collection<Lease> getExpiredCandidateLeases() { final long now = Time.monotonicNow(); <START> return leases.values().stream() .filter(lease -> lease.expiredHardLimit(now)) .collect(Collectors.toCollection(HashSet::new)); <END> }</code><technical_language>I prefer loop in @daryn-sharp's original code. Collection<Lease> expired = new HashSet<>(); for (Lease lease : leases) { if (lease.expiredHardLimit(now)) { expired.add(lease); } } This streams code change if want pull this branch 2. I @daryn-sharp stream()'s more expensive</technical_language>

Target:
private synchronized Collection<Lease> getExpiredCandidateLeases() { final long now = Time.monotonicNow(); Collection<Lease> expired = new HashSet<>(); for (Lease lease : leases.values()) { if (lease.expiredHardLimit(now)) { expired.add(lease); } } return expired; }
Source:
<code><START> public BookKeeper.DigestType getDigestType() { <END> if (digestType.equals(LedgerMetadataFormat.DigestType.HMAC)) { return BookKeeper.DigestType.MAC; } else { return BookKeeper.DigestType.CRC32; } }</code><technical_language>is this public</technical_language>

Target:
BookKeeper.DigestType getDigestType() { if (digestType.equals(LedgerMetadataFormat.DigestType.HMAC)) { return BookKeeper.DigestType.MAC; } else { return BookKeeper.DigestType.CRC32; } }
Source:
<code>public <T> Set<T> getStores(Class<T> storeClass) { long stamp = acquireReadLock(); try { return stores.keySet().stream() .map(this::unwrapStore) .map(this::unwrapOldSPI) <START> .filter(store -> storeClass.isInstance(store)) <END> .map(store -> (T) store) .collect(Collectors.toCollection(HashSet::new)); } finally { releaseReadLock(stamp); } }</code><technical_language>storeClass::isInstance</technical_language>

Target:
public <T> Set<T> getStores(Class<T> storeClass) { long stamp = acquireReadLock(); try { return stores.stream() .map(StoreStatus::store) .map(this::unwrapStore) .map(this::unwrapOldSPI) .filter(storeClass::isInstance) .map(storeClass::cast) .collect(Collectors.toCollection(HashSet::new)); } finally { releaseReadLock(stamp); } }
Source:
<code>public static String formatPhoneNumber(String phoneValue) { <START> if (phoneValue == null || "".equals(phoneValue)) { <END> phoneValue = ""; } if(phoneValue.isEmpty() || phoneValue.matches(FORMATTED_PHONENUMBER_MASK)){ return phoneValue; } String formattedNumber="("+phoneValue.substring(0,3)+") "+phoneValue.substring(3,6)+"-"+phoneValue.substring(6,phoneValue.length()); return formattedNumber; }</code><technical_language>@idelcano Do need this "".equals(phoneValue)? I do understand why..</technical_language>

Target:
public static String formatPhoneNumber(String phoneValue) { if (phoneValue == null) { phoneValue = ""; } if(phoneValue.isEmpty() || phoneValue.matches(FORMATTED_PHONENUMBER_MASK)){ return phoneValue; } String formattedNumber; if(phoneValue.length()==11) formattedNumber="("+phoneValue.substring(0,3)+") "+phoneValue.substring(3,7)+"-"+phoneValue.substring(6,phoneValue.length()); else formattedNumber="("+phoneValue.substring(0,3)+") "+phoneValue.substring(3,6)+"-"+phoneValue.substring(6,phoneValue.length()); return formattedNumber; }
Source:
<code>public boolean execute() { if (navList != view) { return false; } <START> boolean attachedNow = panel.isAttached(); if (!attached && attachedNow) { attached = true; } else if (attached && !attachedNow) { return false; } <END> start = System.currentTimeMillis(); if (computeConnected()) { return true; } int select = 0; while (row < changes.length()) { ChangeAndCommit info = changes.get(row); String commit = info.commit().commit(); rows.add(new RowSafeHtml( info, connected != null && !connected.contains(commit))); if (revision.equals(commit)) { select = row; } if (longRunning(++row)) { return true; } } navList.rows = rows; navList.movePointerTo(select); return false; }</code><technical_language>This simplified !isAttached() widget is attached DOM</technical_language>

Target:
public boolean execute() { if (navList != view || !panel.isAttached()) { return false; } start = System.currentTimeMillis(); if (connected != null && computeConnected()) { return true; } int select = 0; while (row < changes.length()) { ChangeAndCommit info = changes.get(row); String commit = info.commit().commit(); rows.add(new RowSafeHtml( info, connected != null && !connected.contains(commit))); if (revision.equals(commit)) { select = row; } if (longRunning(++row)) { return true; } } navList.rows = rows; navList.movePointerTo(select, true); return false; }
Source:
<code>public void updated(Dictionary<String, ?> config) throws ConfigurationException { logger.trace("Binding configuration updated"); if (config == null) <START> return; <END> this.refreshInterval = getLongValue(config, "refresh", 10000); this.userCode = (String) config.get("user_code"); int timeout = getIntValue(config, "timeout", 5000); String host = (String) config.get("host"); if (StringUtils.isNotBlank(host)) { this.satelModule = new Ethm1Module(host, getIntValue(config, "port", 7094), timeout, (String) config.get("encryption_key")); } else { this.satelModule = new IntRSModule((String) config.get("port"), timeout); } this.satelModule.addEventListener(this); this.satelModule.open(); setProperlyConfigured(true); logger.trace("Binding properly configured"); }</code><technical_language>please add curly braces</technical_language>

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { logger.trace("Binding configuration updated"); if (config == null) { return; } this.refreshInterval = getLongValue(config, "refresh", 10000); this.userCode = getStringValue(config, "user_code", null); int timeout = getIntValue(config, "timeout", 5000); String host = getStringValue(config, "host", null); if (StringUtils.isNotBlank(host)) { this.satelModule = new Ethm1Module(host, getIntValue(config, "port", 7094), timeout, (String) config.get("encryption_key")); } else { this.satelModule = new IntRSModule((String) config.get("port"), timeout); } this.satelModule.addEventListener(this); this.satelModule.open(); setProperlyConfigured(true); logger.trace("Binding properly configured"); }
Source:
<code>private static boolean sendTweet(final String tweetTxt, final File fileToAttach) { final String abbreviatedTweetTxt = StringUtils.abbreviate(tweetTxt, CHARACTER_LIMIT); try { final StatusUpdate status = new StatusUpdate(abbreviatedTweetTxt); if (fileToAttach != null && fileToAttach.isFile()) { status.setMedia(fileToAttach); } final Status updatedStatus = client.updateStatus(status); logger.debug("Successfully sent Tweet '{}'", updatedStatus.getText()); return true; } catch (TwitterException e) { <START> logger.error("Failed to send Tweet '" + abbreviatedTweetTxt + "' because of: " + e.getLocalizedMessage()); <END> return false; } }</code><technical_language>This a WARN instead of ERROR. Also, need parameterized logging instead of string concatenation</technical_language>

Target:
private static boolean sendTweet(final String tweetTxt, final File fileToAttach) { String abbreviatedTweetTxt = StringUtils.abbreviate(tweetTxt, CHARACTER_LIMIT); try { StatusUpdate status = new StatusUpdate(abbreviatedTweetTxt); if (fileToAttach != null && fileToAttach.isFile()) { status.setMedia(fileToAttach); } Status updatedStatus = client.updateStatus(status); logger.debug("Successfully sent Tweet '{}'", updatedStatus.getText()); return true; } catch (TwitterException e) { logger.warn("Failed to send Tweet '{}' because of : {}", abbreviatedTweetTxt, e.getLocalizedMessage()); return false; } }
Source:
<code>public void notFoundDecodesToEmpty() throws Exception { Response response = Response.builder() .status(404) .reason("NOT FOUND") .headers(Collections.<String, Collection<String>>emptyMap()) <START> .body((byte[]) null) <END> .build(); assertThat((byte[]) new JAXBDecoder(new JAXBContextFactory.Builder().build()) .decode(response, byte[].class)).isEmpty(); }</code><technical_language>I null is default</technical_language>

Target:
public void notFoundDecodesToEmpty() throws Exception { Response response = Response.builder() .status(404) .reason("NOT FOUND") .headers(Collections.<String, Collection<String>>emptyMap()) .build(); assertThat((byte[]) new JAXBDecoder(new JAXBContextFactory.Builder().build()) .decode(response, byte[].class)).isEmpty(); }
Source:
<code>public void shouldCreateGithubLinkActionForJobWithGithubProjectProperty() throws IOException { WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); <START> p.addProperty(new GithubProjectProperty("<LINK_0>")); <END> Collection<? extends Action> actions = factory.createFor(p); assertThat(actions.size(), is(equalTo(1))); GithubLinkAction action = (GithubLinkAction) actions.iterator().next(); assertThat(action.getUrlName(), is(equalTo("<LINK_0>"))); }</code><technical_language>move string constant, duplicate</technical_language>

Target:
public void shouldCreateGithubLinkActionForJobWithGithubProjectProperty() throws IOException { final WorkflowJob job = createExampleJob(); final GithubProjectProperty property = createExampleProperty(); job.addProperty(property); final Collection<? extends Action> actions = factory.createFor(job); assertThat("factored actions list", actions.size(), is(1)); final Action action = actions.iterator().next(); assertThat("instance check", action, is(instanceOf(GithubLinkAction.class))); assertThat("url of action", action.getUrlName(), is(property.getProjectUrlStr())); }
Source:
<code>protected int getContextId() { <START> return contextId; <END> }</code><technical_language>This contextIds, allow remove contextId</technical_language>

Target:
protected int getContextId() { return contextIds.isEmpty() ? -1 : contextIds.get(contextIds.size() - 1); }
Source:
<code>public double accumulate() { <START> return result.doubleValue(); <END> }</code><technical_language>need a rounding here</technical_language>

Target:
public double accumulate() { return result.setScale(Vectors.ROUND_FACTOR, RoundingMode.CEILING).doubleValue(); }
Source:
<code>private void removeGerritTriggerInJobs() { for (Job job : getConfiguredJobs()) { if (!(job instanceof AbstractProject)) { <START> logger.info("Unable to remove Gerrit Trigger ffrom job [" + job.getName() + "]. " <END> + " This feature is only supported for AbstractProject types e.g. Freestyle Jobs."); return; } AbstractProject project = (AbstractProject)job; GerritTrigger trigger = (GerritTrigger)project.getTrigger(GerritTrigger.class); trigger.stop(); try { project.removeTrigger(trigger.getDescriptor()); } catch (IOException e) { logger.error("Error removing Gerrit trigger from job [" + job.getName() + "]. Please check job config"); } trigger = null; try { job.save(); } catch (IOException e) { logger.error("Error saving configuration of job [" + job.getName() + "] while trying to remove Gerrit server [" + name + "]. Please check job config."); } } }</code><technical_language>warning</technical_language>

Target:
private void removeGerritTriggerInJobs() { for (Job job : getConfiguredJobs()) { if (!(job instanceof AbstractProject)) { logger.warn("Unable to remove Gerrit Trigger ffrom job [" + job.getName() + "]. " + " This feature is only supported for AbstractProject types e.g. Freestyle Jobs."); return; } AbstractProject project = (AbstractProject)job; GerritTrigger trigger = (GerritTrigger)project.getTrigger(GerritTrigger.class); trigger.stop(); try { project.removeTrigger(trigger.getDescriptor()); } catch (IOException e) { logger.error("Error removing Gerrit trigger from job [" + job.getName() + "]. Please check job config"); } trigger = null; try { job.save(); } catch (IOException e) { logger.error("Error saving configuration of job [" + job.getName() + "] while trying to remove Gerrit server [" + name + "]. Please check job config."); } } }
Source:
<code>public DFUWorkunitsActionResponse deleteDropZoneFiles(String dropzoneName, List<String> fileNames, String netAddress, String path, String os) throws RemoteException, EspSoapFault { <START> EspStringArray espStringArray = new EspStringArray(); <END> fileNames.forEach(fileName -> espStringArray.addItem(fileName)); DeleteDropZoneFilesRequest request = new DeleteDropZoneFilesRequest(); request.setDropZoneName(dropzoneName); request.setNames(espStringArray); request.setNetAddress(netAddress); request.setPath(path); request.setOS(os); DFUWorkunitsActionResponse response = ((FileSprayStub)stub).deleteDropZoneFiles(request); return response; }</code><technical_language>able connect front: verifyStub(); // Throws exception if stub failed</technical_language>

Target:
public DFUWorkunitsActionResponse deleteDropZoneFiles(String dropzoneName, List<String> fileNames, String netAddress, String path, String os) throws Exception { verifyStub(); EspStringArray espStringArray = new EspStringArray(); fileNames.forEach(fileName -> espStringArray.addItem(fileName)); DeleteDropZoneFilesRequest request = new DeleteDropZoneFilesRequest(); request.setDropZoneName(dropzoneName); request.setNames(espStringArray); request.setNetAddress(netAddress); request.setPath(path); request.setOS(os); DFUWorkunitsActionResponse response = ((FileSprayStub)stub).deleteDropZoneFiles(request); return response; }
Source:
<code>public static void registerSaxonExtensionFunctions( CamelContext camelContext, Class<?> factoryClass, TransformerFactory factory, List<Object> saxonExtensionFunctions) throws Exception { if (saxonExtensionFunctions != null && !saxonExtensionFunctions.isEmpty()) { Method method = factoryClass.getMethod("getConfiguration"); if (method != null) { Object configuration = method.invoke(factory, null); if (configuration != null) { Class<?> extensionClass = camelContext.getClassResolver().resolveMandatoryClass( SAXON_EXTENDED_FUNCTION_DEFINITION_CLASS_NAME, XsltComponent.class.getClassLoader() ); method = configuration.getClass().getMethod("registerExtensionFunction", extensionClass); if (method != null) { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); for (Object extensionFunction : saxonExtensionFunctions) { if (extensionClass.isInstance(extensionFunction)) { <START> LOG.debug("Sazon.registerExtensionFunction {}", extensionFunction); <END> method.invoke(configuration, extensionFunction); } } } else { LOG.warn("Unable to get reference to method registerExtensionFunction on {}", configuration.getClass().getName()); } } else { LOG.warn("Unable to get Saxon configuration ({}) on {}", SAXON_CONFIGURATION_CLASS_NAME, factory.getClass().getName()); } } else { LOG.warn("Unable to get reference to method getConfiguration on {}", factoryClass.getName()); } } }</code><technical_language>is a typo</technical_language>

Target:
public static void registerSaxonExtensionFunctions( CamelContext camelContext, Class<?> factoryClass, TransformerFactory factory, List<Object> saxonExtensionFunctions) throws Exception { if (saxonExtensionFunctions != null && !saxonExtensionFunctions.isEmpty()) { Method method = factoryClass.getMethod("getConfiguration"); if (method != null) { Object configuration = method.invoke(factory, null); if (configuration != null) { Class<?> extensionClass = camelContext.getClassResolver().resolveMandatoryClass( SAXON_EXTENDED_FUNCTION_DEFINITION_CLASS_NAME, XsltComponent.class.getClassLoader() ); method = configuration.getClass().getMethod("registerExtensionFunction", extensionClass); if (method != null) { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); for (Object extensionFunction : saxonExtensionFunctions) { if (extensionClass.isInstance(extensionFunction)) { LOG.debug("Saxon.registerExtensionFunction {}", extensionFunction); method.invoke(configuration, extensionFunction); } } } else { LOG.warn("Unable to get reference to method registerExtensionFunction on {}", configuration.getClass().getName()); } } else { LOG.warn("Unable to get Saxon configuration ({}) on {}", SAXON_CONFIGURATION_CLASS_NAME, factory.getClass().getName()); } } else { LOG.warn("Unable to get reference to method getConfiguration on {}", factoryClass.getName()); } } }
Source:
<code>private static void verifySearchResults(FeedbackResponseCommentSearchResultBundle actual, FeedbackResponseCommentAttributes... expected) { assertEquals(expected.length, actual.numberOfResults); assertEquals(expected.length, actual.comments.size()); int i = 0; for (String key : actual.comments.keySet()) { for (FeedbackResponseCommentAttributes comment : actual.comments.get(key)) { assertEquals(expected[i].commentText, comment.commentText); <START> i++; <END> } } }</code><technical_language>This impose restriction order of results fixed, is other search tests</technical_language>

Target:
private static void verifySearchResults(FeedbackResponseCommentSearchResultBundle actual, FeedbackResponseCommentAttributes... expected) { assertEquals(expected.length, actual.numberOfResults); assertEquals(expected.length, actual.comments.size()); FeedbackResponseCommentAttributes.sortFeedbackResponseCommentsByCreationTime(Arrays.asList(expected)); FeedbackResponseCommentAttributes[] sortedComments = Arrays.asList(expected) .toArray(new FeedbackResponseCommentAttributes[2]); int i = 0; for (String key : actual.comments.keySet()) { for (FeedbackResponseCommentAttributes comment : actual.comments.get(key)) { assertEquals(sortedComments[i].commentText, comment.commentText); i++; } } }
Source:
<code>private ColumnDefinition(Optional<NodeLocation> location, Identifier name, String type, List<Property> properties, Optional<String> comment, boolean nullable, Optional<Literal> defaultValue) { super(location); this.name = requireNonNull(name, "name is null"); this.type = requireNonNull(type, "type is null"); this.properties = requireNonNull(properties, "properties is null"); this.comment = requireNonNull(comment, "comment is null"); this.nullable = nullable; <START> this.defaultValue = defaultValue; <END> }</code><technical_language>requireNonNull(defaultValue, "defaultValue is null")</technical_language>

Target:
private ColumnDefinition(Optional<NodeLocation> location, Identifier name, String type, List<Property> properties, Optional<String> comment, boolean nullable, Optional<Literal> defaultValue) { super(location); this.name = requireNonNull(name, "name is null"); this.type = requireNonNull(type, "type is null"); this.properties = requireNonNull(properties, "properties is null"); this.comment = requireNonNull(comment, "comment is null"); this.nullable = nullable; this.defaultValue = requireNonNull(defaultValue, "Default value is null"); }
Source:
<code>public final Collection<Session> listSessions() throws SubscriptionNotInitializedException, NakadiRuntimeException, ServiceTemporarilyUnavailableException { getLog().info("fetching sessions information"); final List<String> zkSessions; try { zkSessions = getCurator().getChildren().forPath(getSubscriptionPath("/sessions")); } catch (final KeeperException.NoNodeException e) { throw new SubscriptionNotInitializedException(getSubscriptionId()); } catch (Exception ex) { throw new NakadiRuntimeException(ex); } Map result = new HashMap(); for (int i = 0; i < 3; i++) { result = loadDataAsync(zkSessions, key -> getSubscriptionPath("/sessions/" + key), this::deserializeSession); if (result.size() == zkSessions.size()) return result.values(); } <START> if (result.size() != zkSessions.size()) { <END> final Map incompleteResult = result; throw new ServiceTemporarilyUnavailableException("Failed to get all keys " + zkSessions.stream() .filter(v -> !incompleteResult.containsKey(v)) .map(String::valueOf) .collect(Collectors.joining(", ")) + " from ZK", null); } return result.values(); }</code><technical_language>This condition is needed</technical_language>

Target:
public final Collection<Session> listSessions() throws SubscriptionNotInitializedException, NakadiRuntimeException, ServiceTemporarilyUnavailableException { getLog().info("fetching sessions information"); for (int i = 0; i < 5; i++) { try { final List<String> sessions = getCurator().getChildren().forPath(getSubscriptionPath("/sessions")); final Map <String,Session> result = loadDataAsync(sessions, key -> getSubscriptionPath("/sessions/" + key), this::deserializeSession); if (result.size() == sessions.size()) { return result.values(); } } catch (final KeeperException.NoNodeException e) { throw new SubscriptionNotInitializedException(getSubscriptionId()); } catch (Exception ex) { throw new NakadiRuntimeException(ex); } } throw new ServiceTemporarilyUnavailableException("Failed to get all keys from ZK", null); }