auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void loadBalancingTargetPath() { String name = "LoadBalancingTargetTest-loadBalancingDefaultPolicyRoundRobin"; String serverListKey = name + ".ribbon.listOfServers"; server1.enqueue(new MockResponse().setBody("success!")); server2.enqueue(new MockResponse().setBody("success!")); getConfigInstance().setProperty(serverListKey, hostAndPort(server1.url("").url()) + "," + hostAndPort( server2.url("").url())); try { LoadBalancingTarget<TestInterface> target = LoadBalancingTarget.create(TestInterface.class, "http://" + name + "/servers"); TestInterface api = Feign.builder().target(target); api.get(); api.get(); <START> assertEquals(1, server1.getRequestCount()); <END> assertEquals(1, server2.getRequestCount()); } finally { getConfigInstance().clearProperty(serverListKey); } }</code><technical_language>I do assertion path received server. ex server1.takeRequest().getPath()</technical_language>

Target:
public void loadBalancingTargetPath() throws InterruptedException { String name = "LoadBalancingTargetTest-loadBalancingDefaultPolicyRoundRobin"; String serverListKey = name + ".ribbon.listOfServers"; server1.enqueue(new MockResponse().setBody("success!")); getConfigInstance().setProperty(serverListKey, hostAndPort(server1.url("").url())); try { LoadBalancingTarget<TestInterface> target = LoadBalancingTarget.create(TestInterface.class, "http://" + name + "/context-path"); TestInterface api = Feign.builder().target(target); api.get(); assertEquals("http:/ assertEquals("/context-path/servers", server1.takeRequest().getPath()); } finally { getConfigInstance().clearProperty(serverListKey); } }
Source:
<code>protected HttpURLConnection create(URL url) throws IOException, GeneralSecurityException { Boolean verifyHost = false; Boolean verifyChain = true; String httpsProtocol = "TLSv1"; String trustManagerAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); String trustStore = EngineLocalConfig.getInstance().getProperty("ENGINE_PKI_TRUST_STORE"); String trustStoreType = KeyStore.getDefaultType(); String trustStorePassword = EngineLocalConfig.getInstance().getPKITrustStorePassword(); <START> Integer readTimeout = 0; <END> return new HttpURLConnectionBuilder(url).setHttpsProtocol(httpsProtocol) .setReadTimeout(readTimeout) .setTrustManagerAlgorithm(trustManagerAlgorithm) .setTrustStore(trustStore) .setTrustStorePassword(trustStorePassword) .setTrustStoreType(trustStoreType) .setURL(url) .setVerifyChain(verifyChain) .setVerifyHost(verifyHost).create(); }</code><technical_language>avoid temp variables... add readability</technical_language>

Target:
protected HttpURLConnection create(URL url) throws IOException, GeneralSecurityException { return new HttpURLConnectionBuilder(url).setHttpsProtocol("TLSv1") .setReadTimeout(0) .setTrustManagerAlgorithm(TrustManagerFactory.getDefaultAlgorithm()) .setTrustStore(EngineLocalConfig.getInstance().getProperty("ENGINE_PKI_TRUST_STORE")) .setTrustStorePassword(EngineLocalConfig.getInstance().getPKITrustStorePassword()) .setTrustStoreType(KeyStore.getDefaultType()) .setURL(url) .setVerifyChain(true) .setVerifyHost(false).create(); }
Source:
<code>public void delete(Context context, Relationship relationship, boolean copyToLeftItem, boolean copyToRightItem) throws SQLException, AuthorizeException { log.info(org.dspace.core.LogManager.getHeader(context, "delete_relationship", "relationship_id=" + relationship.getID() + "&" + "copyToLeftItem=" + copyToLeftItem + "&" + <START> "copyToRightItem=" + copyToRightItem)); <END> if (isRelationshipValidToDelete(context, relationship) && copyToItemPermissionCheck(context, relationship, copyToLeftItem, copyToRightItem)) { copyMetadataValues(context, relationship, copyToLeftItem, copyToRightItem); if (authorizeService.authorizeActionBoolean(context, relationship.getLeftItem(), Constants.WRITE) || authorizeService.authorizeActionBoolean(context, relationship.getRightItem(), Constants.WRITE)) { relationshipDAO.delete(context, relationship); updatePlaceInRelationship(context, relationship, false); } else { throw new AuthorizeException( "You do not have write rights on this relationship's items"); } } else { throw new IllegalArgumentException("The relationship given was not valid"); } }</code><technical_language>Tiny suggestion. I variable is named copyTo*Item in this code, I if logged info slightly more descriptive...something "copyMetadataValuesToLeftItem" (and RightItem)... "copyMetadataToLeftItem"? Otherwise, for this log statement, understand copyToLeftItem means actual code</technical_language>

Target:
public void delete(Context context, Relationship relationship, boolean copyToLeftItem, boolean copyToRightItem) throws SQLException, AuthorizeException { log.info(org.dspace.core.LogManager.getHeader(context, "delete_relationship", "relationship_id=" + relationship.getID() + "&" + "copyMetadataValuesToLeftItem=" + copyToLeftItem + "&" + "copyMetadataValuesToRightItem=" + copyToRightItem)); if (isRelationshipValidToDelete(context, relationship) && copyToItemPermissionCheck(context, relationship, copyToLeftItem, copyToRightItem)) { copyMetadataValues(context, relationship, copyToLeftItem, copyToRightItem); if (authorizeService.authorizeActionBoolean(context, relationship.getLeftItem(), Constants.WRITE) || authorizeService.authorizeActionBoolean(context, relationship.getRightItem(), Constants.WRITE)) { relationshipDAO.delete(context, relationship); updatePlaceInRelationship(context, relationship); } else { throw new AuthorizeException( "You do not have write rights on this relationship's items"); } } else { throw new IllegalArgumentException("The relationship given was not valid"); } }
Source:
<code>public AuditLogType getAuditLogTypeValue() { <START> switch (getActionState()) { case END_FAILURE: return AuditLogType.USER_DEACTIVATE_STORAGE_DOMAIN_FAILED; default: return AuditLogType.UNASSIGNED; } <END> }</code><technical_language>a straight-forward "if" statement</technical_language>

Target:
public AuditLogType getAuditLogTypeValue() { return getActionState() == CommandActionState.END_FAILURE ? AuditLogType.USER_DEACTIVATE_STORAGE_DOMAIN_FAILED : AuditLogType.UNASSIGNED; }
Source:
<code>public void onError(Throwable t) { if (t == null) { <START> throw new NullPointerException("t is null"); <END> } if (once.compareAndSet(false, true)) { error = t; done = true; drain(); } else { RxJavaPlugins.onError(t); } }</code><technical_language>another sentence stating nulls allowed definition</technical_language>

Target:
public void onError(Throwable t) { ObjectHelper.requireNonNull(t, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); if (once.compareAndSet(false, true)) { error = t; done = true; drain(); } else { RxJavaPlugins.onError(t); } }
Source:
<code>protected Stream<List<String>> getMappedStream(final SnomedReferenceSetMembers results, final RepositoryContext context, final String branch) { final List<String> extraColumns = newArrayList(getHeader()); for (int i = 0; i < 6; i++) { extraColumns.remove(0); } for (int j = 0; j < extraColumns.size(); j++) { switch (extraColumns.get(j)) { case SnomedRf2Headers.FIELD_TARGET_COMPONENT_ID: extraColumns.set(j, SnomedRf2Headers.FIELD_TARGET_COMPONENT); break; default: break; } } return results.stream() .map(member -> { final ImmutableList.Builder<String> builder = ImmutableList.<String>builder() .add(member.getId()) .add(getEffectiveTime(member)) .add(getActive(member)) .add(member.getModuleId()) .add(member.getReferenceSetId()) .add(member.getReferencedComponent().getId()); final Map<String, Object> properties = member.getProperties(); for (final String extraColumn : extraColumns) { Object property = properties.get(extraColumn); if (extraColumn.equals(SnomedRf2Headers.FIELD_QUERY)) { String query = (String) property; <START> query = query.replace("\r", " "); <END> query = query.replace("\n", " "); query = query.replace("\t", " "); property = query; } builder.add(toColumn(property)); } return builder.build(); }); }</code><technical_language>A simplified regex reduce multiple control characters a single space: replaceAll("[\r\n]+", " ")</technical_language>

Target:
protected Stream<List<String>> getMappedStream(final SnomedReferenceSetMembers results, final RepositoryContext context, final String branch) { final List<String> extraColumns = newArrayList(getHeader()); for (int i = 0; i < 6; i++) { extraColumns.remove(0); } for (int j = 0; j < extraColumns.size(); j++) { switch (extraColumns.get(j)) { case SnomedRf2Headers.FIELD_TARGET_COMPONENT_ID: extraColumns.set(j, SnomedRf2Headers.FIELD_TARGET_COMPONENT); break; default: break; } } return results.stream() .map(member -> { final ImmutableList.Builder<String> builder = ImmutableList.<String>builder() .add(member.getId()) .add(getEffectiveTime(member)) .add(getActive(member)) .add(member.getModuleId()) .add(member.getReferenceSetId()) .add(member.getReferencedComponent().getId()); final Map<String, Object> properties = member.getProperties(); for (final String extraColumn : extraColumns) { builder.add(toColumn(extraColumn, properties.get(extraColumn))); } return builder.build(); }); }
Source:
<code>public void createUser_shouldThrowWhenCalledOutsideContextDAO() throws Throwable { try { <START> Daemon.createUser(new User(), "password", null); <END> Assert.fail("Should not be here, an exception should have been thrown in the line above"); } catch (APIException e) { Assert.assertTrue(e.getMessage().startsWith(Context.getMessageSourceService().getMessage("Context.DAO.only", new Object[] { this.getClass().getName() }, null))); } }</code><technical_language>below, ExpectedException</technical_language>

Target:
public void createUser_shouldThrowWhenCalledOutsideContextDAO() throws Throwable { expectedException.expect(APIException.class); expectedException.expectMessage(Context.getMessageSourceService().getMessage("Context.DAO.only", new Object[] { this.getClass().getName() }, null)); Daemon.createUser(new User(), "password", null); }
Source:
<code>protected void copyTemplateToTargetFilesystemStorageIfNeeded(VolumeInfo srcVolumeInfo, StoragePool srcStoragePool, DataStore destDataStore, StoragePool destStoragePool, Host destHost) { VMTemplateStoragePoolVO sourceVolumeTemplateStoragePoolVO = vmTemplatePoolDao.findByPoolTemplate(destStoragePool.getId(), srcVolumeInfo.getTemplateId()); if (sourceVolumeTemplateStoragePoolVO == null && destStoragePool.getPoolType() == StoragePoolType.Filesystem) { DataStore sourceTemplateDataStore = dataStoreManagerImpl.getImageStore(srcVolumeInfo.getDataCenterId()); <START> if (sourceTemplateDataStore != null) { <END> TemplateInfo sourceTemplateInfo = templateDataFactory.getTemplate(srcVolumeInfo.getTemplateId(), sourceTemplateDataStore); TemplateObjectTO sourceTemplate = new TemplateObjectTO(sourceTemplateInfo); LOGGER.debug(String.format("Could not find template [id=%s, name=%s] on the storage pool [id=%s]; copying the template to the target storage pool.", srcVolumeInfo.getTemplateId(), sourceTemplateInfo.getName(), destDataStore.getId())); TemplateInfo destTemplateInfo = templateDataFactory.getTemplate(srcVolumeInfo.getTemplateId(), destDataStore); final TemplateObjectTO destTemplate = new TemplateObjectTO(destTemplateInfo); Answer copyCommandAnswer = sendCopyCommand(destHost, sourceTemplate, destTemplate, destDataStore); if (copyCommandAnswer != null && copyCommandAnswer.getResult()) { updateTemplateReferenceIfSuccessfulCopy(srcVolumeInfo, srcStoragePool, destTemplateInfo, destDataStore); } } } }</code><technical_language>this reason (sourceTemplateDataStore != null) ? If so, need else end manage nulls</technical_language>

Target:
protected void copyTemplateToTargetFilesystemStorageIfNeeded(VolumeInfo srcVolumeInfo, StoragePool srcStoragePool, DataStore destDataStore, StoragePool destStoragePool, Host destHost) { VMTemplateStoragePoolVO sourceVolumeTemplateStoragePoolVO = vmTemplatePoolDao.findByPoolTemplate(destStoragePool.getId(), srcVolumeInfo.getTemplateId()); if (sourceVolumeTemplateStoragePoolVO == null && destStoragePool.getPoolType() == StoragePoolType.Filesystem) { DataStore sourceTemplateDataStore = dataStoreManagerImpl.getRandomImageStore(srcVolumeInfo.getDataCenterId()); if (sourceTemplateDataStore != null) { TemplateInfo sourceTemplateInfo = templateDataFactory.getTemplate(srcVolumeInfo.getTemplateId(), sourceTemplateDataStore); TemplateObjectTO sourceTemplate = new TemplateObjectTO(sourceTemplateInfo); LOGGER.debug(String.format("Could not find template [id=%s, name=%s] on the storage pool [id=%s]; copying the template to the target storage pool.", srcVolumeInfo.getTemplateId(), sourceTemplateInfo.getName(), destDataStore.getId())); TemplateInfo destTemplateInfo = templateDataFactory.getTemplate(srcVolumeInfo.getTemplateId(), destDataStore); final TemplateObjectTO destTemplate = new TemplateObjectTO(destTemplateInfo); Answer copyCommandAnswer = sendCopyCommand(destHost, sourceTemplate, destTemplate, destDataStore); if (copyCommandAnswer != null && copyCommandAnswer.getResult()) { updateTemplateReferenceIfSuccessfulCopy(srcVolumeInfo, srcStoragePool, destTemplateInfo, destDataStore); } } } }
Source:
<code>public NicWithLogicalNetworks(VmNetworkInterface networkInterface) { <START> super(); <END> this.networkInterface = networkInterface; }</code><technical_language>redundant</technical_language>

Target:
public NicWithLogicalNetworks(VmNetworkInterface networkInterface) { this.networkInterface = networkInterface; }
Source:
<code>PageData split(int splitPoint) { int newPageId = index.getPageStore().allocatePage(); PageDataNode p2 = PageDataNode.create(index, newPageId, parentPageId); int firstChild = childPageIds[splitPoint]; <START> for (; splitPoint < entryCount; ) { <END> p2.addChild(p2.entryCount, childPageIds[splitPoint + 1], keys[splitPoint]); removeChild(splitPoint); } int lastChild = childPageIds[splitPoint - 1]; removeChild(splitPoint - 1); childPageIds[splitPoint - 1] = lastChild; p2.childPageIds[0] = firstChild; p2.remapChildren(getPos()); return p2; }</code><technical_language>while instead of for</technical_language>

Target:
PageData split(int splitPoint) { int newPageId = index.getPageStore().allocatePage(); PageDataNode p2 = PageDataNode.create(index, newPageId, parentPageId); int firstChild = childPageIds[splitPoint]; while (splitPoint < entryCount) { p2.addChild(p2.entryCount, childPageIds[splitPoint + 1], keys[splitPoint]); removeChild(splitPoint); } int lastChild = childPageIds[splitPoint - 1]; removeChild(splitPoint - 1); childPageIds[splitPoint - 1] = lastChild; p2.childPageIds[0] = firstChild; p2.remapChildren(getPos()); return p2; }
Source:
<code>private void displayCloudStatus() { boolean isConnected = false; String message; DbxAccountInfo info = null; DbxClient client = DbxUtil.getDbxClient(); if (client != null) { String userToken = client.getAccessToken(); if (userToken != null && !userToken.isEmpty()) { try { info = client.getAccountInfo(); isConnected = true; } catch (DbxException ex) { <START> Exceptions.printStackTrace(ex); <END> } } } if (isConnected) { message = "Connected to Dropbox account as " + info.displayName + "."; CloudStatus.getInstance().setStatus(CloudStatus.STATUS_DBX_CONNECTED, " (" + info.displayName + ")"); } else { message = "Working locally."; CloudStatus.getInstance().setStatus(CloudStatus.STATUS_DISCONNECTED); } LOGGER.log(message); }</code><technical_language>print stacktrace in this case. If I application conected Dropbox I start application, conected Internet, I get stacktrace in a pop window right startup is best. mark status connected move on</technical_language>

Target:
private void displayCloudStatus() { boolean isConnected = false; String message; DbxAccountInfo info = null; DbxClient client = DbxUtil.getDbxClient(); if (client != null) { String userToken = client.getAccessToken(); if (userToken != null && !userToken.isEmpty()) { try { info = client.getAccountInfo(); isConnected = true; } catch (DbxException ex) { } } } if (isConnected) { message = "Connected to Dropbox account as " + info.displayName + "."; Cloud.getInstance().setStatus(Cloud.Status.DBX_CONNECTED, " (" + info.displayName + ")"); } else { message = "Working locally."; Cloud.getInstance().setStatus(Cloud.Status.DISCONNECTED); } LOGGER.log(message); }
Source:
<code>public synchronized void export() { checkAndUpdateSubConfigs(); if (provider != null) { if (export == null) { export = provider.getExport(); } if (delay == null) { delay = provider.getDelay(); } } if (export != null && !export) { return; } if (delay != null && delay > 0) { new NamedThreadFactory("DubboServiceDelayExporter", true).newThread(() -> { try { logger.info("Dubbo service " + interfaceClass.getName() + " will delay export for " + delay + " ms"); TimeUnit.MILLISECONDS.sleep(delay); doExport(); } catch (InterruptedException e) { logger.error("Expected error occured when export " + interfaceClass.getName(), e); } <START> }).start(); <END> } else { doExport(); } }</code><technical_language>call delayExportExecutor.shutdown() method delay task add work queue</technical_language>

Target:
public synchronized void export() { checkAndUpdateSubConfigs(); if (provider != null) { if (export == null) { export = provider.getExport(); } if (delay == null) { delay = provider.getDelay(); } } if (export != null && !export) { return; } if (delay != null && delay > 0) { delayExportExecutor.schedule(this::doExport, delay, TimeUnit.MILLISECONDS); } else { doExport(); } }
Source:
<code>protected void startBackgroundDiscovery() { Expression expression = null; try { expression = new CronExpression( CronHelper.createCronForRepeatEverySeconds(LOCATION_CHANGED_CHECK_INTERVAL)); } catch (ParseException e) { return; } if (expression != null && backgroundJob == null) { AstroDiscoveryLocationChangedTask job = new AstroDiscoveryLocationChangedTask(this); scheduledExecutor.schedule(job, expression); <START> logger.info("Scheduled astro location-changed job every seconds", LOCATION_CHANGED_CHECK_INTERVAL); <END> backgroundJob = job; } }</code><technical_language>debug is enough</technical_language>

Target:
protected void startBackgroundDiscovery() { if (astroDiscoveryJob == null) { astroDiscoveryJob = scheduler.scheduleAtFixedRate(() -> { PointType currentLocation = locationProvider.getLocation(); if (!Objects.equals(currentLocation, previousLocation)) { logger.info("Location has been changed from to {}: Creating new Discovery Results", previousLocation, currentLocation); createResults(currentLocation); previousLocation = currentLocation; } }, 0, LOCATION_CHANGED_CHECK_INTERVAL, TimeUnit.SECONDS); logger.debug("Scheduled astro location-changed job every seconds", LOCATION_CHANGED_CHECK_INTERVAL); } }
Source:
<code>public Symbol getColumn() { if (expression instanceof SymbolReference) { return Symbol.from(expression); } <START> return null; <END> }</code><technical_language>fail in this case. I for returning null -- downstream bugs. This method called checking for isVariable</technical_language>

Target:
public Symbol getColumn() { verify(expression instanceof SymbolReference, "Expect the expression to be a SymbolReference"); return Symbol.from(expression); }
Source:
<code>public boolean followUp(Token t, boolean isPredict) { <START> boolean follow = ( isDynamicResolution() && FEELParser.isVariableNameValid( t.getText() ) ) || this.currentScope.followUp( t.getText(), isPredict ); <END> return follow; }</code><technical_language>create a new method: FEELParser.isVariablePartNameValid(). For instance, a variable numbers, start a number. I afraid fail for a name like: "My Variable 1", method called for token: "Variable" (succeeds), "1" (fails)</technical_language>

Target:
public boolean followUp(Token t, boolean isPredict) { boolean follow = ( isDynamicResolution() && FEELParser.isVariableNamePartValid( t.getText() ) ) || this.currentScope.followUp( t.getText(), isPredict ); return follow; }
Source:
<code>public void messageSizeFuzzTest() throws IOException { int maxSize = 1 << 16; <START> Random random = new Random(11); <END> for ( int i = 0; i < 1000; i++) { int size = random.nextInt( maxSize + 1); byte[] expected = new byte[size]; Arrays.fill(expected, (byte)42); BufferingChunkedInput input = new BufferingChunkedInput( channel( expected, 0, size ) ); byte[] dst = new byte[size]; input.readBytes( dst, 0, size); assertThat( dst, equalTo( expected ) ); } }</code><technical_language>This a fixed seed</technical_language>

Target:
public void messageSizeFuzzTest() throws IOException { int maxSize = 1 << 16; Random random = new Random(); for ( int i = 0; i < 1000; i++) { int size = random.nextInt( maxSize + 1); byte[] expected = new byte[size]; Arrays.fill(expected, (byte)42); BufferingChunkedInput input = new BufferingChunkedInput( channel( expected, 0, size ) ); byte[] dst = new byte[size]; input.readBytes( dst, 0, size); assertThat( dst, equalTo( expected ) ); } }
Source:
<code>public BugzillaRestConfiguration getConfiguration(TaskRepository repository, IOperationMonitor monitor) { try { <START> return new BugzillaRestConfiguration(repository.getUrl(), getProducts(monitor), getFields(monitor)); <END> } catch (Exception e) { StatusHandler.log(new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, "Could not get the Configuration", e)); return null; } }</code><technical_language>I create default-visibility setters configuration instead of passing in constructor inline getProducts getFields methods: config = new BRConfig(); config.setProducts(getContainer(...)); config.setFields(getContainer(...));</technical_language>

Target:
public BugzillaRestConfiguration getConfiguration(TaskRepository repository, IOperationMonitor monitor) { try { BugzillaRestConfiguration config = new BugzillaRestConfiguration(repository.getUrl()); config.setFields(getFields(monitor)); config.setProducts(getProducts(monitor)); return config; } catch (Exception e) { StatusHandler.log(new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, "Could not get the Configuration", e)); return null; } }
Source:
<code>private Set<Long> getDeletedSurveys(DeviceNotificationRequest req) { Set<Long> surveyIds = new HashSet<>(); <START> String[] args = req.getSurveyIds(); <END> if (args != null) { for (String sid : args) { try { surveyIds.add(Long.parseLong(sid)); } catch (NumberFormatException e) { } } if (surveyIds.isEmpty()) { return surveyIds; } Set<Long> foundIds = new HashSet<>(); for (Survey s : new SurveyDAO().listByKeys(surveyIds.toArray(new Long[surveyIds.size()]))) { foundIds.add(s.getKey().getId()); } surveyIds.removeAll(foundIds); } return surveyIds; }</code><technical_language>understanding is is responsibility of populateFields do this conversion of String[] List<Long></technical_language>

