auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Optional<String> getHost(Element element) { String url = element.getAttributeValue( SupportedElements.valueOf(element.getName().toUpperCase()).attribute); URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { return Optional.empty(); } return Optional.of(uri.getHost()); }

Target:
public static Optional<String> getHost(Element element) { String url = element.getAttributeValue( SupportedElements.valueOf(element.getName().toUpperCase(Locale.ROOT)) .attribute); URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { return Optional.empty(); } return Optional.of(uri.getHost()); }
Source:
public void createStore() { dataStore = DataStoreFactory.createDataStore(new MemoryRequiredNameSpaceOptions(counter + "")); final Index index = new IndexImpl( new MockComponents.MockIndexStrategy(), new MockComponents.TestIndexModel("test1")); final DataTypeAdapter<Integer> adapter = new MockComponents.MockAbstractDataAdapter(MOCK_DATA_TYPE_1); dataStore.addType(adapter, index); counter++; }

Target:
public void createStore() { dataStore = DataStoreFactory.createDataStore(new MemoryRequiredOptions()); final Index index = new IndexImpl( new MockComponents.MockIndexStrategy(), new MockComponents.TestIndexModel("test1")); final DataTypeAdapter<Integer> adapter = new MockComponents.MockAbstractDataAdapter(MOCK_DATA_TYPE_1); dataStore.addType(adapter, index); counter++; }
Source:
public void treeMadeExpectedSplits() { final List<Instance<AttributesMap>> instances = Lists.newArrayList(); AttributesMap attributesMap = AttributesMap.newHashMap(); attributesMap.put("a", true); instances.add(new InstanceImpl<AttributesMap>(attributesMap, 1.0)); attributesMap = AttributesMap.newHashMap(); attributesMap.put("a", true); instances.add(new InstanceImpl<AttributesMap>(attributesMap, 0.0)); attributesMap = AttributesMap.newHashMap(); attributesMap.put("a", false); instances.add(new InstanceImpl<AttributesMap>(attributesMap, 0.0)); attributesMap = AttributesMap.newHashMap(); attributesMap.put("a", false); instances.add(new InstanceImpl<AttributesMap>(attributesMap, 0.0)); TreeBuilder treeBuilder = new TreeBuilder().minCategoricalAttributeValueOccurances(0).minLeafInstances(0); Tree tree = treeBuilder.buildPredictiveModel(instances); AttributesMap attributes = new AttributesMap(); attributes.put("a", true); Assert.assertEquals(tree.getProbability(attributes, 1.0),.5); attributes = new AttributesMap(); attributes.put("a", false); Assert.assertEquals(tree.getProbability(attributes, 0.0), 1.0); }

Target:
public void treeMadeExpectedSplits() { final List<Instance<AttributesMap>> instances = Lists.newArrayList(); AttributesMap attributesMap = AttributesMap.newHashMap(); attributesMap.put("a", true); instances.add(new InstanceImpl<AttributesMap>(attributesMap, 1.0)); attributesMap = AttributesMap.newHashMap(); attributesMap.put("a", true); instances.add(new InstanceImpl<AttributesMap>(attributesMap, 0.0)); attributesMap = AttributesMap.newHashMap(); attributesMap.put("a", false); instances.add(new InstanceImpl<AttributesMap>(attributesMap, 0.0)); attributesMap = AttributesMap.newHashMap(); attributesMap.put("a", false); instances.add(new InstanceImpl<AttributesMap>(attributesMap, 0.0)); TreeBuilder treeBuilder = new TreeBuilder().minCategoricalAttributeValueOccurances(0).minLeafInstances(0); Tree tree = treeBuilder.buildPredictiveModel(instances); AttributesMap attributes = new AttributesMap(); attributes.put("a", true); Assert.assertEquals(tree.getProbability(attributes, 1.0),.5); attributes.put("a", false); Assert.assertEquals(tree.getProbability(attributes, 0.0), 1.0); }
Source:
private List<String> visitInvocationArguments(AbstractInvocation invocation) { List<String> argumentNames = new ArrayList<>(); for (ExpressionStatement argument : invocation.getArguments()) { if (invocation instanceof FunctionInvocation && ((FunctionInvocation) invocation).useNamedArguments()) { if (!(argument instanceof NamedArgument)) { throw new IllegalArgumentException("Invocation " + invocation.getName() + " must have either all or none of its arguments named"); } NamedArgument namedArgument = (NamedArgument) argument; argumentNames.add(namedArgument.getName()); argument = namedArgument.getExpression(); } argument.accept(this); } return argumentNames; }

Target:
private List<String> visitInvocationArguments(AbstractInvocation invocation) { List<String> argumentNames = new ArrayList<>(); for (ExpressionStatement argument : invocation.getArguments()) { if (invocation.usesNamedArguments()) { NamedArgument namedArgument = (NamedArgument) argument; argumentNames.add(namedArgument.getName()); argument = namedArgument.getExpression(); } argument.accept(this); } return argumentNames; }
Source:
for (OsType type : OsType.values()) { osTypeValues.add(type.value().toLowerCase()); }

Target:
for (OsType type : OsType.values()) { osTypeValues.add(type.value()); }
Source:
public void run() { dataLakeFileClient.append(TestDataCreationHelper.createRandomInputStream(options.getSize()), 0, options.getSize()); }

Target:
public void run() { inputStream.reset(); dataLakeFileClient.append(TestDataCreationHelper.createRandomInputStream(options.getSize()), 0, options.getSize()); }
Source:
public void onCompleted() { RpcUtils.streamingRPCAndLog(LOG, new RpcUtils.StreamingRpcCallable<OpenLocalBlockResponse>() { @Override public OpenLocalBlockResponse call() throws Exception { if (mLockId != BlockLockManager.INVALID_LOCK_ID) { try { mWorker.unlockBlock(mLockId); } catch (BlockDoesNotExistException e) { LOG.warn("Failed to unlock lock with error {}.", mLockId, e.getMessage()); } mLockId = BlockLockManager.INVALID_LOCK_ID; } else if (mRequest != null) { LOG.warn("Close a closed block {}.", mRequest.getBlockId()); } return null; } @Override public void exceptionCaught(Throwable e) { mResponseObserver.onError(GrpcExceptionUtils.fromThrowable(e)); mLockId = BlockLockManager.INVALID_LOCK_ID; } }, "CloseBlock", false, true, mResponseObserver, "Session=%d, Request=%s", mSessionId, mRequest); }

