auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
Iterable<TemporalField<Image>> updateImages(Channel newChannel, Channel existingChannel) { Map<ImageTheme, TemporalField<Image>> newImageMap = StreamSupport.stream( newChannel.getAllImages().spliterator(), false ) .collect(MoreCollectors.toImmutableMap( temporalImage -> temporalImage.getValue().getTheme(), temporalImage -> temporalImage )); Map<ImageTheme, TemporalField<Image>> existingImages = StreamSupport.stream(existingChannel.getAllImages().spliterator(), false) .map(existingImage -> newImageMap.getOrDefault( existingImage.getValue().getTheme(), existingImage )) .collect(MoreCollectors.toImmutableMap( temporalImage -> temporalImage.getValue().getTheme(), temporalImage -> temporalImage )); return ImmutableSet.<TemporalField<Image>>builder() .addAll(existingImages.values()) .addAll( newImageMap.entrySet().stream() .filter(entry -> !existingImages.keySet().contains(entry.getKey())) .map(Entry::getValue) .collect(Collectors.toSet())) .build(); }

Target:
Iterable<TemporalField<Image>> updateImages(Channel newChannel, Channel existingChannel) { Map<ImageTheme, TemporalField<Image>> newImageMap = StreamSupport.stream( newChannel.getAllImages().spliterator(), false ) .collect(MoreCollectors.toImmutableMap( temporalImage -> temporalImage.getValue().getTheme(), temporalImage -> temporalImage )); Map<ImageTheme, TemporalField<Image>> existingImages = StreamSupport.stream(existingChannel.getAllImages().spliterator(), false) .map(existingImage -> newImageMap.getOrDefault( existingImage.getValue().getTheme(), existingImage )) .collect(MoreCollectors.toImmutableMap( temporalImage -> temporalImage.getValue().getTheme(), temporalImage -> temporalImage )); return ImmutableSet.<TemporalField<Image>>builder() .addAll(existingImages.values()) .addAll( newImageMap.entrySet().stream() .filter(entry -> !existingImages.containsKey(entry.getKey())) .map(Entry::getValue) .collect(Collectors.toSet())) .build(); }
Source:
private void deregisterIndexGauges(String storeId) { String prefix = storeId + SEPERATOR; registry.remove(MetricRegistry.name(Log.class, prefix + "CurrentCapacityUsed")); registry.remove(MetricRegistry.name(Log.class, prefix + "PercentageUsedCapacity")); registry.remove(MetricRegistry.name(Log.class, prefix + "CurrentSegmentCount")); registry.remove(MetricRegistry.name(Log.class, "ByteBufferForAppendTotalCount")); registry.remove(MetricRegistry.name(Log.class, "UnderCompaction" + SEPERATOR + "ByteBufferForAppendTotalCount")); }

Target:
private void deregisterIndexGauges(String storeId) { String prefix = storeId + SEPARATOR; registry.remove(MetricRegistry.name(Log.class, prefix + "CurrentCapacityUsed")); registry.remove(MetricRegistry.name(Log.class, prefix + "PercentageUsedCapacity")); registry.remove(MetricRegistry.name(Log.class, prefix + "CurrentSegmentCount")); registry.remove(MetricRegistry.name(Log.class, "ByteBufferForAppendTotalCount")); registry.remove(MetricRegistry.name(Log.class, "UnderCompaction" + SEPARATOR + "ByteBufferForAppendTotalCount")); }
Source:
protected <T> Observable buildUseCaseObservable(Map<String, T> parameters) { if (parameters == null || !parameters.containsKey(KEY_SURVEY_GROUP_ID) || parameters.get(KEY_SURVEY_GROUP_ID) == null) { return Observable.error(new IllegalArgumentException("Missing survey group id")); } Long surveyGroupId = (Long) parameters.get(KEY_SURVEY_GROUP_ID); Double latitude = (Double) parameters.get(KEY_LATITUDE); Double longitude = (Double) parameters.get(KEY_LONGITUDE); Integer orderBy = (Integer) parameters.get(KEY_ORDER_BY); return surveyRepository.getDataPoints(surveyGroupId, latitude, longitude, orderBy); }

Target:
protected <T> Observable buildUseCaseObservable(Map<String, T> parameters) { if (parameters == null || parameters.get(KEY_SURVEY_GROUP_ID) == null) { return Observable.error(new IllegalArgumentException("Missing survey group id")); } Long surveyGroupId = (Long) parameters.get(KEY_SURVEY_GROUP_ID); Double latitude = (Double) parameters.get(KEY_LATITUDE); Double longitude = (Double) parameters.get(KEY_LONGITUDE); Integer orderBy = (Integer) parameters.get(KEY_ORDER_BY); return surveyRepository.getDataPoints(surveyGroupId, latitude, longitude, orderBy); }
Source:
private void reportErrorForUnmappedTargetPropertiesIfRequired() { ReportingPolicyPrism unmappedTargetPolicy = getUnmappedTargetPolicy(); if ( method instanceof ForgedMethod && ( (ForgedMethod) method ).isAutoMapping() ) { ForgedMethod forgedMethod = (ForgedMethod) this.method; if ( targetProperties.isEmpty() || !unprocessedTargetProperties.isEmpty() ) { if ( forgedMethod.getHistory() == null ) { Type sourceType = this.method.getParameters().get( 0 ).getType(); Type targetType = this.method.getReturnType(); ctx.getMessager().printMessage( this.method.getExecutable(), Message.PROPERTYMAPPING_FORGED_MAPPING_NOT_FOUND, sourceType, targetType, targetType, sourceType ); } else { ForgedMethodHistory history = forgedMethod.getHistory(); ctx.getMessager().printMessage( this.method.getExecutable(), Message.PROPERTYMAPPING_MAPPING_NOT_FOUND, history.createSourcePropertyErrorMessage(), history.getTargetType(), history.createTargetPropertyName(), history.getTargetType(), history.getSourceType() ); } } } else if ( !unprocessedTargetProperties.isEmpty() && unmappedTargetPolicy.requiresReport() ) { Message msg = unmappedTargetPolicy.getDiagnosticKind() == Diagnostic.Kind.ERROR ? Message.BEANMAPPING_UNMAPPED_TARGETS_ERROR : Message.BEANMAPPING_UNMAPPED_TARGETS_WARNING; ctx.getMessager().printMessage( method.getExecutable(), msg, MessageFormat.format( "{0,choice,1#property|1<properties}: \"{1}\"", unprocessedTargetProperties.size(), Strings.join( unprocessedTargetProperties.keySet(), ", " ) ) ); } }