Target:
private Set<Long> getDeletedSurveys(DeviceNotificationRequest req) { Set<Long> surveyIds = req.getSurveyIds(); if (surveyIds.isEmpty()) { return surveyIds; } Set<Long> foundIds = new HashSet<Long>(); Long[] surveyIdsArray = surveyIds.toArray(new Long[surveyIds.size()]); for (Survey s : new SurveyDAO().listByKeys(surveyIdsArray)) { foundIds.add(s.getKey().getId()); } surveyIds.removeAll(foundIds); return surveyIds; }
Source:
<code>private void changeTagListener() { final EditText editTextTag = new EditText(GroupSettingsActivity.this); editTextTag.setId(R.id.editText); final AlertDialog dialog = new AlertDialog.Builder(GroupSettingsActivity.this) .setTitle("Add new tag") .setMessage("The new tag must be between 2 and 20 characters" + ", in lowercase, with no spaces.") .setView(editTextTag) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .create(); dialog.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String text = editTextTag.getText().toString(); if (text.length() < Group.Tag.MIN_TAG_LENGTH) { YieldsApplication.showToast(getApplicationContext(), "The tag is too short"); } else if (text.length() > Group.Tag.MAX_TAG_LENGTH) { YieldsApplication.showToast(getApplicationContext(), "The tag is too long"); } else if (!text.toLowerCase().equals(text)) { YieldsApplication.showToast(getApplicationContext(), <START> "The tag is not in lowercase"); <END> } else if (text.contains(" ")) { YieldsApplication.showToast(getApplicationContext(), "The tag contains spaces"); } else { YieldsApplication.showToast(getApplicationContext(), "Tag \"" + text + "\" added"); Group.Tag tag = new Group.Tag(text); mGroup.addTag(tag); dialog.dismiss(); } } }); }</code><technical_language>Instead of displaying error message annoying user, app convert tag case automatically</technical_language>

