auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Runnable upToChange(final boolean openReplyBox) { return new Runnable() { public void run() { saveAllDrafts(); String b = base != null ? String.valueOf(base.get()) : null; String rev = String.valueOf(revision.get()); Gerrit.display( PageLinks.toChange(changeId, rev), new ChangeScreen2(changeId, b, rev, openReplyBox)); } }; }

Target:
private Runnable upToChange(final boolean openReplyBox) { return new Runnable() { public void run() { if (unsaved.isEmpty()) { goUpToChange(openReplyBox); } else { CallbackGroup group = new CallbackGroup(); saveAllDrafts(group); group.addFinal(new GerritCallback<Void>() { @Override public void onSuccess(Void result) { goUpToChange(openReplyBox); } }).onSuccess(null); } } }; }
Source:
public static void main(String[] args) throws Exception { Injector injector = Guice.createInjector(new UpdateHelperModule(), new CheckHelperAuditModule(), new LdapModule()); HostUpdateHelper hostUpdateHelper = injector.getInstance(HostUpdateHelper.class); try { LOG.info("Host names update started."); String hostChangesFile = args[0]; if (hostChangesFile == null || hostChangesFile.isEmpty()) { throw new AmbariException("Path to file with host names changes is empty or null."); } hostUpdateHelper.setHostChangesFile(hostChangesFile); hostUpdateHelper.initHostChangesFileMap(); hostUpdateHelper.startPersistenceService(); hostUpdateHelper.validateHostChanges(); hostUpdateHelper.checkForSecurity(); hostUpdateHelper.updateHostsInDB(); hostUpdateHelper.updateHostsForTopologyRequests(); hostUpdateHelper.updateHostsForAlertsInDB(); hostUpdateHelper.updateHostsInConfigurations(); LOG.info("Host names update completed successfully."); } catch (AmbariException e) { LOG.error("Exception occurred during host names update, failed", e); throw e; } catch (Throwable e){ LOG.error("Unexpected error, host names update failed", e); throw new Exception("Unexpected error, host names update failed", e); } finally { hostUpdateHelper.stopPersistenceService(); } }

Target:
public static void main(String[] args) throws Exception { Injector injector = Guice.createInjector(new UpdateHelperModule(), new CheckHelperAuditModule(), new LdapModule()); HostUpdateHelper hostUpdateHelper = injector.getInstance(HostUpdateHelper.class); try { LOG.info("Host names update started."); String hostChangesFile = args[0]; if (hostChangesFile == null || hostChangesFile.isEmpty()) { throw new AmbariException("Path to file with host names changes is empty or null."); } hostUpdateHelper.setHostChangesFile(hostChangesFile); hostUpdateHelper.initHostChangesFileMap(); hostUpdateHelper.startPersistenceService(); hostUpdateHelper.validateHostChanges(); hostUpdateHelper.checkForSecurity(); hostUpdateHelper.updateHostsInDB(); hostUpdateHelper.updateHostsForTopologyRequests(); hostUpdateHelper.updateHostsForAlertsInDB(); hostUpdateHelper.updateHostsInConfigurations(); LOG.info("Host names update completed successfully."); } catch (AmbariException e) { LOG.error("Exception occurred during host names update, failed", e); throw e; } finally { hostUpdateHelper.stopPersistenceService(); } }
Source:
public long createSession(Session session, boolean reserve) { long sid = random.nextLong(); synchronized (session) { session.state = reserve ? State.RESERVED : State.UNRESERVED; session.startTime = session.lastAccessTime = System.currentTimeMillis(); } while (sessions.putIfAbsent(sid, session) != null) { sid = random.nextLong(); } return sid; }

Target:
public long createSession(Session session, boolean reserve) { long sid = random.nextLong(); synchronized (session) { Preconditions.checkArgument(session.state == State.NEW); session.state = reserve ? State.RESERVED : State.UNRESERVED; session.startTime = session.lastAccessTime = System.currentTimeMillis(); } while (sessions.putIfAbsent(sid, session) != null) { sid = random.nextLong(); } return sid; }
Source:
protected Case getElement(int recordId, QueryContext context) { if (context == null) { return super.getElement(recordId, context); } CaseGroupResultCache caseGroupCache = context.getQueryCacheOrNull(CaseGroupResultCache.class); CaseObjectCache caseObjectCache = getCaseObjectCacheIfRelevant(context); if (caseObjectCache != null && (caseObjectCache.isLoaded(recordId) || canLoadCaseFromGroup(caseGroupCache, recordId))) { if (!caseObjectCache.isLoaded(recordId)) { Pair<String, LinkedHashSet<Integer>> tranche = caseGroupCache.getTranche(recordId); EvaluationTrace loadTrace = new EvaluationTrace(String.format("Bulk Case Load [%s]", tranche.first)); SqlStorage<ACase> sqlStorage = ((SqlStorage<ACase>)storage); LinkedHashSet<Integer> body = tranche.second; sqlStorage.bulkRead(body, caseObjectCache.getLoadedCaseMap()); loadTrace.setOutcome("Loaded: " + body.size()); context.reportTrace(loadTrace); } return caseObjectCache.getLoadedCase(recordId); } return super.getElement(recordId, context); }

Target:
protected Case getElement(int recordId, QueryContext context) { if (context == null) { return super.getElement(recordId, context); } CaseSetResultCache caseSetCache = context.getQueryCacheOrNull(CaseSetResultCache.class); CaseObjectCache caseObjectCache = getCaseObjectCacheIfRelevant(context); if(caseObjectCache != null) { if (caseObjectCache.isLoaded(recordId)) { return caseObjectCache.getLoadedCase(recordId); } if (canLoadCaseFromGroup(caseSetCache, recordId)) { Pair<String, LinkedHashSet<Integer>> tranche = caseSetCache.getCaseSetForRecord(recordId); EvaluationTrace loadTrace = new EvaluationTrace(String.format("Bulk Case Load [%s]", tranche.first)); SqlStorage<ACase> sqlStorage = ((SqlStorage<ACase>)storage); LinkedHashSet<Integer> body = tranche.second; sqlStorage.bulkRead(body, caseObjectCache.getLoadedCaseMap()); loadTrace.setOutcome("Loaded: " + body.size()); context.reportTrace(loadTrace); return caseObjectCache.getLoadedCase(recordId); } } return super.getElement(recordId, context); }
Source:
protected void initInternal(final FilterConfig filterConfig) throws ServletException { if (!isIgnoreInitConfiguration()) { super.initInternal(filterConfig); setCasServerLoginUrl(getPropertyFromInitParams(filterConfig, "casServerLoginUrl", null)); log.trace("Loaded CasServerLoginUrl parameter: " + this.casServerLoginUrl); setRenew(parseBoolean(getPropertyFromInitParams(filterConfig, "renew", "false"))); log.trace("Loaded renew parameter: " + this.renew); setGateway(parseBoolean(getPropertyFromInitParams(filterConfig, "gateway", "false"))); log.trace("Loaded gateway parameter: " + this.gateway); String[] excludeUrls = parseExcludePatterns(getPropertyFromInitParams(filterConfig, EXCLUDE_PARAMETERS_INIT_PARAM, "false")); setExcludePatterns(excludeUrls); log.trace("exclude patterns: " + excludePatterns); final String gatewayStorageClass = getPropertyFromInitParams(filterConfig, "gatewayStorageClass", null); if (gatewayStorageClass != null) { try { this.gatewayStorage = (GatewayResolver) Class.forName(gatewayStorageClass).newInstance(); } catch (final Exception e) { log.error(e,e); throw new ServletException(e); } } } }