Target:
private void reportErrorForUnmappedTargetPropertiesIfRequired() { ReportingPolicyPrism unmappedTargetPolicy = getUnmappedTargetPolicy(); if ( method instanceof ForgedMethod && ( (ForgedMethod) method ).isForgedNamedBased() ) { ForgedMethod forgedMethod = (ForgedMethod) this.method; if ( targetProperties.isEmpty() || !unprocessedTargetProperties.isEmpty() ) { if ( forgedMethod.getHistory() == null ) { Type sourceType = this.method.getParameters().get( 0 ).getType(); Type targetType = this.method.getReturnType(); ctx.getMessager().printMessage( this.method.getExecutable(), Message.PROPERTYMAPPING_FORGED_MAPPING_NOT_FOUND, sourceType, targetType, targetType, sourceType ); } else { ForgedMethodHistory history = forgedMethod.getHistory(); ctx.getMessager().printMessage( this.method.getExecutable(), Message.PROPERTYMAPPING_MAPPING_NOT_FOUND, history.createSourcePropertyErrorMessage(), history.getTargetType(), history.createTargetPropertyName(), history.getTargetType(), history.getSourceType() ); } } } else if ( !unprocessedTargetProperties.isEmpty() && unmappedTargetPolicy.requiresReport() ) { Message msg = unmappedTargetPolicy.getDiagnosticKind() == Diagnostic.Kind.ERROR ? Message.BEANMAPPING_UNMAPPED_TARGETS_ERROR : Message.BEANMAPPING_UNMAPPED_TARGETS_WARNING; ctx.getMessager().printMessage( method.getExecutable(), msg, MessageFormat.format( "{0,choice,1#property|1<properties}: \"{1}\"", unprocessedTargetProperties.size(), Strings.join( unprocessedTargetProperties.keySet(), ", " ) ) ); } }
Source:
public static FormatStep hostnameFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth, final String precision) { return hostnameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, true); }

Target:
public static FormatStep hostnameFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth, final String precision) { return new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, precision) { public String getSegmentedSubject(final ExtLogRecord record) { return record.getHostName(); } }; }
Source:
protected Channel createChannel(String hostString, int channelCount) throws IOException { InetAddress host = getHost(hostString); Channel channels[] = new Channel[channelCount]; for (int i = 0; i < channelCount; i++) { ReconnectingChannel reconnectingChannel = createReconnectingChannel(host); clientCloseHandlers.add(reconnectingChannel); channels[i] = reconnectingChannel; } return wrapChannel(new ChannelPool(channels)); }

Target:
protected Channel createChannel(String hostString, int channelCount) throws IOException { InetSocketAddress host = getSocketAddress(hostString); Channel channels[] = new Channel[channelCount]; for (int i = 0; i < channelCount; i++) { ReconnectingChannel reconnectingChannel = createReconnectingChannel(host); clientCloseHandlers.add(reconnectingChannel); channels[i] = reconnectingChannel; } return wrapChannel(new ChannelPool(channels)); }
Source:
public void testGetMappedValue() { ConcurrentHashMap map = map5(); assertNull(((ConcurrentHashMap.KeySetView)(map.keySet())).getMappedValue()); try { map.keySet(null); shouldThrow(); } catch (NullPointerException success) ConcurrentHashMap.KeySetView set = map.keySet(one); assertFalse(set.add(one)); assertTrue(set.add(six)); assertTrue(set.add(seven)); assertTrue(set.getMappedValue() == one); assertTrue(map.get(one) != one); assertTrue(map.get(six) == one); assertTrue(map.get(seven) == one); }

Target:
public void testGetMappedValue() { ConcurrentHashMap map = map5(); assertNull(((ConcurrentHashMap.KeySetView) map.keySet()).getMappedValue()); try { map.keySet(null); shouldThrow(); } catch (NullPointerException success) ConcurrentHashMap.KeySetView set = map.keySet(one); assertFalse(set.add(one)); assertTrue(set.add(six)); assertTrue(set.add(seven)); assertTrue(set.getMappedValue() == one); assertTrue(map.get(one) != one); assertTrue(map.get(six) == one); assertTrue(map.get(seven) == one); }
Source:
public KafkaEightSimpleConsumerFirehoseFactory( @JsonProperty("brokerList") List<String> brokerList, @JsonProperty("partitionIdList") List<Integer> partitionIdList, @JsonProperty("clientId") String clientId, @JsonProperty("feed") String feed, @JsonProperty("queueBufferLength") Integer queueBufferLength, @JsonProperty("resetBehavior") String resetBehavior ) { this.brokerList = brokerList; this.partitionIdList = partitionIdList; this.clientId = clientId; this.feed = feed; this.queueBufferLength = queueBufferLength == null ? 20000 : queueBufferLength; log.info("queueBufferLength loaded as[%s]", this.queueBufferLength); this.earliest = "latest".equalsIgnoreCase(resetBehavior) ? false : true; log.info("Default behavior of cosumer set to earliest? [%s]", this.earliest); }

Target:
public KafkaEightSimpleConsumerFirehoseFactory( @JsonProperty("brokerList") List<String> brokerList, @JsonProperty("partitionIdList") List<Integer> partitionIdList, @JsonProperty("clientId") String clientId, @JsonProperty("feed") String feed, @JsonProperty("queueBufferLength") Integer queueBufferLength, @JsonProperty("resetBehavior") String resetBehavior ) { this.brokerList = brokerList; this.partitionIdList = partitionIdList; this.clientId = clientId; this.feed = feed; this.queueBufferLength = queueBufferLength == null ? DEFAULT_QUEUE_BUFFER_LENGTH : queueBufferLength; log.info("queueBufferLength loaded as[%s]", this.queueBufferLength); this.earliest = RESET_TO_LATEST.equalsIgnoreCase(resetBehavior) ? false : true; log.info("Default behavior of cosumer set to earliest? [%s]", this.earliest); }
Source:
public static InstallState getInstallState() { if (!Boolean.getBoolean("jenkins.install.runSetupWizard")) { if (Functions.getIsUnitTest()) { return InstallState.TEST; } if (Boolean.getBoolean("hudson.Main.development")) { return InstallState.DEVELOPMENT; } } VersionNumber lastRunVersion = new VersionNumber(getLastExecVersion()); if (lastRunVersion.compareTo(NEW_INSTALL_VERSION) == 0) { if(!Jenkins.getInstance().getJobNames().isEmpty()) { return InstallState.UPGRADE; } return InstallState.NEW; } VersionNumber currentRunVersion = new VersionNumber(getCurrentExecVersion()); if (lastRunVersion.isOlderThan(currentRunVersion)) { return InstallState.UPGRADE; } else if (lastRunVersion.isNewerThan(currentRunVersion)) { return InstallState.DOWNGRADE; } else { return InstallState.RESTART; } }

