auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void saveNewCommentsByFeedbackParticipant(List<FeedbackResponseCommentAttributes> commentsToSave) throws EntityDoesNotExistException { for (FeedbackResponseCommentAttributes frc : commentsToSave) { String responseRecipient = getRequestParamValue(frc.feedbackResponseId); FeedbackResponseAttributes response = logic.getFeedbackResponse(frc.feedbackQuestionId, frc.commentGiver, responseRecipient); frc.feedbackResponseId = response.getId(); try { logic.createFeedbackResponseComment(frc); } catch (InvalidParametersException e) { setStatusForException(e); } statusToAdmin += this.getClass().getName() + ":<br>" + "Adding comment to response: " + frc.feedbackResponseId + "<br>" + "in course/feedback session: " + frc.courseId + "/" + frc.feedbackSessionName + "<br>" + "by: " + frc.commentGiver + " at " + frc.createdAt + "<br>" + "comment text: " + frc.commentText.getValue(); } }

Target:
private void saveNewCommentsByFeedbackParticipant(List<FeedbackResponseCommentAttributes> commentsToSave) throws EntityDoesNotExistException { for (FeedbackResponseCommentAttributes frc : commentsToSave) { try { logic.createFeedbackResponseComment(frc); logic.putDocument(frc); statusToAdmin += this.getClass().getName() + ":<br>" + "Adding comment to response: " + frc.feedbackResponseId + "<br>" + "in course/feedback session: " + frc.courseId + "/" + frc.feedbackSessionName + "<br>" + "by: " + frc.commentGiver + " at " + frc.createdAt + "<br>" + "comment text: " + frc.commentText.getValue(); } catch (InvalidParametersException e) { setStatusForException(e); } } }
Source:
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(); 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"); }

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:
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; 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; }

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:
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, mAccountStore.hasAccessToken() ) ); tagHolder.onBind(uiState); }

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:
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()); } customLogValues.put("StorageDomainNames", domainNames.toString()); } setNonOperational(NonOperationalReason.STORAGE_DOMAIN_UNREACHABLE, customLogValues); return false; } return true; }

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:
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()); when(taskContext.getStore("null-null-window-w1")).thenReturn(new TestInMemoryStore<>(storeKeySerde, storeValSerde)); when(runner.getStreamSpec("integers")).thenReturn(new StreamSpec("integers", "integers", "kafka")); }

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:
public PublicKey get() { try { final String keyValue = System.getenv().get(SIGNATURE_PUBLIC_KEY_ENV); 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()); } }

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:
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.equal(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; }

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:
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, null, null, getClass(), null); 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")); }

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:
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(); Thread.currentThread().interrupt(); } } } }; t.start(); }

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:
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)); if (mReportInvocation) { mListener.invocationStarted(context); } } catch (InvalidProtocolBufferException e) { throw new RuntimeException(e); } }

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:
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); } Guid spId = getVmTemplate().getStoragePoolId(); Set<Guid> sdIds = destStorages.keySet(); MultipleStorageDomainsValidator storageDomainsValidator = getStorageDomainsValidator(spId, sdIds); return validate(storageDomainsValidator.allDomainsWithinThresholds()) && validate(storageDomainsValidator.allDomainsHaveSpaceForNewDisks(disks)); }

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:
public BitCache writeResponseToCache(Context c) throws IOException { BitCache cache = null; try (InputStream input = getInputStream()) { 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; } }

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:
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(); }) .doOnError(e -> { throw log.sqlFailureWritingBatch(e); }); }

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:
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 )); } final boolean enableKodiEntry = KoreUtil.isServiceSupportedByKore(item.getServiceId()) && PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(context.getString(R.string.show_play_with_kodi_key), false); 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(); }

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:
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())) .isEqualTo(PartitionInfo.of(WriteInfoPartitioner.getShard(writes.get(0)), true, 1L)); assertThat(Iterables.getOnlyElement(partitions.values())) .hasSameElementsAs(writes); }

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:
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); } LOG.debug(String.format("Calling registered handler for aggregated statistics %s...", masterAggregatorStats)); handler.call(aggregatorStats); masterAggregatorStats = aggregatorStats; LOG.debug(String.format("Heartbeat responses processed")); }

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:
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); } if (event.causeOfChange == AccountAction.FETCH_ACCOUNT) { refreshAccountDetails(); mDispatcher.dispatch(AccountActionBuilder.newFetchSettingsAction()); } else if (event.causeOfChange == AccountAction.FETCH_SETTINGS) { mDispatcher.dispatch(SiteActionBuilder.newFetchSitesAction()); } }

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:
public void setInstalledCharStart(int charStart) throws CoreException { int existingValue = ensureMarker().getAttribute(IMarker.CHAR_START, -1); if (charStart != existingValue) { setAttribute(IMarker.CHAR_START, charStart); setAttribute( IMarker.MESSAGE, getMarkerMessage() ); } }

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:
protected BitmapFont newBitmapFont(BitmapFont.BitmapFontData data, Array<TextureRegion> pageRegions, boolean integer) { return new BitmapFont(data, pageRegions, true); }

