auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void callServiceAndGetMetrics() throws Exception { verifier.verifyExists(); MetricsAreaFragment wsrMetricsArea = wsePage.getWebServiceRequestMetricsArea(); double requests = wsrMetricsArea.getMetricNumber(NUMBER_OF_REQUEST); assertEquals(0.0, requests); verifier.verifyAttribute("request-count", 0L); callWebservice(false); wsePage.refreshStats(); wsrMetricsArea = wsePage.getWebServiceRequestMetricsArea(); requests = wsrMetricsArea.getMetricNumber(NUMBER_OF_REQUEST); assertEquals(3.0, requests); verifier.verifyAttribute("request-count", 3L); double responses = wsrMetricsArea.getMetricNumber(RESPONSES); assertEquals(3.0, responses); verifier.verifyAttribute("response-count", 3L); double faults = wsrMetricsArea.getMetricNumber(FAULTS); assertEquals(0.0, faults); verifier.verifyAttribute("fault-count", 0L); <START> wsePage.navigateInDeploymentsMenu(); <END> Graphene.createPageFragment(MBUITreeNavigation.class, wsePage.getContentRoot()) .step("subsystem") .step("webservices") .step("endpoint") .step("test:TestService") .navigateToTreeItem() .clickLabel(); mbuiNavigation.checkAndAssertMBuiValueOf("Request count", "3"); mbuiNavigation.checkAndAssertMBuiValueOf("Response count", "3"); mbuiNavigation.checkAndAssertMBuiValueOf("Fault count", "0"); }</code><technical_language>I suggest mark org.jboss.hal.testsuite.mbui.MbuiNavigation.MbuiNavigation(WebDriver) deprecated</technical_language>

Target:
public void callServiceAndGetMetrics() throws Exception { verifier.verifyExists(); MetricsAreaFragment wsrMetricsArea = wsePage.getWebServiceRequestMetricsArea(); double requests = wsrMetricsArea.getMetricNumber(NUMBER_OF_REQUEST); assertEquals(0.0, requests); verifier.verifyAttribute("request-count", 0L); callWebservice(false); wsePage.refreshStats(); wsrMetricsArea = wsePage.getWebServiceRequestMetricsArea(); requests = wsrMetricsArea.getMetricNumber(NUMBER_OF_REQUEST); assertEquals(3.0, requests); verifier.verifyAttribute("request-count", 3L); double responses = wsrMetricsArea.getMetricNumber(RESPONSES); assertEquals(3.0, responses); verifier.verifyAttribute("response-count", 3L); double faults = wsrMetricsArea.getMetricNumber(FAULTS); assertEquals(0.0, faults); verifier.verifyAttribute("fault-count", 0L); wsePage.navigateInDeploymentsMenu(); treeNavigationPage.treeNavigation() .step("subsystem") .step("webservices") .step("endpoint") .step("test:TestService") .navigateToTreeItem() .clickLabel(); FormItemTableFragment table = treeNavigationPage.formItemTable(); assertEquals(table.getValueOf("Request count"), "3"); assertEquals(table.getValueOf("Response count"), "3"); assertEquals(table.getValueOf("Fault count"), "0"); }
Source:
<code>public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) { Long id = parseTargetId(targetId); if (permission == ProfilePermission.EDIT_OWN_PROFILE && ((JCUser) authentication.getPrincipal()).getId() != id) { return false; } <START> JtalksPermission jtalksPermission; <END> ObjectIdentity objectIdentity = aclUtil.createIdentity(id, targetType); Sid sid = sidFactory.createPrincipal(authentication); List<AccessControlEntry> aces; List<GroupAce> controlEntries; if (permission instanceof Permission) { jtalksPermission = (JtalksPermission) permission; } else { jtalksPermission = getPermission(permission); } try { aces = ExtendedMutableAcl.castAndCreate(mutableAclService.readAclById(objectIdentity)).getEntries(); controlEntries = aclManager.getGroupPermissionsFilteredByPermissionOn(objectIdentity, jtalksPermission); } catch (NotFoundException nfe) { aces = new ArrayList<>(); controlEntries = new ArrayList<>(); } if (isRestrictedForSid(sid, aces, jtalksPermission) || isRestrictedForGroup(controlEntries, authentication, jtalksPermission) || isRestrictedPersonalPermission(authentication, jtalksPermission)) { return false; } else if (isAllowedForSid(sid, aces, jtalksPermission) || isAllowedForGroup(controlEntries, authentication, jtalksPermission) || isAllowedPersonalPermission(authentication, jtalksPermission)) { return true; } return false; }</code><technical_language>One-liner nicer: JtalksPermission jtalksPermission = permission instanceof Permission ? permission : getPermission(permission);</technical_language>