Target:
public static InstallState getInstallState() { if (!Boolean.getBoolean("jenkins.install.runSetupWizard")) { if (Functions.getIsUnitTest()) { return InstallState.TEST; } if (Boolean.getBoolean("hudson.Main.development")) { return InstallState.DEVELOPMENT; } } VersionNumber lastRunVersion = new VersionNumber(getLastExecVersion()); if (lastRunVersion.compareTo(NEW_INSTALL_VERSION) == 0) { if (!Jenkins.getInstance().getItemMap().isEmpty()) { return InstallState.UPGRADE; } return InstallState.NEW; } VersionNumber currentRunVersion = new VersionNumber(getCurrentExecVersion()); if (lastRunVersion.isOlderThan(currentRunVersion)) { return InstallState.UPGRADE; } else if (lastRunVersion.isNewerThan(currentRunVersion)) { return InstallState.DOWNGRADE; } else { return InstallState.RESTART; } }
Source:
private CoordinationUtils getCoordinationUtils() throws Exception { ApplicationConfig appConfig = new ApplicationConfig(config); String clazz = appConfig.getCoordinationServiceFactoryClass(); if (clazz != null) { CoordinationServiceFactory factory = ClassLoaderHelper.fromClassName(clazz); String groupId = String.format("app-%s-%s", config.get(JobConfig.JOB_NAME()), config.get(JobConfig.JOB_ID(), "1")); return factory.getCoordinationService(groupId, String.valueOf(processorId), config); } else { return null; } }

Target:
CoordinationUtils getCoordinationUtils() throws Exception { ApplicationConfig appConfig = new ApplicationConfig(config); String clazz = appConfig.getCoordinationServiceFactoryClass(); if (clazz != null) { CoordinationServiceFactory factory = ClassLoaderHelper.fromClassName(clazz); String groupId = String.format("app-%s-%s", appConfig.getAppName(), appConfig.getAppId()); return factory.getCoordinationService(groupId, uid, config); } else { return null; } }
Source:
public void testParseFileSizeWithUnits() throws Exception { final SyndFeed feed = getSyndFeed("org/rometools/feed/module/mediarss/filesize-with-unit.xml"); final List<SyndEntry> entries = feed.getEntries(); final MediaEntryModule m1 = (MediaEntryModule) entries.get(0).getModule(MediaModule.URI); assertThat(m1.getMediaContents()[0].getFileSize(), is(valueOf(2).multiply(valueOf(1024).pow(3)).longValue())); final MediaEntryModule m2 = (MediaEntryModule) entries.get(1).getModule(MediaModule.URI); assertThat(m2.getMediaContents()[0].getFileSize(), is(valueOf(1.1).multiply(valueOf(1024).pow(3)).longValue())); final MediaEntryModule m3 = (MediaEntryModule) entries.get(2).getModule(MediaModule.URI); assertThat(m3.getMediaContents()[0].getFileSize(), is(valueOf(2).multiply(valueOf(1024).pow(2)).longValue())); final MediaEntryModule m4 = (MediaEntryModule) entries.get(3).getModule(MediaModule.URI); assertThat(m4.getMediaContents()[0].getFileSize(), is(2L)); final MediaEntryModule m5 = (MediaEntryModule) entries.get(4).getModule(MediaModule.URI); assertThat(m5.getMediaContents()[0].getFileSize(), is(valueOf(5.5).multiply(valueOf(1024).pow(4)).longValue())); final MediaEntryModule m6 = (MediaEntryModule) entries.get(5).getModule(MediaModule.URI); assertThat(m6.getMediaContents()[0].getFileSize(), is(valueOf(9000).multiply(valueOf(1024)).longValue())); }

Target:
public void testParseFileSizeWithUnits() throws Exception { final SyndFeed feed = getSyndFeed("org/rometools/feed/module/mediarss/filesize-with-unit.xml"); final List<SyndEntry> entries = feed.getEntries(); final MediaEntryModule module = (MediaEntryModule) entries.get(0).getModule(MediaModule.URI); Long parsedFileSize = module.getMediaContents()[0].getFileSize(); assertThat(parsedFileSize, is(new BigDecimal(1000).pow(3).longValue())); }
Source:
public static final void transform(Group group, Matrix4d m) { for (Atom atom : group.getAtoms()) { transform(atom, m); } for (Group altG : group.getAltLocs()) { for (Atom atom : altG.getAtoms()) { transform(atom, m); } } }

Target:
public static final void transform(Group group, Matrix4d m) { for (Atom atom : group.getAtoms()) { transform(atom, m); } for (Group altG : group.getAltLocs()) { transform(altG, m); } }
Source:
private PerfData testMyers(int characters) { PerfData ret = new PerfData(); String a = DiffTestDataGenerator.generateSequence(characters, 971, 3); String b = DiffTestDataGenerator.generateSequence(characters, 1621, 5); CharArray ac = new CharArray(a); CharArray bc = new CharArray(b); CharCmp cmp = new CharCmp(); int D = 0; int cpuTimeChanges = 0; long lastReadout = 0; long interimTime = 0; int repetitions = 0; stopwatch.start(); while (cpuTimeChanges < minCPUTimerTicks && interimTime < longTaskBoundary) { D = MyersDiff.INSTANCE.diff(cmp, ac, bc).size(); repetitions++; interimTime = stopwatch.readout(); if (interimTime != lastReadout) { cpuTimeChanges++; lastReadout = interimTime; } } ret.runningTime = stopwatch.stop() / repetitions; ret.N = ac.size() + bc.size(); ret.D = D; System.out.println(ret.toString()); return ret; }