Target:
protected BitmapFont newBitmapFont(BitmapFont.BitmapFontData data, Array<TextureRegion> pageRegions, boolean integer) { return new BitmapFont(data, pageRegions, integer); }
Source:
public List<NamedFactory<Channel>> getChannelForwardingFactories(FactoryManager manager) { return LocalAgentFactory.DEFAULT_FORWARDING_CHANNELS; }

Target:
public List<NamedFactory<Channel>> getChannelForwardingFactories(FactoryManager manager) { return useUnixAgentFactory ? UnixAgentFactory.DEFAULT_FORWARDING_CHANNELS : LocalAgentFactory.DEFAULT_FORWARDING_CHANNELS; }
Source:
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 && analysis.getScope(sourceNode) .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; }

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:
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) { LOG.trace("consume offset not changed"); continue; } final long newOffset = info.getConsumedOffset(); updateOffset(info.topic, info.partition, newOffset); info.resetComsumedOffsetChanged(lastChanged); LOG.debug("Committed " + info.partition + " for topic " + info.topic); } } }

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:
public void onProcessExit(ProcessExitEvent event) { unregisterHandlers(); if (consoleProcess_ != null) { consoleProcess_.reap(new VoidServerRequestCallback()); } consoleProcess_ = null; fireEvent(new TerminalSessionStoppedEvent(terminalTitle_, this)); }

Target:
public void onProcessExit(ProcessExitEvent event) { unregisterHandlers(); if (consoleProcess_ != null) { consoleProcess_.reap(new VoidServerRequestCallback()); } consoleProcess_ = null; eventBus_.fireEvent(new TerminalSessionStoppedEvent(terminalTitle_, this)); }
Source:
public static boolean isElementFromSourceCode(@Nullable Element element) { if (element == null) { return false; } if (element instanceof ClassSymbol) { return isElementFromSourceCodeImpl((ClassSymbol) element); } return isElementFromSourceCode(element.getEnclosingElement()); }

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:
public ByteBuffer getImageBytes() { if (!open.get()) { return null; } ByteBuffer byteBuffer = ByteBuffer.allocate(resolution.width * resolution.height * 3); getImageBytes(byteBuffer); return byteBuffer; }

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:
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("&"); } sb.append("appender=").append(appender); amp = true; } } builder.url(sb.toString()).put(Util.EMPTY_REQUEST); return client.execute(builder); }

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:
public String getJobCoordinationServiceFactoryClassName() { String jobCooridanationFactoryClassName = get(JOB_COORDINATIOIN_SERVICE_FACTORY, "org.apache.samza.zk.ZkCoordinationServiceFactory"); if (Strings.isNullOrEmpty(jobCooridanationFactoryClassName)) { throw new ConfigException( String.format("Missing config - %s. Cannot start coordiantion service!", JOB_COORDINATOR_FACTORY)); } return jobCooridanationFactoryClassName; }

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:
public synchronized boolean update(final Connection connection, InetSocketAddress newPeerAddress) { if (connection != null && connections.update(connection.getConnectionId())) { InetSocketAddress oldPeerAddress = connection.getPeerAddress(); if (oldPeerAddress != newPeerAddress && (oldPeerAddress == null || !oldPeerAddress.equals(newPeerAddress))) { 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; } }

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:
@Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { this._queue.add(new Delivery(envelope, properties, body)); }

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

Target:
public SearchMandateResponseBuilder withMandates(List<MandateResponse> mandates) { this.mandates = List.copyOf(mandates); return this; }
Source:
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); } else { } } }

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:
public ByteArraySeekableStream(byte[] bytes) { inputStream = new ByteArrayInputStream(bytes); length = bytes.length; }

