auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void onMethodInvocationFound(MethodInvocationTree mit) { ExpressionTree expressionToEvaluate = mit.arguments().get(1); if (expressionToEvaluate.is(Tree.Kind.IDENTIFIER)) { Symbol variable = ((IdentifierTree) expressionToEvaluate).symbol(); ExpressionTree lastAssignmentOrDeclaration = ReassignmentFinder.getClosestReassignmentOrDeclarationExpression(mit, variable); if (lastAssignmentOrDeclaration != null && !usedBetween(variable, lastAssignmentOrDeclaration, mit)) { expressionToEvaluate = lastAssignmentOrDeclaration; } } if (isRequestOrCookieDataRetrieval(expressionToEvaluate)) { addIssue(mit, "Make sure the user is authenticated before this data is stored in the session."); } }

Target:
protected void onMethodInvocationFound(MethodInvocationTree mit) { for (ExpressionTree argument : mit.arguments()) { checkArgument(argument, mit, mit); } }
Source:
public void getAllCandidateShouldCallRepositoryWithAscendingSortWhenPassingAscendingFilterRequest() { Sort ascendingSort = new Sort(Sort.Direction.ASC, SORT_FIELD); Collection<CandidateDTO> result = candidateService.getAllCandidate(ascendingFilterRequest); ArgumentCaptor<String> nameArgumentCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> emailArgumentCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> phoneArgumentCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Sort> sortArgumentCaptor = ArgumentCaptor.forClass(Sort.class); verify(candidateRepository).findAllCandidatesByFilterRequest( nameArgumentCaptor.capture(), emailArgumentCaptor.capture(), phoneArgumentCaptor.capture(), sortArgumentCaptor.capture()); assertThat(nameArgumentCaptor.getValue(), equalTo(NAME)); assertThat(emailArgumentCaptor.getValue(), equalTo(EMAIL)); assertThat(phoneArgumentCaptor.getValue(), equalTo(PHONE)); assertThat(sortArgumentCaptor.getValue(), equalTo(ascendingSort)); }

Target:
public void getAllCandidateShouldCallRepositoryWithAscendingSortWhenPassingAscendingFilterRequest() { Collection<CandidateDTO> result = candidateService.getAllCandidate(ascendingFilterRequest); verify(candidateRepository).findAllCandidatesByFilterRequest(NAME, EMAIL, PHONE, ascendingSort); }
Source:
public RegisteredPackage open(@Nonnull PackageId id) throws IOException { try { Node node = getPackageNode(id); if (node == null && baseRegistry != null) { if (baseRegistry.contains(id)) { return baseRegistry.open(id); } } return node == null ? null : new JcrRegisteredPackage(open(node, false)); } catch (RepositoryException e) { throw new IOException(e); } }

Target:
public RegisteredPackage open(@Nonnull PackageId id) throws IOException { try { Node node = getPackageNode(id); if (node == null && baseRegistry != null) { return baseRegistry.open(id); } return node == null ? null : new JcrRegisteredPackage(open(node, false)); } catch (RepositoryException e) { throw new IOException(e); } }
Source:
private Object sortPlugins(List<JSONObject> list) { List<JSONObject> sorted = new ArrayList<>(list); Collections.sort(sorted, new Comparator<JSONObject>() { public int compare(JSONObject j1, JSONObject j2) { return j1.getString("name").compareTo(j2.getString("name")); } ; }); return sorted; }

Target:
private Object sortPlugins(List<JSONObject> list) { List<JSONObject> sorted = new ArrayList<>(list); Collections.sort(sorted, new Comparator<JSONObject>() { public int compare(JSONObject j1, JSONObject j2) { return j1.getString("name").compareTo(j2.getString("name")); } }); return sorted; }
Source:
private static int suffixMatch(String changedFile, String coverageFile) { int changedFileSize = changedFile.length(); int coverageFileSize = coverageFile.length(); if (coverageFileSize > changedFileSize) { return 0; } int rIndex = 1; while (coverageFileSize - rIndex >= 0 && coverageFile.charAt(coverageFileSize - rIndex) == changedFile.charAt( changedFileSize - rIndex)) { rIndex++; } return rIndex - 1; }

Target:
private static int suffixMatch(String changedFile, String coverageFile) { int changedFileSize = changedFile.length(); int coverageFileSize = coverageFile.length(); if (coverageFileSize > changedFileSize) { return 0; } int rIndex = 1; while (coverageFileSize - rIndex >= 0 && coverageFile.charAt(coverageFileSize - rIndex) == changedFile.charAt( changedFileSize - rIndex)) { rIndex++; } if (rIndex < coverageFileSize && coverageFile.charAt(rIndex - 1) != '/') { return 0; } return rIndex - 1; }
Source:
public ImmutableSpongePersistingData(Boolean value) { super(ImmutablePersistingData.class, value, Keys.PERSISTS, SpongePersistingData.class, true); this.cachedValue = ImmutableSpongeValue.cachedOf(Keys.PERSISTS, true, this.value); }

Target:
public ImmutableSpongePersistingData(Boolean value) { super(ImmutablePersistingData.class, value, Keys.PERSISTS, SpongePersistingData.class, false); }
Source:
private static Long getFileSizeForDirName(String fileSizeDirName) { Long sizeInBytes = null; if (fileSizeDirName.startsWith(FILE_SIZE_DIR_PREFIX)) { String sizeString = fileSizeDirName.substring(FILE_SIZE_DIR_PREFIX.length()); try { sizeInBytes = Long.parseLong(sizeString); } catch (NumberFormatException ignored) { } } return sizeInBytes; }

Target:
private static Long getFileSizeForDirName(String fileSizeDirName) { Long sizeInBytes = null; if (fileSizeDirName.startsWith(FILE_SIZE_DIR_PREFIX)) { String sizeString = fileSizeDirName.substring(FILE_SIZE_DIR_PREFIX.length()); sizeInBytes = Long.parseLong(sizeString); } return sizeInBytes; }
Source:
public void visitNode(Tree tree) { TypeSymbol classSymbol = ((ClassTree) tree).symbol(); Set<Symbol> fieldsReadOnAnotherInstance = FieldsReadOnAnotherInstanceVisitor.getFrom(classSymbol); classSymbol.memberSymbols().stream() .filter(PrivateFieldUsedLocallyCheck::isPrivateField) .filter(s -> !s.usages().isEmpty()) .filter(s -> !fieldsReadOnAnotherInstance.contains(s)) .forEach(s -> checkPrivateField(s, classSymbol)); }