Target:
private void changeTagListener() { final EditText editTextTag = new EditText(GroupSettingsActivity.this); editTextTag.setId(R.id.editText); final AlertDialog dialog = new AlertDialog.Builder(GroupSettingsActivity.this) .setTitle("Add new tag") .setMessage("The new tag must be between 2 and 20 characters" + ", in lowercase, with no spaces.") .setView(editTextTag) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .create(); dialog.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String text = editTextTag.getText().toString().toLowerCase().replace(' ', '_'); if (text.length() < Group.Tag.MIN_TAG_LENGTH) { YieldsApplication.showToast(getApplicationContext(), "The tag is too short"); } else if (text.length() > Group.Tag.MAX_TAG_LENGTH) { YieldsApplication.showToast(getApplicationContext(), "The tag is too long"); } else { YieldsApplication.showToast(getApplicationContext(), "Tag \"" + text + "\" added"); Group.Tag tag = new Group.Tag(text); mGroup.addTag(tag); dialog.dismiss(); } } }); }
Source:
<code>public void testDescribeImagesWithInvalidFilter() { String region = getFirst(ec2Api.getConfiguredRegions(), null); <START> if (region != null) { <END> Set<? extends Image> allResults = client.describeImagesInRegion(region); assertNotNull(allResults); assert allResults.size() >= 2 : allResults.size(); Iterator<? extends Image> iterator = allResults.iterator(); String id1 = iterator.next().getId(); Set<? extends Image> filterResult = client.describeImagesInRegionWithFilter(region, ImmutableMultimap.<String, String>builder() .put("invalid-filter-id", id1) .build()); assertNotNull(filterResult); assertEquals(filterResult.size(), 1); iterator = filterResult.iterator(); assertEquals(iterator.next().getId(), id1); } }</code><technical_language>Especially expecting exception here...should test fail explicitly if regions configured</technical_language>