Target:
public void onCompleted() { RpcUtils.streamingRPCAndLog(LOG, new RpcUtils.StreamingRpcCallable<OpenLocalBlockResponse>() { @Override public OpenLocalBlockResponse call() throws Exception { if (mLockId != BlockLockManager.INVALID_LOCK_ID) { try { mWorker.unlockBlock(mLockId); } catch (BlockDoesNotExistException e) { LOG.warn("Failed to unlock lock of block with error {}.", mLockId, mRequest.getBlockId(), e.getMessage()); } mLockId = BlockLockManager.INVALID_LOCK_ID; } else if (mRequest != null) { LOG.warn("Close a closed block {}.", mRequest.getBlockId()); } return null; } @Override public void exceptionCaught(Throwable e) { mResponseObserver.onError(GrpcExceptionUtils.fromThrowable(e)); mLockId = BlockLockManager.INVALID_LOCK_ID; } }, "CloseBlock", false, true, mResponseObserver, "Session=%d, Request=%s", mSessionId, mRequest); }
Source:
public VergeRangersEffect() { super(FILTER_CARD_LAND); staticText = "As long as an opponent controls more lands than you, you may play lands from the top of your library."; }

Target:
public VergeRangersEffect() { super(StaticFilters.FILTER_CARD_LAND); staticText = "As long as an opponent controls more lands than you, you may play lands from the top of your library."; }
Source:
public boolean validatePMAgentPort() { String portStr = null; Integer port = getParameters().getAgent().getPort(); if (port == null) { if (getParameters().getAgent().getOptionsMap().containsKey(PORT)) { portStr = getParameters().getAgent().getOptionsMap().get(PORT); } else { return true; } } portStr = portStr == null ? getParameters().getAgent().getPort().toString() : portStr; return portStr.equals("") || ValidationUtils.validatePort(port); }

Target:
public boolean validatePMAgentPort() { String portStr = null; Integer port = getParameters().getAgent().getPort(); if (port == null) { if (getParameters().getAgent().getOptionsMap().containsKey(PORT)) { portStr = getParameters().getAgent().getOptionsMap().get(PORT); if (StringUtils.isNumeric(portStr)) { port = Integer.parseInt(portStr); } else { return false; } } else { return true; } } portStr = portStr == null ? getParameters().getAgent().getPort().toString() : portStr; return portStr.equals("") || ValidationUtils.validatePort(port); }
Source:
public static void setup() { CqlSession session = SESSION_RULE.session(); for (String query : createStatements(CCM_RULE)) { session.execute( SimpleStatement.builder(query).setExecutionProfile(SESSION_RULE.slowProfile()).build()); } InventoryMapper mapper = InventoryMapper.builder(SESSION_RULE.session()) .withResultProducers( new VoidListenableFutureProducer(), new SingleEntityListenableFutureProducer()) .build(); dao = mapper.productDao(SESSION_RULE.keyspace()); }

Target:
public static void setup() { CqlSession session = SESSION_RULE.session(); for (String query : createStatements(CCM_RULE)) { session.execute( SimpleStatement.builder(query).setExecutionProfile(SESSION_RULE.slowProfile()).build()); } InventoryMapper mapper = InventoryMapper.builder(SESSION_RULE.session()).build(); dao = mapper.productDao(SESSION_RULE.keyspace()); }
Source:
public void addSchemaUrl(String schemaName) { new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) .until(visibilityOf(addSchemaUrlInput)); addSchemaUrlInput.sendKeys(schemaName); new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) .until(visibilityOfElementLocated(By.id("askValue-dialog-ok"))) .click(); }

Target:
public void addSchemaUrl(String schemaName) { webDriverHelper.waitVisibility(addSchemaUrlInput); addSchemaUrlInput.sendKeys(schemaName); webDriverHelper.waitAndClick(By.id("askValue-dialog-ok")); }
Source:
public static Thread runInDaemonThread(final Runnable runnable, DaemonToken token) { if (!ModuleFactory.isTokenValid(token)) { throw new ContextAuthenticationException("Invalid token " + token); } DaemonThread thread = new DaemonThread() { @Override public void run() { isDaemonThread.set(true); try { Context.openSession(); new Thread(runnable).start(); } finally { Context.closeSession(); } } }; thread.start(); return thread; }

Target:
public static Thread runInDaemonThread(final Runnable runnable, DaemonToken token) { if (!ModuleFactory.isTokenValid(token)) { throw new ContextAuthenticationException("Invalid token " + token); } DaemonThread thread = new DaemonThread() { @Override public void run() { isDaemonThread.set(true); try { Context.openSession(); runnable.run(); } finally { Context.closeSession(); } } }; thread.start(); return thread; }
Source:
public void invalidateAll(boolean async) { if (!lock.tryLock()) { return; } try { if (async) { executorService.execute(new Runnable() { @Override public void run() { cache.invalidateAll(builderFactory); } }); } else { cache.invalidateAll(builderFactory); } } finally { lock.unlock(); } }

Target:
public void invalidateAll(boolean async) { if (async) { executorService.execute(new Runnable() { @Override public void run() { safeInvalidateAll(builderFactory); } }); } else { safeInvalidateAll(builderFactory); } }
Source:
public static int primaryKeyOid(RelationInfo relationInfo) { var primaryKey = relationInfo.primaryKey().stream().map(ColumnIdent::name).collect(Collectors.joining()); var b = new BytesRef(Type.PRIMARY_KEY.toString() + relationInfo.ident().fqn() + primaryKey); return murmurhash3_x86_32(b.bytes, b.offset, b.length, 0); }

Target:
public static int primaryKeyOid(RelationInfo relationInfo) { var primaryKey = Lists2.joinOn(" ", relationInfo.primaryKey(), ColumnIdent::name); var b = new BytesRef(Type.PRIMARY_KEY.toString() + relationInfo.ident().fqn() + primaryKey); return murmurhash3_x86_32(b.bytes, b.offset, b.length, 0); }
Source:
public EdxRatingBar(Context context, AttributeSet attrs) { super(context, attrs); }