Target:
public void visitNode(Tree tree) { TypeSymbol classSymbol = ((ClassTree) tree).symbol(); Set<Symbol> fieldsReadOnAnotherInstance = FieldsReadOnAnotherInstanceVisitor.getFrom(tree); classSymbol.memberSymbols().stream() .filter(PrivateFieldUsedLocallyCheck::isPrivateField) .filter(s -> !s.usages().isEmpty()) .filter(s -> !fieldsReadOnAnotherInstance.contains(s)) .forEach(s -> checkPrivateField(s, classSymbol)); }
Source:
void handleResponse(ResponseInfo responseInfo) { int correlationId = ((PutRequest) responseInfo.getRequest()).getCorrelationId(); correlationIdToPutChunk.remove(correlationId).handleResponse(responseInfo); }

Target:
void handleResponse(ResponseInfo responseInfo) { int correlationId = ((PutRequest) responseInfo.getRequest()).getCorrelationId(); PutOperation putOperation = correlationIdToPutOperation.remove(correlationId); if (putOperations.contains(putOperation)) { putOperation.handleResponse(responseInfo); if (putOperation.isOperationComplete()) { putOperations.remove(putOperation); onComplete(putOperation); } } }
Source:
public void setActive(final boolean active) { super.setActive(active); DELETE_SEARCH_SIZE = Platform.getPreferencesService().getInt( EditPlugin.ID, PreferenceConstants.P_DELETE_TOOL_RADIUS, 6, null); DELETE_CONFIRM = Platform.getPreferencesService().getBoolean( EditPlugin.ID, PreferenceConstants.P_DELETE_TOOL_CONFIRM, true, null); setStatusBarMessage(active); }

Target:
public void setActive(final boolean active) { super.setActive(active); setStatusBarMessage(active); }
Source:
private void updateDeviceAddresses() { if (isEmulatedMachineChanged()) { log.info("Emulated machine changed for VM: {}. Clearing device addresses.", getVm().getName()); getVmDeviceDao().clearAllDeviceAddressesByVmId(getVmId()); VmDevicesMonitoring.Change change = VmDevicesMonitoring.getInstance().createChange(System.nanoTime()); change.updateVm(getVmId(), VmDevicesMonitoring.EMPTY_HASH); change.flush(); } }

Target:
private void updateDeviceAddresses() { if (isEmulatedMachineChanged()) { log.info("Emulated machine changed for VM: ({}). Clearing device addresses.", getVm().getName(), getVm().getId()); getVmDeviceDao().clearAllDeviceAddressesByVmId(getVmId()); VmDevicesMonitoring.Change change = vmDevicesMonitoring.createChange(System.nanoTime()); change.updateVm(getVmId(), VmDevicesMonitoring.EMPTY_HASH); change.flush(); } }
Source:
public DataRecord getMetadataRecord(String name) { return null; }

Target:
public DataRecord getMetadataRecord(String name) { if (null == name) { throw new IllegalArgumentException("The wildcard must not be null"); } Iterator<DataStore> iter = delegateHandler.getAllDelegatesIterator(); while (iter.hasNext()) { DataStore ds = iter.next(); if (ds instanceof SharedDataStore) { DataRecord result = ((SharedDataStore) ds).getMetadataRecord(name); if (null != result) { return result; } } } return null; }
Source:
public EmbeddedCacheManager getDefaultCacheManager(@OverrideDefault Instance<EmbeddedCacheManager> providedDefaultCacheManager, @Default Configuration defaultConfiguration) { if (!providedDefaultCacheManager.isUnsatisfied()) { if (log.isTraceEnabled()) { log.tracef("Default cache manager overridden by '%s'", providedDefaultCacheManager); } return providedDefaultCacheManager.get(); } return new DefaultCacheManager(defaultConfiguration); }

Target:
public EmbeddedCacheManager getDefaultCacheManager(@OverrideDefault Instance<EmbeddedCacheManager> providedDefaultCacheManager, @Default Configuration defaultConfiguration) { if (!providedDefaultCacheManager.isUnsatisfied()) { log.tracef("Default cache manager overridden by '%s'", providedDefaultCacheManager); return providedDefaultCacheManager.get(); } return new DefaultCacheManager(defaultConfiguration); }
Source:
Supplier<Map<String, String>> reset() { return Memoize.referenceSupplier(() -> { Map<String, String> map = Arrays.stream(ResourcesPlugin.getWorkspace() .getRoot() .getProjects()) .filter(IProject::isOpen) .map(this::findBndrunFiles) .flatMap(Collection::stream) .map(IResource::getFullPath) .collect(toMap(IPath::toPortableString, IPath::toPortableString)); ResourcesPlugin.getWorkspace() .addResourceChangeListener(listener); return map; }, SoftReference::new); }