Target:
protected void initInternal(final FilterConfig filterConfig) throws ServletException { if (!isIgnoreInitConfiguration()) { super.initInternal(filterConfig); setCasServerLoginUrl(getPropertyFromInitParams(filterConfig, "casServerLoginUrl", null)); log.trace("Loaded CasServerLoginUrl parameter: " + this.casServerLoginUrl); setRenew(parseBoolean(getPropertyFromInitParams(filterConfig, "renew", "false"))); log.trace("Loaded renew parameter: " + this.renew); setGateway(parseBoolean(getPropertyFromInitParams(filterConfig, "gateway", "false"))); log.trace("Loaded gateway parameter: " + this.gateway); Pattern[] excludeUrls = parseExcludePatterns(getPropertyFromInitParams(filterConfig, EXCLUDE_PARAMETERS_INIT_PARAM, "false")); setExcludePatterns(excludeUrls); log.trace("Exclude patterns: " + excludePatterns); final String gatewayStorageClass = getPropertyFromInitParams(filterConfig, "gatewayStorageClass", null); if (gatewayStorageClass != null) { try { this.gatewayStorage = (GatewayResolver) Class.forName(gatewayStorageClass).newInstance(); } catch (final Exception e) { log.error(e,e); throw new ServletException(e); } } } }
Source:
public AddressEntry getOrCreateAddressEntry(String offerId, AddressEntry.Context context) { Optional<AddressEntry> addressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> offerId.equals(e.getOfferId())) .filter(e -> context == e.getContext()) .findAny(); if (addressEntry.isPresent()) { return addressEntry.get(); } else { Optional<AddressEntry> emptyAvailableAddressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> AddressEntry.Context.AVAILABLE == e.getContext()) .filter(e -> isAddressUnused(e.getAddress())) .findAny(); if (emptyAvailableAddressEntry.isPresent()) { return addressEntryList.swapAvailableToAddressEntryWithOfferId(emptyAvailableAddressEntry.get(), context, offerId); } else { AddressEntry entry = new AddressEntry(wallet.freshReceiveKey(), context, offerId, true); addressEntryList.addAddressEntry(entry); return entry; } } }

Target:
public AddressEntry getOrCreateAddressEntry(String offerId, AddressEntry.Context context) { Optional<AddressEntry> addressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> offerId.equals(e.getOfferId())) .filter(e -> context == e.getContext()) .findAny(); if (addressEntry.isPresent()) { return addressEntry.get(); } else { Optional<AddressEntry> emptyAvailableAddressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> AddressEntry.Context.AVAILABLE == e.getContext()) .filter(e -> isAddressUnused(e.getAddress())) .filter(e -> Script.ScriptType.P2PKH.equals(e.getAddress().getOutputScriptType())) .findAny(); if (emptyAvailableAddressEntry.isPresent()) { return addressEntryList.swapAvailableToAddressEntryWithOfferId(emptyAvailableAddressEntry.get(), context, offerId); } else { DeterministicKey key = (DeterministicKey) wallet.findKeyFromAddress(wallet.freshReceiveAddress(Script.ScriptType.P2PKH)); AddressEntry entry = new AddressEntry(key, context, offerId, false); addressEntryList.addAddressEntry(entry); return entry; } } }
Source:
private void checkShutdown() { if (completedOrFailedEvalCount.incrementAndGet() == initServerCount + addedServerContextCount.get() + initWorkerCount + addedWorkerContextCount.get()) { for (final ActiveContext serverContext : serverContexts) { serverContext.close(); } for (final ActiveContext workerContext : workerContextsToClose) { workerContext.close(); } isComplete = true; } }

Target:
private void checkShutdown() { if (completedOrFailedEvalCount.incrementAndGet() == initServerCount + addedServerContextCount.get() + initWorkerCount + addedWorkerContextCount.get()) { if (isJobFinished.compareAndSet(false, true)) { Executors.newSingleThreadExecutor().submit(new Runnable() { @Override public void run() { while (optimizationOrchestrator.isPlanExecuting()) { try { LOG.log(Level.INFO, "It's time to shutdown active contexts, but wait for completion of plan execution"); Thread.sleep(SHUTDOWN_TRIAL_INTERVAL_MS); } catch (final InterruptedException e) { LOG.log(Level.FINEST, "Interrupted while waiting for plan finish", e); } } for (final ActiveContext serverContext : serverContexts) { serverContext.close(); } for (final ActiveContext workerContext : workerContextsToClose) { workerContext.close(); } } }); } } }
Source:
public static Order findAndExtractOrder(ArrayList<Order> position, String symbol) { for (Order stock : position) { if (stock.getStockSymbol().equals(symbol)) { position.remove(stock); return stock; } } return null; }

Target:
public static Order findAndExtractOrder(ArrayList<Order> position, String symbol) { if(position != null && symbol != null){ for (Order stock : position) { if (stock.getStockSymbol().equals(symbol)) { position.remove(stock); return stock; } } } return null; }
Source:
public void enterFieldkey(ABCMusicParser.FieldkeyContext ctx) { Letter letter = Letter.fromChar(ctx.key().keynote().basenote() .getText().charAt(0)); SingleAccidental accidental = SingleAccidental.NATURAL; boolean major = true; if (ctx.key().keynote().keyaccidental().size() != 0) { if (ctx.key().keynote().keyaccidental().get(0).getText().hashCode() == "b" .hashCode()) { accidental = SingleAccidental.FLAT; } else if (ctx.key().keynote().keyaccidental().get(0).getText() .hashCode() == "#".hashCode()) { accidental = SingleAccidental.SHARP; } } if (ctx.key().modeminor().size() != 0 && ctx.key().modeminor().get(0).getText().hashCode() == "m" .hashCode()) { major = false; } KeySignature keySignature = new KeySignature(letter, accidental, major); System.out.println("Key: Accidental = " + accidental.name() + "; Letter = " + letter.name() + "; Major = " + major); }

