auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public SamzaHistogram(MetricsRegistry registry, String group, String name, List<Double> percentiles) { this.histogram = new Histogram(new ExponentiallyDecayingReservoir()); this.percentiles = percentiles; this.gauges = this.percentiles.stream() .filter(x -> x > 0 && x <= 100) .collect(Collectors.toMap(Function.identity(), x -> registry.newGauge(group, new HistogramGauge(name + "_" + String.valueOf(0), 0D)))); }

Target:
public SamzaHistogram(MetricsRegistry registry, String group, String name, List<Double> percentiles) { this.histogram = new Histogram(new ExponentiallyDecayingReservoir()); this.percentiles = percentiles; this.gauges = this.percentiles.stream() .filter(x -> x > 0 && x <= 100) .collect(Collectors.toMap(Function.identity(), x -> registry.newGauge(group, new HistogramGauge(x, name + "_" + String.valueOf(x), 0D)))); }
Source:
private void externalLibraryNullChecks(MethodInvocationTree tree) { if (isNonNullUsed(tree)) { contentResources.replace(tree.arguments().get(0).toString(), true); } else if (isAllNonNullUsed(tree)) { tree.arguments().forEach(contentResource -> contentResources.replace(contentResource.toString(), true)); } else if (insideIfStatement && isThisIsNullMethod(tree)) { insideEqualNullCheck = true; } }

Target:
private void externalLibraryNullChecks(MethodInvocationTree tree) { if (isNonNullUsed(tree)) { contentResources.replace(tree.arguments().get(METHOD_FIRST_ARGUMENT).toString(), true); } else if (isAllNonNullUsed(tree)) { tree.arguments().forEach(contentResource -> contentResources.replace(contentResource.toString(), true)); } else if (insideIfStatement && isThisIsNullMethod(tree)) { insideEqualNullCheck = true; } }
Source:
protected String[][] formatTableContents() { final ArrayList<String[]> formatArray = new ArrayList<String[]>(); int lineCount = 0; for (final DetailedS3Object detailedObject : this.objects) { if((detailedObject.getBlobs() != null) && !Guard.isNullOrEmpty(detailedObject.getBlobs().getObjects())) { for (final BulkObject object : detailedObject.getBlobs().getObjects()) { if (object.getPhysicalPlacement() != null) { if (!Guard.isNullOrEmpty(object.getPhysicalPlacement().getTapes())) { for (final Tape tape : object.getPhysicalPlacement().getTapes()) { final String[] bucketArray = new String[this.columnCount]; bucketArray[0] = nullGuard(detailedObject.getName()); bucketArray[1] = nullGuardToString(detailedObject.getBucketId()); bucketArray[2] = nullGuardToString(detailedObject.getOwner()); bucketArray[3] = nullGuardToString(detailedObject.getSize()); bucketArray[4] = nullGuardToString(detailedObject.getType()); bucketArray[5] = nullGuardToDate(detailedObject.getCreationDate(), DATE_FORMAT); bucketArray[6] = nullGuard(tape.getBarCode()); bucketArray[7] = nullGuardToString(tape.getState()); formatArray.add(bucketArray); lineCount++; } } } } } } String[][] ret = new String[lineCount][this.columnCount]; return formatArray.toArray(ret); }

Target:
protected String[][] formatTableContents() { final ArrayList<String[]> formatArray = new ArrayList<String[]>(); int lineCount = 0; for (final DetailedS3Object detailedObject : this.objects) { if((detailedObject.getBlobs() != null) && !Guard.isNullOrEmpty(detailedObject.getBlobs().getObjects())) { for (final BulkObject object : detailedObject.getBlobs().getObjects()) { if (object.getPhysicalPlacement() != null) { if (!Guard.isNullOrEmpty(object.getPhysicalPlacement().getTapes())) { for (final Tape tape : object.getPhysicalPlacement().getTapes()) { formatArray.add(writeLine(tape, detailedObject)); lineCount++; } } } } } } final String[][] ret = new String[lineCount][this.columnCount]; return formatArray.toArray(ret); }
Source:
public void write( final int b ) throws IOException { if ( nanos < 0 ) { nanos = System.nanoTime(); } super.write( b ); }

Target:
public void write( final int b ) throws IOException { if ( nanos == null ) { nanos = System.nanoTime(); timer = timerProvider.apply( RAW_IO_WRITE ); } super.write( b ); }
Source:
UnicastProcessor(int capacityHint) { this(capacityHint, true); }

Target:
UnicastProcessor(int capacityHint) { this(capacityHint,null, true); }
Source:
default boolean matches(ItemStack stack) { return Preconditions.checkNotNull(stack, "stack").getItem().equals(this); }

Target:
default boolean matches(ItemStack stack) { return checkNotNull(stack, "stack").getItem().equals(this); }
Source:
private static void insertAccount(SQLiteDatabase arg0, String name, int enabled, int flags) { ContentValues arg1 = new ContentValues(); arg1.put(DB.ACCOUNT.NAME, name); if (enabled >= 0) { arg1.put(DB.ACCOUNT.ENABLED, enabled); } if (flags >= 0) { arg1.put(DB.ACCOUNT.FLAGS, flags); } arg1.put(DB.ACCOUNT.FORMAT, FileFormats.GPX.getValue()); arg1.put(DB.ACCOUNT.AUTH_METHOD, "dummy"); long newId = arg0.insertWithOnConflict(DB.ACCOUNT.TABLE, null, arg1, SQLiteDatabase.CONFLICT_IGNORE); if (newId == -1 && arg1.size() > 1) { String arr[] = { arg1.getAsString(DB.ACCOUNT.NAME) }; arg1.remove(DB.ACCOUNT.FORMAT); arg1.remove(DB.ACCOUNT.AUTH_METHOD); arg0.update(DB.ACCOUNT.TABLE, arg1, DB.ACCOUNT.NAME + " = ?", arr); Log.v("DBhelper", "update: " + arg1); } }