Target:
private PerfData testMyers(int characters) { PerfData ret = new PerfData(); String a = DiffTestDataGenerator.generateSequence(characters, 971, 3); String b = DiffTestDataGenerator.generateSequence(characters, 1621, 5); CharArray ac = new CharArray(a); CharArray bc = new CharArray(b); CharCmp cmp = new CharCmp(); int D = 0; int cpuTimeChanges = 0; long lastReadout = 0; long interimTime = 0; int repetitions = 0; stopwatch.start(); while (cpuTimeChanges < minCPUTimerTicks && interimTime < longTaskBoundary) { D = MyersDiff.INSTANCE.diff(cmp, ac, bc).size(); repetitions++; interimTime = stopwatch.readout(); if (interimTime != lastReadout) { cpuTimeChanges++; lastReadout = interimTime; } } ret.runningTime = stopwatch.stop() / repetitions; ret.N = ac.size() + bc.size(); ret.D = D; return ret; }
Source:
private void startPlugins() { IExtensionRegistry registry = Platform.getExtensionRegistry(); IExtensionPoint point = registry.getExtensionPoint(PlatformUI.PLUGIN_ID, IWorkbenchRegistryConstants.PL_STARTUP); final IExtension[] extensions = point.getExtensions(); if (extensions.length == 0) { return; } int numProcessors = Runtime.getRuntime().availableProcessors(); final JobGroup jobGroup = new JobGroup("Workbench early startup job group", numProcessors * 2, 1); new EarlyStartupJob(jobGroup) { @Override protected IStatus run(IProgressMonitor monitor) { HashSet<String> disabledPlugins = new HashSet<String>( Arrays.asList(getDisabledEarlyActivatedPlugins())); monitor.beginTask(WorkbenchMessages.Workbench_startingPlugins, extensions.length); for (int i = 0; i < extensions.length; ++i) { if (monitor.isCanceled() || !isRunning()) { return Status.CANCEL_STATUS; } final IExtension extension = extensions[i]; if (!disabledPlugins.contains(extension.getNamespace())) { new EarlyStartupJob(jobGroup) { @Override protected IStatus run(IProgressMonitor monitor) { monitor.beginTask(extension.getNamespaceIdentifier(), 1); SafeRunner.run(new EarlyStartupRunnable(extension)); monitor.done(); return Status.OK_STATUS; } }.schedule(); } monitor.worked(1); } monitor.done(); return Status.OK_STATUS; } }.schedule(); }

Target:
private void startPlugins() { IExtensionRegistry registry = Platform.getExtensionRegistry(); IExtensionPoint point = registry.getExtensionPoint(PlatformUI.PLUGIN_ID, IWorkbenchRegistryConstants.PL_STARTUP); final IExtension[] extensions = point.getExtensions(); if (extensions.length == 0) { return; } int numProcessors = Runtime.getRuntime().availableProcessors(); final JobGroup jobGroup = new JobGroup("Workbench early startup job group", numProcessors * 2, 1); new EarlyStartupJob(jobGroup) { @Override protected IStatus run(IProgressMonitor monitor) { HashSet<String> disabledPlugins = new HashSet<String>( Arrays.asList(getDisabledEarlyActivatedPlugins())); monitor.beginTask(WorkbenchMessages.Workbench_startingPlugins, extensions.length); for (int i = 0; i < extensions.length; ++i) { if (monitor.isCanceled() || !isRunning()) { return Status.CANCEL_STATUS; } final IExtension extension = extensions[i]; if (!disabledPlugins.contains(extension.getNamespace())) { new EarlyStartupJob(jobGroup) { @Override protected IStatus run(IProgressMonitor monitor) { monitor.beginTask(extension.getNamespaceIdentifier(), 1); if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } SafeRunner.run(new EarlyStartupRunnable(extension)); monitor.done(); return Status.OK_STATUS; } }.schedule(); } monitor.worked(1); } monitor.done(); return Status.OK_STATUS; } }.schedule(); }
Source:
public void evict(I id) { try { this.dispatcher.executeOnGroup(new EvictCommand<>(id)); } catch (CommandDispatcherException e) { InfinispanEjbLogger.ROOT_LOGGER.warn(e.getLocalizedMessage(), e); } }

Target:
public void evict(I id) { InfinispanEjbLogger.ROOT_LOGGER.tracef("Passivating stateful session bean %s", id); this.evictor.evict(id); }
Source:
private int execute(CommandLine commandLine, int timeout) throws IOException { DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout * 1000); executor.setWatchdog(watchdog); executor.setExitValue(0); return executor.execute(commandLine); }

Target:
private int execute(CommandLine commandLine, int timeout) throws IOException { DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(TimeUnit.SECONDS.toMillis(timeout)); executor.setWatchdog(watchdog); executor.setExitValue(0); return executor.execute(commandLine); }
Source:
public SyncUserInfo retrieveInfoForUser(final String providerUserIdentity, final String provider) throws ObjectServerError { if (Util.isEmptyString(providerUserIdentity)) { throw new IllegalArgumentException("Not-null 'providerUserIdentity' required."); } if (Util.isEmptyString(provider)) { throw new IllegalArgumentException("None empty 'provider' required."); } if (!isAdmin()) { throw new IllegalArgumentException("SyncUser needs to be admin in order to lookup other users ID."); } AuthenticationServer authServer = SyncManager.getAuthServer(); LookupUserIdResponse response = authServer.retrieveUser(getSyncUser().getUserToken(), provider, providerUserIdentity, getAuthenticationUrl()); if (!response.isValid()) { if (response.getError().getErrorCode() == ErrorCode.NOT_FOUND) { return null; } else { throw response.getError(); } } else { return SyncUserInfo.fromLookupUserIdResponse(response); } }

Target:
public SyncUserInfo retrieveInfoForUser(final String providerUserIdentity, final String provider) throws ObjectServerError { if (Util.isEmptyString(providerUserIdentity)) { throw new IllegalArgumentException("'providerUserIdentity' cannot be empty."); } if (Util.isEmptyString(provider)) { throw new IllegalArgumentException("'provider' cannot be empty."); } if (!isAdmin()) { throw new IllegalArgumentException("SyncUser needs to be admin in order to lookup other users ID."); } AuthenticationServer authServer = SyncManager.getAuthServer(); LookupUserIdResponse response = authServer.retrieveUser(getSyncUser().getUserToken(), provider, providerUserIdentity, getAuthenticationUrl()); if (!response.isValid()) { if (response.getError().getErrorCode() == ErrorCode.NOT_FOUND) { return null; } else { throw response.getError(); } } else { return SyncUserInfo.fromLookupUserIdResponse(response); } }
Source:
static Optional<Range> calculateRangeForPartitioningKey(HiveColumnHandle column, Type type, List<HivePartition> partitions) { if (!isRangeSupported(type)) { return Optional.empty(); } List<Double> values = partitions.stream() .map(HivePartition::getKeys) .map(keys -> keys.get(column)) .filter(value -> !value.isNull()) .map(NullableValue::getValue) .map(value -> convertPartitionValueToDouble(type, value)) .collect(toImmutableList()); if (values.isEmpty()) { return Optional.empty(); } double min = values.get(0); double max = values.get(0); for (Double value : values) { if (value > max) { max = value; } if (value < min) { min = value; } } return Optional.of(new Range(min, max)); }