Target:
Supplier<Map<String, String>> reset() { return Memoize.supplier(() -> Arrays.stream(ResourcesPlugin.getWorkspace() .getRoot() .getProjects()) .filter(IProject::isOpen) .map(this::findBndrunFiles) .flatMap(Collection::stream) .map( IResource::getFullPath) .collect(toMap(IPath::toPortableString, IPath::toPortableString))); }
Source:
public void replNameEndsWithWhitespace() { Note note = createNote(); Paragraph paragraph = new Paragraph(note, null, interpreterFactory); paragraph.setText("%test\r\n###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); paragraph.setText("%test\t###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); paragraph.setText("%test\u000b###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); paragraph.setText("%test\f###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); paragraph.setText("%test\n###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); paragraph.setText("%test ###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); }

Target:
public void replNameEndsWithWhitespace() { Note note = createNote(); Paragraph paragraph = new Paragraph(note, null, interpreterFactory); paragraph.setText("%test\r\n###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); paragraph.setText("%test\t###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); paragraph.setText("%test\u000b###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); paragraph.setText("%test\f###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); paragraph.setText("%test\n###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); paragraph.setText("%test ###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); paragraph.setText(" %test ###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); paragraph.setText("\n\r%test ###Hello"); assertEquals("test", paragraph.getIntpText()); assertEquals("###Hello", paragraph.getScriptText()); paragraph.setText("%\r\n###Hello"); assertEquals("", paragraph.getIntpText()); assertEquals("%\r\n###Hello", paragraph.getScriptText()); }
Source:
private List<JavaFileScannerContext.Location> flowFromLearnedConstraints(ExplodedGraph.Edge edge, Set<LearnedConstraint> learnedConstraints) { List<JavaFileScannerContext.Location> result = new ArrayList<>(); Set<String> messages = new HashSet<>(); learnedConstraints.stream() .map(lc -> learnedConstraintFlow(lc, edge)) .flatMap(List::stream) .forEach(location -> { if (!location.syntaxNode.is(Tree.Kind.EQUAL_TO, Tree.Kind.NOT_EQUAL_TO) || messages.add(location.msg)) { result.add(location); } }); return result; }

Target:
private List<JavaFileScannerContext.Location> flowFromLearnedConstraints(ExplodedGraph.Edge edge, Set<LearnedConstraint> learnedConstraints) { return learnedConstraints.stream() .map(lc -> learnedConstraintFlow(lc, edge)) .flatMap(List::stream) .distinct() .collect(Collectors.toList()); }
Source:
public SMREntryList (int size, List<SMREntry> smrEntries) { this.size = size; this.smrEntries = smrEntries; }

Target:
public SMREntryList (int size, List<SMREntry> smrEntries) { this.sizeInBytes = size; this.smrEntries = smrEntries; }
Source:
private Symbol flowFromLearnedSymbols(ExplodedGraph.Node currentNode, @Nullable Symbol trackSymbol) { ExplodedGraph.Node parent = currentNode.parent(); if (trackSymbol == null || parent == null) { return null; } Optional<ExplodedGraph.Node.LearnedValue> learnedValue = currentNode.getLearnedSymbols().stream() .filter(lv -> lv.getSymbol().equals(trackSymbol)) .findFirst(); if (learnedValue.isPresent()) { ExplodedGraph.Node.LearnedValue lv = learnedValue.get(); Constraint constraintForSV = parent.programState.getConstraint(lv.getSv()); if (constraintForSV == null) { flow.add(location(parent)); } else { flow.add(location(parent, lv.getSymbol().name() + " is assigned " + constraintForSV.valueAsString())); } return parent.programState.getLastEvaluated(); } return trackSymbol; }

Target:
private Symbol flowFromLearnedSymbols(ExplodedGraph.Node currentNode, @Nullable Symbol trackSymbol) { ExplodedGraph.Node parent = currentNode.parent(); if (trackSymbol == null || parent == null) { return null; } Optional<ExplodedGraph.Node.LearnedValue> learnedValue = currentNode.getLearnedSymbols().stream() .filter(lv -> lv.getSymbol().equals(trackSymbol)) .findFirst(); if (learnedValue.isPresent()) { ExplodedGraph.Node.LearnedValue lv = learnedValue.get(); Constraint constraint = parent.programState.getConstraint(lv.getSv()); JavaFileScannerContext.Location location = constraint == null ? location(parent) : location(parent, lv.getSymbol().name() + " is assigned " + constraint.valueAsString()); flow.add(location); return parent.programState.getLastEvaluated(); } return trackSymbol; }
Source:
private void putMacImplClass(String algorithm, String className) { String prefix = getClass().getPackage().getName() + "."; String supportedKeyClasses = prefix + "OpenSSLKeyHolder"; String supportedKeyFormats = "RAW"; putImplClassWithKeyConstraints( "Mac." + algorithm, prefix + className, supportedKeyClasses, supportedKeyFormats); }

Target:
private void putMacImplClass(String algorithm, String className) { String supportedKeyClasses = PREFIX + "OpenSSLKeyHolder"; String supportedKeyFormats = "RAW"; putImplClassWithKeyConstraints( "Mac." + algorithm, PREFIX + className, supportedKeyClasses, supportedKeyFormats); }
Source:
public void customize() { isRiakOnPath = isPackageInstall ? isRiakOnPath() : true; OsDetails osDetails = getMachine().getMachineDetails().getOsDetails(); List<String> commands = Lists.newLinkedList(); String vmArgsTemplate = processTemplate(entity.getConfig(RiakNode.RIAK_VM_ARGS_TEMPLATE_URL)); DynamicTasks.queueIfPossible(newScript(CUSTOMIZING).body.append("true").newTask()); DynamicTasks.queueIfPossible(SshEffectorTasks.put(getRunDir() + "/vm.args") .contents(Streams.newInputStreamWithContents(vmArgsTemplate)) .machine(getMachine()) .summary("sending the vm.args file to the riak node")); if (osDetails.isMac()) commands.add("ulimit -n 4096"); else if (osDetails.isLinux()) { commands.add(sudo("chown riak:riak " + getRunDir() + "/vm.args")); } commands.add(sudo("mv " + getRunDir() + "/vm.args " + getEtcDir())); commands.add(sudo(format("sed -i -e \"s/127.0.0.1/%s/g\" %s", getPrivateIp(), getAppConfigLocation()))); ScriptHelper customizeScript = newScript(CUSTOMIZING) .failOnNonZeroResultCode() .body.append(commands); if (!isRiakOnPath) { Map<String, String> newPathVariable = ImmutableMap.of("PATH", sbinPath); log.warn("riak command not found on PATH. Altering future commands' environment variables from to {}", getShellEnvironment(), newPathVariable); customizeScript.environmentVariablesReset(newPathVariable); } customizeScript.execute(); entity.setAttribute(RiakNode.RIAK_NODE_NAME, format("riak@%s", getHostname())); }

Target:
public void customize() { newScript(CUSTOMIZING).execute(); isRiakOnPath = isPackageInstall ? isRiakOnPath() : true; OsDetails osDetails = getMachine().getMachineDetails().getOsDetails(); List<String> commands = Lists.newLinkedList(); String vmArgsTemplate = processTemplate(entity.getConfig(RiakNode.RIAK_VM_ARGS_TEMPLATE_URL)); String saveAsVmArgs = Urls.mergePaths(getRunDir(), "vm.args"); DynamicTasks.queueIfPossible(SshEffectorTasks.put(saveAsVmArgs).contents(vmArgsTemplate)); commands.add(sudo("mv " + saveAsVmArgs + " " + getRiakEtcDir())); String appConfigTemplate = processTemplate(entity.getConfig(RiakNode.RIAK_APP_CONFIG_TEMPLATE_URL)); String saveAsAppConfig = Urls.mergePaths(getRunDir(), "app.config"); DynamicTasks.queueIfPossible(SshEffectorTasks.put(saveAsAppConfig).contents(appConfigTemplate)); commands.add(sudo("mv " + saveAsAppConfig + " " + getRiakEtcDir())); if (osDetails.isMac()) { commands.add("ulimit -n 4096"); } else if (osDetails.isLinux()) { commands.add(sudo("chown riak:riak " + getVmArgsLocation())); } ScriptHelper customizeScript = newScript(CUSTOMIZING) .failOnNonZeroResultCode() .body.append(commands); if (!isRiakOnPath) { Map<String, String> newPathVariable = ImmutableMap.of("PATH", sbinPath); log.warn("riak command not found on PATH. Altering future commands' environment variables from to {}", getShellEnvironment(), newPathVariable); customizeScript.environmentVariablesReset(newPathVariable); } customizeScript.execute(); entity.setAttribute(RiakNode.RIAK_NODE_NAME, format("riak@%s", getHostname())); }
Source:
private void initGlusterPeerProcess() { _glusterPeerListSucceeded = true; _glusterPeerProbeSucceeded = true; List<VDS> vdsList = getVdsDAO().getAllForVdsGroupWithStatus(getVdsGroupId(), VDSStatus.Up); if (vdsList != null && vdsList.size() > 0) { VDS upServer = null; for (VDS vds : vdsList) { if (!Guid.OpEquality(getVdsId(), vds.getId())) { upServer = vds; break; } } if (upServer != null) { List<GlusterServerInfo> glusterServers = getGlusterPeers(upServer.getId()); if (glusterServers.size() == 0) { setNonOperational(NonOperationalReason.GLUSTER_PEER_LIST_FAILED); } else if (!hostExists(glusterServers, getVds())) { if (!glusterPeerProbe(upServer.getId(), getVds().gethost_name())) { setNonOperational(NonOperationalReason.GLUSTER_PEER_PROBE_FAILED); } } } } }

Target:
private void initGlusterPeerProcess() { _glusterPeerListSucceeded = true; _glusterPeerProbeSucceeded = true; List<VDS> vdsList = getVdsDAO().getAllForVdsGroupWithStatus(getVdsGroupId(), VDSStatus.Up); if (vdsList != null && vdsList.size() > 0) { VDS upServer = null; for (VDS vds : vdsList) { if (!getVdsId().equals(vds.getId())) { upServer = vds; break; } } if (upServer != null) { List<GlusterServerInfo> glusterServers = getGlusterPeers(upServer.getId()); if (glusterServers.size() == 0) { setNonOperational(NonOperationalReason.GLUSTER_PEER_LIST_FAILED); } else if (!hostExists(glusterServers, getVds())) { if (!glusterPeerProbe(upServer.getId(), getVds().gethost_name())) { setNonOperational(NonOperationalReason.GLUSTER_PEER_PROBE_FAILED); } } } } }
Source:
public void testSocketFinderAllowedInterfacesPrivate() throws Exception { ConcurrentOpenSocketFinder finder = new ConcurrentOpenSocketFinder(socketAlwaysOpen, nodeRunning, userExecutor); finder.allowedInterfaces = ConcurrentOpenSocketFinder.AllowedInterfaces.PRIVATE; HostAndPort result = finder.findOpenSocketOnNode(node, 22, 2000, MILLISECONDS); assertEquals(result, HostAndPort.fromParts(PRIVATE_IP, 22)); }

Target:
public void testSocketFinderAllowedInterfacesPrivate() throws Exception { FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.PRIVATE); assertFalse(ips.contains(PUBLIC_IP)); assertTrue(ips.contains(PRIVATE_IP)); }
Source:
public void init(final ProcessorContext context, final StateStore root) { this.context = (InternalProcessorContext) context; final StreamsMetricsImpl metrics = this.context.metrics(); final String taskName = context.taskId().toString(); expiredRecordSensor = metrics.storeLevelSensor( taskName, name(), EXPIRED_WINDOW_RECORD_DROP, Sensor.RecordingLevel.INFO ); addInvocationRateAndCountToSensor( expiredRecordSensor, "stream-" + metricScope + "-metrics", metrics.storeLevelTagMap(taskName, metricScope, name()), EXPIRED_WINDOW_RECORD_DROP ); segments.openExisting(this.context, observedStreamTime); bulkLoadSegments = new HashSet<>(segments.allSegments()); context.register(root, new RocksDBSegmentsBatchingRestoreCallback()); open = true; }

Target:
public void init(final ProcessorContext context, final StateStore root) { this.context = (InternalProcessorContext) context; final StreamsMetricsImpl metrics = this.context.metrics(); final String threadId = Thread.currentThread().getName(); final String taskName = context.taskId().toString(); expiredRecordSensor = metrics.storeLevelSensor( threadId, taskName, name(), EXPIRED_WINDOW_RECORD_DROP, Sensor.RecordingLevel.INFO ); addInvocationRateAndCountToSensor( expiredRecordSensor, "stream-" + metricScope + "-metrics", metrics.storeLevelTagMap(threadId, taskName, metricScope, name()), EXPIRED_WINDOW_RECORD_DROP ); segments.openExisting(this.context, observedStreamTime); bulkLoadSegments = new HashSet<>(segments.allSegments()); context.register(root, new RocksDBSegmentsBatchingRestoreCallback()); open = true; }
Source:
protected void commitWorkingCopy(IProgressMonitor monitor, Object element, TranslationUnitInfo info, boolean overwrite) throws CoreException { if (monitor == null) monitor= new NullProgressMonitor(); monitor.beginTask("", 100); try { IDocument document= info.fTextFileBuffer.getDocument(); IResource resource= info.fCopy.getResource(); if (resource instanceof IFile && !resource.exists()) { createFileFromDocument(monitor, (IFile) resource, document); return; } try { CoreException saveActionException= null; try { ICProject cproject = CoreModel.getDefault().create(resource.getProject()); performSaveActions(cproject, info.fTextFileBuffer, getSubProgressMonitor(monitor, 20)); } catch (CoreException e) { saveActionException = e; } commitFileBuffer(monitor, info, overwrite); if (saveActionException != null) { throw saveActionException; } } catch (CoreException x) { fireElementStateChangeFailed(element); throw x; } catch (RuntimeException x) { fireElementStateChangeFailed(element); throw x; } } finally { monitor.done(); } }

Target:
protected void commitWorkingCopy(IProgressMonitor monitor, Object element, TranslationUnitInfo info, boolean overwrite) throws CoreException { if (monitor == null) monitor= new NullProgressMonitor(); monitor.beginTask("", 100); try { IDocument document= info.fTextFileBuffer.getDocument(); IResource resource= info.fCopy.getResource(); if (resource instanceof IFile && !resource.exists()) { createFileFromDocument(monitor, (IFile) resource, document); return; } try { CoreException saveActionException= null; IProgressMonitor sub = getSubProgressMonitor(monitor, 20); try { ICProject cproject = CoreModel.getDefault().create(resource.getProject()); performSaveActions(cproject, info.fTextFileBuffer, sub); } catch (CoreException e) { saveActionException = e; } commitFileBuffer(sub, info, overwrite); if (saveActionException != null) { CUIPlugin.log(saveActionException); } } catch (CoreException x) { fireElementStateChangeFailed(element); throw x; } catch (RuntimeException x) { fireElementStateChangeFailed(element); throw x; } } finally { monitor.done(); } }
Source:
public void doAuthorise_shouldRespondAuthorisationSuccess() throws Exception { providerWillAuthorise(); GatewayResponse response = cardAuthorisationService.doAuthorise(charge.getExternalId(), aValidAuthorisationDetails()); assertThat(response.isSuccessful(), is(true)); assertThat(response.getSessionIdentifier().get(), is(SESSION_IDENTIFIER)); assertThat(charge.getProviderSessionId(), is(SESSION_IDENTIFIER)); assertThat(charge.getStatus(), is(AUTHORISATION_SUCCESS.getValue())); assertThat(charge.getGatewayTransactionId(), is(TRANSACTION_ID)); verify(mockedChargeEventDao).persistChargeEventOf(charge, Optional.empty()); assertThat(charge.get3dsDetails(), is(nullValue())); assertThat(charge.getCardDetails(), is(notNullValue())); assertThat(paymentRequest.getChargeTransaction().getGatewayTransactionId(), is(TRANSACTION_ID)); verify(mockPaymentRequestDao).updateChargeTransactionStatus(charge.getExternalId(), AUTHORISATION_READY); verify(mockPaymentRequestDao).updateChargeTransactionStatus(charge.getExternalId(), AUTHORISATION_SUCCESS); }

Target:
public void doAuthorise_shouldRespondAuthorisationSuccess() throws Exception { providerWillAuthorise(); GatewayResponse response = cardAuthorisationService.doAuthorise(charge.getExternalId(), aValidAuthorisationDetails()); assertThat(response.isSuccessful(), is(true)); assertThat(response.getSessionIdentifier().get(), is(SESSION_IDENTIFIER)); assertThat(charge.getProviderSessionId(), is(SESSION_IDENTIFIER)); assertThat(charge.getStatus(), is(AUTHORISATION_SUCCESS.getValue())); assertThat(charge.getGatewayTransactionId(), is(TRANSACTION_ID)); verify(mockedChargeEventDao).persistChargeEventOf(charge, Optional.empty()); assertThat(charge.get3dsDetails(), is(nullValue())); assertThat(charge.getCardDetails(), is(notNullValue())); assertThat(paymentRequest.getChargeTransaction().getGatewayTransactionId(), is(TRANSACTION_ID)); InOrder inOrder = inOrder(mockStatusUpdater); inOrder.verify(mockStatusUpdater).updateChargeTransactionStatus(charge.getExternalId(), AUTHORISATION_READY); inOrder.verify(mockStatusUpdater).updateChargeTransactionStatus(charge.getExternalId(), AUTHORISATION_SUCCESS); }
Source:
public String toString() { final StringBuffer sb = new StringBuffer("FileTailerEvent{"); sb.append("state=").append(state); sb.append(", eventData='").append(eventData).append('\''); sb.append('}'); return sb.toString(); }

Target:
public String toString() { return new StringBuilder("FileTailerEvent{") .append("state=").append(state) .append(", eventData='").append(eventData).append('\'') .append('}').toString(); }
Source:
public void resetCounters() throws Exception { PetFailingPollingSource.STARTED_POLLS = 0; STARTED_POLLS = 0; }

Target:
public void resetCounters() throws Exception { PetFailingPollingSource.STARTED_POLLS = 0; POLL_INVOCATIONS.clear(); STARTED_SOURCES.clear(); STARTED_POLLS = 0; }
Source:
public void should_ignore_test_when_assumption_fails() { assumeThat((Object) "test").isNotNull().isEqualTo("other"); assertThat(true).isFalse(); }

Target:
public void should_ignore_test_when_assumption_fails() { assumeThat(STRING_OBJECT).isNotNull().isEqualTo("other"); assertThat(true).isFalse(); }
Source:
private void buildSketchMenu(JMenu sketchMenu) { sketchMenu.removeAll(); JMenuItem item = newJMenuItem(tr("Verify/Compile"), 'R'); item.addActionListener(event -> handleRun(false, presentHandler, runHandler)); sketchMenu.add(item); item = newJMenuItem(tr("Upload"), 'U'); item.addActionListener(event -> handleExport(false)); sketchMenu.add(item); String OS = System.getProperty("os.name").toLowerCase(); if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") >= 0){ item = newJMenuItemAlt(tr("Upload Using Programmer"), 'U'); } else { item = newJMenuItemShift(tr("Upload Using Programmer"), 'U'); } item.addActionListener(event -> handleExport(true)); sketchMenu.add(item); item = newJMenuItemAlt(tr("Export compiled Binary"), 'S'); item.addActionListener(event -> { if (!(new CanExportInSketchFolder().test(sketchController))) { System.out.println(tr("Export canceled, changes must first be saved.")); return; } handleRun(false, new CanExportInSketchFolder(), presentAndSaveHandler, runAndSaveHandler); }); sketchMenu.add(item); sketchMenu.addSeparator(); item = newJMenuItem(tr("Show Sketch Folder"), 'K'); item.addActionListener(event -> Base.openFolder(sketch.getFolder())); sketchMenu.add(item); item.setEnabled(Base.openFolderAvailable()); if (importMenu == null) { importMenu = new JMenu(tr("Include Library")); MenuScroller.setScrollerFor(importMenu); base.rebuildImportMenu(importMenu); } sketchMenu.add(importMenu); item = new JMenuItem(tr("Add File...")); item.addActionListener(event -> sketchController.handleAddFile()); sketchMenu.add(item); }

Target:
private void buildSketchMenu(JMenu sketchMenu) { sketchMenu.removeAll(); JMenuItem item = newJMenuItem(tr("Verify/Compile"), 'R'); item.addActionListener(event -> handleRun(false, presentHandler, runHandler)); sketchMenu.add(item); item = newJMenuItem(tr("Upload"), 'U'); item.addActionListener(event -> handleExport(false)); sketchMenu.add(item); if (OSUtils.isLinux()) { item = newJMenuItemAlt(tr("Upload Using Programmer"), 'U'); } else { item = newJMenuItemShift(tr("Upload Using Programmer"), 'U'); } item.addActionListener(event -> handleExport(true)); sketchMenu.add(item); item = newJMenuItemAlt(tr("Export compiled Binary"), 'S'); item.addActionListener(event -> { if (!(new CanExportInSketchFolder().test(sketchController))) { System.out.println(tr("Export canceled, changes must first be saved.")); return; } handleRun(false, new CanExportInSketchFolder(), presentAndSaveHandler, runAndSaveHandler); }); sketchMenu.add(item); sketchMenu.addSeparator(); item = newJMenuItem(tr("Show Sketch Folder"), 'K'); item.addActionListener(event -> Base.openFolder(sketch.getFolder())); sketchMenu.add(item); item.setEnabled(Base.openFolderAvailable()); if (importMenu == null) { importMenu = new JMenu(tr("Include Library")); MenuScroller.setScrollerFor(importMenu); base.rebuildImportMenu(importMenu); } sketchMenu.add(importMenu); item = new JMenuItem(tr("Add File...")); item.addActionListener(event -> sketchController.handleAddFile()); sketchMenu.add(item); }
Source:
private void assertGreaterThan(String msg, int a, int b) { assertTrue(msg + ": " + a + " > " + b, a > b); }

Target:
static private void assertGreaterThan(String msg, int a, int b) { assertTrue(msg + ": " + a + " > " + b, a > b); }
Source:
public ConfigAccessor(String zkAddress) { RealmAwareZkClient zkClient; try { zkClient = new FederatedZkClient( new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder().build(), new RealmAwareZkClient.RealmAwareZkClientConfig()); } catch (IOException | InvalidRoutingDataException e) { LOG.info( "ConfigAccessor: not able to connect on multi-realm mode; connecting single-realm mode to ZK: {}", zkAddress, e); zkClient = SharedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddress), new HelixZkClient.ZkClientConfig().setZkSerializer(new ZNRecordSerializer())); } _zkClient = zkClient; _usesExternalZkClient = false; }

Target:
public ConfigAccessor(String zkAddress) { RealmAwareZkClient zkClient; try { zkClient = new FederatedZkClient( new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder().build(), new RealmAwareZkClient.RealmAwareZkClientConfig()); } catch (IOException | InvalidRoutingDataException | IllegalStateException e) { LOG.info( "ConfigAccessor: not able to connect on multi-realm mode; connecting single-realm mode to ZK: {}", zkAddress, e); zkClient = SharedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddress), new HelixZkClient.ZkClientConfig().setZkSerializer(new ZNRecordSerializer())); } _zkClient = zkClient; _usesExternalZkClient = false; }
Source:
final public Date getExtendedExpiresOn() { return this.mExtendedExpiresOn; }