Target:
private static void insertAccount(SQLiteDatabase arg0, String name, int enabled, int flags) { ContentValues arg1 = new ContentValues(); arg1.put(DB.ACCOUNT.NAME, name); if (enabled >= 0) { arg1.put(DB.ACCOUNT.ENABLED, enabled); } if (flags >= 0) { arg1.put(DB.ACCOUNT.FLAGS, flags); } arg1.put(DB.ACCOUNT.FORMAT, FileFormats.DEFAULT_FORMATS.toString()); arg1.put(DB.ACCOUNT.AUTH_METHOD, "dummy"); long newId = arg0.insertWithOnConflict(DB.ACCOUNT.TABLE, null, arg1, SQLiteDatabase.CONFLICT_IGNORE); if (newId == -1 && arg1.size() > 1) { String arr[] = { arg1.getAsString(DB.ACCOUNT.NAME) }; arg1.remove(DB.ACCOUNT.FORMAT); arg1.remove(DB.ACCOUNT.AUTH_METHOD); arg0.update(DB.ACCOUNT.TABLE, arg1, DB.ACCOUNT.NAME + " = ?", arr); Log.v("DBhelper", "update: " + arg1); } }
Source:
public void testDeleteNonExistingPodBeforeWatch() { System.out.println( "Start the test of testDeleteNonExistingPodBeforeWatch testDeleteNonExistingPodBeforeWatch testDeleteNonExistingPodBeforeWatch"); final MixedOperation mixedOperation = mock(MixedOperation.class); final NonNamespaceOperation namespaceOperation = mock(NonNamespaceOperation.class); final PodResource podResource = mock(PodResource.class); doReturn(mixedOperation).when(kubernetesClient).pods(); when(mixedOperation.inNamespace(anyString())).thenReturn(namespaceOperation); when(namespaceOperation.withName(anyString())).thenReturn(podResource); doReturn(Boolean.FALSE).when(podResource).delete(); Watch watch = mock(Watch.class); doReturn(watch).when(podResource).watch(any()); try { new KubernetesPods("", "", clientFactory).doDelete("nonExistingPod").get(5, TimeUnit.SECONDS); } catch (InfrastructureException | InterruptedException | ExecutionException | TimeoutException e) { e.printStackTrace(); } verify(watch).close(); }

Target:
public void testDeleteNonExistingPodBeforeWatch() throws Exception { final MixedOperation mixedOperation = mock(MixedOperation.class); final NonNamespaceOperation namespaceOperation = mock(NonNamespaceOperation.class); final PodResource podResource = mock(PodResource.class); doReturn(mixedOperation).when(kubernetesClient).pods(); when(mixedOperation.inNamespace(anyString())).thenReturn(namespaceOperation); when(namespaceOperation.withName(anyString())).thenReturn(podResource); doReturn(Boolean.FALSE).when(podResource).delete(); Watch watch = mock(Watch.class); doReturn(watch).when(podResource).watch(any()); new KubernetesPods("", "", clientFactory).doDelete("nonExistingPod").get(5, TimeUnit.SECONDS); verify(watch).close(); }
Source:
protected abstract void attemptRegistration(Context context) throws Throwable; protected boolean matchesPhone(String phoneEmail) { Pattern p = Pattern.compile("\n"); Matcher m = p.matcher(phoneEmail.substring(0, 1)); return m.matches(); }

Target:
protected abstract void attemptRegistration(Context context) throws Throwable; protected boolean matchesEmail(String phoneEmail) { return Patterns.EMAIL_ADDRESS.matcher(phoneEmail).matches(); }
Source:
void assignResourceRequests() { while (hasReadyPendingRequest()) { SamzaResourceRequest request = peekReadyPendingRequest().get(); String processorId = request.getProcessorId(); String preferredHost = hostAffinityEnabled ? request.getPreferredHost() : ResourceRequestState.ANY_HOST; Instant requestCreationTime = request.getRequestTimestamp(); LOG.info("Handling assignment for Processor ID: with request {}", processorId, request); if (hasAllocatedResource(preferredHost)) { LOG.info("Found an available container for Processor ID: on the host: {}", processorId, preferredHost); if (hostAffinityEnabled) { state.matchedResourceRequests.incrementAndGet(); } boolean containerLaunchComplete = containerManager.handleContainerLaunch(request, preferredHost, peekAllocatedResource(preferredHost), resourceRequestState, this); if (!containerLaunchComplete) { break; } } else { LOG.info("Did not find any allocated containers for running Processor ID: on the host: {}.", processorId, preferredHost); if (isRequestExpired(request)) { updateExpiryMetrics(request); containerManager.handleExpiredRequest(processorId, preferredHost, request, this, resourceRequestState); if (!hostAffinityEnabled) { LOG.info("Host affinity is disabled on expired request."); break; } } else { LOG.info("Request for Processor ID: on preferred host has not expired yet." + "Request creation time: {}. Current Time: {}. Request timeout: ms", processorId, preferredHost, requestCreationTime, System.currentTimeMillis(), getRequestTimeout(request).toMillis()); break; } } } }

Target:
void assignResourceRequests() { while (hasReadyPendingRequest()) { SamzaResourceRequest request = peekReadyPendingRequest().get(); String processorId = request.getProcessorId(); String preferredHost = hostAffinityEnabled ? request.getPreferredHost() : ResourceRequestState.ANY_HOST; Instant requestCreationTime = request.getRequestTimestamp(); LOG.info("Handling assignment for Processor ID: with request {}", processorId, request); if (hasAllocatedResource(preferredHost)) { LOG.info("Found an available container for Processor ID: on the host: {}", processorId, preferredHost); if (hostAffinityEnabled) { state.matchedResourceRequests.incrementAndGet(); } boolean containerLaunchComplete = containerManager.handleContainerLaunch(request, preferredHost, peekAllocatedResource(preferredHost), resourceRequestState, this); if (!containerLaunchComplete) { break; } } else { LOG.info("Did not find any allocated containers for running Processor ID: on the host: {}.", processorId, preferredHost); if (isRequestExpired(request)) { updateExpiryMetrics(request); containerManager.handleExpiredRequest(processorId, preferredHost, request, this, resourceRequestState); if (!hostAffinityEnabled) { LOG.info("Waiting for resources to get allocated for request {}," + " no retries will be issued since host affinity is disabled", request); break; } } else { LOG.info("Request for Processor ID: on preferred host has not expired yet." + "Request creation time: {}. Current Time: {}. Request timeout: ms", processorId, preferredHost, requestCreationTime, System.currentTimeMillis(), getRequestTimeout(request).toMillis()); break; } } } }
Source:
protected void choiceDestroy(GQuery link) { choices--; showSearchFieldDefault(defaultText); if (isMultiple() && choices > 0 && searchField.val() != null && searchField.val().length() < 1) { resultsHide(); } resultDeselect(Integer.parseInt(link.attr("rel")), link.attr("data-chosensample-value")); link.parents("li").first().remove(); }

