auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String getArticlesFeed(SessionLanguage language) throws IOException, FeedException { <START> SyndFeed feed = new SyndFeedImpl(); <END> feed.setFeedType("rss_2.0"); feed.setTitle("Mix-IT articles"); feed.setLink(MIX_IT_ARTICLES); feed.setDescription(" "); List<Article> articles = articleRepository.findAllPublishedArticle(); List<SyndEntry> entries = new ArrayList<>(); feed.setEntries(entries); for (Article article : articles) { SyndEntry entry = article.buildRssEntry(language); entries.add(entry); } SyndFeedOutput output = new SyndFeedOutput(); return output.outputString(feed); }</code><technical_language>do need annotate this internal method java @JsonView(FlatView.class) method set a protected visibility</technical_language>

Target:
private String getArticlesFeed(SessionLanguage language) throws IOException, FeedException { String baseUrl = absoluteUrlFactory.getBaseUrl(); SyndFeed feed = new SyndFeedImpl(); feed.setFeedType("rss_2.0"); feed.setTitle("Mix-IT articles"); feed.setLink(baseUrl + MIX_IT_ARTICLES); feed.setDescription(" "); List<Article> articles = articleRepository.findAllPublishedArticle(); List<SyndEntry> entries = new ArrayList<>(); feed.setEntries(entries); for (Article article : articles) { SyndEntry entry = article.buildRssEntry(baseUrl, language); entries.add(entry); } SyndFeedOutput output = new SyndFeedOutput(); return output.outputString(feed); }
Source:
<code>public void setupMocks() { MockBrowserCapabilitiesRegistry registry = MockBrowserCapabilitiesRegistry.createSingletonRegistry(); desiredCapabilities = new DesiredCapabilities(registry.getAllBrowserCapabilities().iterator().next() .getRawCapabilities()); permanentStorage = new MockReusedSessionPermanentStorage(); when(serviceLoader.onlyOne(ReusedSessionPermanentStorage.class)).thenReturn(permanentStorage); bind(ApplicationScoped.class, ServiceLoader.class, serviceLoader); try { hubUrl = new URL("http://localhost:5555/wd/hub/"); } catch (MalformedURLException e) { throw new IllegalStateException(e); } runSeleniumServer(); initializationParameter = new InitializationParameter(hubUrl, desiredCapabilities); <START> String browser = System.getProperty("browser", "phantomjs").toLowerCase(); <END> if (browser.equals("chromeheadless")) { when(configuration.getBrowser()).thenReturn("chromeheadless"); ChromeDriverFactory.setChromeOptions(configuration, (DesiredCapabilities) desiredCapabilities); } when(configuration.getBrowser()).thenReturn("xyz"); when(configuration.isRemoteReusable()).thenReturn(true); when(configuration.getCapabilities()).thenReturn(desiredCapabilities); when(configuration.getRemoteAddress()).thenReturn(hubUrl); configuration.setSeleniumServerArgs("-debug true"); }</code><technical_language>do default value? retrieved is for checking if chromeheadless is - care some defaults...</technical_language>

Target:
public void setupMocks() { MockBrowserCapabilitiesRegistry registry = MockBrowserCapabilitiesRegistry.createSingletonRegistry(); desiredCapabilities = new DesiredCapabilities(registry.getAllBrowserCapabilities().iterator().next() .getRawCapabilities()); permanentStorage = new MockReusedSessionPermanentStorage(); when(serviceLoader.onlyOne(ReusedSessionPermanentStorage.class)).thenReturn(permanentStorage); bind(ApplicationScoped.class, ServiceLoader.class, serviceLoader); try { hubUrl = new URL("http://localhost:5555/wd/hub/"); } catch (MalformedURLException e) { throw new IllegalStateException(e); } runSeleniumServer(); initializationParameter = new InitializationParameter(hubUrl, desiredCapabilities); String browser = System.getProperty("browser").toLowerCase(); if (browser.equals("chromeheadless")) { when(configuration.getBrowser()).thenReturn("chromeheadless"); new ChromeDriverFactory().setChromeOptions(configuration, (DesiredCapabilities) desiredCapabilities); } when(configuration.getBrowser()).thenReturn("xyz"); when(configuration.isRemoteReusable()).thenReturn(true); when(configuration.getCapabilities()).thenReturn(desiredCapabilities); when(configuration.getRemoteAddress()).thenReturn(hubUrl); configuration.setSeleniumServerArgs("-debug true"); }
Source:
<code><START> private void addYoutubeCookies(@Nonnull String cookies) { <END> String c_s_gl = ""; String c_goojf = ""; String[] parts = cookies.split(";"); for (String part : parts) { String trimmedPart = part.trim(); if (trimmedPart.startsWith("s_gl")) { c_s_gl = trimmedPart; } if (trimmedPart.startsWith("goojf")) { c_goojf = trimmedPart; } } if (c_s_gl.length() > 0 && c_goojf.length() > 0) { addCookie(cookies); } }</code><technical_language>good check service id first. in case get a reCAPTCHA a service</technical_language>

Target:
private void addYoutubeCookies(@Nonnull String cookies) { if (cookies.contains("s_gl=") || cookies.contains("goojf=") || cookies.contains("VISITOR_INFO1_LIVE=")) { addCookie(cookies); } }
Source:
<code>BinaryMetadataFileStore( final ConcurrentMap<Integer, BinaryMetadataHolder> metadataLocCache, final GridKernalContext ctx, final IgniteLogger log, @Nullable final File binaryMetadataFileStoreDir ) throws IgniteCheckedException { this.metadataLocCache = metadataLocCache; this.ctx = ctx; this.log = log; if (!CU.isPersistenceEnabled(ctx.config())) { <START> this.fileIOFactory = null; <END> return; } else this.fileIOFactory = ctx.config().getDataStorageConfiguration().getFileIOFactory(); if (binaryMetadataFileStoreDir != null) workDir = binaryMetadataFileStoreDir; else { final String subFolder = ctx.pdsFolderResolver().resolveFolders().folderName(); workDir = new File(U.resolveWorkDirectory( ctx.config().getWorkDirectory(), "binary_meta", false ), subFolder); } U.ensureDirectory(workDir, "directory for serialized binary metadata", log); }</code><technical_language>Assignment needed, return constructor is enough</technical_language>