Target:
static Optional<DoubleRange> calculateRangeForPartitioningKey(HiveColumnHandle column, Type type, List<HivePartition> partitions) { if (!isRangeSupported(type)) { return Optional.empty(); } List<Double> values = partitions.stream() .map(HivePartition::getKeys) .map(keys -> keys.get(column)) .filter(value -> !value.isNull()) .map(NullableValue::getValue) .map(value -> convertPartitionValueToDouble(type, value)) .collect(toImmutableList()); if (values.isEmpty()) { return Optional.empty(); } double min = values.get(0); double max = values.get(0); for (Double value : values) { if (value > max) { max = value; } if (value < min) { min = value; } } return Optional.of(new DoubleRange(min, max)); }
Source:
private void showSnackBarWithRetry() { progressBar.setVisibility(View.GONE); if (onClickListener == null) { onClickListener = view -> { setAchievements(); }; } ViewUtil.showDismissibleSnackBar(findViewById(android.R.id.content), R.string.achievements_fetch_failed, R.string.retry, onClickListener); }

Target:
private void showSnackBarWithRetry() { progressBar.setVisibility(View.GONE); ViewUtil.showDismissibleSnackBar(findViewById(android.R.id.content), R.string.achievements_fetch_failed, R.string.retry, view -> setAchievements()); }
Source:
private void savePostAndFinish() { try { updatePostObject(false); } catch (IllegalEditorStateException e) { AppLog.e(T.EDITOR, "Impossible to save and publish the post, we weren't able to update it."); return; } boolean shouldSave = mPost.hasChanges(mOriginalPost) && (mPost.isPublishable() || !isNewPost()); if (shouldSave) { mPostSavedLocally = false; if (isNewPost()) { mPost.setPostStatus(PostStatus.toString(PostStatus.DRAFT)); if (mEditPostSettingsFragment != null) { mEditPostSettingsFragment.updateStatusSpinner(); } } if (mPost.getStatusEnum() != PostStatus.PUBLISHED && mPost.isPublishable()) { publishPost(); } else { savePostLocally(); } } if (isNewPost() && !mPost.isPublishable()) { WordPress.wpDB.deletePost(getPost()); } if (!mPostSavedLocally) { returnResult(shouldSave); finish(); } }

Target:
private void savePostAndFinish() { boolean hasLocalChanges = mPost.isLocallyChanged() || mPost.isLocalDraft(); boolean isFirstTimePublish = isFirstTimePublish(); boolean postUpdateSuccessful = updatePostObject(); if (!postUpdateSuccessful) { return; } boolean hasChanges = PostUtils.postHasEdits(mOriginalPost, mPost); boolean isPublishable = PostUtils.isPublishable(mPost); boolean hasUnpublishedLocalDraftChanges = PostStatus.fromPost(mPost) == PostStatus.DRAFT && isPublishable && hasLocalChanges; boolean shouldSave = (hasChanges || hasUnpublishedLocalDraftChanges) && (isPublishable || !isNewPost()); saveResult(shouldSave, false); if (shouldSave) { if (isNewPost()) { mPost.setStatus(PostStatus.DRAFT.toString()); if (mEditPostSettingsFragment != null) { mEditPostSettingsFragment.updateStatusSpinner(); } } if (PostStatus.fromPost(mPost) != PostStatus.PUBLISHED && isPublishable && NetworkUtils.isNetworkAvailable(this)) { if (!hasFailedMedia()) { savePostOnlineAndFinishAsync(isFirstTimePublish); } } else { savePostLocallyAndFinishAsync(); } } else { if (!isPublishable && isNewPost()) { mDispatcher.dispatch(PostActionBuilder.newRemovePostAction(mPost)); } finish(); } }
Source:
public static void setLanguage(String localeCode) { Configuration config = getInstance().getResources().getConfiguration(); Locale newLocale = LanguageUtil.getLocale(localeCode); config.locale = newLocale; getInstance().getResources().updateConfiguration(config, getInstance().getResources().getDisplayMetrics()); AnkiDroidApp.getInstance().setupNotificationChannels(); }

Target:
public static void setLanguage(String localeCode) { Configuration config = getInstance().getResources().getConfiguration(); Locale newLocale = LanguageUtil.getLocale(localeCode); config.locale = newLocale; getInstance().getResources().updateConfiguration(config, getInstance().getResources().getDisplayMetrics()); }
Source:
private Mono<Response<AnalyzeSentimentResultCollection>> getAnalyzedSentimentResponse( Iterable<TextDocumentInput> documents, AnalyzeSentimentOptions options, Context context) { return service.sentimentWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics(), options == null ? null : options.isIncludeOpinionMining(), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE)) .doOnSubscribe(ignoredValue -> logger.info("A batch of documents - {}", documents.toString())) .doOnSuccess(response -> logger.info("Analyzed sentiment for a batch of documents - {}", response)) .doOnError(error -> logger.warning("Failed to analyze sentiment - {}", error)) .map(this::toAnalyzeSentimentResultCollectionResponse) .onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable)); }

Target:
private Mono<Response<AnalyzeSentimentResultCollection>> getAnalyzedSentimentResponse( Iterable<TextDocumentInput> documents, AnalyzeSentimentOptions options, Context context) { return service.sentimentWithResponseAsync( new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)), options == null ? null : options.getModelVersion(), options == null ? null : options.isIncludeStatistics(), options == null ? null : options.isIncludeOpinionMining(), context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE)) .doOnSubscribe(ignoredValue -> logger.info("A batch of documents - {}", documents.toString())) .doOnSuccess(response -> logger.info("Analyzed sentiment for a batch of documents - {}", response)) .doOnError(error -> logger.warning("Failed to analyze sentiment - {}", error)) .map(this::toAnalyzeSentimentResultCollectionResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExist); }
Source:
protected void executeQueryCommand() { List<DiskImage> diskImages = getDbFacade().getDiskImageDao().getAllSnapshotsForStorageDomain(getParameters().getStorageDomainId()); Map<Guid, DiskImage> diskImagesMap = new HashMap<Guid, DiskImage>(); for (DiskImage diskImage : diskImages) { if (diskImage.getactive()) { diskImage.getSnapshots().add(DiskImage.copyOf(diskImage)); diskImagesMap.put(diskImage.getId(), diskImage); } } for (DiskImage diskImage : diskImages) { if (!diskImage.getactive()) { diskImagesMap.get(diskImage.getId()).getSnapshots().add(diskImage); } } getQueryReturnValue().setReturnValue(new ArrayList<DiskImage>(diskImagesMap.values())); }