Target:
public void enterFieldkey(ABCMusicParser.FieldkeyContext ctx) { Letter letter = Letter.fromChar(ctx.key().keynote().basenote() .getText().charAt(0)); SingleAccidental accidental = SingleAccidental.NATURAL; boolean major = true; System.out.println("ACCIDENTAL: " + ctx.key().keynote().keyaccidental().get(0).getText()); if (ctx.key().keynote().keyaccidental().size() != 0) { if (ctx.key().keynote().keyaccidental().get(0).getText() .equals("b")) { accidental = SingleAccidental.FLAT; } else if (ctx.key().keynote().keyaccidental().get(0).getText() .equals("#")) { accidental = SingleAccidental.SHARP; } } if (ctx.key().modeminor().size() != 0 && ctx.key().modeminor().get(0).getText().equals("m")) { major = false; } KeySignature keySignature = new KeySignature(letter, accidental, major); System.out.println("Key: Accidental = " + accidental.name() + "; Letter = " + letter.name() + "; Major = " + major); }
Source:
private Iterable<? extends AttributeQuery<?>> parseListQuery(HttpServletRequest request) throws QueryParseException { ImmutableSet.Builder<AttributeQuery<?>> operands = ImmutableSet.builder(); for (Entry<String, String[]> param : getParameterMap(request).entrySet()) { Optional<Attribute<?>> optionalAttribute = attributesLookup.attributeFor(param.getKey()); if (optionalAttribute.isPresent()) { Attribute<?> attribute = optionalAttribute.get(); QueryAtomParser<?> parser = parsers.get(attribute); for (String paramString : param.getValue()) { Iterable<String> values; if (attribute.isCollectionOfValues()) { values = splitVals(paramString); } else { values = Collections.singletonList(paramString); } operands.add(parser.parse(param.getKey(), values)); } } } return operands.build(); }

Target:
private Iterable<? extends AttributeQuery<?>> parseListQuery(HttpServletRequest request) throws QueryParseException { ImmutableSet.Builder<AttributeQuery<?>> operands = ImmutableSet.builder(); for (Entry<String, String[]> param : getParameterMap(request).entrySet()) { Optional<Attribute<?>> attribute = attributesLookup.attributeFor(param.getKey()); if (attribute.isPresent()) { QueryAtomParser<?> parser = parsers.get(attribute.get()); for (String paramString : param.getValue()) { Iterable<String> rawValues; if (param.getKey().equals(Attributes.Q.externalName())) { rawValues = Collections.singletonList(paramString); } else { rawValues = splitVals(paramString); } operands.add(parser.parse(param.getKey(), rawValues)); } } } return operands.build(); }
Source:
public Optional<SchedulePeriod> getFinalStub() { SchedulePeriod lastPeriod = getLastPeriod(); if (!isTerm() && !lastPeriod.isRegular(frequency, rollConvention)) { return Optional.of(lastPeriod); } else { return Optional.empty(); } }

Target:
public Optional<SchedulePeriod> getFinalStub() { return (isFinalStub() ? Optional.of(getLastPeriod()) : Optional.empty()); }
Source:
public CustomField getCustomFieldById(int customFieldId) { if(customFields == null) return null; for (CustomField customField : customFields) { if (customFieldId == customField.getId()) { return customField; } } return null; }

Target:
public CustomField getCustomFieldById(int customFieldId) { for (CustomField customField : customFields) { if (customFieldId == customField.getId()) { return customField; } } return null; }
Source:
public BatchItem( final String rawEvent, final boolean strictParsing, final EmptyInjectionConfiguration emptyInjectionConfiguration, final InjectionConfiguration[] injections, final List<Integer> skipCharacters) { this.rawEvent = rawEvent; this.skipCharacters = skipCharacters; this.event = new JSONObject(rawEvent); if (strictParsing) { try { final JSONObject shadowEvent = StrictJsonParser.parseObject(rawEvent); if (!shadowEvent.toString().equals(this.event.toString())) { LOG.debug("[STRICT_JSON_DIFF] Strict parser produced different output for event: {}", rawEvent); } } catch (final Exception e) { LOG.debug("[STRICT_JSON_DIFF] Failed to parse event with strict parser: {}", rawEvent); } } this.eventSize = rawEvent.getBytes(StandardCharsets.UTF_8).length; this.emptyInjectionConfiguration = emptyInjectionConfiguration; this.injections = injections; this.response = new BatchItemResponse(); Optional.ofNullable(this.event.optJSONObject("metadata")) .map(e -> e.optString("eid", null)) .ifPresent(this.response::setEid); }

Target:
public BatchItem( final String rawEvent, final boolean strictParsing, final EmptyInjectionConfiguration emptyInjectionConfiguration, final InjectionConfiguration[] injections, final List<Integer> skipCharacters) { this.rawEvent = rawEvent; this.skipCharacters = skipCharacters; this.event = new JSONObject(rawEvent); if (strictParsing) { try { final JSONObject shadowEvent = StrictJsonParser.parseObject(rawEvent); final String shadowOutput = shadowEvent.toString(); final String usualOutput = this.event.toString(); if (!shadowOutput.equals(usualOutput)) { LOG.debug("[STRICT_JSON_DIFF] Strict parser produced different output for event: " + "Strict parser output: Old parser output: {}", rawEvent, shadowOutput, usualOutput); } } catch (final Exception e) { LOG.debug("[STRICT_JSON_DIFF] Failed to parse event with strict parser: Error message: {}", rawEvent, e.getMessage()); } } this.eventSize = rawEvent.getBytes(StandardCharsets.UTF_8).length; this.emptyInjectionConfiguration = emptyInjectionConfiguration; this.injections = injections; this.response = new BatchItemResponse(); Optional.ofNullable(this.event.optJSONObject("metadata")) .map(e -> e.optString("eid", null)) .ifPresent(this.response::setEid); }
Source:
private void handleCluster(HttpGetCommand command) { Node node = textCommandService.getNode(); NetworkingService ns = node.getNetworkingService(); EndpointManager cem = ns.getEndpointManager(CLIENT); AggregateEndpointManager aem = ns.getAggregateEndpointManager(); ClusterServiceImpl clusterService = node.getClusterService(); JsonArray membersArray = new JsonArray(); clusterService.getMembers() .stream() .map(m -> new JsonObject() .add("address", m.getAddress().toString()) .add("liteMember", m.isLiteMember()) .add("localMember", m.localMember()) .add("uuid", m.getUuid().toString()) .add("memberVersion", m.getVersion().toString())) .forEach(membersArray::add); JsonObject response = new JsonObject() .add("memberList", clusterService.getMemberListString()) .add("members", membersArray) .add("connectionCount", cem.getActiveConnections().size()) .add("allConnectionCount", aem.getActiveConnections().size()); prepareResponse(command, response); }