Target:
public void testDescribeImagesWithInvalidFilter() { String region = getFirst(ec2Api.getConfiguredRegions(), null); assertNotNull(region, "region should not be null"); Set<? extends Image> allResults = client.describeImagesInRegion(region); assertNotNull(allResults); assertTrue(allResults.size() >= 2); String id1 = allResults.iterator().next().getId(); Set<? extends Image> filterResult = client.describeImagesInRegionWithFilter(region, ImmutableMultimap.<String, String>builder() .put("invalid-filter-id", id1) .build()); assertNotNull(filterResult); assertEquals(filterResult.size(), 1); assertEquals(filterResult.iterator().next().getId(), id1); }
Source:
<code>public static SecurityFactory<SSLContext> createSslContextFactory(ProtocolSelector protocolSelector, Supplier<Provider[]> providerSupplier, String providerName) { Provider[] providers = providerSupplier.get(); final Map<String, List<Provider>> preferredProviderByAlgorithm = new IdentityHashMap<>(); for (Provider provider : providers) { if (providerName != null && ! providerName.equals(provider.getName())) { continue; } Set<Service> services = provider.getServices(); if (services != null) { for (Provider.Service service : services) { if (serviceType.equals(service.getType())) { String protocolName = service.getAlgorithm(); <START> List<Provider> providerList = preferredProviderByAlgorithm.get(protocolName); <END> if (providerList == null) { providerList = new ArrayList<>(); preferredProviderByAlgorithm.put(protocolName, providerList); } providerList.add(provider); } } } } final String[] supportedProtocols = protocolSelector.evaluate(preferredProviderByAlgorithm.keySet().toArray(NO_STRINGS)); if (supportedProtocols.length > 0) { return () -> { for (String protocol : supportedProtocols) { List<Provider> providerList = preferredProviderByAlgorithm.get(protocol); if (providerList != null) { for (Provider provider : providerList) { try { return SSLContext.getInstance(protocol, provider); } catch (NoSuchAlgorithmException ignored) } } } throw ElytronMessages.log.noAlgorithmForSslProtocol(); }; } return SSLUtils::throwIt; }</code><technical_language>In general this kind of written this: preferredProviderByAlgorithm.computeIfAbsent(protocolName, p -> new ArrayList<>()).add(provider);</technical_language>