Target:
final Date getExtendedExpiresOn() { return mExtendedExpiresOn; }
Source:
final public void initialize() { if (previous != null && (previous.isScheduled())) { previous.cancel(); } onInitialize(); }

Target:
public final void initialize() { if (previous != null && previous.isScheduled()) { previous.cancel(); } onInitialize(); }
Source:
public ArrayList<String> getProxyProperties() { ArrayList<String> properties = new ArrayList<String>(); String prop = System.getProperty("http.proxyHost"); if (prop != null) { properties.add("-Dhttp.proxyHost=" + prop); } prop = System.getProperty("http.proxyPort"); if (prop != null) { properties.add("-Dhttp.proxyPort=" + prop); } prop = System.getProperty("https.proxyHost"); if (prop != null) { properties.add("-Dhttps.proxyHost=" + prop); } prop = System.getProperty("https.proxyPort"); if (prop != null) { properties.add("-Dhttps.proxyPort=" + prop); } prop = System.getProperty("http.nonProxyHosts"); if (prop != null) { properties.add("-Dhttp.nonProxyHosts=" + prop); } return properties; }

Target:
public ArrayList<String> getProxyProperties() { ArrayList<String> properties = new ArrayList<String>(); addProxyProperty(properties, "http.proxyHost"); addProxyProperty(properties, "http.proxyPort"); addProxyProperty(properties, "https.proxyHost"); addProxyProperty(properties, "https.proxyPort"); addProxyProperty(properties, "http.nonProxyHosts"); return properties; }
Source:
public Integer getPreKmerLength() { if(preKmerLength == null) preKmerLength = new Integer(0); return preKmerLength; }