Target:
private void handleCluster(HttpGetCommand command) { Node node = textCommandService.getNode(); NetworkingService ns = node.getNetworkingService(); EndpointManager cem = ns.getEndpointManager(CLIENT); AggregateEndpointManager aem = ns.getAggregateEndpointManager(); ClusterServiceImpl clusterService = node.getClusterService(); JsonArray membersArray = new JsonArray(); clusterService.getMembers() .stream() .map(m -> new JsonObject() .add("address", m.getAddress().toString()) .add("liteMember", m.isLiteMember()) .add("localMember", m.localMember()) .add("uuid", m.getUuid().toString()) .add("memberVersion", m.getVersion().toString())) .forEach(membersArray::add); JsonObject response = new JsonObject() .add("members", membersArray) .add("connectionCount", cem.getActiveConnections().size()) .add("allConnectionCount", aem.getActiveConnections().size()); prepareResponse(command, response); }
Source:
public boolean canHandle(Object object) { return DanglingStereotypeApplicationMergeViewerItem.class.isInstance(object); }

Target:
public boolean canHandle(Object object) { return object instanceof DanglingStereotypeApplicationMergeViewerItem; }
Source:
public void initialize(int kfactor) throws JSONException, KeeperException, InterruptedException, ExecutionException { final long maxWaitTime = TimeUnit.MINUTES.toSeconds(60); long remainingWaitTime = maxWaitTime; final long retryInterval = 10; while(remainingWaitTime > 0) { VoltZK.createCatalogUpdateBlocker(m_messenger.getZK(), VoltZK.rejoinActiveBlocker); if (m_messenger.getZK().exists(VoltZK.uacActiveBlocker, false) == null) { return; } VoltZK.removeCatalogUpdateBlocker(m_messenger.getZK(), VoltZK.rejoinActiveBlocker, REJOINLOG); REJOINLOG.info(String.format("Rejoin node is waiting %d seconds for @UpdateApplicationCatalog to finish", retryInterval)); try { Thread.sleep(TimeUnit.SECONDS.toMillis(retryInterval)); } catch (InterruptedException ignoreIt) { } remainingWaitTime -= retryInterval; } VoltDB.crashLocalVoltDB("Rejoin node is timed out " + maxWaitTime + " seconds waiting for @UpdateApplicationCatalog, " + "please retry node rejoin later manually."); }

Target:
public void initialize(int kfactor) throws JSONException, KeeperException, InterruptedException, ExecutionException { final long maxWaitTime = TimeUnit.MINUTES.toSeconds(60); long remainingWaitTime = maxWaitTime; final long retryInterval = 10; while(remainingWaitTime > 0) { VoltZK.createCatalogUpdateBlocker(m_messenger.getZK(), VoltZK.rejoinActiveBlocker); if (m_messenger.getZK().exists(VoltZK.uacActiveBlocker, false) == null) { return; } VoltZK.removeCatalogUpdateBlocker(m_messenger.getZK(), VoltZK.rejoinActiveBlocker, REJOINLOG); REJOINLOG.info(String.format("Rejoin node will wait %d seconds for @UpdateApplicationCatalog to finish", retryInterval)); try { Thread.sleep(TimeUnit.SECONDS.toMillis(retryInterval)); } catch (InterruptedException ignoreIt) { } remainingWaitTime -= retryInterval; } VoltDB.crashLocalVoltDB("Rejoin node is timed out " + maxWaitTime + " seconds waiting for @UpdateApplicationCatalog, " + "please retry node rejoin later manually."); }
Source:
List<LogSegmentMetadata> getLogSegments() throws IOException; CompletableFuture<List<LogSegmentMetadata>> getLogSegmentsAsync(); void registerListener(LogSegmentListener listener) throws IOException; void unregisterListener(LogSegmentListener listener); CompletableFuture<AsyncLogWriter> openAsyncLogWriter(); default CompletableFuture<AsyncLogWriter> openAsyncLogWriter(LedgerMetadata ledgerMetadata) { throw new UnsupportedOperationException(); }