Target:
protected void choiceDestroy(GQuery link) { choices--; showSearchFieldDefault(defaultText); if (isMultiple() && choices > 0 && searchField.val() != null && searchField.val().length() < 1) { resultsHide(); } resultDeselect(Integer.parseInt(link.attr("rel")), link.attr("data-chosen-value")); link.parents("li").first().remove(); }
Source:
public void runFailedAutoStartVM(Guid vmId) { final AuditLogableBase event = new AuditLogableBase(); event.setVmId(vmId); AuditLogDirector.log(event, AuditLogType.HA_VM_FAILED); log.infoFormat("Restart of the Highly Available VM was initiated due to failure. VM Name:{0}, VM Id:{1}", event.getVmName(), vmId); final VdcReturnValueBase result = Backend.getInstance().runInternalAction(VdcActionType.RunVm, new RunVmParams(vmId), ExecutionHandler.createInternalJobContext()); if (!result.getSucceeded()) { AuditLogDirector.log(event, AuditLogType.HA_VM_RESTART_FAILED); } }

Target:
public void runFailedAutoStartVM(Guid vmId) { final AuditLogableBase event = new AuditLogableBase(); event.setVmId(vmId); AuditLogDirector.log(event, AuditLogType.HA_VM_FAILED); log.infoFormat("Failed to start Highly Available VM. Attempting to restart. VM Name: {0}, VM Id:{1}", event.getVmName(), vmId); final VdcReturnValueBase result = Backend.getInstance().runInternalAction(VdcActionType.RunVm, new RunVmParams(vmId), ExecutionHandler.createInternalJobContext()); if (!result.getSucceeded()) { AuditLogDirector.log(event, AuditLogType.HA_VM_RESTART_FAILED); } }
Source:
protected boolean canDoAction() { ProviderValidator validator = new ProviderValidator(getProvider()); return validate(validator.providerIsSet()) && super.canDoAction(); }

Target:
protected boolean canDoAction() { ProviderValidator validator = new ProviderValidator(getProvider()); return validate(validator.providerIsSet()); }
Source:
public void startBucket(String bucketKey) { BulkCommand command = getCurrentCommand(); Serializable auditParam = command.getParam(NXAuditEventsService.DISABLE_AUDIT_LOGGER); disableAudit = auditParam != null && Boolean.parseBoolean(auditParam.toString()); retentionManager = Framework.getService(RetentionManager.class); ruleId = (String) command.getParam(PARAM_RULE_ID); }

Target:
public void startBucket(String bucketKey) { BulkCommand command = getCurrentCommand(); Serializable auditParam = command.getParam(NXAuditEventsService.DISABLE_AUDIT_LOGGER); disableAudit = auditParam != null && Boolean.parseBoolean(auditParam.toString()); retentionManager = Framework.getService(RetentionManager.class); ruleId = command.getParam(PARAM_RULE_ID); }
Source:
public Form() { }

Target:
public Form() { this(FormType.DEFAULT); }
Source:
public ValidationResult validate() { Collection<NetworkAttachment> attachmentsToConfigure = getAttachmentsToConfigure(); ValidationResult vr = ValidationResult.VALID; vr = skipValidation(vr) ? vr : new NicLabelValidator(params, existingInterfacesMap, bondsMap, hostSetupNetworksValidatorHelper).validate(); vr = skipValidation(vr) ? vr : validNewOrModifiedNetworkAttachments(); vr = skipValidation(vr) ? vr : validRemovedNetworkAttachments(); vr = skipValidation(vr) ? vr : validNewOrModifiedBonds(); vr = skipValidation(vr) ? vr : validRemovedBonds(attachmentsToConfigure); vr = skipValidation(vr) ? vr : attachmentsDontReferenceSameNetworkDuplicately(attachmentsToConfigure); vr = skipValidation(vr) ? vr : networksUniquelyConfiguredOnHost(attachmentsToConfigure); vr = skipValidation(vr) ? vr : validateNetworkExclusiveOnNics(attachmentsToConfigure); vr = skipValidation(vr) ? vr : new NetworkMtuValidator(networkBusinessEntityMap).validateMtu( attachmentsToConfigure); vr = skipValidation(vr) ? vr : validateCustomProperties(); vr = skipValidation(vr) ? vr : validateQos(attachmentsToConfigure); vr = skipValidation(vr) ? vr : validateBondModeVsNetworksAttachedToIt(attachmentsToConfigure); vr = skipValidation(vr) ? vr : networkAttachmentIpConfigurationValidator.validateNetworkAttachmentIpConfiguration(params.getNetworkAttachments()); return vr; }

Target:
public ValidationResult validate() { Collection<NetworkAttachment> attachmentsToConfigure = getAttachmentsToConfigure(); ValidationResult vr = ValidationResult.VALID; vr = skipValidation(vr) ? vr : new NicLabelValidator(params, existingInterfacesMap, bondsMap, hostSetupNetworksValidatorHelper).validate(); vr = skipValidation(vr) ? vr : validNewOrModifiedNetworkAttachments(); vr = skipValidation(vr) ? vr : validRemovedNetworkAttachments(); vr = skipValidation(vr) ? vr : validNewOrModifiedBonds(); vr = skipValidation(vr) ? vr : validRemovedBonds(attachmentsToConfigure); vr = skipValidation(vr) ? vr : attachmentsDontReferenceSameNetworkDuplicately(attachmentsToConfigure); vr = skipValidation(vr) ? vr : networksUniquelyConfiguredOnHost(attachmentsToConfigure); vr = skipValidation(vr) ? vr : validateNetworkExclusiveOnNics(attachmentsToConfigure); vr = skipValidation(vr) ? vr : new NetworkMtuValidator(networkBusinessEntityMap).validateMtu( attachmentsToConfigure); vr = skipValidation(vr) ? vr : validateCustomProperties(); vr = skipValidation(vr) ? vr : validateQos(attachmentsToConfigure); vr = skipValidation(vr) ? vr : validateBondModeVsNetworksAttachedToIt(attachmentsToConfigure); return vr; }
Source:
protected Control createDialogArea(Composite parent) { Composite main = new Composite(parent, SWT.NONE); main.setLayout(new GridLayout(1, false)); GridDataFactory.fillDefaults().grab(true, true).applyTo(main); if (result.getFetchResult() != null) { FetchResultDialog dlg = new FetchResultDialog(getParentShell(), repo, result.getFetchResult(), result.getFetchedFrom()); dlg.createDialogArea(main); } if (result.getMergeResult() != null) { MergeResultDialog dlg = new MergeResultDialog(getParentShell(), repo, result.getMergeResult()); dlg.createDialogArea(main); } return main; }