Target:
public static SecurityFactory<SSLContext> createSslContextFactory(ProtocolSelector protocolSelector, Supplier<Provider[]> providerSupplier, String providerName) { Provider[] providers = providerSupplier.get(); final Map<String, List<Provider>> preferredProviderByAlgorithm = new IdentityHashMap<>(); for (Provider provider : providers) { if (providerName != null && ! providerName.equals(provider.getName())) { continue; } Set<Service> services = provider.getServices(); if (services != null) { for (Provider.Service service : services) { if (serviceType.equals(service.getType())) { String protocolName = service.getAlgorithm(); List<Provider> providerList = preferredProviderByAlgorithm.computeIfAbsent(protocolName, s -> new ArrayList<>()); providerList.add(provider); } } } } final String[] supportedProtocols = protocolSelector.evaluate(preferredProviderByAlgorithm.keySet().toArray(NO_STRINGS)); if (supportedProtocols.length > 0) { return () -> { for (String protocol : supportedProtocols) { List<Provider> providerList = preferredProviderByAlgorithm.getOrDefault(protocol, Collections.emptyList()); for (Provider provider : providerList) { try { return SSLContext.getInstance(protocol, provider); } catch (NoSuchAlgorithmException ignored) } } throw ElytronMessages.log.noAlgorithmForSslProtocol(); }; } return SSLUtils::throwIt; }
Source:
<code>public RowExpressionFormatter(ConnectorSession session, FunctionManager functionManager) { <START> this.functionManager = functionManager; <END> this.standardFunctionResolution = new FunctionResolution(functionManager); this.session = requireNonNull(session, "session is null"); }</code><technical_language>StandardFunctionResolution for constructor; more general</technical_language>