Target:
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) { Long id = parseTargetId(targetId); if (permission == ProfilePermission.EDIT_OWN_PROFILE && ((JCUser) authentication.getPrincipal()).getId() != id) { return false; } JtalksPermission jtalksPermission = permission instanceof Permission ? (JtalksPermission) permission : getPermission(permission); ObjectIdentity objectIdentity = aclUtil.createIdentity(id, targetType); Sid sid = sidFactory.createPrincipal(authentication); List<AccessControlEntry> aces; List<GroupAce> controlEntries; try { aces = ExtendedMutableAcl.castAndCreate(mutableAclService.readAclById(objectIdentity)).getEntries(); controlEntries = aclManager.getGroupPermissionsFilteredByPermissionOn(objectIdentity, jtalksPermission); } catch (NotFoundException nfe) { aces = new ArrayList<>(); controlEntries = new ArrayList<>(); } if (jtalksPermission instanceof ProfilePermission && authentication.getPrincipal() instanceof JCUser){ if (isRestrictedPersonalPermission(authentication, jtalksPermission)) return false; else if (isAllowedPersonalPermission(authentication, jtalksPermission)) return true; } if (isRestrictedForSid(sid, aces, jtalksPermission) || isRestrictedForGroup(controlEntries, authentication, jtalksPermission)) { return false; } else if (isAllowedForSid(sid, aces, jtalksPermission) || isAllowedForGroup(controlEntries, authentication, jtalksPermission)) { return true; } return false; }
Source:
<code>private void renderTagHeader( ReaderTag currentTag, TagHeaderViewHolder tagHolder, Boolean isFollowButtonEnabled ) { if (currentTag == null) { return; } Function0<Unit> onFollowButtonClicked = () -> { toggleFollowButton(tagHolder.itemView.getContext(), currentTag, tagHolder); return Unit.INSTANCE; }; ReaderTagHeaderUiState uiState = new ReaderTagHeaderUiState( currentTag.getLabel(), new FollowButtonUiState( onFollowButtonClicked, ReaderTagTable.isFollowedTagName(currentTag.getTagSlug()), isFollowButtonEnabled, <START> mAccountStore.hasAccessToken() <END> ) ); tagHolder.onBind(uiState); }</code><technical_language>Tag header changes released RI FF flag removed [here](<LINK_0> time allow tags locally for logged out users. remove this access token check now</technical_language>

Target:
private void renderTagHeader( ReaderTag currentTag, TagHeaderViewHolder tagHolder, Boolean isFollowButtonEnabled ) { if (currentTag == null) { return; } Function0<Unit> onFollowButtonClicked = () -> { toggleFollowButton(tagHolder.itemView.getContext(), currentTag, tagHolder); return Unit.INSTANCE; }; ReaderTagHeaderUiState uiState = new ReaderTagHeaderUiState( currentTag.getLabel(), new FollowButtonUiState( onFollowButtonClicked, ReaderTagTable.isFollowedTagName(currentTag.getTagSlug()), isFollowButtonEnabled ) ); tagHolder.onBind(uiState); }
Source:
<code>private boolean initVirtResources() { if (InitializeStorage()) { processFence(); processStoragePoolStatus(); runUpdateMomPolicy(getVdsGroup(), getVds()); } else { Map<String, String> customLogValues = new HashMap<>(); customLogValues.put("StoragePoolName", getStoragePoolName()); if (problematicDomains != null) { StringBuilder domainNames = new StringBuilder(); for (StorageDomainStatic domain : problematicDomains) { if (domainNames.length() > 0) { domainNames.append(", "); } domainNames.append(domain.getStorageName()); <START> } <END> customLogValues.put("StorageDomainNames", domainNames.toString()); } setNonOperational(NonOperationalReason.STORAGE_DOMAIN_UNREACHABLE, customLogValues); return false; } return true; }</code><technical_language>This entire block (read: should) replaced Entities.objectNames</technical_language>

Target:
private boolean initVirtResources() { if (InitializeStorage()) { processFence(); processStoragePoolStatus(); runUpdateMomPolicy(getVdsGroup(), getVds()); } else { Map<String, String> customLogValues = new HashMap<>(); customLogValues.put("StoragePoolName", getStoragePoolName()); if (problematicDomains != null && !problematicDomains.isEmpty()) { customLogValues.put("StorageDomainNames", StringUtils.join(Entities.objectNames(problematicDomains), ',')); } setNonOperational(NonOperationalReason.STORAGE_DOMAIN_UNREACHABLE, customLogValues); return false; } return true; }
Source:
<code>public void setup() throws Exception { config = mock(Config.class); taskContext = mock(TaskContextImpl.class); runner = mock(ApplicationRunner.class); Serde storeKeySerde = new TimeSeriesKeySerde(new IntegerSerde()); Serde storeValSerde = new IntegerEnvelopeSerde(); when(taskContext.getSystemStreamPartitions()).thenReturn(ImmutableSet .of(new SystemStreamPartition("kafka", "integers", new Partition(0)))); when(taskContext.getMetricsRegistry()).thenReturn(new MetricsRegistryMap()); <START> when(taskContext.getStore("null-null-window-w1")).thenReturn(new TestInMemoryStore<>(storeKeySerde, storeValSerde)); <END> when(runner.getStreamSpec("integers")).thenReturn(new StreamSpec("integers", "integers", "kafka")); }</code><technical_language>nit: nice set actual mock strings instead of null here</technical_language>

Target:
public void setup() throws Exception { config = mock(Config.class); when(config.get(JobConfig.JOB_NAME())).thenReturn("jobName"); when(config.get(eq(JobConfig.JOB_ID()), anyString())).thenReturn("jobId"); taskContext = mock(TaskContextImpl.class); runner = mock(ApplicationRunner.class); Serde storeKeySerde = new TimeSeriesKeySerde(new IntegerSerde()); Serde storeValSerde = new IntegerEnvelopeSerde(); when(taskContext.getSystemStreamPartitions()).thenReturn(ImmutableSet .of(new SystemStreamPartition("kafka", "integers", new Partition(0)))); when(taskContext.getMetricsRegistry()).thenReturn(new MetricsRegistryMap()); when(taskContext.getStore("jobName-jobId-window-w1")) .thenReturn(new TestInMemoryStore<>(storeKeySerde, storeValSerde)); when(runner.getStreamSpec("integers")).thenReturn(new StreamSpec("integers", "integers", "kafka")); }
Source:
<code>public PublicKey get() { try { <START> final String keyValue = System.getenv().get(SIGNATURE_PUBLIC_KEY_ENV); <END> if (Strings.isNullOrEmpty(keyValue)) { throw new IllegalStateException("Signature key for token validation is not found"); } final String algorithm = System.getenv().get(SIGNATURE_ALGORITHM_ENV); if (Strings.isNullOrEmpty(algorithm)) { throw new IllegalStateException("Algorithm for signature key is not defined"); } final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(keyValue)); return KeyFactory.getInstance(algorithm).generatePublic(keySpec); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { throw new IllegalStateException(ex.getCause()); } }</code><technical_language>inject guice</technical_language>

Target:
public PublicKey get() { try { return KeyFactory.getInstance(algorithm) .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey))); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { throw new IllegalStateException(ex.getCause()); } }
Source:
<code>public static SWTBotTreeItem getTreeItem(SWTBotTreeItem[] treeElements, String searchedLabel, boolean enabledItemsOnly, boolean expandItems) { SWTBotTreeItem treeItem = null; if (treeElements != null) { for (SWTBotTreeItem item : treeElements) { String text = item.getText(); if ((!enabledItemsOnly || item.isEnabled()) && <START> Objects.equal(searchedLabel, <END> text)) { treeItem = item; } else { boolean oldExpanded = item.isExpanded(); if (expandItems) { item.expand(); } treeItem = getTreeItem(item.getItems(), searchedLabel, enabledItemsOnly, expandItems); if (treeItem == null && expandItems && !oldExpanded) { item.collapse(); } } if (treeItem != null) { break; } } } return treeItem; }</code><technical_language>Objects.equals java.util instead of com.google.common.base.Objects</technical_language>