Target:
protected Control createDialogArea(Composite parent) { Composite main = new Composite(parent, SWT.VERTICAL); main.setLayout(new GridLayout(1, false)); GridDataFactory.fillDefaults().grab(true, true).applyTo(main); Group fetchResultGroup = new Group(main, SWT.SHADOW_ETCHED_IN); fetchResultGroup .setText(UIText.PullResultDialog_FetchResultGroupHeader); fetchResultGroup.setLayout(new GridLayout(1, false)); GridDataFactory.fillDefaults().grab(true, true).applyTo( fetchResultGroup); if (result.getFetchResult() != null) { FetchResultDialog dlg = new FetchResultDialog(getParentShell(), repo, result.getFetchResult(), result.getFetchedFrom()); Control fresult = dlg.createDialogArea(fetchResultGroup); GridDataFactory.fillDefaults().grab(true, true).hint(SWT.DEFAULT, 130).applyTo(fresult); } Group mergeResultGroup = new Group(main, SWT.SHADOW_ETCHED_IN); mergeResultGroup .setText(UIText.PullResultDialog_MergeResultGroupHeader); mergeResultGroup.setLayout(new GridLayout(1, false)); GridDataFactory.fillDefaults().grab(true, true).applyTo( mergeResultGroup); if (result.getMergeResult() != null) { MergeResultDialog dlg = new MergeResultDialog(getParentShell(), repo, result.getMergeResult()); dlg.createDialogArea(mergeResultGroup); } return main; }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getSysPrepUserName() == null ^ getParameters().getSysPrepPassword() == null) { return failCanDoAction(VdcBllMessages.VM_CANNOT_RUN_ONCE_WITH_ILLEGAL_SYSPREP_PARAM); } if (getParameters().getVmInit() != null) { if (!OsRepositoryImpl.INSTANCE.isWindows(getVm().getOs()) && !FeatureSupported.cloudInit(getVm().getVdsGroupCompatibilityVersion())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CLOUD_INIT_IS_NOT_SUPPORTED); } if (getParameters().getVmInit().isPasswordAlreadyStored()) { VmBase temp = new VmBase(); temp.setId(getParameters().getVmId()); VmHandler.updateVmInitFromDB(temp, false); getParameters().getVmInit().setRootPassword(temp.getVmInit().getRootPassword()); } } if (getParameters().getVmPayload() == null) { loadPayload(); } return true; }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getSysPrepUserName() == null ^ getParameters().getSysPrepPassword() == null) { return failCanDoAction(VdcBllMessages.VM_CANNOT_RUN_ONCE_WITH_ILLEGAL_SYSPREP_PARAM); } if (getParameters().getVmInit() != null) { if (!OsRepositoryImpl.INSTANCE.isWindows(getVm().getOs()) && !FeatureSupported.cloudInit(getVm().getVdsGroupCompatibilityVersion())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CLOUD_INIT_IS_NOT_SUPPORTED); } if (getParameters().getVmInit().isPasswordAlreadyStored()) { VmBase temp = new VmBase(); temp.setId(getParameters().getVmId()); VmHandler.updateVmInitFromDB(temp, false); getParameters().getVmInit().setRootPassword(temp.getVmInit().getRootPassword()); } } return true; }
Source:
public void testRuleTableGDSTWorkItem() throws Exception { final String xml = loadResource("WorkItem.gdst"); final GuidedDecisionTable52 table52 = GuidedDTXMLPersistence.getInstance() .unmarshal(xml); final Analyzer analyzer = analyzerProvider.makeAnalyser(table52); analyzer.resetChecks(); analyzer.analyze(); final Set<Issue> analysisReport = analyzerProvider.getAnalysisReport(); for (final Issue issue : analysisReport) { System.out.println(issue.getCheckType()); System.out.println(issue.getDebugMessage()); } assertTrue(analysisReport.isEmpty()); }

Target:
public void testRuleTableGDSTWorkItem() throws Exception { final String xml = loadResource("WorkItem.gdst"); final GuidedDecisionTable52 table52 = GuidedDTXMLPersistence.getInstance() .unmarshal(xml); final Analyzer analyzer = analyzerProvider.makeAnalyser(table52); analyzer.resetChecks(); analyzer.analyze(); final Set<Issue> analysisReport = analyzerProvider.getAnalysisReport(); assertTrue(analysisReport.isEmpty()); }
Source:
public void updatingTimestampForOneShardDoesNotAffectOthers() { progress.updateLastSweptTimestampPartition(10, true, 1024L); assertThat(progress.getLastSweptTimestampPartition(20, true)).isEqualTo(-1L); progress.updateLastSweptTimestampPartition(20, true, 512L); assertThat(progress.getLastSweptTimestampPartition(20, true)).isEqualTo(512L); assertThat(progress.getLastSweptTimestampPartition(10, true)).isEqualTo(1024L); }

Target:
public void updatingTimestampForOneShardDoesNotAffectOthers() { assertThat(progress.getLastSweptTimestampPartition(CONSERVATIVE_TEN)).isEqualTo(INITIAL_TIMESTAMP); assertThat(progress.getLastSweptTimestampPartition(CONSERVATIVE_TWENTY)).isEqualTo(INITIAL_TIMESTAMP); progress.updateLastSweptTimestampPartition(CONSERVATIVE_TEN, 1024L); assertThat(progress.getLastSweptTimestampPartition(CONSERVATIVE_TWENTY)).isEqualTo(INITIAL_TIMESTAMP); progress.updateLastSweptTimestampPartition(CONSERVATIVE_TWENTY, 512L); assertThat(progress.getLastSweptTimestampPartition(CONSERVATIVE_TWENTY)).isEqualTo(512L); assertThat(progress.getLastSweptTimestampPartition(CONSERVATIVE_TEN)).isEqualTo(1024L); }
Source:
protected void deleteItems(List<Scene> selectedItems) { setShowProgressBar(true); for (Scene item : selectedItems) { try { sceneController.delete(item); } catch (IOException e) { Log.e(TAG, Log.getStackTraceString(e)); } adapter.remove(item); } ToastUtil.showSuccess(getActivity(), getResources().getQuantityString(R.plurals.deleted_scenes, selectedItems.size(), selectedItems.size())); finishActionMode(); if (adapter.getItems().isEmpty()) { createEmptySceneWithDefaultName(); } Project currentProject = ProjectManager.getInstance().getCurrentProject(); if (currentProject.getSceneList().size() < 2) { switchToSpriteListFragment(currentProject); } }