Target:
BinaryMetadataFileStore( final ConcurrentMap<Integer, BinaryMetadataHolder> metadataLocCache, final GridKernalContext ctx, final IgniteLogger log, @Nullable final File binaryMetadataFileStoreDir ) throws IgniteCheckedException { this.metadataLocCache = metadataLocCache; this.ctx = ctx; this.log = log; if (!CU.isPersistenceEnabled(ctx.config())) return; fileIOFactory = ctx.config().getDataStorageConfiguration().getFileIOFactory(); if (binaryMetadataFileStoreDir != null) workDir = binaryMetadataFileStoreDir; else { final String subFolder = ctx.pdsFolderResolver().resolveFolders().folderName(); workDir = new File(U.resolveWorkDirectory( ctx.config().getWorkDirectory(), "binary_meta", false ), subFolder); } U.ensureDirectory(workDir, "directory for serialized binary metadata", log); }
Source:
<code>protected void unloadAndKillData(final String dataSource) throws Exception { <START> ArrayList<String> dates = coordinator.getSegmentDatesForDataSource(dataSource); <END> Collections.sort (dates); String first = dates.get(0).split("/")[0]; String last = dates.get(dates.size() -1).split("/")[1]; unloadAndKillData (dataSource, first, last); }</code><technical_language>rename intervals</technical_language>