Target:
public static SWTBotTreeItem getTreeItem(SWTBotTreeItem[] treeElements, String searchedLabel, boolean enabledItemsOnly, boolean expandItems) { SWTBotTreeItem treeItem = null; if (treeElements != null) { for (SWTBotTreeItem item : treeElements) { String text = item.getText(); if ((!enabledItemsOnly || item.isEnabled()) && Objects.equals(searchedLabel, text)) { treeItem = item; } else { boolean oldExpanded = item.isExpanded(); if (expandItems) { item.expand(); } treeItem = getTreeItem(item.getItems(), searchedLabel, enabledItemsOnly, expandItems); if (treeItem == null && expandItems && !oldExpanded) { item.collapse(); } } if (treeItem != null) { break; } } } return treeItem; }
Source:
<code>public void testExistingTargetFilePlainOutput() throws Exception { exit.checkAssertionAfterwards(() -> { final LocalizedMessage auditStartMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, AUDIT_STARTED_MESSAGE, null, null, getClass(), null); final LocalizedMessage auditFinishMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, AUDIT_FINISHED_MESSAGE, <START> null, null, getClass(), null); <END> assertEquals(String.format(Locale.ROOT, auditStartMessage.getMessage() + "%n" + auditFinishMessage.getMessage() + "%n"), systemOut.getLog()); assertEquals("", systemErr.getLog()); }); Main.main("-c", getPath("config-classname.xml"), "-f", "plain", getPath("InputMain.java")); }</code><technical_language>@subkrish , please move final LocalizedMessage auditStartMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, AUDIT_STARTED_MESSAGE, null, null, getClass(), null); final LocalizedMessage auditFinishMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, AUDIT_FINISHED_MESSAGE, null, null, getClass(), null); class fields, locallized messages is changeable, a constants</technical_language>

Target:
public void testExistingTargetFilePlainOutput() throws Exception { exit.checkAssertionAfterwards(() -> { assertEquals(auditStartMessage.getMessage() + EOL + auditFinishMessage.getMessage() + EOL, systemOut.getLog()); assertEquals("", systemErr.getLog()); }); Main.main("-c", getPath("config-classname.xml"), "-f", "plain", getPath("InputMain.java")); }
Source:
<code>public static void threadDumpStartup() throws Exception { if (!logStartupPerformanceIssues) return; final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); final File f = new File(getRootDirectory(), "/startup-threadDump" + dateFormat.format(new Date()) + ".txt"); if (!f.exists()) { try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } Thread t = new Thread("Support core plugin startup diagnostics") { @Override public void run() { while (true) { final Jenkins jenkins = Jenkins.getInstanceOrNull(); if (jenkins == null || jenkins.getInitLevel() != InitMilestone.COMPLETED) { continue; } try (PrintStream ps = new PrintStream(new FileOutputStream(f, true), false, "UTF-8")) { ps.println("=== Thread dump at " + new Date() + " ==="); ThreadDumps.threadDump(ps); ps.flush(); TimeUnit.SECONDS.sleep(secondsPerThreadDump); } catch (FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); <START> Thread.currentThread().interrupt(); <END> } } } }; t.start(); }</code><technical_language>Is necessary do interrupt end of finally block? This generate a thread dump start immediately kill thread. if exceptions thrown display message, do a return;</technical_language>