Target:
protected void deleteItems(List<Scene> selectedItems) { setShowProgressBar(true); for (Scene item : selectedItems) { try { sceneController.delete(item); } catch (IOException e) { Log.e(TAG, Log.getStackTraceString(e)); } adapter.remove(item); } ToastUtil.showSuccess(getActivity(), getResources().getQuantityString(R.plurals.deleted_scenes, selectedItems.size(), selectedItems.size())); finishActionMode(); if (adapter.getItems().isEmpty()) { createEmptySceneWithDefaultName(); } Project currentProject = ProjectManager.getInstance().getCurrentProject(); if (currentProject.getSceneList().size() < 2) { ProjectManager.getInstance().setCurrentlyEditedScene(currentProject.getDefaultScene()); switchToSpriteListFragment(); } }
Source:
public Sequence<T> run(final Query<T> query) { final boolean isBySegment = query.getContextBySegment(false); final boolean shouldFinalize = query.getContextFinalize(true); Function<T, T> finalizerFn; if (shouldFinalize) { if (isBySegment) { finalizerFn = new Function<T, T>() { final Function<T, T> baseFinalizer = toolChest.makePostComputeManipulatorFn( query, new MetricManipulationFn() { @Override public Object manipulate(AggregatorFactory factory, Object object) { return factory.finalizeComputation(factory.deserialize(object)); } } ); @Override @SuppressWarnings("unchecked") public T apply(@Nullable T input) { Result<BySegmentResultValueClass<T>> result = (Result<BySegmentResultValueClass<T>>) input; BySegmentResultValueClass<T> resultsClass = result.getValue(); return (T) new Result<BySegmentResultValueClass>( result.getTimestamp(), new BySegmentResultValueClass( Lists.transform(resultsClass.getResults(), baseFinalizer), resultsClass.getSegmentId(), resultsClass.getInterval() ) ); } }; } else { finalizerFn = toolChest.makePostComputeManipulatorFn( query, new MetricManipulationFn() { @Override public Object manipulate(AggregatorFactory factory, Object object) { return factory.finalizeComputation(object); } } ); } } else { finalizerFn = toolChest.makePostComputeManipulatorFn( query, new MetricManipulationFn() { @Override public Object manipulate(AggregatorFactory factory, Object object) { return object; } } ); } return Sequences.map( baseRunner.run(query.withOverriddenContext(ImmutableMap.<String, Object>of("finalize", false))), finalizerFn ); }

Target:
public Sequence<T> run(final Query<T> query) { final boolean isBySegment = query.getContextBySegment(false); final boolean shouldFinalize = query.getContextFinalize(true); final Query<T> queryToRun; final Function<T, T> finalizerFn; if (shouldFinalize) { queryToRun = query.withOverriddenContext(ImmutableMap.<String, Object>of("finalize", false)); if (isBySegment) { finalizerFn = new Function<T, T>() { final Function<T, T> baseFinalizer = toolChest.makePostComputeManipulatorFn( query, new FinalizeMetricManipulationFn() ); @Override @SuppressWarnings("unchecked") public T apply(@Nullable T input) { Result<BySegmentResultValueClass<T>> result = (Result<BySegmentResultValueClass<T>>) input; BySegmentResultValueClass<T> resultsClass = result.getValue(); return (T) new Result<BySegmentResultValueClass>( result.getTimestamp(), new BySegmentResultValueClass( Lists.transform(resultsClass.getResults(), baseFinalizer), resultsClass.getSegmentId(), resultsClass.getInterval() ) ); } }; } else { finalizerFn = toolChest.makePostComputeManipulatorFn(query, new FinalizeMetricManipulationFn()); } } else { queryToRun = query; finalizerFn = toolChest.makePostComputeManipulatorFn( query, new IdentityMetricManipulationFn() ); } return Sequences.map( baseRunner.run(queryToRun), finalizerFn ); }
Source:
public void createPartControl(Composite parent) { super.createPartControl(parent); pinPropertySheetAction.addPropertyChangeListener(new IPropertyChangeListener(){ @Override public void propertyChange(PropertyChangeEvent event) { if (IAction.CHECKED.equals(event.getProperty())) { updateContentDescription(); } } }); IMenuManager menuManager = getViewSite().getActionBars() .getMenuManager(); menuManager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); menuManager.add(pinPropertySheetAction); IToolBarManager toolBarManager = getViewSite().getActionBars() .getToolBarManager(); menuManager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); toolBarManager.add(pinPropertySheetAction); SaveablesList saveables = (SaveablesList) getSite().getService(ISaveablesLifecycleListener.class); saveables.addModelLifecycleListener(saveablesTracker); getSite().getPage().getWorkbenchWindow().getWorkbench().getHelpSystem() .setHelp(getPageBook(), IPropertiesHelpContextIds.PROPERTY_SHEET_VIEW); }

Target:
public void createPartControl(Composite parent) { super.createPartControl(parent); pinPropertySheetAction.addPropertyChangeListener(new IPropertyChangeListener(){ @Override public void propertyChange(PropertyChangeEvent event) { if (IAction.CHECKED.equals(event.getProperty())) { updateContentDescription(); } } }); IMenuManager menuManager = getViewSite().getActionBars() .getMenuManager(); menuManager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); menuManager.add(pinPropertySheetAction); IToolBarManager toolBarManager = getViewSite().getActionBars() .getToolBarManager(); menuManager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); toolBarManager.add(pinPropertySheetAction); SaveablesList saveables = (SaveablesList) getSite().getService(ISaveablesLifecycleListener.class); if (saveables != null) { saveables.addModelLifecycleListener(saveablesTracker); } getSite().getPage().getWorkbenchWindow().getWorkbench().getHelpSystem() .setHelp(getPageBook(), IPropertiesHelpContextIds.PROPERTY_SHEET_VIEW); }
Source:
private static List<List<ScheduledSplit>> assignSplitsToTasks(List<ScheduledSplit> scheduledSplits, int numTasks) { List<List<ScheduledSplit>> assignedSplits = new ArrayList<>(); for (int i = 0; i < numTasks; i++) { assignedSplits.add(new ArrayList<>()); } for (ScheduledSplit split : scheduledSplits) { int taskId = split.hashCode() % numTasks; if (taskId < 0) { taskId += numTasks; } assignedSplits.get(taskId).add(split); } return assignedSplits; }