Target:
public EdxRatingBar(Context context, AttributeSet attrs) { super(context, attrs); init(); }
Source:
public static String subscribeQueue(AmazonSNS sns, AmazonSQS sqs, String snsTopicArn, String sqsQueueUrl, boolean extendPolicy) throws AmazonClientException, AmazonServiceException { List<String> sqsAttrNames = Arrays.asList(QueueAttributeName.QueueArn.toString(), QueueAttributeName.Policy.toString()); Map<String, String> sqsAttrs = sqs.getQueueAttributes(sqsQueueUrl, sqsAttrNames).getAttributes(); String sqsQueueArn = sqsAttrs.get(QueueAttributeName.QueueArn.toString()); String policyJson = sqsAttrs.get(QueueAttributeName.Policy.toString()); Policy policy = extendPolicy || policyJson == null || policyJson.length() == 0 ? Policy.fromJson(policyJson) : new Policy(); policy.getStatements().add(new Statement(Effect.Allow) .withId("topic-subscription-" + snsTopicArn) .withPrincipals(Principal.AllUsers) .withActions(SQSActions.SendMessage) .withResources(new Resource(sqsQueueArn)) .withConditions(ConditionFactory.newSourceArnCondition(snsTopicArn))); Map<String, String> newAttrs = new HashMap<String, String>(); newAttrs.put(QueueAttributeName.Policy.toString(), policy.toJson()); sqs.setQueueAttributes(new SetQueueAttributesRequest(sqsQueueUrl, newAttrs)); SubscribeResult subscribeResult = sns.subscribe(snsTopicArn, "sqs", sqsQueueArn); return subscribeResult.getSubscriptionArn(); }

Target:
public static String subscribeQueue(AmazonSNS sns, AmazonSQS sqs, String snsTopicArn, String sqsQueueUrl, boolean extendPolicy) throws AmazonClientException, AmazonServiceException { List<String> sqsAttrNames = Arrays.asList(QueueAttributeName.QueueArn.toString(), QueueAttributeName.Policy.toString()); Map<String, String> sqsAttrs = sqs.getQueueAttributes(sqsQueueUrl, sqsAttrNames).getAttributes(); String sqsQueueArn = sqsAttrs.get(QueueAttributeName.QueueArn.toString()); String policyJson = sqsAttrs.get(QueueAttributeName.Policy.toString()); Policy policy = extendPolicy && policyJson != null && policyJson.length() > 0 ? Policy.fromJson(policyJson) : new Policy(); policy.getStatements().add(new Statement(Effect.Allow) .withId("topic-subscription-" + snsTopicArn) .withPrincipals(Principal.AllUsers) .withActions(SQSActions.SendMessage) .withResources(new Resource(sqsQueueArn)) .withConditions(ConditionFactory.newSourceArnCondition(snsTopicArn))); Map<String, String> newAttrs = new HashMap<String, String>(); newAttrs.put(QueueAttributeName.Policy.toString(), policy.toJson()); sqs.setQueueAttributes(new SetQueueAttributesRequest(sqsQueueUrl, newAttrs)); SubscribeResult subscribeResult = sns.subscribe(snsTopicArn, "sqs", sqsQueueArn); return subscribeResult.getSubscriptionArn(); }
Source:
public void theGetRetrieveConfigurationRequestIsReceived() throws Throwable { this.correlationUidPattern = Pattern.compile(this.organisationId.getOrganisationId() + "\\|\\|\\|\\S{17}\\|\\|\\|\\S{17}"); this.testCase = this.wsdlProjectFactory.createWsdlTestCase(SOAP_PROJECT_XML, TEST_SUITE_XML, TEST_CASE_XML); PROPERTIES_MAP.put("DeviceIdentificationE", this.deviceId.getDeviceId()); PROPERTIES_MAP.put("OrganisationIdentification", this.organisationId.getOrganisationId()); final TestCaseResult runTestStepByName = this.testCaseRunner.runWsdlTestCase(this.testCase, PROPERTIES_MAP, TEST_CASE_NAME_REQUEST); final TestStepResult runTestStepByNameResult = runTestStepByName.getRunTestStepByName(); final WsdlTestCaseRunner wsdlTestCaseRunner = runTestStepByName.getResults(); assertEquals(TestStepStatus.OK, runTestStepByNameResult.getStatus()); for (final TestStepResult tcr : wsdlTestCaseRunner.getResults()) { this.response = ((MessageExchange) tcr).getResponseContent(); this.correlationUidMatcher = this.correlationUidPattern.matcher(this.response); } this.correlationUidMatcher.find(); this.correlationUid = this.correlationUidMatcher.group(); }

Target:
public void theGetRetrieveConfigurationRequestIsReceived() throws Throwable { this.correlationUidPattern = Pattern.compile(this.organisationId.getOrganisationId() + "\\|\\|\\|\\S{17}\\|\\|\\|\\S{17}"); this.testCase = this.wsdlProjectFactory.createWsdlTestCase(SOAP_PROJECT_XML, TEST_SUITE_XML, TEST_CASE_XML); PROPERTIES_MAP.put("DeviceIdentificationE", this.deviceId.getDeviceId()); PROPERTIES_MAP.put("OrganisationIdentification", this.organisationId.getOrganisationId()); final TestCaseResult runTestStepByName = this.testCaseRunner.runWsdlTestCase(this.testCase, PROPERTIES_MAP, TEST_CASE_NAME_REQUEST); final TestStepResult runTestStepByNameResult = runTestStepByName.getRunTestStepByName(); final WsdlTestCaseRunner wsdlTestCaseRunner = runTestStepByName.getResults(); assertEquals(TestStepStatus.OK, runTestStepByNameResult.getStatus()); for (final TestStepResult tcr : wsdlTestCaseRunner.getResults()) { this.response = ((MessageExchange) tcr).getResponseContent(); this.correlationUidMatcher = this.correlationUidPattern.matcher(this.response); } assertTrue(this.correlationUidMatcher.find()); this.correlationUid = this.correlationUidMatcher.group(); }
Source:
private void recoverSegment(long segmentIndex, long segmentId, PbdSegmentName segmentName) throws IOException { PBDSegment<M> segment; if (segmentName.m_quarantined) { segment = new PbdQuarantinedSegment<>(segmentName.m_file, segmentIndex, segmentId); } else { segment = m_pbdSegmentFactory.create(segmentIndex, segmentId, segmentName.m_file, m_usageSpecificLog, m_extraHeaderSerializer); try { if (segment.getNumEntries() == 0 && m_segments.isEmpty()) { m_usageSpecificLog.info("Found Empty Segment with entries: " + segment.getNumEntries() + " For: " + segment.file().getName()); m_usageSpecificLog.info("Segment " + segment.file() + " (final: " + segment.isFinal() + "), will be closed and deleted during init"); segment.closeAndDelete(); return; } if (!segment.isFinal()) { m_usageSpecificLog.warn("Segment " + segment.file() + " (final: " + segment.isFinal() + "), has been recovered but is not in a final state"); } else if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug( "Segment " + segment.file() + " (final: " + segment.isFinal() + "), has been recovered"); } } catch (IOException e) { m_usageSpecificLog.warn( "Failed to retrieve entry count from segment " + segment.file() + ". Quarantining segment", e); quarantineSegment(segment); return; } finally { segment.close(); } } m_segments.put(segment.segmentIndex(), segment); }