Target:
public RowExpressionFormatter(ConnectorSession session, FunctionManager functionManager) { this.session = requireNonNull(session, "session is null"); this.functionMetadataManager = requireNonNull(functionManager, "function manager is null"); this.standardFunctionResolution = new FunctionResolution(functionManager); }
Source:
<code>private synchronized Optional<String> getAdditionalFailureInfo(long allocated, long delta) { Map<String, Long> queryAllocations = memoryPool.getTaggedMemoryAllocations().get(queryId); StringBuilder additionalInfo = new StringBuilder() .append("Allocated: ") .append(succinctBytes(allocated)) .append(", Delta: ") .append(succinctBytes(delta)); if (queryAllocations == null) { return Optional.of(additionalInfo.toString()); } String topConsumers = queryAllocations.entrySet() <START> .stream() <END> .sorted(comparingByValue(Comparator.reverseOrder())) .limit(3) .collect(toMap(Entry::getKey, entry -> succinctBytes(entry.getValue()), (e1, e2) -> e1, LinkedHashMap::new)) .toString(); additionalInfo.append(", Top Consumers: ").append(topConsumers); return Optional.of(additionalInfo.toString()); }</code><technical_language>code style, .stream prev line</technical_language>

Target:
private String getAdditionalFailureInfo(long allocated, long delta) { Map<String, Long> queryAllocations = memoryPool.getTaggedMemoryAllocations().get(queryId); String additionalInfo = format("Allocated: %s, Delta: %s", succinctBytes(allocated), succinctBytes(delta)); if (queryAllocations == null) { return additionalInfo; } String topConsumers = queryAllocations.entrySet().stream() .sorted(comparingByValue(Comparator.reverseOrder())) .limit(3) .collect(toImmutableMap(Entry::getKey, e -> succinctBytes(e.getValue()))) .toString(); return format("%s, Top Consumers: %s", additionalInfo, topConsumers); }
Source:
<code>public void testTTL_entryShouldNotBeReachableAfterTTL() { IMap<Integer, String> map = createSimpleMap(); <START> map.put(1, "value0", 0, TimeUnit.SECONDS); <END> sleepSeconds(1); assertFalse(map.containsKey(1)); }</code><technical_language>this entry infinite ttl</technical_language>

Target:
public void testTTL_entryShouldNotBeReachableAfterTTL() { IMap<Integer, String> map = createSimpleMap(); map.put(1, "value0", 1, TimeUnit.SECONDS); sleepSeconds(1); assertFalse(map.containsKey(1)); }
Source:
<code>private ArrayList<LinkInfo> parseForLinks(String inSubType) throws IOException { PDActionRemoteGoTo goTo; PDActionLaunch launch; PDActionURI uri; PDFileSpecification fspec; <START> ArrayList<LinkInfo> li = new ArrayList<>(); <END> List allPages = pdfDoc.getDocumentCatalog().getAllPages(); for (Object pageObject : allPages) { PDPage page = (PDPage) pageObject; stripper.extractRegions(page); List<PDAnnotation> annotations = page.getAnnotations(); for (PDAnnotation annot : annotations) { if (!(annot instanceof PDAnnotationLink)) { continue; } PDAnnotationLink link = (PDAnnotationLink) annot; PDAction action = link.getAction(); if (!action.getSubType().equals(inSubType)) { continue; } String urlText = stripper.getTextForRegion("" + annotations.indexOf(annot)); String urlValue = null; switch (inSubType) { case PDActionRemoteGoTo.SUB_TYPE: goTo = (PDActionRemoteGoTo) action; fspec = goTo.getFile(); urlValue = fspec.getFile(); break; case PDActionLaunch.SUB_TYPE: launch = (PDActionLaunch) action; fspec = launch.getFile(); urlValue = fspec.getFile(); break; case PDActionURI.SUB_TYPE: uri = (PDActionURI) action; urlValue = uri.getURI(); break; } if (StringUtils.isNotBlank(urlValue)) { li.add(new LinkInfo(allPages.indexOf(page) + 1, inSubType, urlText, urlValue)); } } } return li; }</code><technical_language>List<LinkInfo> li = new ArrayList<>()</technical_language>

Target:
private List<LinkInfo> parseForLinks(String inSubType) throws IOException { PDActionRemoteGoTo goTo; PDActionLaunch launch; PDActionURI uri; PDFileSpecification fspec; List<LinkInfo> li = new ArrayList<>(); List allPages = pdfDoc.getDocumentCatalog().getAllPages(); for (Object pageObject : allPages) { PDPage page = (PDPage) pageObject; stripper.extractRegions(page); List<PDAnnotation> annotations = page.getAnnotations(); for (PDAnnotation annot : annotations) { if (!(annot instanceof PDAnnotationLink)) { continue; } PDAnnotationLink link = (PDAnnotationLink) annot; PDAction action = link.getAction(); if (!action.getSubType().equals(inSubType)) { continue; } String urlText = stripper.getTextForRegion(String.valueOf(annotations.indexOf(annot))); String urlValue = null; switch (inSubType) { case PDActionRemoteGoTo.SUB_TYPE: goTo = (PDActionRemoteGoTo) action; fspec = goTo.getFile(); urlValue = fspec.getFile(); break; case PDActionLaunch.SUB_TYPE: launch = (PDActionLaunch) action; fspec = launch.getFile(); urlValue = fspec.getFile(); break; case PDActionURI.SUB_TYPE: uri = (PDActionURI) action; urlValue = uri.getURI(); break; } if (StringUtils.isNotBlank(urlValue)) { li.add(new LinkInfo(allPages.indexOf(page) + 1, inSubType, urlText, urlValue)); } } } return li; }
Source:
<code>public StyledString getStyledText(Object element) { try { if (element instanceof Repository) return getStyledTextFor((Repository) element); if (element instanceof GitModelRepository) return getStyledTextFor(((GitModelRepository) element) .getRepository()); } catch (IOException e) { Activator <START> .logError(UIText.GitLabelProvider_UnableToRetrieveLabel, e); <END> } return new StyledString(getText(element)); }</code><technical_language>add element.toString error</technical_language>