Target:
public static void threadDumpStartup() throws Exception { if (!logStartupPerformanceIssues) return; final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); final File f = new File(getRootDirectory(), "/startup-threadDump" + dateFormat.format(new Date()) + ".txt"); if (!f.exists()) { try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } Thread t = new Thread("Support core plugin startup diagnostics") { @Override public void run() { try { while (true) { final Jenkins jenkins = Jenkins.getInstanceOrNull(); if (jenkins == null || jenkins.getInitLevel() != InitMilestone.COMPLETED) { continue; } try (PrintStream ps = new PrintStream(new FileOutputStream(f, true), false, "UTF-8")) { ps.println("=== Thread dump at " + new Date() + " ==="); ThreadDumps.threadDump(ps); ps.flush(); TimeUnit.SECONDS.sleep(secondsPerThreadDump); } catch (FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } }; t.start(); }
Source:
<code>private void handleInvocationStart(TestRecord startInvocationProto) { Any anyDescription = startInvocationProto.getDescription(); if (!anyDescription.is(Context.class)) { throw new RuntimeException("Expected Any description of type Context"); } try { IInvocationContext context = InvocationContext.fromProto(anyDescription.unpack(Context.class)); <START> if (mReportInvocation) { <END> mListener.invocationStarted(context); } } catch (InvalidProtocolBufferException e) { throw new RuntimeException(e); } }</code><technical_language>this if check initializing context. in line 158. like: if (mReportInvocation) { Log... return; }</technical_language>

Target:
private void handleInvocationStart(TestRecord startInvocationProto) { if (!mReportInvocation) { CLog.d("Skipping invocation start reporting."); return; } Any anyDescription = startInvocationProto.getDescription(); if (!anyDescription.is(Context.class)) { throw new RuntimeException("Expected Any description of type Context"); } try { IInvocationContext context = InvocationContext.fromProto(anyDescription.unpack(Context.class)); mListener.invocationStarted(context); } catch (InvalidProtocolBufferException e) { throw new RuntimeException(e); } }
Source:
<code>protected boolean validateSpaceRequirements() { int numOfVms = getParameters().getVmsCount(); Collection<DiskImage> diskDummies = ImagesHandler.getDisksDummiesForStorageAllocations(diskInfoDestinationMap.values()); Collection<DiskImage> disks = new HashSet<>(); for (int i = 0; i < numOfVms; ++i) { disks.addAll(diskDummies); <START> } <END> Guid spId = getVmTemplate().getStoragePoolId(); Set<Guid> sdIds = destStorages.keySet(); MultipleStorageDomainsValidator storageDomainsValidator = getStorageDomainsValidator(spId, sdIds); return validate(storageDomainsValidator.allDomainsWithinThresholds()) && validate(storageDomainsValidator.allDomainsHaveSpaceForNewDisks(disks)); }</code><technical_language>this part - I pool 3 VMs edit pool add 3 additional VMs. This code check if enough space for 6 VMs disks of 3 VMs exist, no</technical_language>

Target:
protected boolean validateSpaceRequirements() { int numOfVms = getParameters().getVmsCount(); Collection<DiskImage> diskDummies = ImagesHandler.getDisksDummiesForStorageAllocations(diskInfoDestinationMap.values()); Collection<DiskImage> disks = new ArrayList<>(numOfVms * diskDummies.size()); for (int i = 0; i < numOfVms; ++i) { disks.addAll(diskDummies); } Guid spId = getVmTemplate().getStoragePoolId(); Set<Guid> sdIds = destStorages.keySet(); MultipleStorageDomainsValidator storageDomainsValidator = getStorageDomainsValidator(spId, sdIds); return validate(storageDomainsValidator.allDomainsWithinThresholds()) && validate(storageDomainsValidator.allDomainsHaveSpaceForNewDisks(disks)); }
Source:
<code>public BitCache writeResponseToCache(Context c) throws IOException { BitCache cache = null; <START> try (InputStream input = getInputStream()) { <END> cache = BitCacheFactory.getCache(new AndroidCacheDirSetup(c), dataSizeGuess); cache.initializeCache(); OutputStream cacheOut = cache.getCacheStream(); Log.i("commcare-network", "Starting network read, expected content size: " + dataSizeGuess + "b"); StreamsUtil.writeFromInputToOutputNew(new BufferedInputStream(input), cacheOut, new StreamsUtil.StreamReadObserver() { long lastOutput = 0; static final int PERCENT_INCREASE_THRESHOLD = 4; @Override public void notifyCurrentCount(long bytesRead) { boolean notify; if (lastOutput == 0) { Log.i("commcare-network", "First" + bytesRead + " bytes received from network: "); } if (dataSizeGuess == -1) { lastOutput = bytesRead; return; } int percentIncrease = (int)(((bytesRead - lastOutput) * 100) / dataSizeGuess); notify = percentIncrease > PERCENT_INCREASE_THRESHOLD; if (notify && task != null) { lastOutput = bytesRead; int totalRead = (int)(((bytesRead) * 100) / dataSizeGuess); task.reportDownloadProgress(totalRead); } } }); return cache; } catch (IOException e) { cache.release(); throw e; } }</code><technical_language>it. yeah I do globalizing variables for reason avoided. HttpUtils.parseUserVisibleError called for a specific response code 406 in code , behaviour retained</technical_language>

Target:
public BitCache writeResponseToCache(Context c) throws IOException { BitCache cache = null; try (InputStream input = getInputStream()) { final long dataSizeGuess = ModernHttpRequester.getContentLength(response); cache = BitCacheFactory.getCache(new AndroidCacheDirSetup(c), dataSizeGuess); cache.initializeCache(); OutputStream cacheOut = cache.getCacheStream(); Log.i("commcare-network", "Starting network read, expected content size: " + dataSizeGuess + "b"); StreamsUtil.writeFromInputToOutputNew(new BufferedInputStream(input), cacheOut, new StreamsUtil.StreamReadObserver() { long lastOutput = 0; static final int PERCENT_INCREASE_THRESHOLD = 4; @Override public void notifyCurrentCount(long bytesRead) { boolean notify; if (lastOutput == 0) { Log.i("commcare-network", "First" + bytesRead + " bytes received from network: "); } if (dataSizeGuess == -1) { lastOutput = bytesRead; return; } int percentIncrease = (int)(((bytesRead - lastOutput) * 100) / dataSizeGuess); notify = percentIncrease > PERCENT_INCREASE_THRESHOLD; if (notify && task != null) { lastOutput = bytesRead; int totalRead = (int)(((bytesRead) * 100) / dataSizeGuess); task.reportDownloadProgress(totalRead); } } }); return cache; } catch (IOException e) { cache.release(); throw e; } }
Source:
<code>private Flowable<List<MarshallableEntry<? extends K, ? extends V>>> createBatchFlowable(PreparedStatement upsertBatch, Publisher<MarshallableEntry<? extends K, ? extends V>> publisher) { return Flowable.fromPublisher(publisher) .doOnNext(entry -> { String keyStr = key2Str(entry.getKey()); prepareUpsertStatement(entry, keyStr, getSegment(entry), upsertBatch); upsertBatch.addBatch(); }) .buffer(configuration.maxBatchSize()) .doOnNext(i -> { upsertBatch.executeBatch(); upsertBatch.clearBatch(); <START> }) <END> .doOnError(e -> { throw log.sqlFailureWritingBatch(e); }); }</code><technical_language>this is good. I a idea of better, if is doable rxjava2 API. I suggest removing doOnNext move do a for loop list. This lambda allow JVM optimize a bit easier</technical_language>

Target:
private Flowable<List<MarshallableEntry<? extends K, ? extends V>>> createBatchFlowable(PreparedStatement upsertBatch, Publisher<MarshallableEntry<? extends K, ? extends V>> publisher) { return Flowable.fromPublisher(publisher) .buffer(configuration.maxBatchSize()) .doOnNext(entries -> { for (MarshallableEntry<? extends K, ? extends V> entry : entries) { String keyStr = key2Str(entry.getKey()); prepareUpsertStatement(entry, keyStr, getSegment(entry), upsertBatch); upsertBatch.addBatch(); } upsertBatch.executeBatch(); upsertBatch.clearBatch(); }) .doOnError(e -> { throw log.sqlFailureWritingBatch(e); }); }
Source:
<code>protected void showStreamDialog(final StreamInfoItem item) { final Context context = getContext(); final Activity activity = getActivity(); if (context == null || context.getResources() == null || activity == null) { return; } final ArrayList<StreamDialogEntry> entries = new ArrayList<>(); if (PlayerHolder.getType() != null) { entries.add(StreamDialogEntry.enqueue); } if (item.getStreamType() == StreamType.AUDIO_STREAM) { entries.addAll(Arrays.asList( StreamDialogEntry.start_here_on_background, StreamDialogEntry.append_playlist, StreamDialogEntry.share )); } else { entries.addAll(Arrays.asList( StreamDialogEntry.start_here_on_background, StreamDialogEntry.start_here_on_popup, StreamDialogEntry.append_playlist, StreamDialogEntry.share )); } <START> final boolean enableKodiEntry = KoreUtil.isServiceSupportedByKore(item.getServiceId()) && PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(context.getString(R.string.show_play_with_kodi_key), false); <END> if (enableKodiEntry) { entries.add(StreamDialogEntry.play_on_kodi); } StreamDialogEntry.setEnabledEntries(entries); StreamDialogEntry.start_here_on_background.setCustomAction((fragment, infoItem) -> NavigationHelper.playOnBackgroundPlayer(context, getPlayQueueStartingAt(infoItem), true)); new InfoItemDialog(activity, item, StreamDialogEntry.getCommands(context), (dialog, which) -> StreamDialogEntry.clickOn(which, this, item)).show(); }</code><technical_language>provide this a method in KoreUtil if logic for show kodi entry is centralized copied 3 places</technical_language>

Target:
protected void showStreamDialog(final StreamInfoItem item) { final Context context = getContext(); final Activity activity = getActivity(); if (context == null || context.getResources() == null || activity == null) { return; } final ArrayList<StreamDialogEntry> entries = new ArrayList<>(); if (PlayerHolder.getType() != null) { entries.add(StreamDialogEntry.enqueue); } if (item.getStreamType() == StreamType.AUDIO_STREAM) { entries.addAll(Arrays.asList( StreamDialogEntry.start_here_on_background, StreamDialogEntry.append_playlist, StreamDialogEntry.share )); } else { entries.addAll(Arrays.asList( StreamDialogEntry.start_here_on_background, StreamDialogEntry.start_here_on_popup, StreamDialogEntry.append_playlist, StreamDialogEntry.share )); } if (KoreUtil.shouldShowPlayWithKodi(context, item)) { entries.add(StreamDialogEntry.play_with_kodi); } StreamDialogEntry.setEnabledEntries(entries); StreamDialogEntry.start_here_on_background.setCustomAction((fragment, infoItem) -> NavigationHelper.playOnBackgroundPlayer(context, getPlayQueueStartingAt(infoItem), true)); new InfoItemDialog(activity, item, StreamDialogEntry.getCommands(context), (dialog, which) -> StreamDialogEntry.clickOn(which, this, item)).show(); }
Source:
<code>public void partitionWritesByShardStrategyTimestampGroupsOnShardClash() { List<WriteInfo> writes = new ArrayList<>(); for (int i = 0; i <= WriteInfoPartitioner.SHARDS; i++) { writes.add(getWriteInfoWithFixedCellHash(CONSERVATIVE, i)); } Map<PartitionInfo, List<WriteInfo>> partitions = partitioner.partitionWritesByShardStrategyTimestamp(writes); assertThat(Iterables.getOnlyElement(partitions.keySet())) <START> .isEqualTo(PartitionInfo.of(WriteInfoPartitioner.getShard(writes.get(0)), true, 1L)); <END> assertThat(Iterables.getOnlyElement(partitions.values())) .hasSameElementsAs(writes); }</code><technical_language>nit: a containsExactly method preferable, IIRC if 0 2+ elements getOnlyElement throw clear of error message</technical_language>

Target:
public void partitionWritesByShardStrategyTimestampGroupsOnShardClash() { List<WriteInfo> writes = new ArrayList<>(); for (int i = 0; i <= WriteInfoPartitioner.SHARDS; i++) { writes.add(getWriteInfoWithFixedCellHash(CONSERVATIVE, i)); } Map<PartitionInfo, List<WriteInfo>> partitions = partitioner.partitionWritesByShardStrategyTimestamp(writes); assertThat(partitions.keySet()) .containsExactly(PartitionInfo.of(WriteInfoPartitioner.getShard(writes.get(0)), true, 1L)); assertThat(partitions.values()) .containsExactly(writes); }
Source:
<code>void onHeartbeatResponses(List<Message> heartbeatResponses) { LOG.debug(String.format("Handling heartbeat responses %s...", heartbeatResponses)); AggregatorStats aggregatorStats = new AggregatorStats(); for (Message msg : heartbeatResponses) { aggregateInfo(aggregatorStats, msg); } <START> LOG.debug(String.format("Calling registered handler for aggregated statistics %s...", masterAggregatorStats)); <END> handler.call(aggregatorStats); masterAggregatorStats = aggregatorStats; LOG.debug(String.format("Heartbeat responses processed")); }</code><technical_language>I reason identical log messages for announcements heartbeats. messages ease problem investigation force copy/paste them. If want identical I suggest extract LOG.debug handler.call a separate method call twice</technical_language>

Target:
void onHeartbeatResponses(List<Message> heartbeatResponses) { LOG.debug(String.format("Handling heartbeat responses %s...", heartbeatResponses)); AggregatorStats aggregatorStats = new AggregatorStats(); boolean successfullyAggregatedAtLeastOne = false; for (Message msg : heartbeatResponses) { if (aggregateInfo(aggregatorStats, msg)) { successfullyAggregatedAtLeastOne = true; } } if (successfullyAggregatedAtLeastOne) { LOG.debug(String.format("Calling registered handler for heartbeat statistics %s...", masterAggregatorStats)); handler.call(aggregatorStats); masterAggregatorStats = aggregatorStats; LOG.debug(String.format("Heartbeat responses processed")); } }
Source:
<code>public void onAccountChanged(AccountStore.OnAccountChanged event) { if (!isAdded()) { return; } if (event.isError()) { AppLog.e(AppLog.T.API, "onAccountChanged has error: " + event.error.type + " - " + event.error.message); ToastUtils.showToast(getContext(), R.string.error_fetch_my_profile); <START> } <END> if (event.causeOfChange == AccountAction.FETCH_ACCOUNT) { refreshAccountDetails(); mDispatcher.dispatch(AccountActionBuilder.newFetchSettingsAction()); } else if (event.causeOfChange == AccountAction.FETCH_SETTINGS) { mDispatcher.dispatch(SiteActionBuilder.newFetchSitesAction()); } }</code><technical_language>a return error toast is shown</technical_language>

Target:
public void onAccountChanged(AccountStore.OnAccountChanged event) { if (!isAdded()) { return; } if (event.isError()) { AppLog.e(AppLog.T.API, "onAccountChanged has error: " + event.error.type + " - " + event.error.message); ToastUtils.showToast(getContext(), R.string.error_fetch_my_profile); return; } if (event.causeOfChange == AccountAction.FETCH_ACCOUNT) { refreshAccountDetails(); mDispatcher.dispatch(AccountActionBuilder.newFetchSettingsAction()); } else if (event.causeOfChange == AccountAction.FETCH_SETTINGS) { mDispatcher.dispatch(SiteActionBuilder.newFetchSitesAction()); } }
Source:
<code>public void setInstalledCharStart(int charStart) throws CoreException { int existingValue = ensureMarker().getAttribute(IMarker.CHAR_START, -1); if (charStart != existingValue) { <START> setAttribute(IMarker.CHAR_START, charStart); <END> setAttribute( IMarker.MESSAGE, getMarkerMessage() ); } }</code><technical_language>setInstalledLineNumber, this set RESET_INSTALLED_LOCATION</technical_language>

Target:
public void setInstalledCharStart(int charStart) throws CoreException { int existingValue = ensureMarker().getAttribute(IMarker.CHAR_START, -1); if (charStart != existingValue) { setAttribute(IMarker.CHAR_START, charStart); setAttribute(RESET_INSTALLED_LOCATION, Boolean.TRUE); setAttribute( IMarker.MESSAGE, getMarkerMessage() ); } }
Source:
<code>protected BitmapFont newBitmapFont(BitmapFont.BitmapFontData data, Array<TextureRegion> pageRegions, boolean integer) { <START> return new BitmapFont(data, pageRegions, true); <END> }</code><technical_language>integer parameter instead of true i</technical_language>

Target:
protected BitmapFont newBitmapFont(BitmapFont.BitmapFontData data, Array<TextureRegion> pageRegions, boolean integer) { return new BitmapFont(data, pageRegions, integer); }
Source:
<code>public List<NamedFactory<Channel>> getChannelForwardingFactories(FactoryManager manager) { <START> return LocalAgentFactory.DEFAULT_FORWARDING_CHANNELS; <END> }</code><technical_language>this depends O/S type ? E.g: java return OsUtils.isUnix() ? UnixAgentFactory.DEFAULT_FORWARDING_CHANNELS : LocalAgentFactory.DEFAULT_FORWARDING_CHANNELS;</technical_language>

Target:
public List<NamedFactory<Channel>> getChannelForwardingFactories(FactoryManager manager) { return useUnixAgentFactory ? UnixAgentFactory.DEFAULT_FORWARDING_CHANNELS : LocalAgentFactory.DEFAULT_FORWARDING_CHANNELS; }
Source:
<code>protected Scope visitQuery(Query node, Optional<Scope> scope) { Scope withScope = analyzeWith(node, scope); Scope queryBodyScope = process(node.getQueryBody(), withScope); if (node.getOrderBy().isPresent()) { analyzeOrderBy(node, queryBodyScope); } else { analysis.setOrderByExpressions(node, emptyList()); } analysis.setOutputExpressions(node, descriptorToFields(queryBodyScope)); Scope queryScope = Scope.builder() .withParent(withScope) .withRelationType(RelationId.of(node), queryBodyScope.getRelationType()) .build(); Multimap<QualifiedObjectName, String> tableColumnMap = analysis.getColumnReferenceFields().values().stream() .filter(fieldId -> { Node sourceNode = fieldId.getRelationId().getSourceNode(); return sourceNode instanceof Table <START> && analysis.getScope(sourceNode) <END> .getRelationType() .getFieldByIndex(fieldId.getFieldIndex()) .getOriginTable().isPresent(); }) .collect( toMultimap( fieldId -> analysis.getScope(fieldId.getRelationId().getSourceNode()) .getRelationType() .getFieldByIndex(fieldId.getFieldIndex()) .getOriginTable().orElseThrow(() -> new IllegalStateException("No origin table for field")), fieldId -> analysis.getScope(fieldId.getRelationId().getSourceNode()) .getRelationType() .getFieldByIndex(fieldId.getFieldIndex()) .getName().orElseThrow(() -> new IllegalStateException("No name for field")), ArrayListMultimap::create)); tableColumnMap.keySet() .forEach(tableName -> accessControl.checkCanSelectFromColumns(session.getRequiredTransactionId(), session.getIdentity(), tableName, tableColumnMap.get(tableName))); analysis.setScope(node, queryScope); return queryScope; }</code><technical_language>do need this</technical_language>

Target:
protected Scope visitQuery(Query node, Optional<Scope> scope) { Scope withScope = analyzeWith(node, scope); Scope queryBodyScope = process(node.getQueryBody(), withScope); if (node.getOrderBy().isPresent()) { analyzeOrderBy(node, queryBodyScope); } else { analysis.setOrderByExpressions(node, emptyList()); } analysis.setOutputExpressions(node, descriptorToFields(queryBodyScope)); Scope queryScope = Scope.builder() .withParent(withScope) .withRelationType(RelationId.of(node), queryBodyScope.getRelationType()) .build(); analysis.getTableColumnReferences().asMap() .forEach((tableName, columns) -> accessControl.checkCanSelectFromColumns(session.getRequiredTransactionId(), session.getIdentity(), tableName, ImmutableSet.copyOf(columns))); analysis.setScope(node, queryScope); return queryScope; }
Source:
<code>public void commitOffsets() { for (Map.Entry<String, Map<String, PartitionTopicInfo>> e : allPartitions.entrySet()) { for (PartitionTopicInfo info : e.getValue().values()) { final long lastChanged = info.getConsumedOffsetChanged().get(); if (lastChanged == 0) { <START> LOG.trace("consume offset not changed"); <END> continue; } final long newOffset = info.getConsumedOffset(); updateOffset(info.topic, info.partition, newOffset); info.resetComsumedOffsetChanged(lastChanged); LOG.debug("Committed " + info.partition + " for topic " + info.topic); } } }</code><technical_language>this log useless, remove</technical_language>

Target:
public void commitOffsets() { for (Map.Entry<String, List<PartitionTopicInfo>> e : allPartitions.entrySet()) { for (PartitionTopicInfo info : e.getValue()) { final long lastChanged = info.getConsumedOffsetChanged().get(); if (lastChanged == 0) { continue; } final long newOffset = info.getConsumedOffset(); updateOffset(info.topic, info.partition, newOffset); info.resetComsumedOffsetChanged(lastChanged); LOG.debug("Committed " + info.partition + " for topic " + info.topic); } } }
Source:
<code>public void onProcessExit(ProcessExitEvent event) { unregisterHandlers(); if (consoleProcess_ != null) { consoleProcess_.reap(new VoidServerRequestCallback()); } consoleProcess_ = null; <START> fireEvent(new TerminalSessionStoppedEvent(terminalTitle_, this)); <END> }</code><technical_language>Is a reason events fired global event bus? put events convention allows easy extensibility point for other parts of system react. (It registration/unregistration a easier need HasHandlers direct wiring.)</technical_language>

Target:
public void onProcessExit(ProcessExitEvent event) { unregisterHandlers(); if (consoleProcess_ != null) { consoleProcess_.reap(new VoidServerRequestCallback()); } consoleProcess_ = null; eventBus_.fireEvent(new TerminalSessionStoppedEvent(terminalTitle_, this)); }
Source:
<code>public static boolean isElementFromSourceCode(@Nullable Element element) { if (element == null) { return false; } if (element instanceof ClassSymbol) { return isElementFromSourceCodeImpl((ClassSymbol) element); } <START> return isElementFromSourceCode(element.getEnclosingElement()); <END> }</code><technical_language>enclosingClass save a hops..</technical_language>

Target:
public static boolean isElementFromSourceCode(@Nullable Element element) { if (element == null) { return false; } if (element instanceof Symbol.ClassSymbol) { return isElementFromSourceCodeImpl((Symbol.ClassSymbol) element); } return isElementFromSourceCode(element.getEnclosingElement()); }
Source:
<code>public ByteBuffer getImageBytes() { <START> if (!open.get()) { <END> return null; } ByteBuffer byteBuffer = ByteBuffer.allocate(resolution.width * resolution.height * 3); getImageBytes(byteBuffer); return byteBuffer; }</code><technical_language>black image. valid image once. :(</technical_language>

Target:
public ByteBuffer getImageBytes() { if (!open.get()) { return null; } try { ByteBuffer buffer = ByteBuffer.allocate(arraySize()); buffer.put(readNextFrame()); } catch (IOException e) { e.printStackTrace(); } return null; }
Source:
<code>public CompletionStage<RestResponse> setLogger(String name, String level, String... appenders) { Request.Builder builder = new Request.Builder(); StringBuilder sb = new StringBuilder(baseLoggingURL); sb.append("/loggers/").append(sanitize(name)).append("?"); boolean amp = false; if (level != null) { sb.append("level=").append(level); amp = true; } if (appenders != null) { for(String appender : appenders) { if (amp) { sb.append("&"); } <START> sb.append("appender=").append(appender); <END> amp = true; } } builder.url(sb.toString()).put(Util.EMPTY_REQUEST); return client.execute(builder); }</code><technical_language>nitpick: sb.append("appender=").append(String.join("%appender=", appenders))</technical_language>

Target:
public CompletionStage<RestResponse> setLogger(String name, String level, String... appenders) { Request.Builder builder = new Request.Builder(); StringBuilder sb = new StringBuilder(baseLoggingURL); sb.append("/loggers/"); if (name != null) { sb.append(sanitize(name)); } sb.append("?"); boolean amp = false; if (level != null) { sb.append("level=").append(level); amp = true; } if (appenders != null) { for(String appender : appenders) { if (amp) { sb.append("&"); } sb.append("appender=").append(appender); amp = true; } } builder.url(sb.toString()).put(Util.EMPTY_REQUEST); return client.execute(builder); }
Source:
<code>public String getJobCoordinationServiceFactoryClassName() { String jobCooridanationFactoryClassName = get(JOB_COORDINATIOIN_SERVICE_FACTORY, "org.apache.samza.zk.ZkCoordinationServiceFactory"); if (Strings.isNullOrEmpty(jobCooridanationFactoryClassName)) { throw new ConfigException( <START> String.format("Missing config - %s. Cannot start coordiantion service!", JOB_COORDINATOR_FACTORY)); <END> } return jobCooridanationFactoryClassName; }</code><technical_language>Is this exception message accurate? If default Factory class? caused missing config missing config is acceptable</technical_language>

Target:
public String getJobCoordinationServiceFactoryClassName() { String jobCooridanationFactoryClassName = get(JOB_COORDINATIOIN_SERVICE_FACTORY, "org.apache.samza.zk.ZkCoordinationServiceFactory"); if (Strings.isNullOrEmpty(jobCooridanationFactoryClassName)) { throw new ConfigException( String.format("config '%s' is set to empty. Cannot instantiate coordination utils!", JOB_COORDINATOR_FACTORY)); } return jobCooridanationFactoryClassName; }
Source:
<code>public synchronized boolean update(final Connection connection, InetSocketAddress newPeerAddress) { if (connection != null && connections.update(connection.getConnectionId())) { InetSocketAddress oldPeerAddress = connection.getPeerAddress(); <START> if (oldPeerAddress != newPeerAddress && (oldPeerAddress == null || !oldPeerAddress.equals(newPeerAddress))) { <END> LOG.debug("{}connection: updated, address changed from to {}!", tag, connection.getConnectionId(), oldPeerAddress, newPeerAddress); if (oldPeerAddress != null) { connectionsByAddress.remove(oldPeerAddress, connection); } connection.setPeerAddress(newPeerAddress); if (newPeerAddress != null) { addToAddressConnections(connection); } } else { LOG.debug("{}connection: - updated!", tag, connection.getConnectionId(), newPeerAddress); } return true; } else { if (connection != null) { LOG.debug("{}connection: - update failed!", tag, connection.getConnectionId(), newPeerAddress); } return false; } }</code><technical_language>connection.equalsPeerAddress</technical_language>

Target:
public synchronized boolean update(final Connection connection, InetSocketAddress newPeerAddress) { if (connection == null) { return false; } if (connections.update(connection.getConnectionId())) { if (!connection.equalsPeerAddress(newPeerAddress)) { InetSocketAddress oldPeerAddress = connection.getPeerAddress(); LOG.debug("{}connection: updated, address changed from to {}!", tag, connection.getConnectionId(), oldPeerAddress, newPeerAddress); if (oldPeerAddress != null) { connectionsByAddress.remove(oldPeerAddress, connection); } connection.setPeerAddress(null); if (newPeerAddress != null) { connection.setPeerAddress(newPeerAddress); addToAddressConnections(connection); } } else { LOG.debug("{}connection: - updated!", tag, connection.getConnectionId(), newPeerAddress); } return true; } else { LOG.debug("{}connection: - update failed!", tag, connection.getConnectionId(), newPeerAddress); return false; } }
Source:
<code>@Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) <START> throws IOException <END> { this._queue.add(new Delivery(envelope, properties, body)); }</code><technical_language>IOException is thrown</technical_language>

Target:
@Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) { this.queue.add(new Delivery(envelope, properties, body)); }
Source:
<code>public SearchMandateResponseBuilder withMandates(List<MandateResponse> mandates) { <START> this.mandates = mandates; <END> return this; }</code><technical_language>![image](<LINK_0></technical_language>

Target:
public SearchMandateResponseBuilder withMandates(List<MandateResponse> mandates) { this.mandates = List.copyOf(mandates); return this; }
Source:
<code>static void checkLocationPermissions(Activity targetActivity, AirMapInterface airMapInterface) { <START> if (hasSelfPermissions(targetActivity, LOCATION_PERMISSIONS)) { <END> airMapInterface.onLocationPermissionsGranted(); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { targetActivity.requestPermissions(LOCATION_PERMISSIONS, LOCATION_PERMISSION_REQUEST_CODE); } else { } } }</code><technical_language>I need this</technical_language>

Target:
static void checkLocationPermissions(Activity targetActivity, AirMapInterface airMapInterface) { if (hasSelfPermissions(targetActivity, LOCATION_PERMISSIONS)) { airMapInterface.onLocationPermissionsGranted(); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { targetActivity.requestPermissions(LOCATION_PERMISSIONS, LOCATION_PERMISSION_REQUEST_CODE); } }
Source:
<code>public ByteArraySeekableStream(byte[] bytes) { inputStream = new ByteArrayInputStream(bytes); <START> length = bytes.length; <END> }</code><technical_language>add requireNonNull for bytes</technical_language>

Target:
public ByteArraySeekableStream(byte[] bytes) { inputStream = new ByteArrayInputStream(requireNonNull(bytes, "Input byte array is null")); length = bytes.length; }
Source:
<code>protected IParser getParser() { <START> final EObject parentSemanticElement = getContextElement() != null <END> && getContextElement() instanceof EObject ? (EObject) getContextElement() : null; if (null != configuration && null != parentSemanticElement) { return configuration.createParser(parentSemanticElement); } return null; }</code><technical_language>write this conditional expression in complete syntax</technical_language>

Target:
protected IParser getParser() { EObject parentSemanticElement = null; final Object contextElement = getContextElement(); if (null != contextElement && contextElement instanceof EObject) { parentSemanticElement = (EObject) contextElement; } if (null != configuration && null != parentSemanticElement) { return configuration.createParser(parentSemanticElement); } return null; }
Source:
<code>private Disposable unsubscribeInUiThread(final Action unsubscribe) { return Disposables.fromAction(new Action() { @Override public void run() throws Exception { if (Looper.getMainLooper() == Looper.myLooper()) { unsubscribe.run(); } else { final Scheduler.Worker inner = AndroidSchedulers.mainThread().createWorker(); inner.schedule(new Runnable() { @Override public void run() { try { unsubscribe.run(); } catch (Exception e) { <START> e.printStackTrace(); <END> } inner.dispose(); } }); } } }); }</code><technical_language>Please, do print StackTrace. Call onError(message, exception) method message</technical_language>

Target:
private Disposable unsubscribeInUiThread(final Action unsubscribe) { return Disposables.fromAction(new Action() { @Override public void run() throws Exception { if (Looper.getMainLooper() == Looper.myLooper()) { unsubscribe.run(); } else { final Scheduler.Worker inner = AndroidSchedulers.mainThread().createWorker(); inner.schedule(new Runnable() { @Override public void run() { try { unsubscribe.run(); } catch (Exception e) { onError("Could not unregister receiver in UI Thread", e); } inner.dispose(); } }); } } }); }
Source:
<code>private Set<SelectLocationPage> getNotVisitedLocationPages() { final Set<SelectLocationPage> locationPages = new HashSet<SelectLocationPage>(); for (final IWizardPage page : getPages()) { if (SelectLocationPage.class.isInstance(page)) { final SelectLocationPage locationPage = SelectLocationPage.class.cast(page); <START> if (!locationPage.wasAlreadyVisible()) { <END> locationPages.add(locationPage); } } } return locationPages; }</code><technical_language>try remove level of nesting</technical_language>

Target:
private Set<SelectLocationPage> getNotVisitedLocationPages() { final Set<SelectLocationPage> locationPages = new HashSet<SelectLocationPage>(); for (final IWizardPage page : getPages()) { addNotAlreadyVisibleLocationPage(page, locationPages); } return locationPages; }
Source:
<code>public boolean hasUseBackgroundNetworksPermission(int uid) { final String[] names = mPackageManager.getPackagesForUid(uid); if (null == names || names.length <START> <= 0) <END> return false; try { final PackageInfo app = mPackageManager.getPackageInfo(names[0], GET_PERMISSIONS); return hasUseBackgroundNetworksPermission(app); } catch (NameNotFoundException e) { loge("NameNotFoundException " + names[0]); return false; } }</code><technical_language>Nit: this (should?) == instead of <=</technical_language>

Target:
public boolean hasUseBackgroundNetworksPermission(int uid) { final String[] names = mPackageManager.getPackagesForUid(uid); if (null == names || names.length == 0) return false; try { final PackageInfo app = mPackageManager.getPackageInfo(names[0], GET_PERMISSIONS); return hasUseBackgroundNetworksPermission(app); } catch (NameNotFoundException e) { loge("NameNotFoundException " + names[0], e); return false; } }
Source:
<code>public boolean isSatisfied(AbstractTestFixture fixture) { <START> return !Boolean.parseBoolean(fixture.getProperty("api_key_enabled")); <END> }</code><technical_language>if introduce a constant for this rule reference it</technical_language>

Target:
public boolean isSatisfied(AbstractTestFixture fixture) { return !Boolean.parseBoolean(fixture.getProperty(IBugzillaRestConstants.API_KEY_ENABLED_PROPERTY)); }