Target:
protected void unloadAndKillData(final String dataSource) throws Exception { ArrayList<String> intervals = coordinator.getSegmentIntervals(dataSource); Collections.sort (intervals); String first = intervals.get(0).split("/")[0]; String last = intervals.get(intervals.size() -1).split("/")[1]; unloadAndKillData (dataSource, first, last); }
Source:
<code><START> public static void canSetConfigParm() throws Exception { <END> SWTBotShell shell = openProperties("Autotools", "Configure Settings"); bot.treeWithLabel("Configure Settings").expandNode("configure") .select("Advanced"); SWTBotText text = bot.textWithLabel("Additional command-line options"); text.typeText("--enable-jeff"); bot.button("OK").click(); bot.waitUntil(Conditions.shellCloses(shell), 120000); IProject project = checkProject(); assertTrue(project != null); IPath path = project.getLocation(); path = path.append(".autotools"); File f = new File(path.toOSString()); assertTrue(f.exists()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document d = db.parse(f); Element e = d.getDocumentElement(); NodeList cfgs = e.getElementsByTagName("configuration"); assertEquals(1, cfgs.getLength()); Node n = cfgs.item(0); NodeList l = n.getChildNodes(); boolean foundUser = false; for (int y = 0; y < l.getLength(); ++y) { Node child = l.item(y); if (child.getNodeName().equals("option")) { NamedNodeMap optionAttrs = child.getAttributes(); Node idNode = optionAttrs.getNamedItem("id"); Node valueNode = optionAttrs.getNamedItem("value"); assertTrue(idNode != null); assertTrue(valueNode != null); String id = idNode.getNodeValue(); String value = valueNode.getNodeValue(); if (id.equals("user")) { foundUser = true; assertEquals(value, "--enable-jeff"); } } } assertTrue(foundUser); canBuildWithConfigParm(); }</code><technical_language>I top part of this file moved a routine called initConfigParm remainder is performing a test canSetConfigParm is actual test. opposed this part of beforeClass</technical_language>

Target:
public void canSetConfigParm() throws Exception { IProject project = checkProject(); assertTrue(project != null); IPath path = project.getLocation(); path = path.append(".autotools"); File f = new File(path.toOSString()); assertTrue(f.exists()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document d = db.parse(f); Element e = d.getDocumentElement(); NodeList cfgs = e.getElementsByTagName("configuration"); assertTrue(cfgs.getLength() > 0); Node n = cfgs.item(0); NodeList l = n.getChildNodes(); boolean foundUser = false; for (int y = 0; y < l.getLength(); ++y) { Node child = l.item(y); if (child.getNodeName().equals("option")) { NamedNodeMap optionAttrs = child.getAttributes(); Node idNode = optionAttrs.getNamedItem("id"); Node valueNode = optionAttrs.getNamedItem("value"); assertTrue(idNode != null); assertTrue(valueNode != null); String id = idNode.getNodeValue(); String value = valueNode.getNodeValue(); if (id.equals("user")) { foundUser = true; assertEquals(value, "--enable-jeff"); } } } assertTrue(foundUser); }
Source:
<code>private static MetricFamilySamples.Sample buildStatusSample(String name, String status, double value) { return new MetricFamilySamples.Sample( name, <START> Collections.singletonList("status"), <END> Collections.singletonList(status), value); }</code><technical_language>call this code</technical_language>

Target:
private static MetricFamilySamples.Sample buildStatusSample(String name, String status, double value) { return new MetricFamilySamples.Sample( name, Collections.singletonList("code"), Collections.singletonList(status), value); }
Source:
<code>@Test public void getResourceById() throws IOException { Request request = new Request.Builder(RESOURCE_ID_URI).build(); Utils.ResourceResult result = Utils.getResources(mockPackageResourceContext(), request); <START> <END> assertThat(result.id).isEqualTo(RESOURCE_ID_1); }</code><technical_language>extra line. remove</technical_language>

Target:
@Test public void getResourceById() throws IOException { Request request = new Request.Builder(RESOURCE_ID_URI).build(); Resources resources = Utils.getResources(mockPackageResourceContext(), request); int id = Utils.getResourceId(resources, request); assertThat(id).isEqualTo(RESOURCE_ID_1); }
Source:
<code>private WeightedDoubleReservoirSample(WeightedDoubleReservoirSample other) { <START> checkArgument(other.size <= other.samples.length, "size must not be larger than samples"); <END> this.size = other.size; this.samples = new double[other.samples.length]; this.weights = new double[other.weights.length]; System.arraycopy(other.samples, 0, samples, 0, size); System.arraycopy(other.weights, 0, weights, 0, size); checkArguments(); }</code><technical_language>this is redundant; this method assume other is a valid instance</technical_language>

Target:
private WeightedDoubleReservoirSample(WeightedDoubleReservoirSample other) { this.count = other.count; this.samples = Arrays.copyOf(other.samples, other.samples.length); this.weights = Arrays.copyOf(other.weights, other.weights.length); }
Source:
<code>private void initTls12IfNeeded() { <START> if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 22) { <END> CommCareNetworkServiceGenerator.customizeRetrofitSetup(new ForceTLS12BuilderConfig()); } }</code><technical_language>[less 20](<LINK_0></technical_language>

Target:
private void initTls12IfNeeded() { if (useConscryptSecurity()) { Security.insertProviderAt(Conscrypt.newProvider(), 1); } if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 22) { CommCareNetworkServiceGenerator.customizeRetrofitSetup(new ForceTLS12BuilderConfig()); } }
Source:
<code>public List<HiveObjectPrivilege> listPrincipalDBGrantsAll(String principalName, PrincipalType principalType) { List<HiveObjectPrivilege> results = Collections.emptyList(); try { openTransaction(); results = convertDB(listPrincipalAllDBGrant(principalName, principalType)); commitTransaction(); } catch (Exception e) { throw new RuntimeException(e); } finally { <START> rollbackAndCleanup(true, null); <END> } return results; }</code><technical_language>transaction unable rollback exception happens</technical_language>

Target:
public List<HiveObjectPrivilege> listPrincipalDBGrantsAll(String principalName, PrincipalType principalType) { List<HiveObjectPrivilege> results = Collections.emptyList(); boolean success = false; try { openTransaction(); results = convertDB(listPrincipalAllDBGrant(principalName, principalType)); success = commitTransaction(); } catch (Exception e) { throw new RuntimeException(e); } finally { rollbackAndCleanup(success, null); } return results; }
Source:
<code>public List<String> getClusteringKeyPredicates() { if (clusteringPushDownResult.getDomainQuery().isEmpty()) { return ImmutableList.of(); } ImmutableList.Builder<String> clusteringColumnSql = ImmutableList.builder(); <START> return clusteringColumnSql.add(Joiner.on(" AND ").join(clusteringPushDownResult.getDomainQuery())).build(); <END> }</code><technical_language>need for a builder here, return ImmutableList.of(Joiner.on(" ").join(clusteringPushDownResult.getDomainQuery());</technical_language>

Target:
public String getClusteringKeyPredicates() { return clusteringPushDownResult.getDomainQuery(); }
Source:
<code>public boolean isNull() { <START> return false; <END> }</code><technical_language>I return true, in sqlCompatible, returning in non-sqlCompatible sqlCompatible in fact this method dependent this config, mentioned previous of review case</technical_language>

Target:
public boolean isNull() { return true; }
Source:
<code>public void testZsetInboundConfigurationWithSingleScoreAndSynchronization() throws Exception{ RedisConnectionFactory jcf = this.getConnectionFactoryForTest(); this.prepareZset(jcf); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("zset-inbound-adapter.xml", this.getClass()); SourcePollingChannelAdapter zsetAdapterWithSingleScoreAndSynchronization = context.getBean("zsetAdapterWithSingleScoreAndSynchronization", SourcePollingChannelAdapter.class); SourcePollingChannelAdapter zsetAdapterNoScore = context.getBean("zsetAdapterNoScore", SourcePollingChannelAdapter.class); QueueChannel redisChannel = context.getBean("redisChannel", QueueChannel.class); QueueChannel otherRedisChannel = context.getBean("otherRedisChannel", QueueChannel.class); zsetAdapterNoScore.start(); Message<RedisZSet<Object>> message = (Message<RedisZSet<Object>>) redisChannel.receive(1000); assertNotNull(message); assertEquals(13, message.getPayload().size()); zsetAdapterNoScore.stop(); zsetAdapterWithSingleScoreAndSynchronization.start(); message = (Message<RedisZSet<Object>>) otherRedisChannel.receive(1000); assertNotNull(message); assertEquals(2, message.getPayload().rangeByScore(18, 18).size()); <START> Thread.sleep(1000); <END> zsetAdapterNoScore.start(); message = (Message<RedisZSet<Object>>) redisChannel.receive(1000); assertNotNull(message); assertEquals(11, message.getPayload().size()); zsetAdapterNoScore.stop(); context.close(); }</code><technical_language>I problem. instead of a hard wait (which long enough a busy CI server), while(n++ < 100 && message.getPayload().size() != 11) { Thread.sleep(100); }</technical_language>

Target:
public void testZsetInboundConfigurationWithSingleScoreAndSynchronization() throws Exception{ RedisConnectionFactory jcf = this.getConnectionFactoryForTest(); this.prepareZset(jcf); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("zset-inbound-adapter.xml", this.getClass()); SourcePollingChannelAdapter zsetAdapterWithSingleScoreAndSynchronization = context.getBean("zsetAdapterWithSingleScoreAndSynchronization", SourcePollingChannelAdapter.class); SourcePollingChannelAdapter zsetAdapterNoScore = context.getBean("zsetAdapterNoScore", SourcePollingChannelAdapter.class); QueueChannel redisChannel = context.getBean("redisChannel", QueueChannel.class); QueueChannel otherRedisChannel = context.getBean("otherRedisChannel", QueueChannel.class); zsetAdapterNoScore.start(); Message<RedisZSet<Object>> message = (Message<RedisZSet<Object>>) redisChannel.receive(1000); assertNotNull(message); assertEquals(13, message.getPayload().size()); zsetAdapterNoScore.stop(); zsetAdapterWithSingleScoreAndSynchronization.start(); message = (Message<RedisZSet<Object>>) otherRedisChannel.receive(1000); assertNotNull(message); assertEquals(2, message.getPayload().rangeByScore(18, 18).size()); zsetAdapterNoScore.start(); message = (Message<RedisZSet<Object>>) redisChannel.receive(1000); assertNotNull(message); int n = 0; while(n++ < 100 && message.getPayload().size() != 11) { Thread.sleep(100); } assertTrue(n < 100); zsetAdapterNoScore.stop(); context.close(); }
Source:
<code><START> public static void migrateRealm(final RealmConfiguration configuration, final RealmMigrationNeededException cause) <END> throws FileNotFoundException { BaseRealm.migrateRealm(configuration, null, new MigrationCallback() { @Override public void migrationComplete() { } }, cause); }</code><technical_language>This package private</technical_language>

Target:
private static void migrateRealm(final RealmConfiguration configuration, final RealmMigrationNeededException cause) throws FileNotFoundException { BaseRealm.migrateRealm(configuration, null, new MigrationCallback() { @Override public void migrationComplete() { } }, cause); }
Source:
<code>protected Predicate<Trigger> matchTriggerFor(final TriggerEvent event) { DockerEvent dockerEvent = (DockerEvent) event; String account = dockerEvent.getContent().getAccount(); String repository = dockerEvent.getContent().getRepository(); return trigger -> trigger.getType().equals(TRIGGER_TYPE) && <START> trigger.getRepository().equals(repository) && <END> trigger.getAccount().equals(account) && triggerPatternMatches(trigger, dockerEvent.getContent().getTag()); }</code><technical_language>return isMatchingTrigger(trigger) put logic in method</technical_language>

Target:
protected Predicate<Trigger> matchTriggerFor(final TriggerEvent event) { return trigger -> isMatchingTrigger((DockerEvent)event, trigger); }
Source:
<code>public void getExternalIdsFiltersSubstudyInExternalIdentifierInfo() { BridgeUtils.setRequestContext(new RequestContext.Builder() .withCallerSubstudies(ImmutableSet.of("substudyA", "substudyB")).build()); DynamoExternalIdentifier extId1 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId1"); extId1.setSubstudyId(null); DynamoExternalIdentifier extId2 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId2"); extId2.setSubstudyId("substudyA"); DynamoExternalIdentifier extId3 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId3"); extId3.setSubstudyId("substudyB"); DynamoExternalIdentifier extId4 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId4"); extId4.setSubstudyId("substudyC"); DynamoExternalIdentifier extId5 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId5"); extId5.setSubstudyId("substudyD"); setupQueryOfIds(ImmutableList.of(extId1, extId2, extId3, extId4, extId5)); ForwardCursorPagedResourceList<ExternalIdentifierInfo> externalIds = dao.getExternalIds(TEST_STUDY, null, 10, null, null); assertNull(externalIds.getItems().get(0).getSubstudyId()); assertEquals("substudyA", externalIds.getItems().get(1).getSubstudyId()); assertEquals("substudyB", externalIds.getItems().get(2).getSubstudyId()); assertNull(externalIds.getItems().get(3).getSubstudyId()); <START> assertNull(externalIds.getItems().get(4).getSubstudyId()); <END> }</code><technical_language>verify of external IDs, if some of substudies filtered out</technical_language>

Target:
public void getExternalIdsFiltersSubstudyInExternalIdentifierInfo() { BridgeUtils.setRequestContext(new RequestContext.Builder() .withCallerSubstudies(ImmutableSet.of("substudyA", "substudyB")).build()); DynamoExternalIdentifier extId1 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId1"); extId1.setSubstudyId(null); DynamoExternalIdentifier extId2 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId2"); extId2.setSubstudyId("substudyA"); DynamoExternalIdentifier extId3 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId3"); extId3.setSubstudyId("substudyB"); DynamoExternalIdentifier extId4 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId4"); extId4.setSubstudyId("substudyC"); DynamoExternalIdentifier extId5 = new DynamoExternalIdentifier(TestConstants.TEST_STUDY_IDENTIFIER, "extId5"); extId5.setSubstudyId("substudyD"); setupQueryOfIds(ImmutableList.of(extId1, extId2, extId3, extId4, extId5)); ForwardCursorPagedResourceList<ExternalIdentifierInfo> externalIds = dao.getExternalIds(TEST_STUDY, null, 10, null, null); assertExternalId(externalIds.getItems().get(0), "extId1", null); assertExternalId(externalIds.getItems().get(1), "extId2", "substudyA"); assertExternalId(externalIds.getItems().get(2), "extId3", "substudyB"); assertExternalId(externalIds.getItems().get(3), "extId4", null); assertExternalId(externalIds.getItems().get(4), "extId5", null); }
Source:
<code>public static void createFromResourceUrl(Context context, final URL resourceUrl, final AuthenticationParamCallback callback) { if (callback == null) { throw new IllegalArgumentException("callback"); } Logger.v(TAG, "createFromResourceUrl"); final Handler handler = new Handler(context.getMainLooper()); sThreadExecutor.submit(new Runnable() { @Override public void run() { HashMap<String, String> headers = new HashMap<String, String>(); headers.put(WebRequestHandler.HEADER_ACCEPT, WebRequestHandler.HEADER_ACCEPT_JSON); HttpWebResponse webResponse = null; <START> try { <END> webResponse = sWebRequest.sendGet(resourceUrl, headers); try { onCompleted(null, parseResponse(webResponse)); } catch (ResourceAuthenticationChallengeException exc) { onCompleted(exc, null); } } catch (IOException e) { onCompleted(e, null); } } void onCompleted(final Exception exception, final AuthenticationParameters param) { handler.post(new Runnable() { @Override public void run() { callback.onCompleted(exception, param); return; } }); } }); }</code><technical_language>I removal for checking getResponseException, wrapping IOException, idea :disappointed:</technical_language>