Target:
public StyledString getStyledText(Object element) { try { if (element instanceof Repository) return getStyledTextFor((Repository) element); if (element instanceof GitModelRepository) return getStyledTextFor(((GitModelRepository) element) .getRepository()); } catch (IOException e) { Activator.logError(NLS.bind( UIText.GitLabelProvider_UnableToRetrieveLabel, element.toString()), e); } return new StyledString(getText(element)); }
Source:
<code>private Message getMessage(TopicPartition topicPartition, long offset, SimpleConsumer consumer) { LOG.info("fetching message topic " + topicPartition.getTopic() + " partition " + topicPartition.getPartition() + " offset " + offset); final int MAX_MESSAGE_SIZE_BYTES = 100000; final String clientName = getClientName(topicPartition); kafka.api.FetchRequest request = new FetchRequestBuilder().clientId(clientName) .addFetch(topicPartition.getTopic(), topicPartition.getPartition(), offset, MAX_MESSAGE_SIZE_BYTES) .build(); FetchResponse response = consumer.fetch(request); if (response.hasError()) { consumer.close(); throw new RuntimeException("Error fetching offset data. Reason: " + response.errorCode(topicPartition.getTopic(), topicPartition.getPartition())); } Iterator<MessageAndOffset> messageSetIterator = response.messageSet(topicPartition.getTopic(), topicPartition.getPartition()).iterator(); if (messageSetIterator.hasNext()) { MessageAndOffset messageAndOffset = messageSetIterator.next(); ByteBuffer payload = messageAndOffset.message().payload(); byte[] payloadBytes = new byte[payload.limit()]; payload.get(payloadBytes); return new Message(topicPartition.getTopic(), topicPartition.getPartition(), messageAndOffset.offset(), payloadBytes); } else { <START> return null; <END> } }</code><technical_language>this returns null</technical_language>

Target:
private Message getMessage(TopicPartition topicPartition, long offset, SimpleConsumer consumer) { LOG.info("fetching message topic " + topicPartition.getTopic() + " partition " + topicPartition.getPartition() + " offset " + offset); final int MAX_MESSAGE_SIZE_BYTES = mConfig.getMaxMessageSizeBytes(); final String clientName = getClientName(topicPartition); kafka.api.FetchRequest request = new FetchRequestBuilder().clientId(clientName) .addFetch(topicPartition.getTopic(), topicPartition.getPartition(), offset, MAX_MESSAGE_SIZE_BYTES) .build(); FetchResponse response = consumer.fetch(request); if (response.hasError()) { consumer.close(); throw new RuntimeException("Error fetching offset data. Reason: " + response.errorCode(topicPartition.getTopic(), topicPartition.getPartition())); } MessageAndOffset messageAndOffset = response.messageSet( topicPartition.getTopic(), topicPartition.getPartition()).iterator().next(); ByteBuffer payload = messageAndOffset.message().payload(); byte[] payloadBytes = new byte[payload.limit()]; payload.get(payloadBytes); return new Message(topicPartition.getTopic(), topicPartition.getPartition(), messageAndOffset.offset(), payloadBytes); }
Source:
<code>private Void handleServices(ServiceNodeDiscoverer serviceNodeDiscoverer, Cluster cluster, List<String> availableServices) { availableServices.parallelStream() .filter(ServiceConfigurations::contains) .forEach(serviceName -> { try { <START> transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE); <END> LOG.debug("service start {}", serviceName); Service service = addService(cluster, serviceName); Map<String, String> flattenConfigurations = new ConcurrentHashMap<>(); Map<String, Map<String, String>> configurations = serviceNodeDiscoverer.getConfigurations(serviceName); handleConfigurations(serviceNodeDiscoverer, flattenConfigurations, configurations, service); List<String> components = serviceNodeDiscoverer.getComponents(serviceName); handleComponents(serviceNodeDiscoverer, serviceName, flattenConfigurations, service, components); transactionManager.commitTransaction(); } catch (Exception e) { transactionManager.rollbackTransaction(); throw e; } }); return null; }</code><technical_language>work parallelStream()? If do need change handleComponents() handleConfigurations() stream()? If not, need change this stream() well</technical_language>

Target:
private Void handleServices(ServiceNodeDiscoverer serviceNodeDiscoverer, Cluster cluster, List<String> availableServices) { availableServices.parallelStream() .filter(ServiceConfigurations::contains) .forEach(serviceName -> { try { transactionManager.beginTransaction(TransactionIsolation.DEFAULT); LOG.debug("service start {}", serviceName); Service service = addService(cluster, serviceName); Map<String, String> flattenConfigurations = new ConcurrentHashMap<>(); Map<String, Map<String, String>> configurations = serviceNodeDiscoverer.getConfigurations(serviceName); handleConfigurations(serviceNodeDiscoverer, flattenConfigurations, configurations, service); List<String> components = serviceNodeDiscoverer.getComponents(serviceName); handleComponents(serviceNodeDiscoverer, serviceName, flattenConfigurations, service, components); transactionManager.commitTransaction(); } catch (Exception e) { transactionManager.rollbackTransaction(); throw e; } }); return null; }
Source:
<code>private static GHRepository lookUpRepo(GitHub github, @NonNull Job<?,?> job) throws IOException { if (github == null) { return null; } SCMSource src = SCMSource.SourceByItem.findSource(job); if (src instanceof GitHubSCMSource) { GitHubSCMSource source = (GitHubSCMSource) src; if (source.getScanCredentialsId() != null) { <START> return github.getRepository(GitHubSCMSourceHelper.build(source).repo); <END> } } return null; }</code><technical_language>changes getters, this reverted, right</technical_language>