Target:
private void recoverSegment(long segmentIndex, long segmentId, PbdSegmentName segmentName) throws IOException { PBDSegment<M> segment; if (segmentName.m_quarantined) { segment = new PbdQuarantinedSegment<>(segmentName.m_file, segmentIndex, segmentId); } else { segment = m_pbdSegmentFactory.create(segmentIndex, segmentId, segmentName.m_file, m_usageSpecificLog, m_extraHeaderSerializer); try { if (segment.getNumEntries() == 0 && m_segments.isEmpty()) { if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Found Empty Segment with entries: " + segment.getNumEntries() + " For: " + segment.file().getName()); m_usageSpecificLog.debug("Segment " + segment.file() + " (final: " + segment.isFinal() + "), will be closed and deleted during init"); } segment.closeAndDelete(); return; } if (!segment.isFinal()) { m_usageSpecificLog.warn("Segment " + segment.file() + " (final: " + segment.isFinal() + "), has been recovered but is not in a final state"); } else if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug( "Segment " + segment.file() + " (final: " + segment.isFinal() + "), has been recovered"); } } catch (IOException e) { m_usageSpecificLog.warn( "Failed to retrieve entry count from segment " + segment.file() + ". Quarantining segment", e); quarantineSegment(segment); return; } finally { segment.close(); } } m_segments.put(segment.segmentIndex(), segment); }
Source:
private static void loadExtensions(ModuleService moduleService, Map<String, Object> argMap) { ExtensionsManager extensionsManager = new ExtensionsManager(); extensionsManager.getGlobalContext().put( Base.GlobalContextKeys.APPLICATION_NAME, Base.ApplicationNames.OVIRT_ENGINE_EXTENSIONS_TOOL ); moduleService.getContext().put(ModuleService.EXTENSION_MANAGER, extensionsManager); List<File> files = (List<File>)argMap.get("extension-file"); if(files == null) { files = listFiles( ((String) argMap.get("extensions-dir")), "properties" ); } List<String> loadedExtensions = new LinkedList<>(); for(File f : files) { log.debug("Loading extension file '{}'", f.getName()); try { loadedExtensions.add(extensionsManager.load(f)); } catch (Exception ex) { log.error("Can't load extension '{}', ignoring.", f.getName()); log.debug("Exception:", ex); } } for(String extension : loadedExtensions) { try { extensionsManager.initialize(extension); log.debug("Extension '{}' initialized", extension); } catch (Exception ex) { log.error("Can't initialize extension '{}', ignoring.", extension); log.debug("Exception:", ex); } } extensionsManager.dump(); }

Target:
private static void loadExtensions(ModuleService moduleService, Map<String, Object> argMap) { ExtensionsManager extensionsManager = new ExtensionsManager(); extensionsManager.getGlobalContext().put( Base.GlobalContextKeys.APPLICATION_NAME, Base.ApplicationNames.OVIRT_ENGINE_EXTENSIONS_TOOL ); moduleService.getContext().put(ModuleService.EXTENSION_MANAGER, extensionsManager); List<File> files = (List<File>)argMap.get("extension-file"); if(files == null) { files = listFiles( ((String) argMap.get("extensions-dir")), "properties" ); } List<String> loadedExtensions = new LinkedList<>(); for(File f : files) { log.debug("Loading extension file '{}'", f.getName()); try { loadedExtensions.add(extensionsManager.load(f)); } catch (Exception ex) { log.error("Extension '{}' load failed (ignored): {}", f.getName(), ex.getMessage()); log.debug("Exception:", ex); } } for(String extension : loadedExtensions) { try { extensionsManager.initialize(extension); log.debug("Extension '{}' initialized", extension); } catch (Exception ex) { log.error("Extension '{}' initialization failed (ignored): {}", extension, ex.getMessage()); log.debug("Exception:", ex); } } extensionsManager.dump(); }
Source:
public static LeadershipId random() { return ImmutableLeadershipId.builder() .id(UUID.randomUUID()) .build(); }

Target:
public static LeadershipId random() { return create(UUID.randomUUID()); }
Source:
protected PerunClient setupPerunClient(HttpServletRequest req) throws InternalErrorException, RpcException { if (req.getHeader("OIDC_CLAIM_audience") != null && !req.getHeader("OIDC_CLAIM_audience").isEmpty()) { String clientId = req.getHeader("OIDC_CLAIM_audience"); List<PerunClient.Scope> scopes = new ArrayList<>(); for (String scope : req.getHeader("OIDC_CLAIM_scopes").split(",")) { scopes.add(PerunClient.Scope.valueOf(scope.trim().toUpperCase())); } return new PerunClient(clientId, scopes); } return new PerunClient(); }

Target:
protected PerunClient setupPerunClient(HttpServletRequest req) throws InternalErrorException, RpcException { if (req.getHeader("OIDC_CLAIM_audience") != null && !req.getHeader("OIDC_CLAIM_audience").isEmpty()) { String clientId = req.getHeader("OIDC_CLAIM_audience"); List<PerunClient.Scope> scopes = new ArrayList<>(); for (String scope : req.getHeader("OIDC_CLAIM_scopes").split(",")) { try { scopes.add(PerunClient.Scope.valueOf(scope.trim().toUpperCase())); } catch (IllegalArgumentException e) { throw new InternalErrorException("Scope "+scope.trim().toUpperCase()+" is unknown.", e); } } return new PerunClient(clientId, scopes); } return new PerunClient(); }
Source:
public ComponentValidationDiagnostic validate(final IBranchPath branchPath, final SnomedConceptIndexEntry concept) { final SnomedDescriptions descriptions = SnomedRequests.prepareSearchDescription() .filterByActive(true) .filterByType(Concepts.FULLY_SPECIFIED_NAME) .filterByConceptId(concept.getId()) .build(branchPath.getPath()) .executeSync(getBus()); if (descriptions.getTotal() > 1) { final List<SnomedDescriptionIndexEntry> snomedDescriptionIndexEntries = SnomedDescriptionIndexEntry.fromDescriptions(descriptions); final Multimap<String, String> languageRefsetIdToDescriptionIdMap = HashMultimap.create(); for (final SnomedDescriptionIndexEntry indexEntry : snomedDescriptionIndexEntries) { final Set<String> languageRefsetIdsWithPreferredMember = Maps.filterValues(indexEntry.getAcceptabilityMap(), Predicates.equalTo(Acceptability.PREFERRED)).keySet(); for (final String id : languageRefsetIdsWithPreferredMember) { languageRefsetIdToDescriptionIdMap.put(id, indexEntry.getId()); } } final List<ComponentValidationDiagnostic> diagnostics = newArrayList(); for (final Entry<String, Collection<String>> entry : languageRefsetIdToDescriptionIdMap.asMap().entrySet()) { if (entry.getValue().size() > 1) { diagnostics.add(new ComponentValidationDiagnosticImpl(concept.getId(), createErrorMessage(concept, entry, branchPath), ID, SnomedTerminologyComponentConstants.CONCEPT_NUMBER, error())); } } if (!diagnostics.isEmpty()) { return new ComponentValidationDiagnosticImpl(concept.getId(), ID, SnomedTerminologyComponentConstants.CONCEPT_NUMBER, diagnostics); } } return createOk(concept.getId(), ID, SnomedTerminologyComponentConstants.CONCEPT_NUMBER); }

Target:
public ComponentValidationDiagnostic validate(final IBranchPath branchPath, final SnomedConceptIndexEntry concept) { final SnomedDescriptions descriptions = SnomedRequests.prepareSearchDescription() .filterByActive(true) .filterByType(Concepts.FULLY_SPECIFIED_NAME) .filterByConceptId(concept.getId()) .build(branchPath.getPath()) .executeSync(getBus()); if (descriptions.getTotal() > 1) { final Multimap<String, String> languageRefsetIdToDescriptionIdMap = HashMultimap.create(); for (final ISnomedDescription description : descriptions) { final Set<String> languageRefsetIdsWithPreferredMember = Maps.filterValues(description.getAcceptabilityMap(), Predicates.equalTo(Acceptability.PREFERRED)).keySet(); for (final String id : languageRefsetIdsWithPreferredMember) { languageRefsetIdToDescriptionIdMap.put(id, description.getId()); } } final List<ComponentValidationDiagnostic> diagnostics = newArrayList(); for (final Entry<String, Collection<String>> entry : languageRefsetIdToDescriptionIdMap.asMap().entrySet()) { if (entry.getValue().size() > 1) { diagnostics.add(new ComponentValidationDiagnosticImpl(concept.getId(), createErrorMessage(concept, entry, branchPath), ID, SnomedTerminologyComponentConstants.CONCEPT_NUMBER, error())); } } if (!diagnostics.isEmpty()) { return new ComponentValidationDiagnosticImpl(concept.getId(), ID, SnomedTerminologyComponentConstants.CONCEPT_NUMBER, diagnostics); } } return createOk(concept.getId(), ID, SnomedTerminologyComponentConstants.CONCEPT_NUMBER); }
Source:
public TipManager setAsRead(Tip tip) { fReadList.remove(new Integer(tip.hashCode())); fReadList.add(new Integer(tip.hashCode())); return this; }

Target:
public TipManager setAsRead(Tip tip) { fReadList.remove(Integer.valueOf(tip.hashCode())); fReadList.add(Integer.valueOf(tip.hashCode())); return this; }
Source:
public void shouldRemoveCommentsFromXml() { String templateWithComments = "<ClinicalDocument>\n" + "<!-- This is comment line -->\n" + "</ClinicalDocument>"; byte[] bytes = templateWithComments.getBytes(); Byte[] byteObjects = new Byte[bytes.length]; int i = 0; for (byte b : bytes) { byteObjects[i++] = new Byte(b); } String templateWithoutComments = "<ClinicalDocument>\n" + "\n" + "</ClinicalDocument>"; Map<String, String> properties = new HashMap<>(); CdaTemplate cdaTemplate = new CdaTemplate(); cdaTemplate.setTemplateData(byteObjects); bytes = new byte[cdaTemplate.getTemplateData().length]; i = 0; for (Byte b : cdaTemplate.getTemplateData()) { bytes[i++] = b.byteValue(); } assertEquals(templateWithoutComments, new String(bytes)); }

Target:
public void shouldRemoveCommentsFromXml() { String templateWithComments = "<ClinicalDocument>\n" + "<!-- This is comment line -->\n" + "</ClinicalDocument>"; byte[] bytes = templateWithComments.getBytes(); Byte[] byteObjects = new Byte[bytes.length]; int i = 0; for (byte b : bytes) { byteObjects[i++] = b; } String templateWithoutComments = "<ClinicalDocument>\n" + "\n" + "</ClinicalDocument>"; CdaTemplate cdaTemplate = new CdaTemplate(); cdaTemplate.setTemplateData(byteObjects); bytes = new byte[cdaTemplate.getTemplateData().length]; i = 0; for (Byte b : cdaTemplate.getTemplateData()) { bytes[i++] = b; } assertEquals(templateWithoutComments, new String(bytes)); }
Source:
public void handlesWhitespaceAfterLinks() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html( "Hi [google](<LINK_0> how are you?" ), Matchers.equalTo( MarkdownTxtmarkTest.replaceNewLine( "<p>Hi \n<a href=\"<LINK_1>\">google</a> how are you?</p>\n" ) ) ); }

Target:
public void handlesWhitespaceAfterLinks() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html( "Hi [google](<LINK_0> how are you?" ), Matchers.equalTo( MarkdownTxtmarkTest.join( "MarkdownTxtmarkTest.START_PARAGRAPHHi ", "<a href=\"<LINK_1>\">google</a> how are you?</p>", "" ) ) ); }
Source:
public void notifyChanged(Notification notification) { super.notifyChanged(notification); if (NotationPackage.eINSTANCE.getDrawerStyle_Collapsed() == notification.getFeature()) { ((AbstractDiagramElementContainerEditPart) getHost()).notifyChanged(notification); } }