Target:
protected void executeQueryCommand() { List<DiskImage> diskImages = getDbFacade().getDiskImageDao().getAllSnapshotsForStorageDomain(getParameters().getStorageDomainId()); Map<Guid, DiskImage> diskImagesMap = new HashMap<Guid, DiskImage>(); for (DiskImage diskImage : diskImages) { if (diskImage.getactive()) { diskImage.getSnapshots().add(diskImage); diskImagesMap.put(diskImage.getId(), diskImage); } } for (DiskImage diskImage : diskImages) { if (!diskImage.getactive()) { diskImagesMap.get(diskImage.getId()).getSnapshots().add(diskImage); } } getQueryReturnValue().setReturnValue(new ArrayList<DiskImage>(diskImagesMap.values())); }
Source:
public Set<SecurityGroup> listSecurityGroupsForNode(String id) { checkNotNull(id, "id"); ZoneAndId zoneAndId = ZoneAndId.fromSlashEncoded(id); String zone = zoneAndId.getZone(); String instanceId = zoneAndId.getId(); Optional<? extends ServerWithSecurityGroupsApi> serverApi = client.getServerWithSecurityGroupsExtensionForZone(zone); Optional<? extends SecurityGroupApi> sgApi = client.getSecurityGroupExtensionForZone(zone); if (!serverApi.isPresent() || !sgApi.isPresent()) { return ImmutableSet.of(); } ServerWithSecurityGroups instance = serverApi.get().get(instanceId); if (instance == null) { return ImmutableSet.of(); } Set<String> groupNames = instance.getSecurityGroupNames(); Set<? extends SecurityGroupInZone> rawGroups = sgApi.get().list().filter(nameIn(groupNames)).transform(groupToGroupInZone(zone)).toSet(); return ImmutableSet.copyOf(transform(filter(rawGroups, notNull()), groupConverter)); }

Target:
public Set<SecurityGroup> listSecurityGroupsForNode(String id) { ZoneAndId zoneAndId = ZoneAndId.fromSlashEncoded(checkNotNull(id, "id")); String zone = zoneAndId.getZone(); String instanceId = zoneAndId.getId(); Optional<? extends ServerWithSecurityGroupsApi> serverApi = api.getServerWithSecurityGroupsExtensionForZone(zone); Optional<? extends SecurityGroupApi> sgApi = api.getSecurityGroupExtensionForZone(zone); if (!serverApi.isPresent() || !sgApi.isPresent()) { return ImmutableSet.of(); } ServerWithSecurityGroups instance = serverApi.get().get(instanceId); if (instance == null) { return ImmutableSet.of(); } Set<String> groupNames = instance.getSecurityGroupNames(); Set<? extends SecurityGroupInZone> rawGroups = sgApi.get().list().filter(nameIn(groupNames)).transform(groupToGroupInZone(zone)).toSet(); return ImmutableSet.copyOf(transform(filter(rawGroups, notNull()), groupConverter)); }
Source:
protected Object doWork() { validateArguments(); logger.info("Starting allelic panel of normals creation..."); final AllelicPanelOfNormals allelicPoN = new AllelicPanelOfNormalsCreator(inputFiles).create(siteFrequency); logger.info("Allelic panel of normals created."); logger.info("Writing allelic panel of normals to output HDF5 file..."); allelicPoN.write(outputFile, HDF5File.OpenMode.CREATE); logger.info("Allelic panel of normals written to " + outputFile + "."); if (outputTSVFile != null) { allelicPoN.write(outputTSVFile); logger.info("Allelic panel of normals written as tab-separated values to " + outputTSVFile + "."); } return "SUCCESS"; }

Target:
protected Object doWork() { validateArguments(); if (!new HDF5Library().load(null)) { throw new UserException.HardwareFeatureException("Cannot load the required HDF5 library. " + "HDF5 is currently supported on x86-64 architecture and Linux or OSX systems."); } logger.info("Starting allelic panel of normals creation..."); final AllelicPanelOfNormals allelicPoN = new AllelicPanelOfNormalsCreator(inputFiles).create(siteFrequencyThreshold); logger.info("Allelic panel of normals created."); logger.info("Writing allelic panel of normals to output HDF5 file..."); allelicPoN.write(outputFile, HDF5File.OpenMode.CREATE); logger.info("Allelic panel of normals written to " + outputFile + "."); if (outputTSVFile != null) { allelicPoN.write(outputTSVFile); logger.info("Allelic panel of normals written as tab-separated values to " + outputTSVFile + "."); } return "SUCCESS"; }
Source:
public void visitFileExceptionWrapper(Path source, Path relativePath) { try { visitFile(source, relativePath); } catch (IOException ex) { throw new RuntimeException(); } }

Target:
public void visitFileExceptionWrapper(Path source, Path relativePath) { try { visitFile(source, relativePath); } catch (IOException ex) { throw new RuntimeException(ex); } }
Source:
public synchronized void open(String partitionName) throws ObjectStoreException { lock.lock(); try { super.open(partitionName); } finally { lock.unlock(); } }

Target:
public void open(String partitionName) throws ObjectStoreException { lock.lock(); try { super.open(partitionName); } finally { lock.unlock(); } }
Source:
static ILamiViewer createLamiChart(Composite parent, LamiResultTable resultTable, LamiChartModel chartModel) { switch (chartModel.getChartType()) { case BAR_CHART: return new LamiBarChartViewer(parent, resultTable, chartModel); case XY_SCATTER: return new LamiScatterViewer(parent, resultTable, chartModel); case PIE_CHART: default: throw new UnsupportedOperationException(); } }

Target:
static ILamiViewer createLamiChart(Composite parent, LamiResultTable resultTable, LamiChartModel chartModel) { switch (chartModel.getChartType()) { case BAR_CHART: return new LamiBarChartViewer(parent, resultTable, chartModel); case XY_SCATTER: return new LamiScatterViewer(parent, resultTable, chartModel); case PIE_CHART: default: throw new UnsupportedOperationException("Unsupported chart type: " + chartModel.toString()); } }
Source:
public void process() throws Exception { while (streamTask.inputProcessor.isAvailable() && streamTask.mailboxProcessor.isMailboxLoopRunning()) { processSingleStep(); } }