Target:
private static GHRepository lookUpRepo(GitHub github, @NonNull Job<?,?> job) throws IOException { if (github == null) { return null; } SCMSource src = SCMSource.SourceByItem.findSource(job); if (src instanceof GitHubSCMSource) { GitHubSCMSource source = (GitHubSCMSource) src; if (source.getScanCredentialsId() != null) { return github.getRepository(source.getRepoOwner() + "/" + source.getRepository()); } } return null; }
Source:
<code>public Optional<Integer> setMilestone(String repoId, int issueId, String issueTitle, Optional<Integer> issueMilestone) throws IOException { Issue createdIssue = new Issue(); createdIssue.setNumber(issueId); createdIssue.setTitle(issueTitle); Milestone gitHubMilestone = new Milestone(); if (issueMilestone.isPresent()) { gitHubMilestone.setNumber(issueMilestone.get()); <START> } <END> createdIssue.setMilestone(gitHubMilestone); Issue returnedIssue = issueService.editIssue(RepositoryId.createFromId(repoId), createdIssue); if (returnedIssue.getMilestone() == null) { return Optional.empty(); } return Optional.of(returnedIssue.getMilestone().getNumber()); }</code><technical_language>This part issueMilestone.ifPresent(gitHubMilestone::setNumber);</technical_language>

Target:
public Optional<Integer> setMilestone(String repoId, int issueId, String issueTitle, Optional<Integer> issueMilestone) throws IOException { Issue createdIssue = new Issue(); createdIssue.setNumber(issueId); createdIssue.setTitle(issueTitle); Milestone gitHubMilestone = new Milestone(); issueMilestone.ifPresent(gitHubMilestone::setNumber); createdIssue.setMilestone(gitHubMilestone); Issue returnedIssue = issueService.editIssue(RepositoryId.createFromId(repoId), createdIssue); return Optional.ofNullable(returnedIssue.getMilestone()) .map(Milestone::getNumber); }
Source:
<code>private void checkTotalSizeOfBroadcastableRelations(Context context, ExecutionBlock block) { List<ScanNode> broadcastCandidates = new ArrayList<>(); <START> broadcastCandidates.addAll(block.getBroadcastRelations()); <END> Collections.sort(broadcastCandidates, relSizeComparator); long totalBroadcastVolume = 0; long largeThreshold = context.thresholdForCrossJoin > context.thresholdForNonCrossJoin ? context.thresholdForCrossJoin : context.thresholdForNonCrossJoin; int i; for (i = 0; i < broadcastCandidates.size(); i++) { long volumeOfCandidate = GlobalPlanRewriteUtil.getTableVolume(broadcastCandidates.get(i)); if (totalBroadcastVolume + volumeOfCandidate > largeThreshold) { break; } totalBroadcastVolume += volumeOfCandidate; } for (; i < broadcastCandidates.size(); ) { ScanNode nonBroadcast = broadcastCandidates.remove(i); block.removeBroadcastRelation(nonBroadcast); } }</code><technical_language>rewritten a single constructor call</technical_language>

Target:
private void checkTotalSizeOfBroadcastableRelations(Context context, ExecutionBlock block) { List<ScanNode> broadcastCandidates = new ArrayList<>(block.getBroadcastRelations()); Collections.sort(broadcastCandidates, relSizeComparator); long totalBroadcastVolume = 0; long largeThreshold = context.thresholdForCrossJoin > context.thresholdForNonCrossJoin ? context.thresholdForCrossJoin : context.thresholdForNonCrossJoin; int i; for (i = 0; i < broadcastCandidates.size(); i++) { long volumeOfCandidate = GlobalPlanRewriteUtil.getTableVolume(broadcastCandidates.get(i)); if (totalBroadcastVolume + volumeOfCandidate > largeThreshold) { break; } totalBroadcastVolume += volumeOfCandidate; } for (; i < broadcastCandidates.size(); ) { ScanNode nonBroadcast = broadcastCandidates.remove(i); block.removeBroadcastRelation(nonBroadcast); } }
Source:
<code>private Set<String> searchOrganizationWithAdminPermission(DbSession dbSession) { <START> return dbClient.organizationDao().selectByPermission(dbSession, userSession.getUserId(), ADMINISTER.getKey()).stream() <END> .map(OrganizationDto::getUuid) .collect(toSet()); }</code><technical_language>return empty set user is logged</technical_language>

Target:
private Set<String> searchOrganizationWithAdminPermission(DbSession dbSession) { Integer userId = userSession.getUserId(); return userId == null ? emptySet() : dbClient.organizationDao().selectByPermission(dbSession, userId, ADMINISTER.getKey()).stream().map(OrganizationDto::getUuid).collect(toSet()); }
Source:
<code><START> private DefaultDockerClient(final Builder builder) { <END> this(builder.uri); }</code><technical_language>connectTimeoutMillis readTimeoutMillis in builder unused</technical_language>

Target:
private DefaultDockerClient(final Builder builder) { URI originalUri = checkNotNull(builder.uri, "uri"); final ClientConfig config = DEFAULT_CONFIG .connectorProvider(new ApacheConnectorProvider()) .property(ClientProperties.CONNECT_TIMEOUT, (int) builder.connectTimeoutMillis) .property(ClientProperties.READ_TIMEOUT, (int) builder.readTimeoutMillis) .property(ApacheClientProperties.CONNECTION_MANAGER, new PoolingHttpClientConnectionManager(getSchemeRegistry(originalUri))); this.client = ClientBuilder.newClient(config); if (originalUri.getScheme().equals("unix")) { this.uri = UnixConnectionSocketFactory.sanitizeUri(originalUri); } else { this.uri = originalUri; } }