Target:
public void notifyChanged(Notification notification) { super.notifyChanged(notification); if (NotationPackage.eINSTANCE.getDrawerStyle_Collapsed() == notification.getFeature()) { regionPart.notifyChanged(notification); } }
Source:
public String getHostname() { return HOSTNAME; }

Target:
public String getHostname() { return hostname; }
Source:
public static List<IdentityProvider> createProviders(Environment env, Collection<IdentityProviderConfig> providerConfigurations) { final ImmutableList.Builder<IdentityProvider> providers = ImmutableList.builder(); Iterator<IdentityProviderFactory> it = FACTORIES.iterator(); while (it.hasNext()) { IdentityProviderFactory factory = it.next(); Optional<IdentityProviderConfig> providerConfig = providerConfigurations.stream().filter(conf -> conf.getClass() == factory.getConfigType()).findFirst(); if (providerConfig.isPresent()) { try { providers.add(factory.create(env, providerConfig.get())); } catch (Exception e) { throw new SnowowlRuntimeException(String.format("Couldn't initialize '{}''s identity provider", factory), e); } } } return providers.build(); }

Target:
public static List<IdentityProvider> createProviders(Environment env, Collection<IdentityProviderConfig> providerConfigurations) { final ImmutableList.Builder<IdentityProvider> providers = ImmutableList.builder(); Iterator<IdentityProviderFactory> it = FACTORIES.iterator(); while (it.hasNext()) { IdentityProviderFactory<IdentityProviderConfig> factory = it.next(); Optional<IdentityProviderConfig> providerConfig = providerConfigurations.stream().filter(conf -> conf.getClass() == factory.getConfigType()).findFirst(); if (providerConfig.isPresent()) { try { providers.add(factory.create(env, providerConfig.get())); } catch (Exception e) { throw new SnowowlRuntimeException(String.format("Couldn't initialize '{}''s identity provider", factory), e); } } } return providers.build(); }
Source:
public String render(Boolean valueToRender) { if(valueToRender == null) return ""; if (trueText == null || falseText == null) { return valueToRender.toString(); } return valueToRender.booleanValue() ? trueText : falseText; }