Target:
public Integer getPreKmerLength() { return preKmerLength; }
Source:
private Double getEntriesReadInBatchMeanThorough() { return (Double) getGaugeThorough(AtlasDbMetricNames.BATCH_SIZE_MEAN).getValue(); }

Target:
private Double getEntriesReadInBatchMeanThorough() { Gauge<Double> gauge = getGaugeThorough(AtlasDbMetricNames.BATCH_SIZE_MEAN); return gauge.getValue(); }
Source:
public void handleRequest(HttpServerExchange httpServerExchange) throws Exception { if (httpServerExchange.isInIoThread()) { httpServerExchange.dispatch(this); return; } Matcher matcher = INFLUX_URI_PATTERN.matcher(httpServerExchange.getRequestURI()); if (!matcher.matches()) { next.handleRequest(httpServerExchange); return; } HeaderMap requestHeaders = httpServerExchange.getRequestHeaders(); String databaseName = matcher.group(1); if (!UUID_PATTERN.matcher(databaseName).matches()) { httpServerExchange.setStatusCode(400); httpServerExchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); httpServerExchange.getResponseSender().send("Database name is not a valid identifier.", UTF_8); return; } requestHeaders.put(PERSONA_HEADER, databaseName); Map<String, Deque<String>> requestParameters = httpServerExchange.getQueryParameters(); Deque<String> usernameParamValues = requestParameters.get(USERNAME_PARAM_NAME); Deque<String> passwordParamValues = requestParameters.get(PASSWORD_PARAM_NAME); if (usernameParamValues != null && passwordParamValues != null) { String concat = usernameParamValues.getFirst() + ":" + passwordParamValues.getFirst(); String encoded = Base64.getEncoder().encodeToString(concat.getBytes(UTF_8)); String authHeader = "Basic " + encoded; requestHeaders.put(Headers.AUTHORIZATION, authHeader); httpServerExchange.getQueryParameters().remove(USERNAME_PARAM_NAME); httpServerExchange.getQueryParameters().remove(PASSWORD_PARAM_NAME); } next.handleRequest(httpServerExchange); }