Target:
public static void createFromResourceUrl(Context context, final URL resourceUrl, final AuthenticationParamCallback callback) { if (callback == null) { throw new IllegalArgumentException("callback"); } Logger.v(TAG, "createFromResourceUrl"); final Handler handler = new Handler(context.getMainLooper()); sThreadExecutor.submit(new Runnable() { @Override public void run() { HashMap<String, String> headers = new HashMap<String, String>(); headers.put(WebRequestHandler.HEADER_ACCEPT, WebRequestHandler.HEADER_ACCEPT_JSON); final HttpWebResponse webResponse; try { webResponse = sWebRequest.sendGet(resourceUrl, headers); try { onCompleted(null, parseResponse(webResponse)); } catch (ResourceAuthenticationChallengeException exc) { onCompleted(exc, null); } } catch (IOException e) { onCompleted(e, null); } } void onCompleted(final Exception exception, final AuthenticationParameters param) { handler.post(new Runnable() { @Override public void run() { callback.onCompleted(exception, param); return; } }); } }); }
Source:
<code>public boolean matches(MethodParams params) { if (!params.match(parameters)) { return false; } @SuppressWarnings("unchecked") Class<? extends Message> firstParameter = (Class<? extends Message>) params.type(0); Optional<EntityVisibility> visibilityOption = EntityVisibility.of(firstParameter); <START> if(!visibilityOption.isPresent()) { <END> return false; } EntityVisibility visibility = visibilityOption.get(); if (visibility.canSubscribe()) { return true; } else { throw new InsufficientVisibilityError(TypeName.of(firstParameter), visibility); } }</code><technical_language>Please fix formatting</technical_language>