Target:
public String render(Boolean valueToRender) { if (valueToRender == null){ return ""; } if (trueText == null || falseText == null) { return valueToRender.toString(); } return valueToRender.booleanValue() ? trueText : falseText; }
Source:
public void removeAlert(String authId, String journalKey, String subjectName) throws IOException { String nedId = getUserIdFromAuthId(authId); if (nedId == null) { throw new RuntimeException("failed to get NED ID"); } JsonArray alerts = userApi.requestObject(String.format("individuals/%s/alerts", nedId), JsonArray.class); JsonObject alert = findMatchingAlert(alerts, journalKey); if (alert == null) { throw new RuntimeException("no subject alert found"); } RemoveResult result = removeSubjectFromAlert(alert, subjectName); if (result == RemoveResult.NOT_FOUND) { throw new RuntimeException("matching subject alert not found"); } String alertId = String.valueOf(alert.getAsJsonPrimitive("id").getAsLong()); if (result == RemoveResult.EMPTY_AFTER_REMOVE) { userApi.deleteObject(String.format("individuals/%s/alerts/%s", nedId, alertId)); } else { userApi.putObject(String.format("individuals/%s/alerts/%s", nedId, alertId), alert); } }

Target:
public void removeAlert(String authId, String journalKey, String subjectName) throws IOException { String userId = userApi.getUserIdFromAuthId(authId); List<Alert> alerts = fetchAlerts(userId); Alert alert = findMatchingAlert(alerts, journalKey) .orElseThrow(() -> new SubjectAlertException("no subject alert found")); RemoveResult result = removeSubjectFromAlert(alert, subjectName); if (result == RemoveResult.NOT_FOUND) { throw new SubjectAlertException("matching subject alert not found"); } String alertId = alert.getId().toString(); if (result == RemoveResult.EMPTY_AFTER_REMOVE) { userApi.deleteObject(String.format("individuals/%s/alerts/%s", userId, alertId)); } else { userApi.putObject(String.format("individuals/%s/alerts/%s", userId, alertId), alert); } }
Source:
protected ILogData getNextEntry(QueuedStreamContext context, long maxGlobal) { boolean useBackpointers = this.runtime.getParameters().isFollowBackpointersEnabled(); if (context.readQueue.isEmpty() && context.readCpQueue.isEmpty() && !fillReadQueue(maxGlobal, context)) { return null; } if (maxGlobal < context.checkpointSuccessStartAddr) { throw new TrimmedException(); } NavigableSet<Long> getFrom; if (context.readCpQueue.size() > 0) { getFrom = context.readCpQueue; context.setGlobalPointer(context.checkpointSuccessStartAddr); } else { getFrom = context.readQueue; } if (context.readCpQueue.isEmpty() && context.readQueue.first() > maxGlobal) { return null; } if (useBackpointers) { if (getFrom.size() > 0) { final long thisRead = getFrom.pollFirst(); ILogData ld = read(thisRead); if (getFrom == context.readQueue) { addToResolvedQueue(context, thisRead, ld); } return ld; } } else { boolean getNext; do { if (getFrom.size() > 0) { final long thisRead = getFrom.pollFirst(); int counter = 1; List<Long> batchRead = new ArrayList<>(); batchRead.add(thisRead); Iterator<Long> it = getFrom.iterator(); while (it.hasNext() && counter < batchSize) { batchRead.add(it.next()); counter++; } log.trace("getNextEntry[{}]: reading {}, if not present read batch of addresses: {}", this, thisRead, batchRead); ILogData ld = readRange(thisRead, batchRead); if (getFrom == context.readQueue) { if (ld.containsStream(this.id)) { addToResolvedQueue(context, thisRead, ld); return ld; } else { log.trace("getNextEntry[{}]: the data for address does not belong to this stream. Skip.", this, thisRead); getNext = true; } } else { return ld; } } else { getNext = false; } } while (getNext); } return null; }