Target:
public void handleRequest(HttpServerExchange httpServerExchange) throws Exception { if (httpServerExchange.isInIoThread()) { httpServerExchange.dispatch(this); return; } Matcher matcher = INFLUX_URI_PATTERN.matcher(httpServerExchange.getRequestURI()); if (!matcher.matches()) { next.handleRequest(httpServerExchange); return; } HeaderMap requestHeaders = httpServerExchange.getRequestHeaders(); String databaseName = matcher.group(1); try { UUID.fromString(databaseName); } catch (IllegalArgumentException e) { httpServerExchange.setStatusCode(400); httpServerExchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); httpServerExchange.getResponseSender().send("Database name is not a valid identifier.", UTF_8); return; } requestHeaders.put(PERSONA_HEADER, databaseName); Map<String, Deque<String>> requestParameters = httpServerExchange.getQueryParameters(); Deque<String> usernameParamValues = requestParameters.get(USERNAME_PARAM_NAME); Deque<String> passwordParamValues = requestParameters.get(PASSWORD_PARAM_NAME); if (usernameParamValues != null && passwordParamValues != null) { String concat = usernameParamValues.getFirst() + ":" + passwordParamValues.getFirst(); String encoded = Base64.getEncoder().encodeToString(concat.getBytes(UTF_8)); String authHeader = "Basic " + encoded; requestHeaders.put(Headers.AUTHORIZATION, authHeader); httpServerExchange.getQueryParameters().remove(USERNAME_PARAM_NAME); httpServerExchange.getQueryParameters().remove(PASSWORD_PARAM_NAME); } next.handleRequest(httpServerExchange); }
Source:
public void setUOM(@NonNull final org.compiere.model.I_M_InventoryLine inventoryLine) { final UomId stockUOMId = inventoryLine.getM_Product_ID() > 0 ? productBL.getStockUOMId(ProductId.ofRepoId(inventoryLine.getM_Product_ID())) : UomId.ofRepoIdOrNull(0); inventoryLine.setC_UOM_ID(stockUOMId != null ? stockUOMId.getRepoId() : 0); }