Target:
public void process() throws Exception { while (processSingleStep()) { } }
Source:
private static XeSource source(final Alias alias) throws IOException { final String email; final String newEmail; if (alias.email().contains(EMAIL_SEPARATOR)) { final String[] index = alias.email().split(EMAIL_SEPARATOR); email = index[0]; newEmail = index[1]; } else { email = alias.email(); newEmail = ""; } return new XeAppend( "alias", new XeDirectives( new Directives() .add("name").set(alias.name()).up() .add("locale").set(alias.locale().toString()).up() .add("photo").set(alias.photo().toString()).up() .add("email").set(email).up() .add("newEmail").set(newEmail) ) ); }

Target:
private static XeSource source(final Alias alias) throws IOException { final String email; final String newEmail; final String[] emails = alias.email().split("!"); if (emails.length > 1) { email = emails[0]; newEmail = emails[1]; } else { email = alias.email(); newEmail = ""; } return new XeAppend( "alias", new XeDirectives( new Directives() .add("name").set(alias.name()).up() .add("locale").set(alias.locale().toString()).up() .add("photo").set(alias.photo().toString()).up() .add("email").set(email).up() .add("newEmail").set(newEmail) ) ); }
Source:
public void handleCommand(ChannelUID channelUID, Command command) { try { if (channelUID.getId().equals(CHANNEL_DimmableLight)) { if (command instanceof PercentType) { PercentType commandString = ((PercentType) command); putlightDimmer(commandString.toString()); } else if (command instanceof DecimalType) { IncreaseDecreaseType commandString = ((IncreaseDecreaseType) command); putlightDimmer(commandString.toString()); System.err.println(command.toString()); } } else if (channelUID.getId().equals(CHANNEL_LCD)) { if (command instanceof StringType) { StringType commandString = ((StringType) command); putLCD(commandString.toString()); } } else if (channelUID.getId().equals(CHANNEL_WallSwitch)) { if (command instanceof OnOffType) { OnOffType commandString = ((OnOffType) command); putLightOnOff(commandString.toString()); } } else { logger.error("Linked Channel does not support PUT. Invalid channel linked "); } } catch (Exception ex) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Could not control device at IP address: " + this.getConfig().get("ipAddress")); } }

Target:
public void handleCommand(ChannelUID channelUID, Command command) { try { if (channelUID.getId().equals(CHANNEL_DimmableLight)) { if (command instanceof PercentType) { PercentType commandString = ((PercentType) command); putlightDimmer(commandString.toString()); } else if (command instanceof DecimalType) { IncreaseDecreaseType commandString = ((IncreaseDecreaseType) command); putlightDimmer(commandString.toString()); } } else if (channelUID.getId().equals(CHANNEL_LCD)) { if (command instanceof StringType) { StringType commandString = ((StringType) command); putLCD(commandString.toString()); } } else if (channelUID.getId().equals(CHANNEL_WallSwitch)) { if (command instanceof OnOffType) { OnOffType commandString = ((OnOffType) command); putLightOnOff(commandString.toString()); } } else { logger.error("Linked Channel does not support PUT. Invalid channel linked "); } } catch (Exception ex) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Could not control device at IP address: " + this.getConfig().get("ipAddress")); } }
Source:
public EventFields read(Kryo kryo, Input input, Class<EventFields> eventFieldsClass) { int entries = intSerializer.read(kryo, input, Integer.class); for (int i = 0; i < entries; i++) { String key = null; try { key = stringSerializer.read(kryo, input, String.class); } catch (Throwable e) { System.out.println(input); throw new RuntimeException(e); } ColumnVisibility vis = new ColumnVisibility(valueSerializer.read(kryo, input, byte[].class)); byte[] value = valueSerializer.read(kryo, input, byte[].class); byte[] metadata = valueSerializer.read(kryo, input, byte[].class); put(key, new FieldValue(vis, value, metadata)); } return this; }

Target:
public EventFields read(Kryo kryo, Input input, Class<EventFields> eventFieldsClass) { int entries = intSerializer.read(kryo, input, Integer.class); for (int i = 0; i < entries; i++) { String key = stringSerializer.read(kryo, input, String.class); ColumnVisibility vis = new ColumnVisibility(valueSerializer.read(kryo, input, byte[].class)); byte[] value = valueSerializer.read(kryo, input, byte[].class); byte[] metadata = valueSerializer.read(kryo, input, byte[].class); put(key, new FieldValue(vis, value, metadata)); } return this; }
Source:
ConnectionValidationResult testConnectivity(Object connection) { ConnectionHandler<Object> connectionHandler; lock.lock(); try { connectionHandler = connections.get(new Reference<>(connection)).getSecond(); } finally { lock.unlock(); } if (connectionHandler == null) { throw new IllegalArgumentException("Cannot validate a connection which was not generated through this " + ConnectionProvider.class.getSimpleName()); } return connectionManager.testConnectivity(connection, connectionHandler); }

Target:
ConnectionValidationResult testConnectivity(Object connection) { ConnectionHandler<Object> connectionHandler = connections.getIfPresent(new Reference<>(connection)).getSecond(); if (connectionHandler == null) { throw new IllegalArgumentException("Cannot validate a connection which was not generated through this " + ConnectionProvider.class.getSimpleName()); } return connectionManager.testConnectivity(connection, connectionHandler); }
Source:
void updatePartitionWeightStats(Map<String, Integer> partitionWeightMap) { synchronized (_dynamicCapacityMetricsMap) { if (_dynamicCapacityMetricsMap.keySet().equals(partitionWeightMap.keySet())) { for (Map.Entry<String, Integer> entry : partitionWeightMap.entrySet()) { _dynamicCapacityMetricsMap.get(entry.getKey()).updateValue((long) entry.getValue()); } return; } _dynamicCapacityMetricsMap.clear(); final String gaugeMetricSuffix = "Gauge"; for (Map.Entry<String, Integer> entry : partitionWeightMap.entrySet()) { String capacityKey = entry.getKey(); _dynamicCapacityMetricsMap.put(capacityKey, new SimpleDynamicMetric<>(capacityKey + gaugeMetricSuffix, (long) entry.getValue())); } } updateAttributesInfo(buildAttributeList(), "Resource monitor for resource: " + getResourceName()); }

Target:
void updatePartitionWeightStats(Map<String, Integer> partitionWeightMap) { synchronized (_dynamicCapacityMetricsMap) { if (_dynamicCapacityMetricsMap.keySet().equals(partitionWeightMap.keySet())) { for (Map.Entry<String, Integer> entry : partitionWeightMap.entrySet()) { _dynamicCapacityMetricsMap.get(entry.getKey()).updateValue((long) entry.getValue()); } return; } _dynamicCapacityMetricsMap.clear(); for (Map.Entry<String, Integer> entry : partitionWeightMap.entrySet()) { String capacityKey = entry.getKey(); _dynamicCapacityMetricsMap.put(capacityKey, new SimpleDynamicMetric<>(capacityKey + GAUGE_METRIC_SUFFIX, (long) entry.getValue())); } } updateAttributesInfo(buildAttributeList(), "Resource monitor for resource: " + getResourceName()); }
Source:
private FileVisitResult callback(Path absolutePath, ParserConfiguration configuration, Callback callback) throws IOException { if (!Files.exists(absolutePath)) { return TERMINATE; } Path localPath = root.relativize(absolutePath); Log.trace("Parsing %s", localPath); ParseResult<CompilationUnit> result = new JavaParser(configuration).parse(COMPILATION_UNIT, provider(absolutePath)); result.getResult().ifPresent(cu -> cu.setStorage(absolutePath)); switch (callback.process(localPath, absolutePath, result)) { case SAVE: result.getResult().ifPresent(cu -> save(cu, absolutePath)); case DONT_SAVE: return CONTINUE; case TERMINATE: return TERMINATE; default: throw new AssertionError("Return an enum defined in SourceRoot.Callback.Result"); } }

Target:
private FileVisitResult callback(Path absolutePath, ParserConfiguration configuration, Callback callback) throws IOException { Path localPath = root.relativize(absolutePath); Log.trace("Parsing %s", localPath); ParseResult<CompilationUnit> result = new JavaParser(configuration).parse(COMPILATION_UNIT, provider(absolutePath)); result.getResult().ifPresent(cu -> cu.setStorage(absolutePath)); switch (callback.process(localPath, absolutePath, result)) { case SAVE: result.getResult().ifPresent(cu -> save(cu, absolutePath)); case DONT_SAVE: return CONTINUE; case TERMINATE: return TERMINATE; default: throw new AssertionError("Return an enum defined in SourceRoot.Callback.Result"); } }
Source:
public void testReplicationRefreshSource() throws Exception { for (int i = 0; i < BATCH; i++) { byte[] r = Bytes.toBytes(i); table1.put(new Put(r).addColumn(famName, famName, r)); } Optional<RegionServerThread> server = UTIL1.getMiniHBaseCluster().getLiveRegionServerThreads() .stream() .filter(rst -> CollectionUtils.isNotEmpty(rst.getRegionServer().getRegions(tablename))) .findAny(); Assert.assertTrue(server.isPresent()); server.get().getRegionServer().abort("stopping for test"); UTIL1.waitFor(60000, () -> UTIL1.getMiniHBaseCluster().getLiveRegionServerThreads().size() == NUM_SLAVES1 - 1); UTIL1.waitTableAvailable(tablename); Replication replication = (Replication) UTIL1.getMiniHBaseCluster() .getLiveRegionServerThreads().get(0).getRegionServer().getReplicationSourceService(); UTIL1.waitFor(60000, () -> !replication.getReplicationManager().getOldSources().isEmpty()); hbaseAdmin.disableReplicationPeer(PEER_ID2); LOG.info("has replicated rows before disable peer", checkReplicationData()); hbaseAdmin.enableReplicationPeer(PEER_ID2); UTIL2.waitFor(30000, () -> { int count = checkReplicationData(); LOG.info("Waiting all logs pushed to slave. Expected , actual {}", BATCH, count); return count == BATCH; }); }

Target:
public void testReplicationRefreshSource() throws Exception { for (int i = 0; i < BATCH; i++) { byte[] r = Bytes.toBytes(i); table1.put(new Put(r).addColumn(famName, famName, r)); } Optional<RegionServerThread> server = UTIL1.getMiniHBaseCluster().getLiveRegionServerThreads() .stream() .filter(rst -> CollectionUtils.isNotEmpty(rst.getRegionServer().getRegions(tablename))) .findAny(); Assert.assertTrue(server.isPresent()); server.get().getRegionServer().abort("stopping for test"); UTIL1.waitFor(60000, () -> UTIL1.getMiniHBaseCluster().getLiveRegionServerThreads().size() == NUM_SLAVES1 - 1); UTIL1.waitTableAvailable(tablename); Replication replication = (Replication) UTIL1.getMiniHBaseCluster() .getLiveRegionServerThreads().get(0).getRegionServer().getReplicationSourceService(); UTIL1.waitFor(60000, () -> !replication.getReplicationManager().getOldSources().isEmpty()); hbaseAdmin.disableReplicationPeer(PEER_ID2); LOG.info("has replicated rows before disable peer", checkReplicationData()); hbaseAdmin.enableReplicationPeer(PEER_ID2); UTIL2.waitFor(60000, () -> { int count = checkReplicationData(); LOG.info("Waiting all logs pushed to slave. Expected , actual {}", BATCH, count); return count == BATCH; }); }
Source:
private void decrementRequested() { while (true) { long r = requested.get(); if (r == Long.MAX_VALUE) { return; } else if (requested.compareAndSet(r, r - 1)) { return; } } }

Target:
private void decrementRequested() { AtomicLong localRequested = this.requested; while (true) { long r = localRequested.get(); if (r == Long.MAX_VALUE) { return; } else if (localRequested.compareAndSet(r, r - 1)) { return; } } }
Source:
public static boolean postAndWait(Handler handler, final Runnable r) { if (handler.getLooper().getThread() == Thread.currentThread()) { r.run(); return true; } WaitableRunnable wrapper = new WaitableRunnable(r); if (!handler.post(wrapper)) { return false; } wrapper.join(); return true; }

Target:
public static boolean postAndWait(Handler handler, final Runnable r) { if (Looper.myLooper() == handler.getLooper()) { r.run(); return true; } WaitableRunnable wrapper = new WaitableRunnable(r); if (!handler.post(wrapper)) { return false; } wrapper.join(); return true; }
Source:
protected Object executeWithSubject() throws Exception { if (inputOption) { printTransformers(InputTransformer.class, INPUT); return null; } if (metacardOption) { printTransformers(MetacardTransformer.class, METACARD); return null; } printTransformers(InputTransformer.class, INPUT); printTransformers(MetacardTransformer.class, METACARD); return null; }

Target:
protected Object executeWithSubject() throws Exception { if (!inputOption && !metacardOption) { inputOption = true; metacardOption = true; } if (inputOption) { printTransformers(InputTransformer.class, INPUT); } if (metacardOption) { printTransformers(MetacardTransformer.class, METACARD); } return null; }