Target:
private static List<List<ScheduledSplit>> assignSplitsToTasks(List<ScheduledSplit> scheduledSplits, int numTasks) { List<List<ScheduledSplit>> assignedSplits = new ArrayList<>(); for (int i = 0; i < numTasks; i++) { assignedSplits.add(new ArrayList<>()); } for (ScheduledSplit split : scheduledSplits) { int taskId = Objects.hash(split.getPlanNodeId(), split.getSequenceId()) % numTasks; if (taskId < 0) { taskId += numTasks; } assignedSplits.get(taskId).add(split); } return assignedSplits; }
Source:
private boolean shouldPerformRecursiveChanges(List changes) { if (!changes.isEmpty()) { StringBuilder message = new StringBuilder(IDEWorkbenchMessages.ResourceInfo_recursiveChangesSummary) .append("\n"); for (int i = 0; i < changes.size(); i++) { message.append(((IResourceChange) changes.get(i)).getMessage()); } message.append(IDEWorkbenchMessages.ResourceInfo_recursiveChangesQuestion); MessageDialog dialog = new MessageDialog(getShell(), IDEWorkbenchMessages.ResourceInfo_recursiveChangesTitle, null, message.toString(), MessageDialog.QUESTION, 1, IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL); return dialog.open() == 0; } return false; }

Target:
private boolean shouldPerformRecursiveChanges(List changes) { if (!changes.isEmpty()) { StringBuilder message = new StringBuilder(IDEWorkbenchMessages.ResourceInfo_recursiveChangesSummary) .append('\n'); for (int i = 0; i < changes.size(); i++) { message.append(((IResourceChange) changes.get(i)).getMessage()); } message.append(IDEWorkbenchMessages.ResourceInfo_recursiveChangesQuestion); MessageDialog dialog = new MessageDialog(getShell(), IDEWorkbenchMessages.ResourceInfo_recursiveChangesTitle, null, message.toString(), MessageDialog.QUESTION, 1, IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL); return dialog.open() == 0; } return false; }
Source:
public void testOnNextPropagation() throws Exception { LOG.info("gRPC pingAsyncSync method aync test start"); final CountDownLatch latch = new CountDownLatch(1); PingRequest pingRequest = PingRequest.newBuilder().setPingName(GRPC_TEST_PING_VALUE).setPingId(GRPC_TEST_PING_ID).build(); PongResponseStreamObserver responseObserver = new PongResponseStreamObserver(latch); StreamObserver<PingRequest> requestObserver = asyncNonBlockingStub.pingAsyncSync(responseObserver); requestObserver.onNext(pingRequest); latch.await(5, TimeUnit.SECONDS); MockEndpoint mockEndpoint = getMockEndpoint("mock:async-propagation"); mockEndpoint.expectedMessageCount(1); mockEndpoint.expectedHeaderValuesReceivedInAnyOrder(GrpcConstants.GRPC_EVENT_TYPE_HEADER, GrpcConstants.GRPC_EVENT_TYPE_ON_NEXT); mockEndpoint.expectedHeaderValuesReceivedInAnyOrder(GrpcConstants.GRPC_METHOD_NAME_HEADER, "pingAsyncSync"); PongResponse pongResponse = responseObserver.getPongResponse(); assertNotNull(pongResponse); assertEquals(GRPC_TEST_PING_ID, pongResponse.getPongId()); assertEquals(GRPC_TEST_PING_VALUE + GRPC_TEST_PONG_VALUE, pongResponse.getPongName()); }

Target:
public void testOnNextPropagation() throws Exception { LOG.info("gRPC pingAsyncSync method aync test start"); final CountDownLatch latch = new CountDownLatch(1); PingRequest pingRequest = PingRequest.newBuilder().setPingName(GRPC_TEST_PING_VALUE).setPingId(GRPC_TEST_PING_ID).build(); PongResponseStreamObserver responseObserver = new PongResponseStreamObserver(latch); StreamObserver<PingRequest> requestObserver = asyncOnNextStub.pingAsyncSync(responseObserver); requestObserver.onNext(pingRequest); latch.await(5, TimeUnit.SECONDS); MockEndpoint mockEndpoint = getMockEndpoint("mock:async-on-next-propagation"); mockEndpoint.expectedMessageCount(1); mockEndpoint.expectedHeaderValuesReceivedInAnyOrder(GrpcConstants.GRPC_EVENT_TYPE_HEADER, GrpcConstants.GRPC_EVENT_TYPE_ON_NEXT); mockEndpoint.expectedHeaderValuesReceivedInAnyOrder(GrpcConstants.GRPC_METHOD_NAME_HEADER, "pingAsyncSync"); mockEndpoint.assertIsSatisfied(); PongResponse pongResponse = responseObserver.getPongResponse(); assertNotNull(pongResponse); assertEquals(GRPC_TEST_PING_ID, pongResponse.getPongId()); assertEquals(GRPC_TEST_PING_VALUE + GRPC_TEST_PONG_VALUE, pongResponse.getPongName()); }
Source:
public void checkExecuteCommandWithEmptyVdsId() { parameters.setStorageServerConnection(NFSConnection); parameters.setVdsId(Guid.Empty); doNothing().when(storageServerConnectionDAO).remove(NFSConnection.getid()); command.executeCommand(); }

Target:
public void checkExecuteCommandWithEmptyVdsId() { parameters.setStorageServerConnection(NFSConnection); parameters.setVdsId(Guid.Empty); doNothing().when(storageServerConnectionDAO).remove(NFSConnection.getid()); command.executeCommand(); verify(command, never()).disconnectStorage(); }
Source:
public int getTechIntroYear() { if (campaignOptions.limitByYear()) { return calendar.get(Calendar.YEAR); } else { return 0; } }

Target:
public int getTechIntroYear() { if (campaignOptions.limitByYear()) { return calendar.get(Calendar.YEAR); } else { return Integer.MAX_VALUE; } }
Source:
public void getAttachment(Long attachmentId) throws IOException { Attachment attachment = attachments.load(attachmentId); if (attachment == null) { result.notFound(); return; } try { InputStream is = fileStorage.open(attachment); response.setHeader("Content-Type", attachment.getMime()); send(is); } catch (FileNotFoundException e) { result.notFound(); } }