Target:
public void setUOM(@NonNull final org.compiere.model.I_M_InventoryLine inventoryLine) { final UomId stockUOMId = inventoryLine.getM_Product_ID() > 0 ? productBL.getStockUOMId(inventoryLine.getM_Product_ID()) : null; inventoryLine.setC_UOM_ID(UomId.toRepoId(stockUOMId)); }
Source:
private boolean isSearchTableHeaderCorrect(int tableNum) { List<String> expectedSearchTableHeaders; List<String> actualSessionTableHeaders; int numColumns = searchPage.getNumberOfColumnsFromDataTable(tableNum); switch (searchPage.getDataTableId(tableNum)) { case "search_table_instructor": if (numColumns != 5) { return false; } expectedSearchTableHeaders = Arrays.asList("Course", "Name", "Google ID", "Institute", "Options"); actualSessionTableHeaders = new ArrayList<String>(); for (int i = 0 ; i < numColumns ; i++) { actualSessionTableHeaders.add(searchPage.getHeaderValueFromDataTable(tableNum, 0, i)); } break; case "search_table": if (numColumns != 6) { return false; } expectedSearchTableHeaders = Arrays.asList("Institute", "Course[Section](Team)", "Name", "Google ID[Details]", "Comments", "Options"); actualSessionTableHeaders = new ArrayList<String>(); for (int i = 0 ; i < numColumns ; i++) { actualSessionTableHeaders.add(searchPage.getHeaderValueFromDataTable(tableNum, 0, i)); } break; default: return false; } return actualSessionTableHeaders.equals(expectedSearchTableHeaders); }

Target:
private boolean isSearchTableHeaderCorrect(int tableNum) { List<String> expectedSearchTableHeaders; List<String> actualSessionTableHeaders; int numColumns = searchPage.getNumberOfColumnsFromDataTable(tableNum); switch (searchPage.getDataTableId(tableNum)) { case "search_table_instructor": if (numColumns != ADMIN_SEARCH_INSTRUCTOR_TABLE_NUM_COLUMNS) { return false; } expectedSearchTableHeaders = Arrays.asList("Course", "Name", "Google ID", "Institute", "Options"); actualSessionTableHeaders = new ArrayList<String>(); for (int i = 0 ; i < numColumns ; i++) { actualSessionTableHeaders.add(searchPage.getHeaderValueFromDataTable(tableNum, 0, i)); } break; case "search_table": if (numColumns != ADMIN_SEARCH_STUDENT_TABLE_NUM_COLUMNS) { return false; } expectedSearchTableHeaders = Arrays.asList("Institute", "Course[Section](Team)", "Name", "Google ID[Details]", "Comments", "Options"); actualSessionTableHeaders = new ArrayList<String>(); for (int i = 0 ; i < numColumns ; i++) { actualSessionTableHeaders.add(searchPage.getHeaderValueFromDataTable(tableNum, 0, i)); } break; default: return false; } return actualSessionTableHeaders.equals(expectedSearchTableHeaders); }
Source:
public void emitBatch(final long batchId, final TridentCollector collector) { List<List<Object>> batch = this.getBatches().get(batchId); if (batch == null) { batch = new ArrayList<List<Object>>(); if (index >= outputs.length && isCycle()) { index = 0; } for (int i = 0; i < getMaxBatchSize(); index++, i++) { if (index == outputs.length) { index = 0; } batch.add(outputs[index]); } this.getBatches().put(batchId, batch); } for (List<Object> list : batch) { collector.emit(list); } }