Target:
public boolean matches(MethodParams params) { if (!params.match(criteria)) { return false; } @SuppressWarnings("unchecked") Class<? extends Message> firstParameter = (Class<? extends Message>) params.type(0); Optional<EntityVisibility> visibilityOption = EntityVisibility.of(firstParameter); if (!visibilityOption.isPresent()) { return false; } EntityVisibility visibility = visibilityOption.get(); if (visibility.canSubscribe()) { return true; } else { throw new InsufficientVisibilityError(TypeName.of(firstParameter), visibility); } }
Source:
<code>public boolean requiresRedirect(RedirectionContext context, HttpClientResponse<O> response) { int statusCode = response.getStatus().code(); <START> return statusCode >= 301 && statusCode <= 308; <END> }</code><technical_language>304 is for HTTP caching, for redirect</technical_language>

Target:
public boolean requiresRedirect(RedirectionContext context, HttpClientResponse<O> response) { int statusCode = response.getStatus().code(); return Arrays.binarySearch(REDIRECTABLE_STATUS_CODES, statusCode) >= 0; }
Source:
<code>protected void done() { try { reportLaunchButton.setEnabled(true); reportToUser(get()); } catch (InterruptedException | ExecutionException exception) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error during html report generation : {}", exception.getMessage(), exception); } <START> List<String> reportException = new ArrayList<>(); <END> reportException.add(exception.getMessage()); reportToUser(reportException); } }</code><technical_language>add exceptions rootException? If not, Arrays.asList(exception.getMessage())</technical_language>

Target:
protected void done() { try { reportLaunchButton.setEnabled(true); reportToUser(get()); } catch (InterruptedException | ExecutionException exception) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error during html report generation: {}", exception.getMessage(), exception); } reportToUser(Arrays.asList(exception.getMessage())); } }
Source:
<code>public void startLogin(Activity activity) { String phone = null; for (AuthUI.IdpConfig idpConfig : mFlowParameters.providerInfo) { if (idpConfig.getProviderId().equals(AuthUI.PHONE_VERIFICATION_PROVIDER)) { <START> phone = idpConfig.getParams().getString(EXTRA_DEFAULT_PHONE); <END> } } activity.startActivityForResult( PhoneVerificationActivity.createIntent(activity, mFlowParameters, phone), RC_PHONE_FLOW); }</code><technical_language>consistent, statically import this instead AuthUI.EXTRA_DEFAULT_PHONE</technical_language>

Target:
public void startLogin(Activity activity) { String phone = null; for (AuthUI.IdpConfig idpConfig : mFlowParameters.providerInfo) { if (idpConfig.getProviderId().equals(AuthUI.PHONE_VERIFICATION_PROVIDER)) { phone = idpConfig.getParams().getString(AuthUI.EXTRA_DEFAULT_PHONE); } } activity.startActivityForResult( PhoneVerificationActivity.createIntent(activity, mFlowParameters, phone), RC_PHONE_FLOW); }
Source:
<code>public void testServiceUnderMaintenance() throws Exception { MockWebServer server = mockWebServer(); <START> for ( int i = 0; i <= MAX_RETRIES; i++ ) END> server.enqueue( new MockResponse().setResponseCode(503).setBody(payloadFromResource( "/maintenance-503.html" ))); ProfitBricksApi pbApi = api(server.getUrl("/")); DataCenterApi api = pbApi.dataCenterApi(); try { api.clearDataCenter("some-datacenter-id"); fail( "Request should have failed."); } catch (Exception ex){ assertTrue(ex instanceof RuntimeException, "Exception should be RuntimeException"); } finally { pbApi.close(); server.shutdown(); } }</code><technical_language>set Constants.PROPERTY_MAX_RETRIES property building context a if need 5 retries</technical_language>

Target:
public void testServiceUnderMaintenance() throws Exception { MockWebServer server = mockWebServer(); for (int i = 0; i <= MAX_RETRIES; i++) server.enqueue(new MockResponse().setResponseCode(503).setBody(payloadFromResource("/maintenance-503.html"))); ProfitBricksApi pbApi = api(server.getUrl("/")); DataCenterApi api = pbApi.dataCenterApi(); try { api.clearDataCenter("some-datacenter-id"); fail("Request should have failed."); } catch (Exception ex) { assertTrue(ex instanceof HttpResponseException, "Exception should be HttpResponseException"); } finally { pbApi.close(); server.shutdown(); } }
Source:
<code>public boolean filterLog(Map<String, String> filters, String logLine) { if (filters == null) { return true; } boolean result = true; for (Entry<String, String> entry : filters.entrySet()) { if (!logLine.matches( String.format(".*\\[%s=%s\\].*", entry.getKey(), entry.getValue()))) { <START> result = result & false; <END> } } return result; }</code><technical_language>simplified return false;</technical_language>

Target:
public boolean filterLog(Map<String, String> filters, String logLine) { if (filters == null) { return true; } boolean result = true; for (Entry<String, String> entry : filters.entrySet()) { if (!logLine.matches( String.format(".*\\[%s=%s\\].*", entry.getKey(), entry.getValue()))) { return false; } } return true; }
Source:
<code>static String createKey(Request data, StringBuilder builder) { if (data.uri != null) { String path = data.uri.toString(); builder.ensureCapacity(path.length() + KEY_PADDING); builder.append(path); } else { builder.ensureCapacity(KEY_PADDING); builder.append(data.resourceId); } builder.append('\n'); if (data.rotationDegrees != 0) { builder.append("rotation:").append(data.rotationDegrees); if (data.hasRotationPivot) { builder.append('@').append(data.rotationPivotX).append('x').append(data.rotationPivotY); } builder.append('\n'); } if (data.targetWidth != 0) { builder.append("resize:").append(data.targetWidth).append('x').append(data.targetHeight); builder.append('\n'); } if (data.centerCrop) { builder.append("centerCrop\n"); } else if (data.centerInside) { builder.append("centerInside\n"); } if (data.transformations != null) { for (int i = 0, count = data.transformations.size(); i < count; i++) { builder.append(data.transformations.get(i).key()); builder.append('\n'); } } if (data.density != 0) { <START> builder.append("density:").append(data.density); <END> builder.append('\n'); } return builder.toString(); }</code><technical_language>formatting 2 spaces</technical_language>

Target:
static String createKey(Request data, StringBuilder builder) { if (data.uri != null) { String path = data.uri.toString(); builder.ensureCapacity(path.length() + KEY_PADDING); builder.append(path); } else { builder.ensureCapacity(KEY_PADDING); builder.append(data.resourceId); } builder.append('\n'); if (data.rotationDegrees != 0) { builder.append("rotation:").append(data.rotationDegrees); if (data.hasRotationPivot) { builder.append('@').append(data.rotationPivotX).append('x').append(data.rotationPivotY); } builder.append('\n'); } if (data.targetWidth != 0) { builder.append("resize:").append(data.targetWidth).append('x').append(data.targetHeight); builder.append('\n'); } if (data.centerCrop) { builder.append("centerCrop\n"); } else if (data.centerInside) { builder.append("centerInside\n"); } if (data.transformations != null) { for (int i = 0, count = data.transformations.size(); i < count; i++) { builder.append(data.transformations.get(i).key()); builder.append('\n'); } } if (data.originalDensity != 0) { builder.append("originalDensity:").append(data.originalDensity); builder.append('\n'); } return builder.toString(); }
Source:
<code><START> public Guid getFirstQuotaForUserId(Guid storagePoolId, Guid adElementId) { <END> List<Quota> quotas = getQuotaDao().getQuotaByAdElementId(adElementId, storagePoolId, false); if (quotas.isEmpty()) { return getDefaultQuotaId(storagePoolId); } return quotas.get(0).getId(); }</code><technical_language>I if default quota is returned user permissions consume it. If not, quota returned</technical_language>

Target:
public Guid getFirstQuotaForUserId(Guid storagePoolId, Guid adElementId) { List<Quota> quotas = getQuotaDao().getQuotaByAdElementId(adElementId, storagePoolId, false); Guid defaultQuotaId = getDefaultQuotaId(storagePoolId); if (quotas.isEmpty()) { return defaultQuotaId; } for (Quota quota : quotas) { if (quota.getId().equals(defaultQuotaId)) { return defaultQuotaId; } } return quotas.get(0).getId(); }
Source:
<code>private CompletableFuture<Void> runFailureDetectorTask(PollReport pollReport) { return CompletableFuture.runAsync(() -> { if (!pollReport.getClusterState().isReady()){ log.info("Cluster state is not ready: {}", pollReport.getClusterState()); return; } correctWrongEpochs(pollReport); try { if (pollReport.isCurrentLayoutSlotUnFilled()) { handleFailure(Collections.emptySet(), pollReport); return; } if (!pollReport.getWrongEpochs().isEmpty()) { return; } } catch (Exception ex) { log.error("Can't fill slot. Poll report: {}", pollReport, ex); } boolean handleFailure = handleFailure(pollReport); <START> if (handleFailure) { <END> return; } handleSequencer(serverContext.copyManagementLayout()); handleHealing(pollReport, serverContext.copyManagementLayout()); }, failureDetectorWorker); }</code><technical_language>Ideally, reach this condition. If wrong epochs, corrected slot filled earlier. Anyways, a good idea this check</technical_language>

Target:
private CompletableFuture<DetectorTask> runFailureDetectorTask(PollReport pollReport) { if (!pollReport.getClusterState().isReady()) { log.info("Cluster state is not ready: {}", pollReport.getClusterState()); return DETECTOR_TASK_SKIPPED; } return CompletableFuture.supplyAsync(() -> { correctWrongEpochs(pollReport); try { if (pollReport.isCurrentLayoutSlotUnFilled()) { detectFailure(Collections.emptySet(), pollReport).get(); return DetectorTask.COMPLETED; } if (!pollReport.getWrongEpochs().isEmpty()) { log.debug("Wait for next iteration. Poll report contains wrong epochs: {}", pollReport.getWrongEpochs() ); return DetectorTask.COMPLETED; } } catch (Exception ex) { log.error("Can't fill slot. Poll report: {}", pollReport, ex); } DetectorTask healing = detectHealing(pollReport, serverContext.copyManagementLayout()); if (healing == DetectorTask.COMPLETED){ return DetectorTask.COMPLETED; } DetectorTask handleFailure = detectFailure(pollReport); if (handleFailure == DetectorTask.COMPLETED) { return DetectorTask.COMPLETED; } handleSequencer(serverContext.copyManagementLayout()); return DetectorTask.COMPLETED; }, failureDetectorWorker); }
Source:
<code>public CompletableFuture<Void> visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { Object key = command.getKey(); TypeConverter<Object, Object, Object, Object> converter = determineTypeConverter(command.getFlags()); if (ctx.isOriginLocal()) { command.setKey(converter.boxKey(key)); } ctx.onReturn((ctx1, command1, rv, throwable) -> { if (throwable != null) throw throwable; <START> if (rv == null) { <END> return null; } if (needsUnboxing(ctx1)) { return CompletableFuture.completedFuture(converter.unboxValue(rv)); } return null; }); return ctx.continueInvocation(); }</code><technical_language>IMO, merge ifs if (rv == null || !needsUnboxing(ctx1)) return null;</technical_language>

Target:
public CompletableFuture<Void> visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { Object key = command.getKey(); TypeConverter<Object, Object, Object, Object> converter = determineTypeConverter(command.getFlags()); if (ctx.isOriginLocal()) { command.setKey(converter.boxKey(key)); } return ctx.onReturn((rCtx, rCommand, rv, throwable) -> { if (throwable != null) throw throwable; if (rv == null || !needsUnboxing(rCtx)) { return null; } return CompletableFuture.completedFuture(converter.unboxValue(rv)); }); }
Source:
<code>private void recalculatePercent() { <START> int percent = (int) (totalRead * 100 / size); <END> if ( percent > lastReportedPercent ) { lastReportedPercent = percent; listener.onProgress( percent ); } }</code><technical_language>i add additional check more 100 :)</technical_language>

Target:
private void recalculatePercent() { int percent = (int) (totalRead * 100 / size); if ( percent > 100 ) { percent = 100; } if ( percent < 0 ) { percent = 0; } if ( percent > lastReportedPercent ) { lastReportedPercent = percent; listener.onProgress( percent ); } }
Source:
<code>protected void registerItems(RuntimeEngine runtime) { RegisterableItemsFactory factory = environment.getRegisterableItemsFactory(); KieSession ksession = ((InternalRuntimeEngine) runtime).internalGetKieSession(); Map<String, WorkItemHandler> handlers = factory.getWorkItemHandlers(runtime); for (Entry<String, WorkItemHandler> entry : handlers.entrySet()) { ksession.getWorkItemManager().registerWorkItemHandler(entry.getKey(), entry.getValue()); } Map<String, Object> globals = factory.getGlobals(runtime); for (Entry<String, Object> entry : globals.entrySet()) { ksession.setGlobal(entry.getKey(), entry.getValue()); } List<ProcessEventListener> processListeners = factory.getProcessEventListeners(runtime); for (ProcessEventListener listener : processListeners) { ksession.addEventListener(listener); } List<AgendaEventListener> agendaListeners = factory.getAgendaEventListeners(runtime); for (AgendaEventListener listener : agendaListeners) { ksession.addEventListener(listener); } if (factory instanceof SimpleRegisterableItemsFactory) { List<NotificationListener> additionalNotificationListener = ((SimpleRegisterableItemsFactory) factory).getNotificationListeners(runtime); <START> NotificationListenerManager.get().registerAdditionalNotificationListener(additionalNotificationListener); <END> } List<RuleRuntimeEventListener> wmListeners = factory.getRuleRuntimeEventListeners(runtime); for (RuleRuntimeEventListener listener : wmListeners) { ksession.addEventListener(listener); } }</code><technical_language>@elguardian this enough changes in kie-spring-boot modules call NotificationListenerManager.get().registerAdditionalNotificationListener there</technical_language>

Target:
protected void registerItems(RuntimeEngine runtime) { RegisterableItemsFactory factory = environment.getRegisterableItemsFactory(); KieSession ksession = ((InternalRuntimeEngine) runtime).internalGetKieSession(); Map<String, WorkItemHandler> handlers = factory.getWorkItemHandlers(runtime); for (Entry<String, WorkItemHandler> entry : handlers.entrySet()) { ksession.getWorkItemManager().registerWorkItemHandler(entry.getKey(), entry.getValue()); } Map<String, Object> globals = factory.getGlobals(runtime); for (Entry<String, Object> entry : globals.entrySet()) { ksession.setGlobal(entry.getKey(), entry.getValue()); } List<ProcessEventListener> processListeners = factory.getProcessEventListeners(runtime); for (ProcessEventListener listener : processListeners) { ksession.addEventListener(listener); } List<AgendaEventListener> agendaListeners = factory.getAgendaEventListeners(runtime); for (AgendaEventListener listener : agendaListeners) { ksession.addEventListener(listener); } List<RuleRuntimeEventListener> wmListeners = factory.getRuleRuntimeEventListeners(runtime); for (RuleRuntimeEventListener listener : wmListeners) { ksession.addEventListener(listener); } }
Source:
<code>T resolve() { synchronized (m_lock) { if (m_unresolvedPath != null) { <START> m_value = (T) getCatalog().m_operator.getItemForPath(m_unresolvedPath); <END> m_unresolvedPath = null; } return m_value; } }</code><technical_language>getOperator() in place of m_operator</technical_language>

Target:
T resolve() { synchronized (m_lock) { if (m_unresolvedPath != null) { m_value = (T) getCatalog().getCatalogOperator().getItemForPath(m_unresolvedPath); m_unresolvedPath = null; } return m_value; } }
Source:
<code>public void prepareTestProject() throws Exception { projectServiceClient.importProject( ws.getId(), Paths.get( getClass() .getResource("/projects/plugins/JavaTestRunnerPlugin/" + JUNIT4_PROJECT) .toURI()), JUNIT4_PROJECT, ProjectTemplates.CONSOLE_JAVA_SIMPLE); ide.open(ws); ide.waitOpenedWorkspaceIsReadyToUse(); projectExplorer.waitItem(JUNIT4_PROJECT); <START> runCompileCommand(); <END> notifications.waitProgressPopupPanelClose(); consoles.dragConsolesInDefinePosition(VALUE_OF_SHIFTING_CONSOLES_ALONG_X_AXIS); }</code><technical_language>you, please, explain, verification command palette removed</technical_language>

Target:
public void prepareTestProject() throws Exception { CompileCommand compileCommand = new CompileCommand(); testCommandServiceClient.createCommand(DtoConverter.asDto(compileCommand), ws.getId()); projectServiceClient.importProject( ws.getId(), Paths.get( getClass() .getResource("/projects/plugins/JavaTestRunnerPlugin/" + JUNIT4_PROJECT) .toURI()), JUNIT4_PROJECT, ProjectTemplates.CONSOLE_JAVA_SIMPLE); ide.open(ws); loader.waitOnClosed(); projectExplorer.waitItem(JUNIT4_PROJECT); try { runCompileCommandByPallete(compileCommand); } catch (TimeoutException ex) { fail("Known random failure <LINK_0>"); } notifications.waitProgressPopupPanelClose(); consoles.dragConsolesInDefinePosition(VALUE_OF_SHIFTING_CONSOLES_ALONG_X_AXIS); }
Source:
<code>private <T> QueryRunner<T> makeRunner(Query<T> query, QueryRunner<T> baseClientRunner) { QueryToolChest<T, Query<T>> toolChest = warehouse.getToolChest(query); PostProcessingOperator<T> postProcessing = objectMapper.convertValue( query.<String>getContextValue("postProcessing"), new TypeReference<PostProcessingOperator<T>>() { } ); <START> return new ResultLevelCachingQueryRunner<>( <END> new FluentQueryRunnerBuilder<>(toolChest) .create( new SetAndVerifyContextQueryRunner( serverConfig, new RetryQueryRunner<>( baseClientRunner, retryConfig, objectMapper ) ) ) .applyPreMergeDecoration() .mergeResults() .applyPostMergeDecoration() .emitCPUTimeMetric(emitter) .postProcess(postProcessing), toolChest, query, objectMapper, cache, cacheConfig ); }</code><technical_language>this feels violates fluent workflow, is a this work inline fluent query runner</technical_language>

Target:
private <T> QueryRunner<T> makeRunner(Query<T> query, QueryRunner<T> baseClientRunner) { QueryToolChest<T, Query<T>> toolChest = warehouse.getToolChest(query); return new ResultLevelCachingQueryRunner<>(makeRunner(query, baseClientRunner, toolChest), toolChest, query, objectMapper, cache, cacheConfig); }
Source:
<code>public void registerProtofiles(String...classPathResources) throws Exception { <START> for(String classPathResource: classPathResources) { <END> String fileName = Paths.get(classPathResource).getFileName().toString(); String contents = Util.read(this.getClass().getResourceAsStream(classPathResource)); clusterRegistry.put(REGISTRY_SCOPE, fileName, contents); } compile(); }</code><technical_language>space</technical_language>

Target:
public void registerProtofiles(String... classPathResources) throws Exception { FileDescriptorSource fileDescriptorSource = getFileDescriptorSource(); for (String classPathResource : classPathResources) { String fileName = Paths.get(classPathResource).getFileName().toString(); String contents = Util.read(this.getClass().getResourceAsStream(classPathResource)); fileDescriptorSource.addProtoFile(fileName, contents); } clusterRegistry.put(REGISTRY_SCOPE, REGISTRY_KEY, fileDescriptorSource); }
Source:
<code>public PersistentModelBuilder(PersistentModel previous) { this.previous = Preconditions.checkNotNull(previous); <START> this.buildDir = previous.getBuildDir(); <END> this.subprojectPaths = previous.getSubprojectPaths(); this.classpath = previous.getClasspath(); this.derivedResources = previous.getDerivedResources(); this.linkedResources = previous.getLinkedResources(); }</code><technical_language>assignments need guarded if(previous.present)</technical_language>

Target:
public PersistentModelBuilder(PersistentModel previous) { this.previous = Preconditions.checkNotNull(previous); if (previous.isPresent()) { this.buildDir = previous.getBuildDir(); this.subprojectPaths = previous.getSubprojectPaths(); this.classpath = previous.getClasspath(); this.derivedResources = previous.getDerivedResources(); this.linkedResources = previous.getLinkedResources(); } }
Source:
<code>protected void executeCommand() { final VDS vds = getVds(); try (EngineLock monitoringLock = acquireMonitorLock()) { ExecutionHandler.updateSpecificActionJobCompleted(vds.getId(), VdcActionType.MaintenanceVds, false); setSucceeded(setVdsStatus(VDSStatus.Unassigned).getSucceeded()); if (getSucceeded()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { List<Network> networks = getNetworkDao().getAllForCluster(vds.getVdsGroupId()); for (Network net : networks) { NetworkClusterHelper.setStatus(vds.getVdsGroupId(), net); } return null; } }); if (vds.getHighlyAvailableIsConfigured()) { SetHaMaintenanceModeVDSCommandParameters param = new SetHaMaintenanceModeVDSCommandParameters(vds, HaMaintenanceMode.LOCAL, false); if (!runVdsCommand(VDSCommandType.SetHaMaintenanceMode, param).getSucceeded()) { haMaintenanceFailed = true; } } } } logMonitorLockReleased("Activate"); if (vds.getVdsGroupSupportsGlusterService()) { List<String> <START> serviceList = <END> new ArrayList<>(); serviceList.add("glusterd"); runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vds.getId(), serviceList, "restart")); } }</code><technical_language>s/serviceList/glusterServices if this list modified, replace inline Arrays.asList("glusterd")</technical_language>

Target:
protected void executeCommand() { final VDS vds = getVds(); try (EngineLock monitoringLock = acquireMonitorLock()) { ExecutionHandler.updateSpecificActionJobCompleted(vds.getId(), VdcActionType.MaintenanceVds, false); setSucceeded(setVdsStatus(VDSStatus.Unassigned).getSucceeded()); if (getSucceeded()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { List<Network> networks = getNetworkDao().getAllForCluster(vds.getVdsGroupId()); for (Network net : networks) { NetworkClusterHelper.setStatus(vds.getVdsGroupId(), net); } return null; } }); if (vds.getHighlyAvailableIsConfigured()) { SetHaMaintenanceModeVDSCommandParameters param = new SetHaMaintenanceModeVDSCommandParameters(vds, HaMaintenanceMode.LOCAL, false); if (!runVdsCommand(VDSCommandType.SetHaMaintenanceMode, param).getSucceeded()) { haMaintenanceFailed = true; } } } } logMonitorLockReleased("Activate"); if (vds.getVdsGroupSupportsGlusterService()) { runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vds.getId(), Arrays.asList("glusterd"), "restart")); } }