Target:
public InputStreamDownload getAttachment(Long attachmentId) throws IOException { Attachment attachment = attachments.load(attachmentId); InputStream is = attachments.open(attachment); return new InputStreamDownload(is, attachment.getMime(), attachment.getName()); }
Source:
public ServerContext build() { ServerConfiguration conf = new ServerConfiguration() .setSingleMode(single) .setInMemoryMode(memory) .setHandshakeTimeout(handshakeTimeout) .setSequencerConflictWindowSize(seqCache) .setLogSizeQuota(logSizeLimitPercentage) .setStateTransferBatchSize(batchSize) .setMetadataRetention(retention) .setCompressionCodec(compressionCodec); if (logPath != null) { conf.setServerDirectory(logPath); } conf.setVerifyChecksum(verifyChecksum) .setSyncData(syncData) .setHostAddress(address) .setServerPort(port) .setLogUnitCacheRatio(cacheSizeHeapRatio) .setEnableTls(tlsEnabled) .setEnableTlsMutualAuth(tlsMutualAuthEnabled) .setTlsProtocols(tlsProtocols) .setTlsCiphers(tlsCiphers) .setKeystore(keystore) .setKeystorePasswordFile(keystorePasswordFile) .setTruststore(truststore) .setTruststorePasswordFile(truststorePasswordFile) .setEnableSaslPlainTextAuth(saslPlainTextAuth) .setClusterId(clusterId) .setChannelImplementation(implementation); if (implementation == ChannelImplementation.LOCAL) { conf.setTestClientEventLoop(TestThreadGroups.NETTY_CLIENT_GROUP.get().next()) .setTestBossEventLoop(TestThreadGroups.NETTY_BOSS_GROUP.get()) .setTestWorkerEventLoop(TestThreadGroups.NETTY_CLIENT_GROUP.get()); } ServerContext sc = new ServerContext(conf); sc.setServerRouter(serverRouter); return sc; }

Target:
public ServerContext build() { ServerConfiguration conf = new ServerConfiguration() .setSingleMode(single) .setInMemoryMode(memory) .setHandshakeTimeout(handshakeTimeout) .setSequencerConflictWindowSize(seqCache) .setLogSizeQuota(logSizeLimitPercentage) .setStateTransferBatchSize(batchSize) .setMetadataRetention(retention); if (logPath != null) { conf.setServerDirectory(logPath); } conf.setVerifyChecksum(verifyChecksum) .setSyncData(syncData) .setHostAddress(address) .setServerPort(port) .setLogUnitCacheRatio(cacheSizeHeapRatio) .setEnableTls(tlsEnabled) .setEnableTlsMutualAuth(tlsMutualAuthEnabled) .setTlsProtocols(tlsProtocols) .setTlsCiphers(tlsCiphers) .setKeystore(keystore) .setKeystorePasswordFile(keystorePasswordFile) .setTruststore(truststore) .setTruststorePasswordFile(truststorePasswordFile) .setEnableSaslPlainTextAuth(saslPlainTextAuth) .setClusterId(clusterId) .setChannelImplementation(implementation); if (implementation == ChannelImplementation.LOCAL) { conf.setTestClientEventLoop(TestThreadGroups.NETTY_CLIENT_GROUP.get().next()) .setTestBossEventLoop(TestThreadGroups.NETTY_BOSS_GROUP.get()) .setTestWorkerEventLoop(TestThreadGroups.NETTY_CLIENT_GROUP.get()); } ServerContext sc = new ServerContext(conf); sc.setServerRouter(serverRouter); return sc; }
Source:
private void performTestForJDBCParamUsage(String jdbcUrl) throws SQLException { try (HikariDataSource dataSource = getDataSource(jdbcUrl, 1)) { boolean result = new QueryRunner(dataSource).query("select CURRENT_USER", rs -> { rs.next(); String resultUser = rs.getString(1); if(resultUser.endsWith("@%")) resultUser = resultUser.substring(0, resultUser.length() - 2); assertEquals("User from query param is created.", "someuser", resultUser); return true; }); assertTrue("The database returned a record as expected", result); String databaseQuery = "SELECT DATABASE()"; String databaseType = ConnectionUrl.newInstance(jdbcUrl).getDatabaseType(); if(databaseType.equalsIgnoreCase("postgresql") || databaseType.equalsIgnoreCase("postgis")) databaseQuery = "SELECT CURRENT_DATABASE()"; result = new QueryRunner(dataSource).query(databaseQuery, rs -> { rs.next(); String resultDB = rs.getString(1); assertEquals("Database name from URL String is used.", "databasename", resultDB); return true; }); assertTrue("The database returned a record as expected", result); } }

Target:
private void performTestForJDBCParamUsage(String jdbcUrl) throws SQLException { try (HikariDataSource dataSource = getDataSource(jdbcUrl, 1)) { boolean result = new QueryRunner(dataSource).query("select CURRENT_USER", rs -> { rs.next(); String resultUser = rs.getString(1); if (resultUser.endsWith("@%")) { resultUser = resultUser.substring(0, resultUser.length() - 2); } assertEquals("User from query param is created.", "someuser", resultUser); return true; }); assertTrue("The database returned a record as expected", result); String databaseQuery = "SELECT DATABASE()"; String databaseType = ConnectionUrl.newInstance(jdbcUrl).getDatabaseType(); if (databaseType.equalsIgnoreCase("postgresql") || databaseType.equalsIgnoreCase("postgis")) { databaseQuery = "SELECT CURRENT_DATABASE()"; } result = new QueryRunner(dataSource).query(databaseQuery, rs -> { rs.next(); String resultDB = rs.getString(1); assertEquals("Database name from URL String is used.", "databasename", resultDB); return true; }); assertTrue("The database returned a record as expected", result); } }
Source:
public void updateTicketTypeTestNoneThere() { TicketType ticketType = new TicketType("type1", "text", 5F, 0, LocalDateTime.now(), false); ticketType = ticketService.updateTicketType(ticketType.getId(), ticketType); assertFalse(ticketType.isBuyable()); }

Target:
public void updateTicketTypeTestNoneThere() { thrown.expect(TicketTypeNotFoundException.class); thrown.expectMessage("TicketType with ID null not found!"); TicketType ticketType = new TicketType("type1", "text", 5F, 0, LocalDateTime.now(), false); ticketService.updateTicketType(ticketType.getId(), ticketType); }
Source:
private StorableKey buildStorableKey(String namespace, List<QueryParam> queryParams) throws Exception { final Map<Schema.Field, Object> fieldsToVal = new HashMap<>(); StorableKey storableKey = null; try { for (QueryParam qp : queryParams) { if (!queryExecutor.isColumnInNamespace(namespace, qp.getName())) { log.warn("Query parameter does not exist for namespace [{}]. Query parameter ignored.", qp.getName(), namespace); } else { final String val = qp.getValue(); final Schema.Type typeOfVal = Schema.Type.getTypeOfVal(val); fieldsToVal.put(new Schema.Field(qp.getName(), typeOfVal), typeOfVal.getJavaType().getConstructor(String.class).newInstance(val)); } } if (!fieldsToVal.isEmpty()) { final PrimaryKey primaryKey = new PrimaryKey(fieldsToVal); storableKey = new StorableKey(namespace, primaryKey); } log.debug("Building StorableKey from QueryParam: \n\tnamespace = [{}]\n\t queryParams = [{}]\n\t StorableKey = [{}]", namespace, queryParams, storableKey); } catch (Exception e) { log.debug("Exception occurred when attempting to generate StorableKey from QueryParam", e); throw new IllegalQueryParameterException(e); } return storableKey; }