Target:
protected ILogData getNextEntry(QueuedStreamContext context, long maxGlobal) { if (context.readQueue.isEmpty() && context.readCpQueue.isEmpty() && !fillReadQueue(maxGlobal, context)) { return null; } if (maxGlobal < context.checkpointSuccessStartAddr) { throw new TrimmedException(); } NavigableSet<Long> getFrom; if (context.readCpQueue.size() > 0) { getFrom = context.readCpQueue; context.setGlobalPointer(context.checkpointSuccessStartAddr); } else { getFrom = context.readQueue; } if (context.readCpQueue.isEmpty() && context.readQueue.first() > maxGlobal) { return null; } return removeFromQueue(getFrom); }
Source:
private static synchronized byte[] format(File file, Checksum original, Checksum formatted) throws IOException { try (InputStream in = new CheckedInputStream(new BufferedInputStream(new FileInputStream(file)), original)) { ByteArrayOutputStream buffer = FORMATTING_BUFFER != null ? FORMATTING_BUFFER.get() : null; if (buffer == null) { buffer = new ByteArrayOutputStream(); FORMATTING_BUFFER = new WeakReference<>(buffer); } else { buffer.reset(); } XMLSerializer serializer = new XMLSerializer(new CheckedOutputStream(buffer, formatted), FORMAT); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(serializer); reader.setDTDHandler(serializer); reader.parse(new InputSource(in)); return buffer.toByteArray(); } catch (SAXException ex) { throw new IOException(ex); } }

Target:
private byte[] format(File file, Checksum original, Checksum formatted) throws IOException { try (InputStream in = new CheckedInputStream(new BufferedInputStream(new FileInputStream(file)), original)) { ByteArrayOutputStream buffer = formattingBuffer != null ? formattingBuffer.get() : null; if (buffer == null) { buffer = new ByteArrayOutputStream(); formattingBuffer = new WeakReference<>(buffer); } else { buffer.reset(); } XMLSerializer serializer = new XMLSerializer(new CheckedOutputStream(buffer, formatted), format); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(serializer); reader.setDTDHandler(serializer); reader.parse(new InputSource(in)); return buffer.toByteArray(); } catch (SAXException ex) { throw new IOException(ex); } }
Source:
static GlyphPair gp(String original, String mirror) { return new GlyphPair(original, mirror); }

Target:
public static GlyphPair gp(String original, String mirror) { return new GlyphPair(original, mirror); }
Source:
private Class selectSocketChannel() { if (useNativeTransport && OsUtils.isOSLinux()) { return EpollServerSocketChannel.class; } return NioServerSocketChannel.class; }

Target:
private Class<? extends ServerSocketChannel> selectSocketChannel() { if (useNativeTransport && OsUtils.isOSLinux()) { return EpollServerSocketChannel.class; } return NioServerSocketChannel.class; }
Source:
public void testNewQuestionFrame() { ______TS("MCQ: new question (frame) link"); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.selectNewQuestionType("MCQ"); assertTrue(feedbackEditPage.verifyNewMcqQuestionFormIsDisplayed()); if (!feedbackEditPage.isElementSelected("generateMcqOptionsCheckbox--1")) { feedbackEditPage.clickGenerateMcqOptionsCheckbox(-1); } assertFalse(feedbackEditPage.isElementVisible("mcqChoiceTable--1")); feedbackEditPage.clickDiscardChangesLinkForNewQuestion(); ______TS("MCQ: verify UI after cancelling"); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.selectNewQuestionType("MCQ"); assertTrue(feedbackEditPage.verifyNewMcqQuestionFormIsDisplayed()); assertFalse(feedbackEditPage.isElementVisible("mcqChoiceTable--1")); }

Target:
public void testNewQuestionFrame() { ______TS("MCQ: new question (frame) link"); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.selectNewQuestionType("MCQ"); assertTrue(feedbackEditPage.verifyNewMcqQuestionFormIsDisplayed()); if (!feedbackEditPage.isElementSelected("generateMcqOptionsCheckbox--1")) { feedbackEditPage.clickGenerateMcqOptionsCheckbox(-1); } assertFalse(feedbackEditPage.isElementVisible("mcqChoiceTable--1")); feedbackEditPage.clickDiscardChangesLinkForNewQuestion(); feedbackEditPage.waitForConfirmationModalAndClickOk(); ______TS("MCQ: verify UI after cancelling"); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.selectNewQuestionType("MCQ"); assertTrue(feedbackEditPage.verifyNewMcqQuestionFormIsDisplayed()); assertFalse(feedbackEditPage.isElementVisible("mcqChoiceTable--1")); }
Source:
public static boolean interactWithFluidHandler(@Nonnull EntityPlayer player, @Nonnull EnumHand hand, @Nonnull World world, @Nonnull BlockPos pos, @Nullable EnumFacing side) { Preconditions.checkNotNull(player); Preconditions.checkNotNull(hand); Preconditions.checkNotNull(world); Preconditions.checkNotNull(pos); ItemStack heldItem = player.getHeldItem(hand); if (!heldItem.isEmpty()) { IFluidHandler blockFluidHandler = getFluidHandler(world, pos, side); if (blockFluidHandler != null) { IItemHandler playerInventory = new InvWrapper(player.inventory); FluidActionResult fluidActionResult = tryFillContainerAndStow(heldItem, blockFluidHandler, playerInventory, Integer.MAX_VALUE, player); if (!fluidActionResult.isSuccess()) { fluidActionResult = tryEmptyContainerAndStow(heldItem, blockFluidHandler, playerInventory, Integer.MAX_VALUE, player); } if (fluidActionResult.isSuccess()) { player.setHeldItem(hand, fluidActionResult.getResult()); return true; } } } return false; }

Target:
public static boolean interactWithFluidHandler(@Nonnull EntityPlayer player, @Nonnull EnumHand hand, @Nonnull World world, @Nonnull BlockPos pos, @Nullable EnumFacing side) { Preconditions.checkNotNull(player); Preconditions.checkNotNull(hand); Preconditions.checkNotNull(world); Preconditions.checkNotNull(pos); ItemStack heldItem = player.getHeldItem(hand); if (!heldItem.isEmpty()) { IFluidHandler blockFluidHandler = getFluidHandler(world, pos, side); if (blockFluidHandler != null) { IItemHandler playerInventory = player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null); if (playerInventory != null) { FluidActionResult fluidActionResult = tryFillContainerAndStow(heldItem, blockFluidHandler, playerInventory, Integer.MAX_VALUE, player); if (!fluidActionResult.isSuccess()) { fluidActionResult = tryEmptyContainerAndStow(heldItem, blockFluidHandler, playerInventory, Integer.MAX_VALUE, player); } if (fluidActionResult.isSuccess()) { player.setHeldItem(hand, fluidActionResult.getResult()); return true; } } } } return false; }
Source:
public void truncateTables(final Set<TableReference> tablesToTruncate) { if (!tablesToTruncate.isEmpty()) { try { clientPool.run(new FunctionCheckedException<Client, Void, Exception>() { @Override public Void apply(Client client) throws Exception { for (TableReference tableRef : tablesToTruncate) { truncateInternal(client, tableRef); } return null; } @Override public String toString() { return "truncateTables(" + tablesToTruncate.size() + " tables)"; } }); } catch (UnavailableException e) { throw new PalantirRuntimeException("Truncating tables requires all Cassandra nodes" + " to be up and available."); } catch (Exception e) { throw Throwables.throwUncheckedException(e); } } }