Target:
public ByteArraySeekableStream(byte[] bytes) { inputStream = new ByteArrayInputStream(requireNonNull(bytes, "Input byte array is null")); length = bytes.length; }
Source:
protected IParser getParser() { final EObject parentSemanticElement = getContextElement() != null && getContextElement() instanceof EObject ? (EObject) getContextElement() : null; if (null != configuration && null != parentSemanticElement) { return configuration.createParser(parentSemanticElement); } return null; }

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:
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) { e.printStackTrace(); } inner.dispose(); } }); } } }); }

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:
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); if (!locationPage.wasAlreadyVisible()) { locationPages.add(locationPage); } } } return locationPages; }

Target:
private Set<SelectLocationPage> getNotVisitedLocationPages() { final Set<SelectLocationPage> locationPages = new HashSet<SelectLocationPage>(); for (final IWizardPage page : getPages()) { addNotAlreadyVisibleLocationPage(page, locationPages); } return locationPages; }
Source:
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]); return false; } }

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:
public boolean isSatisfied(AbstractTestFixture fixture) { return !Boolean.parseBoolean(fixture.getProperty("api_key_enabled")); }

Target:
public boolean isSatisfied(AbstractTestFixture fixture) { return !Boolean.parseBoolean(fixture.getProperty(IBugzillaRestConstants.API_KEY_ENABLED_PROPERTY)); }
Source:
public void RTEDisabledEditorEntryDefaultPreferredTests_001_CreatePageEntry() { String articleName = PageContent.articleNamePrefix + base.getTimeStamp(); ArticlePageObject article = base.openArticleByName(wikiURL, articleName); VisualEditorPageObject ve = article.createArticleInVEUsingDropdown(articleName); ve.verifyVEToolBarPresent(); ve.verifyEditorSurfacePresent(); ve.logOut(wikiURL); }

Target:
public void RTEDisabledEditorEntryDefaultPreferredTests_001_CreatePageEntry() { String articleName = PageContent.articleNamePrefix + base.getTimeStamp(); ArticlePageObject article = base.openArticleByName(wikiURL, articleName); VisualEditorPageObject ve = article.createArticleInVEUsingDropdown(articleName); ve.verifyVEToolBarPresent(); ve.verifyEditorSurfacePresent(); }
Source:
public boolean isActive(FeatureState featureState, FeatureUser user) { ApplicationContext applicationContext = ContextClassLoaderApplicationContextHolder.get(); if (applicationContext == null) { return false; } List<String> activeProfiles = Arrays.asList(applicationContext.getEnvironment().getActiveProfiles()); List<String> profiles = Strings.splitAndTrim(featureState.getParameter(PARAM_PROFILES), "[\\s,]+"); for (String profile : profiles) { if (activeProfiles.contains(profile)) { return true; } } return false; }

Target:
public boolean isActive(FeatureState featureState, FeatureUser user) { ApplicationContext applicationContext = ContextClassLoaderApplicationContextHolder.get(); if (applicationContext == null) { throw new IllegalStateException("ApplicationContext could not be found, which can occur if there is no bean for " + "TogglzApplicationContextBinderApplicationListener when TogglzAutoConfiguration is not being used"); } List<String> activeProfileNames = getActiveProfileNames(applicationContext); List<Profile> profiles = parseProfiles(featureState); for (Profile profile : profiles) { if (activeProfileNames.contains(profile.name) != profile.negated) { return true; } } return false; }
Source:
protected void ExecuteVmCommand() { if (getVm().getstatus() == VMStatus.Up) { performPlugCommnad(getPlugAction(), diskImage, oldVmDevice); } oldVmDevice.setIsPlugged(!oldVmDevice.getIsPlugged()); getVmDeviceDao().update(oldVmDevice); VmHandler.updateDisksFromDb(getVm()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { VmDeviceUtils.updateBootOrderInVmDevice(getVm().getStaticData()); return null; } }); setSucceeded(true); }

Target:
protected void ExecuteVmCommand() { if (getVm().getstatus() == VMStatus.Up) { performPlugCommnad(getPlugAction(), diskImage, oldVmDevice); } oldVmDevice.setIsPlugged(!oldVmDevice.getIsPlugged()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getVmDeviceDao().update(oldVmDevice); VmHandler.updateDisksFromDb(getVm()); VmDeviceUtils.updateBootOrderInVmDevice(getVm().getStaticData()); return null; } }); setSucceeded(true); }
Source:
private static PathElement counterElement(ModelNode operation) throws OperationFailedException { final PathAddress address = pathAddress(operation.require(OP_ADDR)); final PathElement counterElement = address.getElement(address.size() - 1); return counterElement; }

Target:
private static PathElement counterElement(ModelNode operation) { final PathAddress address = pathAddress(operation.require(OP_ADDR)); final PathElement counterElement = address.getElement(address.size() - 1); return counterElement; }