Target:
private StorableKey buildStorableKey(String namespace, List<QueryParam> queryParams) throws Exception { final Map<Schema.Field, Object> fieldsToVal = new HashMap<>(); StorableKey storableKey = null; try { CaseAgnosticStringSet columnNames = queryExecutor.getColumnNames(namespace); for (QueryParam qp : queryParams) { if (!columnNames.contains(qp.getName())) { log.warn("Query parameter does not exist for namespace [{}]. Query parameter ignored.", qp.getName(), namespace); } else { final String val = qp.getValue(); final Schema.Type typeOfVal = Schema.Type.getTypeOfVal(val); fieldsToVal.put(new Schema.Field(qp.getName(), typeOfVal), typeOfVal.getJavaType().getConstructor(String.class).newInstance(val)); } } if (!fieldsToVal.isEmpty()) { final PrimaryKey primaryKey = new PrimaryKey(fieldsToVal); storableKey = new StorableKey(namespace, primaryKey); } log.debug("Building StorableKey from QueryParam: \n\tnamespace = [{}]\n\t queryParams = [{}]\n\t StorableKey = [{}]", namespace, queryParams, storableKey); } catch (Exception e) { log.debug("Exception occurred when attempting to generate StorableKey from QueryParam", e); throw new IllegalQueryParameterException(e); } return storableKey; }
Source:
public Object handle(CommandMessage<?> command) throws Exception { AtomicReference<Object> resultReference = new AtomicReference<>(); Aggregate<T> aggregate = repository.newInstance(() -> { T newInstance = factoryMethod.call(); resultReference.set(handler.handle(command, newInstance)); return newInstance; }); Object commandHandlingResult = resultReference.get(); return commandHandlingResult != null ? commandHandlingResult : resolveReturnValue(command, aggregate); }

Target:
public Object handle(CommandMessage<?> command) throws Exception { AtomicReference<Object> resultReference = new AtomicReference<>(); Aggregate<T> aggregate = repository.newInstance(() -> { T newInstance = factoryMethod.call(); resultReference.set(handler.handle(command, newInstance)); return newInstance; }); return handlerHasVoidReturnType() ? resolveReturnValue(command, aggregate) : resultReference.get(); }
Source:
protected ScenarioResult fillResult(FactMappingValue expectedResult, Supplier<ResultWrapper<?>> resultSupplier, ExpressionEvaluator expressionEvaluator) { ResultWrapper<?> resultValue = resultSupplier.get(); if (!resultValue.isSatisfied() && resultValue.getErrorMessage().isPresent()) { expectedResult.setExceptionMessage(resultValue.getErrorMessage().get()); } else if (!resultValue.isSatisfied()) { try { expectedResult.setErrorValue(expressionEvaluator.fromObjectToExpression(resultValue.getResult())); } catch (Exception e) { expectedResult.setExceptionMessage(e.getMessage()); } } else { expectedResult.resetStatus(); } return new ScenarioResult(expectedResult, resultValue.getResult()).setResult(resultValue.isSatisfied()); }

Target:
protected ScenarioResult fillResult(FactMappingValue expectedResult, Supplier<ResultWrapper<?>> resultSupplier, ExpressionEvaluator expressionEvaluator) { ResultWrapper<?> resultValue = resultSupplier.get(); if (resultValue.isSatisfied()) { expectedResult.resetStatus(); } else if (resultValue.getErrorMessage().isPresent()) { expectedResult.setExceptionMessage(resultValue.getErrorMessage().get()); } else { try { expectedResult.setErrorValue(expressionEvaluator.fromObjectToExpression(resultValue.getResult())); } catch (Exception e) { expectedResult.setExceptionMessage(e.getMessage()); } } return new ScenarioResult(expectedResult, resultValue.getResult()).setResult(resultValue.isSatisfied()); }
Source:
public DatasetWriter<E> load(StorageKey key) throws Exception { Preconditions.checkArgument(view.contains(key), "View does not contain StorageKey {}", view, key); Preconditions.checkState(view.getDataset() instanceof FileSystemDataset, "FileSystemWriters cannot create writer for " + view.getDataset()); final FileSystemDataset dataset = (FileSystemDataset) view.getDataset(); final DatasetWriter<E> writer = FileSystemWriters.newFileWriter( dataset.getFileSystem(), new Path(dataset.getDirectory(), convert.fromKey(key)), dataset.getDescriptor(), dataset.getPartitionListener(), dataset.getName(), key); writer.open(); return writer; }

Target:
public DatasetWriter<E> load(StorageKey key) throws Exception { Preconditions.checkArgument(view.contains(key), "View does not contain StorageKey {}", view, key); Preconditions.checkState(view.getDataset() instanceof FileSystemDataset, "FileSystemWriters cannot create writer for " + view.getDataset()); FileSystemDataset dataset = (FileSystemDataset) view.getDataset(); Path partition = convert.fromKey(key); DatasetWriter<E> writer = FileSystemWriters.newFileWriter( dataset.getFileSystem(), new Path(dataset.getDirectory(), partition), dataset.getDescriptor()); PartitionListener listener = dataset.getPartitionListener(); if (listener != null) { listener.partitionAdded(dataset.getName(), partition.toString()); } writer.open(); return writer; }
Source:
void processOutputBatch(InputStream[] output, Consumer<InputStream> outputConsumer) { if (output == null || output.length == 0) return; if (allowsEndpointState() && output.length > 0) { setEndpointState(output[0]); } processOutput(output, outputConsumer); }

Target:
void processOutputBatch(InputStream[] output, Consumer<InputStream> outputConsumer) { if (output == null || output.length == 0) return; assignEndpointState(output); for (int i=allowsEndpointState()?1:0; i < output.length; i++) { outputConsumer.accept(output[i]); } }
Source:
private void isSizeExceeded() { if (limitAvailable) { if (incrementalSize > limit) { throw new WcsException("This request is trying to " + readGenerate + " too much data, the limit is " + formatBytes(limit) + " but the actual amount of bytes to be " + readWrite + " is " + formatBytes(incrementalSize)); } } }

Target:
private void isSizeExceeded() { if (limit > 0 && incrementalSize > limit) { throw new WcsException("This request is trying to " + (input ? "read" : "generate") + " too much data, the limit is " + formatBytes(limit) + " but the actual amount of bytes to be " + (input ? "read" : "written") + " is " + formatBytes(incrementalSize)); } }