Target:
public void emitBatch(final long batchId, final TridentCollector collector) { List<List<Object>> batch = this.batches.get(batchId); if (batch == null) { batch = new ArrayList<List<Object>>(); if (index >= outputs.length && cycle) { index = 0; } for (int i = 0; i < maxBatchSize; index++, i++) { if (index == outputs.length) { index = 0; } batch.add(outputs[index]); } this.batches.put(batchId, batch); } for (List<Object> list : batch) { collector.emit(list); } }
Source:
public void putJobCreatedNotification() throws IOException, SignatureException { UUID notificationUUID = null; try { final PutJobCreatedNotificationRegistrationSpectraS3Response response = client .putJobCreatedNotificationRegistrationSpectraS3(new PutJobCreatedNotificationRegistrationSpectraS3Request("test@test.test")); notificationUUID = response.getJobCreatedNotificationRegistrationResult().getId(); assertThat(response.getStatusCode(), is(201)); } finally { client.deleteJobCreatedNotificationRegistrationSpectraS3( new DeleteJobCreatedNotificationRegistrationSpectraS3Request(notificationUUID)); } }

Target:
public void putJobCreatedNotification() throws IOException, SignatureException { UUID notificationUUID = null; try { final PutJobCreatedNotificationRegistrationSpectraS3Response response = client .putJobCreatedNotificationRegistrationSpectraS3(new PutJobCreatedNotificationRegistrationSpectraS3Request("test@test.test")); notificationUUID = response.getJobCreatedNotificationRegistrationResult().getId(); assertThat(response.getStatusCode(), is(201)); } finally { if (notificationUUID != null) { client.deleteJobCreatedNotificationRegistrationSpectraS3( new DeleteJobCreatedNotificationRegistrationSpectraS3Request(notificationUUID)); } } }
Source:
private String getFullPath(final String path) { String result = null; if (ServletUtils.isSane(path)) { List<BrandingTheme> brandingPaths = brandingManager. getBrandingThemes(); for (BrandingTheme brandingTheme: brandingPaths) { if (path.startsWith(brandingTheme.getPath())) { result = brandingManager.getBrandingRootPath(). getAbsolutePath() + path; } } } else { log.error("The path \"" + path + "\" is not sane"); } return result; }

Target:
String getFullPath(final String path) { String result = null; if (ServletUtils.isSane(path)) { result = brandingManager.getBrandingRootPath().getAbsolutePath() + path; } else { log.error("The path \"" + path + "\" is not sane"); } return result; }
Source:
protected String[] getExecutionOrder(String group) { if (GROUP_TOP_LEVEL.equals(group)) { List<String> orderList = new ArrayList<String>(Arrays.asList(super.getExecutionOrder(GROUP_TOP_LEVEL))); orderList.remove(orderList.indexOf("stepRemoteConnection")); orderList.add(orderList.indexOf("stepInitializeBaseSequence") + 1, "stepInitializeSequence_7_2"); orderList.add(orderList.indexOf("stepInitializeSequence_7_2") + 1, "stepAddInferior"); orderList.add(orderList.indexOf("stepSetExecutable") + 1, "stepSetRemoteExecutable"); return orderList.toArray(new String[orderList.size()]); } return null; }

Target:
protected String[] getExecutionOrder(String group) { if (GROUP_TOP_LEVEL.equals(group)) { List<String> orderList = new ArrayList<String>(Arrays.asList(super.getExecutionOrder(GROUP_TOP_LEVEL))); orderList.add(orderList.indexOf("stepInitializeBaseSequence") + 1, "stepInitializeSequence_7_2"); orderList.add(orderList.indexOf("stepInitializeSequence_7_2") + 1, "stepAddInferior"); orderList.add(orderList.indexOf("stepSetExecutable") + 1, "stepSetRemoteExecutable"); return orderList.toArray(new String[orderList.size()]); } return null; }
Source:
private void toggleGoogleDriveSync(){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); final String appFolderId = sharedPreferences.getString(getString(R.string.key_google_drive_app_folder_id), null); if (appFolderId != null){ sharedPreferences.edit().remove(getString(R.string.key_google_drive_app_folder_id)).commit(); mGoogleApiClient.disconnect(); onGoogleDriveFolderForgot(appFolderId); } else { mGoogleApiClient.connect(); } }

Target:
private void toggleGoogleDriveSync(){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); final String appFolderId = sharedPreferences.getString(getString(R.string.key_google_drive_app_folder_id), null); if (appFolderId != null){ sharedPreferences.edit().remove(getString(R.string.key_google_drive_app_folder_id)).commit(); mGoogleApiClient.disconnect(); } else { mGoogleApiClient.connect(); } }
Source:
public boolean isContingentOn(PartialWorld world, BayesNetVar X, BayesNetVar Y, BayesNetVar Z) { TraceParentRecEvalContext context = new TraceParentRecEvalContext(world); if (Z instanceof VarWithDistrib) { ((VarWithDistrib) Z).getDistrib(context); } else if (Z instanceof DerivedVar) { ((DerivedVar) Z).getValue(context); } else { return true; } LinkedList parentTrace = new LinkedList(); parentTrace.addAll(context.getParentTrace()); int x = parentTrace.indexOf(X), y = parentTrace.indexOf(Y); if (x < 0 || y < 0) { return false; } if (X instanceof NumberVar) { if (x < y && world.getCBN().getAncestors(Y).contains(X)) { if (Util.verbose()) { System.out.println("\t Contingent relations type 1: " + X.toString() + " " + Y.toString() + " " + Z.toString()); } return true; } else { return false; } } else { if (x < y) { if (Util.verbose()) { System.out.println("\t Contingent relations type 2: " + X.toString() + " " + Y.toString() + " " + Z.toString()); } return true; } else { return false; } } }

Target:
public boolean isContingentOn(PartialWorld world, BayesNetVar X, BayesNetVar Y, BayesNetVar Z) { TraceParentRecEvalContext context = new TraceParentRecEvalContext(world); if (Z instanceof VarWithDistrib) { ((VarWithDistrib) Z).getDistrib(context); } else if (Z instanceof DerivedVar) { ((DerivedVar) Z).getValue(context); } else { return true; } LinkedList<BayesNetVar> parentTrace = new LinkedList<BayesNetVar>(); parentTrace.addAll(context.getParentTrace()); int x = parentTrace.indexOf(X), y = parentTrace.indexOf(Y); if (x < 0 || y < 0) { return false; } if (X instanceof NumberVar) { if (x < y && world.getCBN().getAncestors(Y).contains(X)) { if (Util.verbose()) { System.out.println("\t Contingent relations type 1: " + X.toString() + " " + Y.toString() + " " + Z.toString()); } return true; } else { return false; } } else { if (x < y) { if (Util.verbose()) { System.out.println("\t Contingent relations type 2: " + X.toString() + " " + Y.toString() + " " + Z.toString()); } return true; } else { return false; } } }