Target:
public void truncateTables(final Set<TableReference> tablesToTruncate) { if (!tablesToTruncate.isEmpty()) { try { runTruncateInternal(tablesToTruncate); } catch (UnavailableException e) { throw new PalantirRuntimeException("Truncating tables requires all Cassandra nodes" + " to be up and available."); } catch (TException e) { throw Throwables.throwUncheckedException(e); } } }
Source:
public synchronized EmbeddedCacheManager startNewNode() { EmbeddedCacheManager cacheManager; try { cacheManager = TestCacheManagerFactory.fromXml(configurationResourceName); } catch (IOException e) { throw new RuntimeException(e); } cacheManagers.add(cacheManager); Cache<K, V> cache = cacheManager.getCache(); caches.add(cache); waitForReashToComplete(cache, caches); TestingUtil.waitForRehashToComplete(caches); return cacheManager; }

Target:
public synchronized EmbeddedCacheManager startNewNode() { EmbeddedCacheManager cacheManager; try { cacheManager = TestCacheManagerFactory.fromXml(configurationResourceName); } catch (IOException e) { throw new RuntimeException(e); } cacheManagers.add(cacheManager); Cache<K, V> cache = cacheManager.getCache(); caches.add(cache); waitForRehashToComplete(cache, caches); return cacheManager; }
Source:
public synchronized Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { String jsonString = json.getAsString(); try { return localFormat.parse(jsonString); } catch (final ParseException ignored) { } try { return local24HourFormat.parse(jsonString); } catch (final ParseException ignored) { } try { return enUsFormat.parse(jsonString); } catch (final ParseException ignored) { } try { return enUs24HourFormat.parse(jsonString); } catch (final ParseException ignored) { } try { return iso8601Format.parse(jsonString); } catch (ParseException e) { Logger.e(TAG, "Could not parse date: " + e.getMessage(), "", ADALError.DATE_PARSING_FAILURE, e); } throw new JsonParseException("Could not parse date: " + jsonString); }

Target:
public synchronized Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { String jsonString = json.getAsString(); try { return iso8601Format.parse(jsonString); } catch (final ParseException ignored) { } try { return localFormat.parse(jsonString); } catch (final ParseException ignored) { } try { return local24HourFormat.parse(jsonString); } catch (final ParseException ignored) { } try { return enUsFormat.parse(jsonString); } catch (final ParseException ignored) { } try { return enUs24HourFormat.parse(jsonString); } catch (final ParseException e) { Logger.e(TAG, "Could not parse date: " + e.getMessage(), "", ADALError.DATE_PARSING_FAILURE, e); } throw new JsonParseException("Could not parse date: " + jsonString); }
Source:
private void processOptions(RepositoryState state) throws JGitInternalException { if (tagger == null) tagger = new PersonIdent(repo); if (name == null || !Repository.isValidRefName(Constants.R_TAGS + name)) throw new JGitInternalException(MessageFormat.format( JGitText.get().tagNameInvalid, name == null ? "<null>" : name)); if (signed) throw new UnsupportedOperationException( JGitText.get().signingNotSupportedOnTag); }

Target:
private void processOptions(RepositoryState state) throws InvalidTagNameException { if (tagger == null) tagger = new PersonIdent(repo); if (name == null || !Repository.isValidRefName(Constants.R_TAGS + name)) throw new InvalidTagNameException(MessageFormat.format(JGitText .get().tagNameInvalid, name == null ? "<null>" : name)); if (signed) throw new UnsupportedOperationException( JGitText.get().signingNotSupportedOnTag); }
Source:
public static Graph createResultTrendGraph(AbstractBuild<?, ?> owner, Boolean isCompleted, List<AWSDeviceFarmTestResult> results) { List<String> rows = new ArrayList<String>(); List<Number> vals = new ArrayList<Number>(); List<NumberOnlyBuildLabel> cols = new ArrayList<NumberOnlyBuildLabel>(); for (AWSDeviceFarmTestResult result : results) { hudson.model.Run<?, ?> build = result.getOwner(); NumberOnlyBuildLabel label = new NumberOnlyBuildLabel(build); rows.add("Pass"); cols.add(label); vals.add(result.getPassCount()); rows.add("Warn"); cols.add(label); vals.add(result.getWarnCount()); rows.add("Fail"); cols.add(label); vals.add(result.getFailCount()); } CategoryDataset dataset = createDataset(vals, rows, cols); Color[] colors = new Color[]{AWSDeviceFarmGraph.PassColor, AWSDeviceFarmGraph.WarnColor, AWSDeviceFarmGraph.FailColor}; return new AWSDeviceFarmGraph(owner, isCompleted, getGraphSize(), dataset, "Build #", "# of tests", colors); }

Target:
public static Graph createResultTrendGraph(AbstractBuild<?, ?> owner, Boolean isCompleted, List<AWSDeviceFarmTestResult> results) { List<String> rows = new ArrayList<String>(); List<Number> vals = new ArrayList<Number>(); List<NumberOnlyBuildLabel> cols = new ArrayList<NumberOnlyBuildLabel>(); for (AWSDeviceFarmTestResult result : results) { Run<?, ?> build = result.getOwner(); NumberOnlyBuildLabel label = new NumberOnlyBuildLabel(build); rows.add("Pass"); cols.add(label); vals.add(result.getPassCount()); rows.add("Warn"); cols.add(label); vals.add(result.getWarnCount()); rows.add("Fail"); cols.add(label); vals.add(result.getFailCount()); } CategoryDataset dataset = createDataset(vals, rows, cols); Color[] colors = new Color[]{AWSDeviceFarmGraph.PassColor, AWSDeviceFarmGraph.WarnColor, AWSDeviceFarmGraph.FailColor}; return new AWSDeviceFarmGraph(owner, isCompleted, getGraphSize(), dataset, "Build #", "# of tests", colors); }
Source:
public void close() { fetches.clear(); buffer.clear(); pendingCalls.clear(); }

Target:
public void close() { fetches.clear(); pendingCalls.clear(); if (buffer != null) { buffer.clear(); } }