Target:
List<LogSegmentMetadata> getLogSegments() throws IOException; CompletableFuture<List<LogSegmentMetadata>> getLogSegmentsAsync(); void registerListener(LogSegmentListener listener) throws IOException; void unregisterListener(LogSegmentListener listener); CompletableFuture<AsyncLogWriter> openAsyncLogWriter(); default CompletableFuture<AsyncLogWriter> openAsyncLogWriter(LedgerMetadata ledgerMetadata) { return FutureUtils.exception(new UnsupportedOperationException()); }
Source:
public void one_awake_notification() { queueModeHelper.assertClientNotRegisterered(); queueModeHelper.client.start(); queueModeHelper.waitForRegistration(1); queueModeHelper.assertClientRegisterered(); queueModeHelper.ensureClientAwake(); queueModeHelper.ensureOneAwakeNotification(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.ensureOneAwakeNotification(); queueModeHelper.waitForAwakeTime(awaketime * 1010); queueModeHelper.ensureClientSleeping(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.ensureClientAwake(); queueModeHelper.resetAwakeLatch(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.ensureOneAwakeNotification(); }

Target:
public void one_awake_notification() { queueModeHelper.assertClientNotRegisterered(); queueModeHelper.client.start(); queueModeHelper.waitForRegistration(1); queueModeHelper.assertClientRegisterered(); queueModeHelper.ensureClientAwake(); queueModeHelper.ensureOneAwakeNotification(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.ensureOneAwakeNotification(); queueModeHelper.waitForAwakeTime(awaketime * 1010); queueModeHelper.ensureClientSleeping(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.ensureClientAwake(); queueModeHelper.resetAwakeLatch(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.ensureOneAwakeNotification(); }
Source:
private static boolean checkIfEmptyRow(List<String> rowData) { if (rowData.isEmpty()) { return true; } return rowData.stream() .anyMatch(r -> r.isEmpty()); }

Target:
private static boolean checkIfEmptyRow(List<String> rowData) { return rowData.stream() .allMatch(r -> r.isEmpty()); }
Source:
public final int getLifetime() { return lifetime; }

Target:
int getLifetime() { return lifetime; }
Source:
public void testConnectionsGetCycled() throws IOException{ TestCloudbigtableConnectionPool pool = new TestCloudbigtableConnectionPool(); Configuration config = new Configuration(); PoolEntry entry1 = pool.getConnection(config, "key"); PoolEntry entry2 = pool.getConnection(config, "key"); pool.returnConnection(entry1); pool.returnConnection(entry2); for (int i = 0; i < 100; i++) { PoolEntry newEntry = pool.getConnection(config, "key"); assertSame(i % 2 == 0 ? entry1 : entry2, newEntry); pool.returnConnection(newEntry); } }

Target:
public void testConnectionsGetCycled() throws IOException{ TestCloudbigtableConnectionPool pool = new TestCloudbigtableConnectionPool(); PoolEntry entry1 = pool.getConnection(config, "key"); PoolEntry entry2 = pool.getConnection(config, "key"); assertNotSame(entry1, entry2); pool.returnConnection(entry1); pool.returnConnection(entry2); for (int i = 0; i < 100; i++) { PoolEntry newEntry = pool.getConnection(config, "key"); assertSame(i % 2 == 0 ? entry1 : entry2, newEntry); pool.returnConnection(newEntry); } }
Source:
static ResourceKey of(final String namespace, final String value) { return builder().namespace(namespace).value(value).build(); }

Target:
static ResourceKey of(final String namespace, final String value) { return ResourceKey.builder().namespace(namespace).value(value).build(); }
Source:
public void storeContentToBinaryStorage(Document currentDocument, EntityKey entityKey, OptionsService optionService, Tuple tuple) { Class entityClass = TableEntityTypeMappingInfo.getEntityClass( entityKey.getTable() ); if ( currentDocument == null ) { return; } for ( String fieldName : currentDocument.keySet() ) { if ( fieldName.equals( "$set" ) ) { Document queryFields = (Document) currentDocument.get( fieldName ); for ( String queryField : queryFields.keySet() ) { storeContentFromFieldToBinaryStorage( queryFields, entityClass, queryField, optionService, tuple ); } } else { storeContentFromFieldToBinaryStorage( currentDocument, entityClass, fieldName, optionService, tuple ); } } }

Target:
public void storeContentToBinaryStorage(Document currentDocument, EntityKey entityKey, OptionsService optionService, Tuple tuple) { Class entityClass = provider.getTableEntityTypeMapping().get( entityKey.getTable() ); if ( currentDocument == null ) { return; } for ( String fieldName : currentDocument.keySet() ) { if ( fieldName.equals( "$set" ) ) { Document queryFields = (Document) currentDocument.get( fieldName ); for ( String queryField : queryFields.keySet() ) { storeContentFromFieldToBinaryStorage( queryFields, entityClass, queryField, optionService, tuple ); } } else { storeContentFromFieldToBinaryStorage( currentDocument, entityClass, fieldName, optionService, tuple ); } } }
Source:
protected void configure(HttpSecurity http) throws Exception { HeadersConfigurer<HttpSecurity> config = http.antMatcher("**").headers().frameOptions().sameOrigin(); config.and().exceptionHandling().accessDeniedHandler(accessDeniedHandler()) .and().formLogin().loginPage("/login").permitAll().defaultSuccessUrl("/auth/welcome") .successHandler(authSuccessHandler).failureUrl("/loginfailed").and().authorizeRequests() .antMatchers("/signin/**", "/connect/**", "/signup/**", "/user/register/**", "/resources/**", "/register*", "/login*", "/logout*", "/createaccount*", "/sites/**", "/public/**", "/search/**", "/home/**", "/sociallogin*", "/forbidden") .permitAll() .antMatchers("/users/**", "/admin/**").hasRole("QUADRIGA_USER_ADMIN") .antMatchers("/", "/auth/welcome**", "/auth/home**", "/auth/about**", "/auth/profile/**", "/rest/**", "/forbidden") .hasAnyRole("QUADRIGA_USER_ADMIN", "QUADRIGA_USER_STANDARD", "QUADRIGA_USER_COLLABORATOR") .antMatchers("/auth/workbench/**", "/auth/rest/**", "/auth/conceptcollections/**", "/auth/conceptdetails/**", "/auth/transformation/**", "/auth/searchitems/**", "/auth/dictionaries/**", "/auth/editing/**", "/auth/networks/**") .hasAnyRole("QUADRIGA_USER_STANDARD", "QUADRIGA_USER_COLLABORATOR") .antMatchers("/users/**", "/admin/**", "/auth/users/**", "/checks/**") .hasRole("QUADRIGA_USER_ADMIN").anyRequest() .hasAnyRole("QUADRIGA_USER_ADMIN", "QUADRIGA_USER_STANDARD", "QUADRIGA_USER_COLLABORATOR") .antMatchers("/**").denyAll() .and().apply(new SpringSocialConfigurer()); }

Target:
protected void configure(HttpSecurity http) throws Exception { HeadersConfigurer<HttpSecurity> config = http.antMatcher("**").headers().frameOptions().sameOrigin(); config.and().exceptionHandling().accessDeniedHandler(accessDeniedHandler()) .and().formLogin().loginPage("/login").permitAll().defaultSuccessUrl("/auth/welcome") .successHandler(authSuccessHandler).failureUrl("/loginfailed").and().authorizeRequests() .antMatchers("/signin/**", "/connect/**", "/signup/**", "/user/register/**", "/resources/**", "/register*", "/login*", "/logout*", "/createaccount*", "/sites/**", "/public/**", "/search/**", "/home/**", "/sociallogin*", "/forbidden") .permitAll() .antMatchers("/users/**", "/admin/**").hasRole("QUADRIGA_USER_ADMIN") .antMatchers("/", "/auth/welcome**", "/auth/home**", "/auth/about**", "/auth/profile/**", "/rest/**") .hasAnyRole("QUADRIGA_USER_ADMIN", "QUADRIGA_USER_STANDARD", "QUADRIGA_USER_COLLABORATOR") .antMatchers("/auth/workbench/**", "/auth/rest/**", "/auth/conceptcollections/**", "/auth/conceptdetails/**", "/auth/transformation/**", "/auth/searchitems/**", "/auth/dictionaries/**", "/auth/editing/**", "/auth/networks/**") .hasAnyRole("QUADRIGA_USER_STANDARD", "QUADRIGA_USER_COLLABORATOR") .antMatchers("/users/**", "/admin/**", "/auth/users/**", "/checks/**") .hasRole("QUADRIGA_USER_ADMIN").anyRequest() .hasAnyRole("QUADRIGA_USER_ADMIN", "QUADRIGA_USER_STANDARD", "QUADRIGA_USER_COLLABORATOR") .antMatchers("/**").denyAll() .and().apply(new SpringSocialConfigurer()); }
Source:
public String toString() { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < this.size; i++) { buffer.append(CharOperation.toString(this.elements[i])).append("\n"); } return buffer.toString(); }

Target:
public String toString() { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < this.size; i++) { buffer.append(CharOperation.toString(this.elements[i])).append("\n"); } return buffer.toString(); }
Source:
public void processEvent(Event event) { if (!event.getDetails().getType().equalsIgnoreCase(DockerEvent.TYPE)) { return; } DockerEvent dockerEvent = objectMapper.convertValue(event, DockerEvent.class); Observable.just(dockerEvent) .doOnNext(this::onEchoResponse) .subscribe(triggerEachMatchFrom(pipelineCache.getPipelines())); }

Target:
public void processEvent(Event event) { super.validateEvent(event); if (!event.getDetails().getType().equalsIgnoreCase(DockerEvent.TYPE)) { return; } DockerEvent dockerEvent = objectMapper.convertValue(event, DockerEvent.class); Observable.just(dockerEvent) .doOnNext(this::onEchoResponse) .subscribe(triggerEachMatchFrom(pipelineCache.getPipelines())); }
Source:
public void testForwardTaskWithMsgEvents() { Task task = new TaskFluent().setName("This is my task name") .addPotentialGroup("Knights Templer") .setAdminUser("Administrator") .getTask(); taskService.addTask(task, new HashMap<String, Object>()); long taskId = task.getId(); assertAuditTaskInfoGroup("Knights Templer", "Ready", taskId); taskService.forward(taskId, "Administrator", "Jon Snow"); List<TaskEvent> taskEvents = taskAuditService.getAllTaskEvents(taskId, new QueryFilter()); Assertions.assertThat(taskEvents).hasSize(2); Assertions.assertThat(taskEvents.get(0).getType()).isEqualTo(TaskEventType.ADDED); Assertions.assertThat(taskEvents.get(0).getUserId()).isNull(); Assertions.assertThat(taskEvents.get(1).getType()).isEqualTo(TaskEventType.FORWARDED); Assertions.assertThat(taskEvents.get(1).getUserId()).isEqualTo("Administrator"); assertNotNull(taskEvents.get(1).getMessage()); Assertions.assertThat(taskEvents.get(1).getMessage()).contains("Jon Snow"); }

Target:
public void testForwardTaskWithMsgEvents() { Task task = new TaskFluent().setName("This is my task name") .addPotentialGroup("Knights Templer") .setAdminUser("Administrator") .addPotentialUser("Administrator") .getTask(); taskService.addTask(task, new HashMap<String, Object>()); long taskId = task.getId(); assertAuditTaskInfoGroup("Knights Templer", "Ready", taskId); taskService.claim(taskId, "Administrator"); assertAuditTaskInfo("Administrator", "Reserved", taskId); taskService.forward(taskId, "Administrator", "Darth Vader"); List<TaskEvent> taskEvents = taskAuditService.getAllTaskEvents(taskId, new QueryFilter()); Assertions.assertThat(taskEvents).hasSize(3); Assertions.assertThat(taskEvents.get(0).getType()).isEqualTo(TaskEventType.ADDED); Assertions.assertThat(taskEvents.get(0).getUserId()).isNull(); Assertions.assertThat(taskEvents.get(1).getType()).isEqualTo(TaskEventType.CLAIMED); Assertions.assertThat(taskEvents.get(1).getUserId()).isEqualTo("Administrator"); Assertions.assertThat(taskEvents.get(2).getType()).isEqualTo(TaskEventType.FORWARDED); Assertions.assertThat(taskEvents.get(2).getUserId()).isEqualTo("Administrator"); Assertions.assertThat(taskEvents.get(2).getMessage()).isNotNull(); Assertions.assertThat(taskEvents.get(2).getMessage()).contains("Darth Vader"); }
Source:
public int getMaxExposureCompensation() { return 10; }

Target:
public int getMaxExposureCompensation() { return 6; }
Source:
private void setConnector(AbstractRepositoryConnector connector) { this.connector = connector; }

Target:
public void setConnector(AbstractRepositoryConnector connector) { this.connector = connector; }
Source:
public void executeLeaderTasksAfterBecomingLeader() { leadershipObserver.executeWhenGainedLeadership(leaderTask); gainLeadership(); verify(leaderTask, times(1)).run(); }

Target:
public void executeLeaderTasksAfterBecomingLeader() { registerFollowerAndLeaderTasks(); gainLeadership(); waitForTasksToFinish(); verify(leaderTask).run(); }
Source:
public boolean hasAdminOrViewPermissions(final CaseInsensitiveString userName, List<Role> memberRoles) { return isUserAnAdmin(userName, memberRoles) || viewConfig.isAdmin(new AdminUser(userName), memberRoles); }

Target:
public boolean hasAdminOrViewPermissions(final CaseInsensitiveString userName, List<Role> memberRoles) { return isUserAnAdmin(userName, memberRoles) || isViewUser(userName, memberRoles); }
Source:
public boolean producesLint() { if (getProject().hasProperty("CONTAINS_LINT_REGISTRY")) { return true; } Jar jarTask = (Jar) getProject().getTasks().findByName(JavaPlugin.JAR_TASK_NAME); if (jarTask != null && (jarTask.getManifest().getAttributes().containsKey("Lint-Registry") || jarTask.getManifest().getAttributes().containsKey("Lint-Registry-v2"))) { return true; } if (getMainJavaResourceDirs().stream() .anyMatch(resourceDir -> new File(resourceDir, "META-INF" + File.separator + "services" + File.separator + "com.android.tools.lint.client.api.IssueRegistry") .exists())) { return true; } else { return false; } }

Target:
public boolean producesLint() { if (getProject().hasProperty("CONTAINS_LINT_REGISTRY")) { return true; } Jar jarTask = (Jar) getProject().getTasks().findByName(JavaPlugin.JAR_TASK_NAME); if (jarTask != null && (jarTask.getManifest().getAttributes().containsKey("Lint-Registry") || jarTask.getManifest().getAttributes().containsKey("Lint-Registry-v2"))) { return true; } return getMainJavaResourceDirs().stream() .anyMatch(resourceDir -> resourceDir.toPath() .resolve("META-INF") .resolve("services") .resolve("com.android.tools.lint.client.api.IssueRegistry") .toFile() .exists()); }
Source:
public boolean canContinue(CruiseConfig cruiseConfig) { if (goConfigService.isAdministrator(username.getUsername().toString())) { return true; } result.unauthorized("Unauthorized to operate on agent", "Unauthorized to operate on agent", HealthStateType.general(HealthStateScope.GLOBAL)); return false; }

Target:
public boolean canContinue(CruiseConfig cruiseConfig) { if (goConfigService.isAdministrator(username.getUsername())) { return true; } result.unauthorized(LocalizedMessage.string("UNAUTHORIZED_TO_OPERATE_AGENTS"), HealthStateType.unauthorised()); return false; }
Source:
Pair<Vector[], Vector> parse() { final List<double[]> dataX = new LinkedList<>(); final List<Double> dataY = new LinkedList<>(); for (final Pair<LongWritable, Text> keyValue : dataSet) { final String line = keyValue.getSecond().toString().trim(); if (line.startsWith("#") || line.length() == 0) { continue; } final String[] split = line.split("\\s+"); final double[] data = new double[numFeatures]; for (int index = 0; index < numFeatures; index++) { data[index] = Double.parseDouble(split[index]); } dataX.add(data); dataY.add(Double.parseDouble(split[numFeatures])); } final double[][] arrayX = new double[dataX.size()][]; final double[][] transposedArrayX = transpose(dataX.toArray(arrayX)); final Vector[] vecX = new Vector[transposedArrayX.length]; for (int arrayIndex = 0; arrayIndex < transposedArrayX.length; arrayIndex++) { vecX[arrayIndex] = vectorFactory.newDenseVector(transposedArrayX[arrayIndex]); } final double[] arrayY = new double[dataY.size()]; int arrayIndex = 0; for (final double y : dataY) { arrayY[arrayIndex++] = y; } final Vector vecY = vectorFactory.newDenseVector(arrayY); return new Pair<>(vecX, vecY); }

Target:
Pair<Vector[], Vector> parse() { final List<Double>[] dataX = (List<Double>[]) Array.newInstance(LinkedList.class, numFeatures); for (int index = 0; index < numFeatures; index++) { dataX[index] = new LinkedList<>(); } final List<Double> dataY = new LinkedList<>(); for (final Pair<LongWritable, Text> keyValue : dataSet) { final String line = keyValue.getSecond().toString().trim(); if (line.startsWith("#") || line.length() == 0) { continue; } final String[] split = line.split("\\s+"); for (int index = 0; index < numFeatures; index++) { dataX[index].add(Double.parseDouble(split[index])); } dataY.add(Double.parseDouble(split[numFeatures])); } final Vector[] vecX = new Vector[numFeatures]; for (int index = 0; index < numFeatures; index++) { vecX[index] = vectorFactory.createDense(Doubles.toArray(dataX[index])); } final Vector vecY = vectorFactory.createDense(Doubles.toArray(dataY)); return new Pair<>(vecX, vecY); }
Source:
public void testCanRetrieveUserWorkspaceWithTrashedDomain() throws InterruptedException { try (CloseableCoreSession userSession = coreFeature.openCoreSession("toto")) { DocumentModel uw = uwm.getCurrentUserPersonalWorkspace(userSession); assertNotNull(uw); } List<DocumentModel> docs = session.getChildren(session.getRootDocument().getRef()) .stream() .collect(Collectors.toList()); TrashService trashService = Framework.getService(TrashService.class); trashService.trashDocuments(docs); bulkService.await(Duration.ofSeconds(30)); session.save(); try (CloseableCoreSession userSession = coreFeature.openCoreSession("toto")) { DocumentModel uw = uwm.getCurrentUserPersonalWorkspace(userSession); assertNull(uw); } trashService.untrashDocuments(docs); bulkService.await(Duration.ofSeconds(30)); session.save(); try (CloseableCoreSession userSession = coreFeature.openCoreSession("toto")) { DocumentModel uw = uwm.getCurrentUserPersonalWorkspace(userSession); assertNotNull(uw); } }

Target:
public void testCanRetrieveUserWorkspaceWithTrashedDomain() { try (CloseableCoreSession userSession = coreFeature.openCoreSession("toto")) { DocumentModel uw = uwm.getCurrentUserPersonalWorkspace(userSession); assertNotNull(uw); } List<DocumentModel> docs = session.getChildren(session.getRootDocument().getRef()) .stream() .collect(Collectors.toList()); TrashService trashService = Framework.getService(TrashService.class); trashService.trashDocuments(docs); coreFeature.waitForAsyncCompletion(); session.save(); try (CloseableCoreSession userSession = coreFeature.openCoreSession("toto")) { DocumentModel uw = uwm.getCurrentUserPersonalWorkspace(userSession); assertNull(uw); } trashService.untrashDocuments(docs); coreFeature.waitForAsyncCompletion(); session.save(); try (CloseableCoreSession userSession = coreFeature.openCoreSession("toto")) { DocumentModel uw = uwm.getCurrentUserPersonalWorkspace(userSession); assertNotNull(uw); } }
Source:
public void resource_loading() { Context context = (Context) RuntimeEnvironment.application; assertEquals(context.getResources().getString(R.string.app_name), "Common"); assertEquals(context.getResources().getColor( com.uber.okbuck.example.parcelable.R.color.fooColor), 0xcccccc); }

Target:
public void resource_loading() { Context context = RuntimeEnvironment.application; int actualColor = Color.parseColor("#cccccc"); assertEquals(context.getResources().getString(R.string.app_name), "Common"); assertEquals(context.getResources().getColor(R.color.fooColor), actualColor); assertEquals(Person.getColor(context), actualColor); }
Source:
private DockstoreTool.RegistryEnum getRegistryEnum(String registry) { for (DockstoreTool.RegistryEnum reg : DockstoreTool.RegistryEnum.values()) { if (registry.equals(reg.name())) { return reg; } } return null; }

Target:
private Optional<DockstoreTool.RegistryEnum> getRegistryEnum(String registry) { for (DockstoreTool.RegistryEnum reg : DockstoreTool.RegistryEnum.values()) { if (registry.equals(reg.name())) { return Optional.of(reg); } } return Optional.empty(); }
Source:
public void translateByteRangeReturnsCorrectRange() throws Exception { ByteRangeConversion byteRange1 = AesCtrCipherDetails.INSTANCE_128_BIT.translateByteRange(5, 10); Assert.assertEquals(byteRange1.getCiphertextStartPositionInclusive(), 0); Assert.assertEquals(byteRange1.getCiphertextEndPositionInclusive(), 15); Assert.assertEquals(byteRange1.getPlaintextBytesToSkipInitially(), 5); Assert.assertEquals(byteRange1.getLengthOfPlaintextIncludingSkipBytes(), 11); ByteRangeConversion byteRange2 = AesCtrCipherDetails.INSTANCE_128_BIT.translateByteRange(5, 22); Assert.assertEquals(byteRange2.getCiphertextStartPositionInclusive(), 0); Assert.assertEquals(byteRange2.getCiphertextEndPositionInclusive(), 31); Assert.assertEquals(byteRange2.getPlaintextBytesToSkipInitially(), 5); Assert.assertEquals(byteRange2.getLengthOfPlaintextIncludingSkipBytes(), 23); ByteRangeConversion byteRange3 = AesCtrCipherDetails.INSTANCE_128_BIT.translateByteRange(32, 35); Assert.assertEquals(byteRange3.getCiphertextStartPositionInclusive(), 32); Assert.assertEquals(byteRange3.getCiphertextEndPositionInclusive(), 47); Assert.assertEquals(byteRange3.getPlaintextBytesToSkipInitially(), 0); }

Target:
public void translateByteRangeReturnsCorrectRange() throws Exception { ByteRangeConversion byteRange1 = AesCtrCipherDetails.INSTANCE_128_BIT.translateByteRange(5, 10); Assert.assertEquals(byteRange1.getCiphertextStartPositionInclusive(), 0); Assert.assertEquals(byteRange1.getCiphertextEndPositionInclusive(), 15); Assert.assertEquals(byteRange1.getPlaintextBytesToSkipInitially(), 5); Assert.assertEquals(byteRange1.getLengthOfPlaintextIncludingSkipBytes(), 11); ByteRangeConversion byteRange2 = AesCtrCipherDetails.INSTANCE_128_BIT.translateByteRange(5, 22); Assert.assertEquals(byteRange2.getCiphertextStartPositionInclusive(), 0); Assert.assertEquals(byteRange2.getCiphertextEndPositionInclusive(), 31); Assert.assertEquals(byteRange2.getPlaintextBytesToSkipInitially(), 5); Assert.assertEquals(byteRange2.getLengthOfPlaintextIncludingSkipBytes(), 23); ByteRangeConversion byteRange3 = AesCtrCipherDetails.INSTANCE_128_BIT.translateByteRange(32, 35); Assert.assertEquals(byteRange3.getCiphertextStartPositionInclusive(), 32); Assert.assertEquals(byteRange3.getCiphertextEndPositionInclusive(), 47); Assert.assertEquals(byteRange3.getPlaintextBytesToSkipInitially(), 0); Assert.assertEquals(byteRange3.getLengthOfPlaintextIncludingSkipBytes(), 4); }
Source:
private void populateNextRate() { if (source.hasNext()) { moveToNextDatapoint(); double difference = getValueDifference(); if (options.isCounter() && difference < 0) { while(source.hasNext()) { moveToNextDatapoint(); difference = getValueDifference(); if (difference > 0) { break; } } if (!source.hasNext()) { markEndOfSeries(); return; } } final double time_delta_secs = getTimeDeltaSecs(); next_rate.reset(next_data.timestamp(), (difference / time_delta_secs)); } else { markEndOfSeries(); } }

Target:
private void populateNextRate() { if (source.hasNext()) { moveToNextDatapoint(); double difference = getValueDifference(); if (options.isCounter() && difference < 0) { while(source.hasNext()) { moveToNextDatapoint(); difference = getValueDifference(); if (difference >= 0) { break; } } if (!source.hasNext()) { markEndOfSeries(); return; } } final double time_delta_secs = getTimeDeltaSecs(); next_rate.reset(next_data.timestamp(), (difference / time_delta_secs)); } else { markEndOfSeries(); } }
Source:
public void withForceFailsIn31Cluster() { validator = spy(new GlusterVolumeValidator()); ValidationResult result = validator.isForceCreateVolumeAllowed(Version.v3_1, true); assertEquals (new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_ADD_BRICK_FORCE_NOT_SUPPORTED), result); }

Target:
public void withForceFailsIn31Cluster() { validator = spy(new GlusterVolumeValidator()); ValidationResult result = validator.isForceCreateVolumeAllowed(Version.v3_1, true); assertThat(result, failsWith(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_ADD_BRICK_FORCE_NOT_SUPPORTED)); }
Source:
public ApplicationServiceImpl(List<BundleStateService> bundleStateServices) { this.bundleStateServices = bundleStateServices; ignoredApplicationNames = new HashSet<>(); BundleContext context = getContext(); if (context == null) { LOGGER.warn("There is no context for this service"); return; } ServiceReference<FeaturesService> featuresServiceRef = context.getServiceReference(FeaturesService.class); this.featuresService = context.getService(featuresServiceRef); try { if (context.getServiceReference("org.apache.karaf.features.BootFinished") == null) { context.addServiceListener(this, "(objectclass=org.apache.karaf.features.BootFinished)"); } } catch (InvalidSyntaxException e) { LOGGER.warn("Failed to create service listener filter", e); } }

Target:
public ApplicationServiceImpl(List<BundleStateService> bundleStateServices) { this.bundleStateServices = bundleStateServices; ignoredApplicationNames = new HashSet<>(); BundleContext context = getContext(); ServiceReference<FeaturesService> featuresServiceRef = context.getServiceReference(FeaturesService.class); this.featuresService = context.getService(featuresServiceRef); try { if (context.getServiceReference("org.apache.karaf.features.BootFinished") == null) { context.addServiceListener(this, "(objectclass=org.apache.karaf.features.BootFinished)"); } } catch (InvalidSyntaxException e) { LOGGER.warn("Failed to create service listener filter", e); } }