auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static boolean equals(final RawText a, final int ai, final RawText b, final int bi) { if (a.hashes.get(ai) != b.hashes.get(bi)) return false; int as = a.lines.get(ai); int bs = b.lines.get(bi); int ae = a.lines.get(ai + 1); int be = b.lines.get(bi + 1); as = trimLeadingWhitespace(a.content, as, ae); bs = trimLeadingWhitespace(b.content, bs, be); ae = trimTrailingWhitespace(a.content, as, ae); be = trimTrailingWhitespace(b.content, bs, be); while (as < ae && bs < be) { byte ac = a.content[as]; byte bc = b.content[bs]; while (as < ae - 1 && isWhitespace(ac)) { as++; ac = a.content[as]; } while (bs < be - 1 && isWhitespace(bc)) { bs++; bc = b.content[bs]; } if (ac != bc) return false; as++; bs++; } return true; }

Target:
private static boolean equals(final RawText a, final int ai, final RawText b, final int bi) { if (a.hashes.get(ai) != b.hashes.get(bi)) return false; int as = a.lines.get(ai); int bs = b.lines.get(bi); int ae = a.lines.get(ai + 1); int be = b.lines.get(bi + 1); as = trimLeadingWhitespace(a.content, as, ae); bs = trimLeadingWhitespace(b.content, bs, be); ae = trimTrailingWhitespace(a.content, as, ae); be = trimTrailingWhitespace(b.content, bs, be); while (as < ae && bs < be) { byte ac = a.content[as]; byte bc = b.content[bs]; while (as < ae - 1 && isWhitespace(ac)) { as++; ac = a.content[as]; } while (bs < be - 1 && isWhitespace(bc)) { bs++; bc = b.content[bs]; } if (ac != bc) return false; as++; bs++; } return ae - as == be - bs; }
Source:
public boolean nameMatchesAny(List<String> names) { for (String name : names) { if (getName().equals(name)) { return true; } } return false; }

Target:
public boolean nameMatchesAny(List<String> names) { return names.contains(getName()); }
Source:
public static boolean findPatternInFile(final File file, final String pattern) { Pattern regexp = Pattern.compile(pattern); Matcher matcher = regexp.matcher(""); try { for (String line : Files.readAllLines(file.toPath())) { matcher.reset(line); if (matcher.find()) { return true; } } } catch (FileNotFoundException e) { throw new IllegalArgumentException(e); } catch (IOException e) { throw new RuntimeException(e); } return false; }

Target:
public static boolean findPatternInFile(final File file, final String pattern) { Pattern regexp = Pattern.compile(pattern); Matcher matcher = regexp.matcher(""); try { for (String line : Files.readAllLines(file.toPath(), StandardCharsets.UTF_8)) { matcher.reset(line); if (matcher.find()) { return true; } } } catch (FileNotFoundException e) { throw new IllegalArgumentException(e); } catch (IOException e) { throw new RuntimeException(e); } return false; }
Source:
private synchronized void releaseExportBytes(long releaseSeqNo, int tuplesSent) throws IOException { if (!m_committedBuffers.isEmpty() && releaseSeqNo < m_committedBuffers.peek().startSequenceNumber()) { tuplesSent = 0; } if (m_lastReleasedSeqNo == releaseSeqNo) { tuplesSent = 0; } long lastSeqNo = 0; while (!m_committedBuffers.isEmpty() && releaseSeqNo >= m_committedBuffers.peek().startSequenceNumber()) { StreamBlock sb = m_committedBuffers.peek(); if (releaseSeqNo >= sb.startSequenceNumber() + sb.rowCount() - 1) { m_committedBuffers.pop(); try { lastSeqNo = sb.startSequenceNumber() + sb.rowCount() - 1; } finally { sb.discard(); } } else if (releaseSeqNo >= sb.startSequenceNumber()) { sb.releaseTo(releaseSeqNo); lastSeqNo = releaseSeqNo; break; } } m_lastReleasedSeqNo = releaseSeqNo; m_gapTracker.truncate(releaseSeqNo); if (exportLog.isDebugEnabled()) { exportLog.debug("Truncate tracker via ack to:" + releaseSeqNo + " now is " + m_gapTracker.toString()); } if (m_committedBuffers.isEmpty()) { lastSeqNo = releaseSeqNo; } m_firstUnpolledSeqNo = Math.max(m_firstUnpolledSeqNo, lastSeqNo + 1); int pendingCount = m_tuplesPending.get(); m_tuplesPending.set(pendingCount - tuplesSent); return; }

Target:
private synchronized void releaseExportBytes(long releaseSeqNo, int tuplesSent) throws IOException { if (!m_committedBuffers.isEmpty() && releaseSeqNo < m_committedBuffers.peek().startSequenceNumber()) { tuplesSent = 0; } if (m_lastReleasedSeqNo == releaseSeqNo) { tuplesSent = 0; } long lastSeqNo = 0; while (!m_committedBuffers.isEmpty() && releaseSeqNo >= m_committedBuffers.peek().startSequenceNumber()) { StreamBlock sb = m_committedBuffers.peek(); if (releaseSeqNo >= sb.lastSequenceNumber()) { m_committedBuffers.pop(); try { lastSeqNo = sb.lastSequenceNumber(); } finally { sb.discard(); } } else if (releaseSeqNo >= sb.startSequenceNumber()) { sb.releaseTo(releaseSeqNo); lastSeqNo = releaseSeqNo; break; } } m_lastReleasedSeqNo = releaseSeqNo; if (m_status == StreamStatus.BLOCKED && m_gapTracker.getFirstGap() != null && releaseSeqNo > m_gapTracker.getFirstGap().getSecond()) { setStatus(StreamStatus.ACTIVE); } m_gapTracker.truncate(releaseSeqNo); if (exportLog.isDebugEnabled()) { exportLog.debug("Truncate tracker via ack to:" + releaseSeqNo + " now is " + m_gapTracker.toString()); } if (m_committedBuffers.isEmpty()) { lastSeqNo = releaseSeqNo; } m_firstUnpolledSeqNo = Math.max(m_firstUnpolledSeqNo, lastSeqNo + 1); int pendingCount = m_tuplesPending.get(); m_tuplesPending.set(pendingCount - tuplesSent); return; }
Source:
private static NameSubstitutionStrategy getNameSubstitutionStrategy(GraphConfiguration config) { String className = config.getString(GraphConfiguration.SEARCH_INDEX_PROP_PREFIX + "." + CONFIG_NAME_SUBSTITUTION_STRATEGY_CLASS_NAME, DEFAULT_NAME_SUBSTITUTION_STRATEGY.getName()); NameSubstitutionStrategy strategy = ConfigurationUtils.createProvider(className, config); if (strategy instanceof SimpleNameSubstitutionStrategy) { ((SimpleNameSubstitutionStrategy) strategy).setSubstitutionList(SimpleSubstitutionUtils.getSubstitutionList(config.getConfig())); } return strategy; }

Target:
private static NameSubstitutionStrategy getNameSubstitutionStrategy(GraphConfiguration config) { String className = config.getString(GraphConfiguration.SEARCH_INDEX_PROP_PREFIX + "." + CONFIG_NAME_SUBSTITUTION_STRATEGY_CLASS_NAME, DEFAULT_NAME_SUBSTITUTION_STRATEGY.getName()); NameSubstitutionStrategy strategy = ConfigurationUtils.createProvider(className, config); strategy.setup(config.getConfig()); return strategy; }
Source:
public String getProbeString() { if (fAddress != null) { return fAddress; } else if (fSymbol != null && fOffset != null) { return fSymbol + "+" + fOffset; } return null; }

Target:
public String getProbeString() { if (fAddress != null) { return fAddress; } else if (fSymbol != null && fOffset != null) { return new StringBuffer(fSymbol).append('+').append(fOffset).toString(); } return null; }
Source:
public void replCommitTxn(CommitTxnRequest rqst) throws LockException { try { if (rqst.isSetReplLastIdInfo()) { lockMgr.clearLocalLockRecords(); stopHeartbeat(); } getMS().replCommitTxn(rqst); } catch (NoSuchTxnException e) { LOG.error("Metastore could not find " + JavaUtils.txnIdToString(rqst.getTxnid())); throw new LockException(e, ErrorMsg.TXN_NO_SUCH_TRANSACTION, JavaUtils.txnIdToString(rqst.getTxnid())); } catch (TxnAbortedException e) { LockException le = new LockException(e, ErrorMsg.TXN_ABORTED, JavaUtils.txnIdToString(rqst.getTxnid()), e.getMessage()); LOG.error(le.getMessage()); throw le; } catch (TException e) { throw new LockException(ErrorMsg.METASTORE_COMMUNICATION_FAILED.getMsg(), e); } finally { if (rqst.isSetReplLastIdInfo()) { txnId = 0; stmtId = -1; numStatements = 0; tableWriteIds.clear(); } } }

Target:
public void replCommitTxn(CommitTxnRequest rqst) throws LockException { try { if (rqst.isSetReplLastIdInfo()) { if (!isTxnOpen()) { throw new RuntimeException("Attempt to commit before opening a transaction"); } clearLocksAndHB(); } getMS().replCommitTxn(rqst); } catch (NoSuchTxnException e) { LOG.error("Metastore could not find " + JavaUtils.txnIdToString(rqst.getTxnid())); throw new LockException(e, ErrorMsg.TXN_NO_SUCH_TRANSACTION, JavaUtils.txnIdToString(rqst.getTxnid())); } catch (TxnAbortedException e) { LockException le = new LockException(e, ErrorMsg.TXN_ABORTED, JavaUtils.txnIdToString(rqst.getTxnid()), e.getMessage()); LOG.error(le.getMessage()); throw le; } catch (TException e) { throw new LockException(ErrorMsg.METASTORE_COMMUNICATION_FAILED.getMsg(), e); } finally { if (rqst.isSetReplLastIdInfo()) { resetTxnInfo(); } } }
Source:
public void enterUnionStyleEnum(SwiftParser.UnionStyleEnumContext ctx) { listenerHelper.verifyUnionStyleEnumOpenBraceStyle(ctx); }

Target:
public void enterUnionStyleEnum(SwiftParser.UnionStyleEnumContext ctx) { listenerHelper.verifyEnumOpenBraceStyle(ctx); }
Source:
protected Void doInBackground() throws Exception { try { List<FileSearch.AttributeType> attrsForGroupingAndSorting = new ArrayList<>(); attrsForGroupingAndSorting.add(groupingAttr); attrsForGroupingAndSorting.addAll(fileSort.getRequiredAttributes()); SearchResults results = FileSearch.runFileSearchDebug(filters, groupingAttr, groupSortAlgorithm, fileSort, Case.getCurrentCase().getSleuthkitCase(), centralRepoDb); DiscoveryEvents.getDiscoveryEventBus().post(new DiscoveryEvents.SearchCompleteEvent(results)); } catch (FileSearchException ex) { logger.log(Level.SEVERE, "Error running file search test", ex); } return null; }

Target:
protected Void doInBackground() throws Exception { try { SearchResults results = FileSearch.runFileSearchDebug(filters, groupingAttr, groupSortAlgorithm, fileSort, Case.getCurrentCase().getSleuthkitCase(), centralRepoDb); DiscoveryEvents.getDiscoveryEventBus().post(new DiscoveryEvents.SearchCompleteEvent(results)); } catch (FileSearchException ex) { logger.log(Level.SEVERE, "Error running file search test", ex); } return null; }
Source:
public void onNext(T element) { env.debug(this + "::onNext(" + element + ")"); if (subscription.isCompleted()) { } else { env.flop("Subscriber::onNext(" + element + ") called before Subscriber::onSubscribe"); } }

Target:
public void onNext(T element) { env.debug(String.format("%s::onNext(%s)", this, element)); if (!subscription.isCompleted()) { env.flop(String.format("Subscriber::onNext(%s) called before Subscriber::onSubscribe", element)); } }
Source:
public void setProjectKey(String projectKey) { this.projectKey = projectKey; }

Target:
public void setProjectKey(String projectKey) { this.projectKey = StringUtils.trimToNull(projectKey); }
Source:
public StringListType(String... rows) { this(Arrays.asList(rows)); }

Target:
public StringListType(String... rows) { typeDetails = Arrays.asList(rows); }
Source:
protected boolean skipLoadForWriteCommand(WriteCommand cmd, Object key, InvocationContext ctx) { if (transactional) { if (!ctx.isOriginLocal() && cmd.loadType() != VisitableCommand.LoadType.OWNER) { return true; } } else { switch (cmd.loadType()) { case DONT_LOAD: return true; case PRIMARY: if (cmd.hasFlag(Flag.CACHE_MODE_LOCAL)) { return cmd.hasFlag(Flag.SKIP_CACHE_LOAD); } if (!cdl.localNodeIsPrimaryOwner(key)) { if (trace) { log.tracef("Skip load for command %s. This node is not the primary owner of %s", cmd, toStr(key)); } return true; } break; case OWNER: if (cmd.hasFlag(Flag.CACHE_MODE_LOCAL)) { return cmd.hasFlag(Flag.SKIP_CACHE_LOAD); } List<Address> owners = cdl.getOwners(key); int index = owners == null ? 0 : owners.indexOf(cdl.getAddress()); if (index != 0 && (index < 0 || ctx.isOriginLocal())) { if (trace) { log.tracef("Skip load for command %s. This node is not the primary owner or backup (and not origin) of %s", cmd, toStr(key)); } return true; } break; } } return super.skipLoadForWriteCommand(cmd, key, ctx); }

Target:
protected boolean skipLoadForWriteCommand(WriteCommand cmd, Object key, InvocationContext ctx) { if (transactional) { if (!ctx.isOriginLocal() && cmd.loadType() != VisitableCommand.LoadType.OWNER) { return true; } } else { switch (cmd.loadType()) { case DONT_LOAD: return true; case PRIMARY: if (cmd.hasFlag(Flag.CACHE_MODE_LOCAL)) { return cmd.hasFlag(Flag.SKIP_CACHE_LOAD); } if (!cdl.localNodeIsPrimaryOwner(key)) { if (trace) { log.tracef("Skip load for command %s. This node is not the primary owner of %s", cmd, toStr(key)); } return true; } break; case OWNER: if (cmd.hasFlag(Flag.CACHE_MODE_LOCAL)) { return cmd.hasFlag(Flag.SKIP_CACHE_LOAD); } List<Address> owners = cdl.getOwners(key); int index = owners == null ? 0 : owners.indexOf(cdl.getAddress()); if (index != 0 && (index < 0 || ctx.isOriginLocal())) { if (trace) { log.tracef("Skip load for command %s. This node is neither the primary owner nor non-origin backup of %s", cmd, toStr(key)); } return true; } break; } } return super.skipLoadForWriteCommand(cmd, key, ctx); }
Source:
private void buildStorageEngine() { assertNonNull(configuration, "The AxonServerConfiguration is a hard requirement and should be provided"); assertNonNull(platformConnectionManager, "The PlatformConnectionManager is a hard requirement and should be provided"); AxonDBClient axonDBClient = new AxonDBClient(configuration, platformConnectionManager); super.storageEngine(AxonIQEventStorageEngine.builder() .snapshotSerializer(snapshotSerializer) .upcasterChain(upcasterChain) .snapshotFilter(snapshotFilter) .eventSerializer(eventSerializer) .configuration(configuration) .eventStoreClient(axonDBClient) .converter(new GrpcMetaDataConverter(eventSerializer)) .build()); }

Target:
private void buildStorageEngine() { assertNonNull(configuration, "The AxonServerConfiguration is a hard requirement and should be provided"); assertNonNull(platformConnectionManager, "The PlatformConnectionManager is a hard requirement and should be provided"); AxonServerEventStoreClient eventStoreClient = new AxonServerEventStoreClient(configuration, platformConnectionManager); super.storageEngine(AxonIQEventStorageEngine.builder() .snapshotSerializer(snapshotSerializer) .upcasterChain(upcasterChain) .snapshotFilter(snapshotFilter) .eventSerializer(eventSerializer) .configuration(configuration) .eventStoreClient(eventStoreClient) .converter(new GrpcMetaDataConverter(eventSerializer)) .build()); }
Source:
public void testRenameTable() { SchemaTableName tableName = new SchemaTableName("test", "test_rename"); metadata.createSchema(SESSION, "test", ImmutableMap.of()); ConnectorOutputTableHandle table = metadata.beginCreateTable( SESSION, new ConnectorTableMetadata(tableName, ImmutableList.of(), ImmutableMap.of()), Optional.empty()); metadata.finishCreateTable(SESSION, table, ImmutableList.of()); SchemaTableName invalidSchemaTableName = new SchemaTableName("rename", "test_renamed"); ConnectorTableHandle tableHandle = metadata.getTableHandle(SESSION, tableName); try { metadata.renameTable(SESSION, tableHandle, invalidSchemaTableName); fail("Should fail because schema does not exist"); } catch (PrestoException ex) { assertEquals(ex.getErrorCode(), NOT_FOUND.toErrorCode()); assertEquals(ex.getMessage(), "Schema rename not found"); } SchemaTableName sameSchemaTableName = new SchemaTableName("test", "test_renamed"); metadata.renameTable(SESSION, metadata.getTableHandle(SESSION, tableName), sameSchemaTableName); assertEquals(metadata.listTables(SESSION, "test"), ImmutableList.of(sameSchemaTableName)); metadata.createSchema(SESSION, "test2", ImmutableMap.of()); SchemaTableName differentSchemaTableName = new SchemaTableName("test2", "test_renamed"); metadata.renameTable(SESSION, metadata.getTableHandle(SESSION, sameSchemaTableName), differentSchemaTableName); assertEquals(metadata.listTables(SESSION, "test"), ImmutableList.of()); assertEquals(metadata.listTables(SESSION, "test2"), ImmutableList.of(differentSchemaTableName)); }

Target:
public void testRenameTable() { SchemaTableName tableName = new SchemaTableName("test_schema", "test_talbe_to_be_renamed"); metadata.createSchema(SESSION, "test_schema", ImmutableMap.of()); ConnectorOutputTableHandle table = metadata.beginCreateTable( SESSION, new ConnectorTableMetadata(tableName, ImmutableList.of(), ImmutableMap.of()), Optional.empty()); metadata.finishCreateTable(SESSION, table, ImmutableList.of()); SchemaTableName invalidSchemaTableName = new SchemaTableName("test_schema_not_exist", "test_table_renamed"); ConnectorTableHandle tableHandle = metadata.getTableHandle(SESSION, tableName); Throwable throwable = expectThrows(SchemaNotFoundException.class, () -> metadata.renameTable(SESSION, tableHandle, invalidSchemaTableName)); assertTrue(throwable.getMessage().equals("Schema test_schema_not_exist not found")); SchemaTableName sameSchemaTableName = new SchemaTableName("test_schema", "test_renamed"); metadata.renameTable(SESSION, metadata.getTableHandle(SESSION, tableName), sameSchemaTableName); assertEquals(metadata.listTables(SESSION, "test_schema"), ImmutableList.of(sameSchemaTableName)); metadata.createSchema(SESSION, "test_different_schema", ImmutableMap.of()); SchemaTableName differentSchemaTableName = new SchemaTableName("test_different_schema", "test_renamed"); metadata.renameTable(SESSION, metadata.getTableHandle(SESSION, sameSchemaTableName), differentSchemaTableName); assertEquals(metadata.listTables(SESSION, "test_schema"), ImmutableList.of()); assertEquals(metadata.listTables(SESSION, "test_different_schema"), ImmutableList.of(differentSchemaTableName)); }
Source:
public CompletableFuture<List<PlayerAchievement>> getPlayerAchievements(Integer playerId) { int currentPlayerId = playerService.getCurrentPlayer().orElseThrow(() -> new IllegalStateException("Player has to be set")).getId(); if (Objects.equals(currentPlayerId, playerId)) { if (readOnlyPlayerAchievements.isEmpty()) { CompletableFuture<List<PlayerAchievement>> achievmentsLoadedFuture = new CompletableFuture<>(); reloadAchievements(achievmentsLoadedFuture); return achievmentsLoadedFuture; } return CompletableFuture.completedFuture(readOnlyPlayerAchievements); } return fafService.getPlayerAchievements(playerId); }

Target:
public CompletableFuture<List<PlayerAchievement>> getPlayerAchievements(Integer playerId) { int currentPlayerId = playerService.getCurrentPlayer().orElseThrow(() -> new IllegalStateException("Player has to be set")).getId(); if (Objects.equals(currentPlayerId, playerId)) { if (readOnlyPlayerAchievements.isEmpty()) { return reloadAchievements(); } return CompletableFuture.completedFuture(readOnlyPlayerAchievements); } return fafService.getPlayerAchievements(playerId); }
Source:
protected void loadDefaultConfigurationFromClasspath(String defaultConfigFile) { try { LOGGER.info("Loading '" + defaultConfigFile + "' from classpath."); configurationUrl = Config.class.getClassLoader().getResource(defaultConfigFile); if (configurationUrl == null) { throw new HazelcastException("Could not find '" + defaultConfigFile + "' in the classpath!" + "This may be due to a wrong-packaged or corrupted jar file."); } in = Config.class.getClassLoader().getResourceAsStream(defaultConfigFile); if (in == null) { throw new HazelcastException("Could not load '" + defaultConfigFile + "' from classpath"); } } catch (RuntimeException e) { throw new HazelcastException(e); } }

Target:
protected void loadDefaultConfigurationFromClasspath(String defaultConfigFile) { try { LOGGER.info(String.format("Loading '%s' from the classpath.", defaultConfigFile)); configurationUrl = Config.class.getClassLoader().getResource(defaultConfigFile); if (configurationUrl == null) { throw new HazelcastException(String.format("Could not find '%s' in the classpath! This may be due to a " + "wrong-packaged or corrupted jar file.", defaultConfigFile)); } in = Config.class.getClassLoader().getResourceAsStream(defaultConfigFile); if (in == null) { throw new HazelcastException(String.format("Could not load '%s' from the classpath", defaultConfigFile)); } } catch (RuntimeException e) { throw new HazelcastException(e); } }
Source:
public static <C extends Credentials> List<C> trackAll(@NonNull Node node, @NonNull List<C> credentials) { if (CredentialsProviderManager.isFingerprintEnabledOrDefault()) { long timestamp = System.currentTimeMillis(); String nodeName = node.getNodeName(); Set<String> jenkinsNodeNames = new HashSet<>(); for (Node n: Jenkins.get().getNodes()) { jenkinsNodeNames.add(n.getNodeName()); } for (Credentials c : credentials) { if (c != null) { try { Fingerprint fingerprint = getOrCreateFingerprintOf(c); BulkChange change = new BulkChange(fingerprint); try { Collection<FingerprintFacet> facets = fingerprint.getFacets(); long start = timestamp; for (Iterator<FingerprintFacet> iterator = facets.iterator(); iterator.hasNext(); ) { FingerprintFacet f = iterator.next(); if (f instanceof NodeCredentialsFingerprintFacet) { if (StringUtils.equals(nodeName, ((NodeCredentialsFingerprintFacet) f).getNodeName())) { start = Math.min(start, f.getTimestamp()); iterator.remove(); } else if (!jenkinsNodeNames.contains(((NodeCredentialsFingerprintFacet) f).getNodeName())) { iterator.remove(); } } } if (jenkinsNodeNames.contains(node.getNodeName())) { facets.add(new NodeCredentialsFingerprintFacet(node, fingerprint, start, timestamp)); } } finally { change.commit(); } } catch (IOException e) { LOGGER.log(Level.FINEST, "Could not track usage of " + c, e); } } } } else { LOGGER.log(Level.FINEST, "TrackAll(Node) called but fingerprints disabled in the global configuration."); } return credentials; }

Target:
public static <C extends Credentials> List<C> trackAll(@NonNull Node node, @NonNull List<C> credentials) { if (CredentialsProvider.FINGERPRINT_ENABLED) { long timestamp = System.currentTimeMillis(); String nodeName = node.getNodeName(); Set<String> jenkinsNodeNames = new HashSet<>(); for (Node n: Jenkins.get().getNodes()) { jenkinsNodeNames.add(n.getNodeName()); } for (Credentials c : credentials) { if (c != null) { try { Fingerprint fingerprint = getOrCreateFingerprintOf(c); BulkChange change = new BulkChange(fingerprint); try { Collection<FingerprintFacet> facets = fingerprint.getFacets(); long start = timestamp; for (Iterator<FingerprintFacet> iterator = facets.iterator(); iterator.hasNext(); ) { FingerprintFacet f = iterator.next(); if (f instanceof NodeCredentialsFingerprintFacet) { if (StringUtils.equals(nodeName, ((NodeCredentialsFingerprintFacet) f).getNodeName())) { start = Math.min(start, f.getTimestamp()); iterator.remove(); } else if (!jenkinsNodeNames.contains(((NodeCredentialsFingerprintFacet) f).getNodeName())) { iterator.remove(); } } } if (jenkinsNodeNames.contains(node.getNodeName())) { facets.add(new NodeCredentialsFingerprintFacet(node, fingerprint, start, timestamp)); } } finally { change.commit(); } } catch (IOException e) { LOGGER.log(Level.FINEST, "Could not track usage of " + c, e); } } } } else { LOGGER.log(Level.FINEST, "TrackAll method (Node variant) called but fingerprints disabled by {0}", FINGERPRINT_ENABLED_NAME); } return credentials; }
Source:
public void addToOrderBook(Order order) { if (order instanceof BuyOrder) { ArrayList<Order> orders; if (buyOrders.containsKey(order.getStockSymbol())) { orders = buyOrders.get(order.getStockSymbol()); } else { orders = new ArrayList<Order>(); } orders.add(order); buyOrders.put(order.getStockSymbol(), orders); } else { ArrayList<Order> orders; if (sellOrders.containsKey(order.getStockSymbol())) { orders = sellOrders.get(order.getStockSymbol()); } else { orders = new ArrayList<Order>(); } orders.add(order); sellOrders.put(order.getStockSymbol(), orders); } }

Target:
public void addToOrderBook(Order order) { if (order instanceof BuyOrder) { addToOrders(buyOrders, order); } else { addToOrders(sellOrders, order); } }
Source:
public TestCase(@JsonProperty(value = "before", required = true) List<Request> setupRequestList, @JsonProperty(value = "request", required = true) Request request, @JsonProperty(value = "after", required = true) List<Request> tearDownRequestList, @JsonProperty(value = "assertions", required = true) List<RequestAndResponseAssertion> assertions) { this.setupRequestList = Optional.fromNullable(tearDownRequestList).or(new ArrayList<Request>()); this.request = request; this.tearDownRequestList = Optional.fromNullable(setupRequestList).or(new ArrayList<Request>()); this.assertions = Optional.fromNullable(assertions).or(new ArrayList<RequestAndResponseAssertion>()); }

Target:
public TestCase(@JsonProperty(value = "before", required = true) List<Request> setupRequestList, @JsonProperty(value = "request", required = true) Request request, @JsonProperty(value = "after", required = true) List<Request> tearDownRequestList, @JsonProperty(value = "assertions", required = true) List<RequestAndResponseAssertion> assertions) { this.setupRequestList = Optional.fromNullable(tearDownRequestList).or(Collections.<Request>emptyList()); this.request = request; this.tearDownRequestList = Optional.fromNullable(setupRequestList).or(Collections.<Request>emptyList()); this.assertions = Optional.fromNullable(assertions).or(Collections.<RequestAndResponseAssertion>emptyList()); }
Source:
private void drawPieChart(PaintEvent e, double series[], Rectangle bounds) { int nelemSeries = series.length; double sumTotal = 0; for (int i = 0; i < nelemSeries; i++) { sumTotal += series[i]; } GC gc = e.gc; gc.setLineWidth(1); int pieWidth = Math.min(bounds.width - X_GAP, bounds.height); int pieX = bounds.x + (bounds.width - pieWidth) / 2; int pieY = bounds.y + (bounds.height - pieWidth) / 2; if (sumTotal == 0) gc.drawOval(pieX, pieY, pieWidth, pieWidth); else { double factor = 100 / sumTotal; int sweepAngle = 0; int incrementAngle = 0; int initialAngle = 90; for (int i = 0; i < nelemSeries; i++) { gc.setBackground(new Color(e.display, chart.colorList.get(i))); if (i == (nelemSeries - 1)) sweepAngle = 360 - incrementAngle; else { double angle = series[i] * factor * 3.6; sweepAngle = (int) Math.round(angle); } gc.fillArc(pieX, pieY, pieWidth, pieWidth, initialAngle, (-sweepAngle)); gc.drawArc(pieX, pieY, pieWidth, pieWidth, initialAngle, (-sweepAngle)); incrementAngle += sweepAngle; initialAngle += (-sweepAngle); } } }

Target:
private void drawPieChart(PaintEvent e, double series[], Rectangle bounds) { int nelemSeries = series.length; double sumTotal = 0; for (int i = 0; i < nelemSeries; i++) { sumTotal += series[i]; } GC gc = e.gc; gc.setLineWidth(1); int pieWidth = Math.min(bounds.width - X_GAP, bounds.height); int pieX = bounds.x + (bounds.width - pieWidth) / 2; int pieY = bounds.y + (bounds.height - pieWidth) / 2; if (sumTotal == 0) { gc.drawOval(pieX, pieY, pieWidth, pieWidth); } else { double factor = 100 / sumTotal; int sweepAngle = 0; int incrementAngle = 0; int initialAngle = 90; for (int i = 0; i < nelemSeries; i++) { gc.setBackground(new Color(e.display, chart.getSliceColor(i))); if (i == (nelemSeries - 1)) { sweepAngle = 360 - incrementAngle; } else { double angle = series[i] * factor * 3.6; sweepAngle = (int) Math.round(angle); } gc.fillArc(pieX, pieY, pieWidth, pieWidth, initialAngle, (-sweepAngle)); gc.drawArc(pieX, pieY, pieWidth, pieWidth, initialAngle, (-sweepAngle)); incrementAngle += sweepAngle; initialAngle += (-sweepAngle); } } }
Source:
public Iterable<RevCommit> call() throws GitAPIException, NoHeadException { checkCallable(); if (pathFilters.size() > 0) walk.setTreeFilter(AndTreeFilter.create( PathFilterGroup.create(pathFilters), TreeFilter.ANY_DIFF)); if (skip > -1 && maxCount > -1) walk.setRevFilter(AndRevFilter.create(SkipRevFilter.create(skip), MaxCountRevFilter.create(maxCount))); else if (skip > -1) walk.setRevFilter(SkipRevFilter.create(skip)); else if (maxCount > -1) walk.setRevFilter(MaxCountRevFilter.create(maxCount)); if (!startSpecified) { try { ObjectId headId = repo.resolve(Constants.HEAD); if (headId == null) throw new NoHeadException( JGitText.get().noHEADExistsAndNoExplicitStartingRevisionWasSpecified); add(headId); } catch (IOException e) { throw new JGitInternalException( JGitText.get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD, e); } } if (onlyMerges) walk.setRevFilter(RevFilter.ONLY_MERGES); if (noMerges) walk.setRevFilter(RevFilter.NO_MERGES); setCallable(false); return walk; }

Target:
public Iterable<RevCommit> call() throws GitAPIException, NoHeadException { checkCallable(); if (pathFilters.size() > 0) walk.setTreeFilter(AndTreeFilter.create( PathFilterGroup.create(pathFilters), TreeFilter.ANY_DIFF)); if (skip > -1 && maxCount > -1) walk.setRevFilter(AndRevFilter.create(SkipRevFilter.create(skip), MaxCountRevFilter.create(maxCount))); else if (skip > -1) walk.setRevFilter(SkipRevFilter.create(skip)); else if (maxCount > -1) walk.setRevFilter(MaxCountRevFilter.create(maxCount)); if (!startSpecified) { try { ObjectId headId = repo.resolve(Constants.HEAD); if (headId == null) throw new NoHeadException( JGitText.get().noHEADExistsAndNoExplicitStartingRevisionWasSpecified); add(headId); } catch (IOException e) { throw new JGitInternalException( JGitText.get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD, e); } } if (this.revFilter != null){ walk.setRevFilter(this.revFilter); } setCallable(false); return walk; }
Source:
public void testCustomMetricsTransport() throws Exception { TestGeneratorInputOperator o1 = dag.addOperator("o1", TestGeneratorInputOperator.class); GenericTestOperator o2 = dag.addOperator("o2", GenericTestOperator.class); dag.addStream("o1.outport", o1.outport, o2.inport1); dag.setAttribute(LogicalPlan.METRICS_TRANSPORT, new TestMetricTransport("xyz")); StramLocalCluster lc = new StramLocalCluster(dag); StreamingContainerManager dnmgr = lc.dnmgr; StramAppContext appContext = new StramTestSupport.TestAppContext(); AppDataPushAgent pushAgent = new AppDataPushAgent(dnmgr, appContext); pushAgent.init(); pushAgent.pushData(); Assert.assertTrue(TestMetricTransport.messages.size() > 0); pushAgent.close(); String msg = TestMetricTransport.messages.get(0); System.out.println("Got this message: " + msg); Assert.assertTrue(msg.startsWith("xyz:")); }

Target:
public void testCustomMetricsTransport() throws Exception { TestGeneratorInputOperator o1 = dag.addOperator("o1", TestGeneratorInputOperator.class); GenericTestOperator o2 = dag.addOperator("o2", GenericTestOperator.class); dag.addStream("o1.outport", o1.outport, o2.inport1); dag.setAttribute(LogicalPlan.METRICS_TRANSPORT, new TestMetricTransport("xyz")); StramLocalCluster lc = new StramLocalCluster(dag); StreamingContainerManager dnmgr = lc.dnmgr; StramAppContext appContext = new StramTestSupport.TestAppContext(); AppDataPushAgent pushAgent = new AppDataPushAgent(dnmgr, appContext); pushAgent.init(); pushAgent.pushData(); Assert.assertTrue(TestMetricTransport.messages.size() > 0); pushAgent.close(); String msg = TestMetricTransport.messages.get(0); Assert.assertTrue(msg.startsWith("xyz:")); }
Source:
public void shutdown() { try { logger.info("Stopping HTTP server."); shutdownHandler.shutdown(); shutdownHandler.awaitShutdown(HTTP_SHUTDOWN_GRACE_PERIOD_MILLIS); undertow.stop(); } catch (final Exception ie) { Thread.currentThread().interrupt(); } logger.info("Stopping thread pools."); mappingProcessors.values().forEach(ProcessingPool::stop); sinks.values().forEach(ProcessingPool::stop); logger.info("Closing HDFS filesystem connection."); try { FileSystem.closeAll(); } catch (final IOException ioe) { logger.warn("Failed to cleanly close HDFS file system.", ioe); } }

Target:
public void shutdown() { try { logger.info("Stopping HTTP server."); shutdownHandler.shutdown(); shutdownHandler.awaitShutdown(HTTP_SHUTDOWN_GRACE_PERIOD_MILLIS); undertow.stop(); } catch (final Exception ie) { Thread.currentThread().interrupt(); } logger.info("Stopping thread pools."); incomingRequestProcessingPool.stop(); sinks.values().forEach(ProcessingPool::stop); logger.info("Closing HDFS filesystem connection."); try { FileSystem.closeAll(); } catch (final IOException ioe) { logger.warn("Failed to cleanly close HDFS file system.", ioe); } }
Source:
private static void addBuiltInFunction(Class<? extends FunctionExpression> f) throws Exception { BuiltInFunction d = f.getAnnotation(BuiltInFunction.class); if (d == null) { return; } int nArgs = d.args().length; BuiltInFunctionInfo value = new BuiltInFunctionInfo(f, d); SINGLE_SIGNATURE_BUILT_IN_FUNCTION_MAP.put(value.getName(), value); do { BuiltInFunctionKey key = new BuiltInFunctionKey(value.getName(), nArgs); if (BUILT_IN_FUNCTION_MAP.put(key, value) != null) { throw new IllegalStateException("Multiple " + value.getName() + " functions with " + nArgs + " arguments"); } } while (--nArgs >= 0 && d.args()[nArgs].defaultValue().length() > 0); while (--nArgs >= 0) { if (d.args()[nArgs].defaultValue().length() > 0) { throw new IllegalStateException("Function " + value.getName() + " has non trailing default value of '" + d.args()[nArgs].defaultValue() + "'. Only trailing arguments may have default values"); } } }

Target:
private static void addBuiltInFunction(Class<? extends FunctionExpression> f) throws Exception { BuiltInFunction d = f.getAnnotation(BuiltInFunction.class); if (d == null) { return; } int nArgs = d.args().length; BuiltInFunctionInfo value = new BuiltInFunctionInfo(f, d); if (d.classType() != FunctionParseNode.FunctionClassType.ABSTRACT) { BUILT_IN_FUNCTION_MULTIMAP.put(value.getName(), value); } if (d.classType() != FunctionParseNode.FunctionClassType.DERIVED) { do { BuiltInFunctionKey key = new BuiltInFunctionKey(value.getName(), nArgs); if (BUILT_IN_FUNCTION_MAP.put(key, value) != null) { throw new IllegalStateException("Multiple " + value.getName() + " functions with " + nArgs + " arguments"); } } while (--nArgs >= 0 && d.args()[nArgs].defaultValue().length() > 0); while (--nArgs >= 0) { if (d.args()[nArgs].defaultValue().length() > 0) { throw new IllegalStateException("Function " + value.getName() + " has non trailing default value of '" + d.args()[nArgs].defaultValue() + "'. Only trailing arguments may have default values"); } } } }
Source:
private InvocationStage handleReadCommand(InvocationContext ctx, AbstractTopologyAffectedCommand command) throws Throwable { if (isLocalOnly(command)) { return invokeNext(ctx, command); } updateTopologyId(command); if (!ctx.isOriginLocal()) { return invokeNext(ctx, command); } return invokeNext(ctx, command).compose((stage, rCtx, rCommand, rv, t) -> { if (t == null) return stage; Throwable ce = t; while (ce instanceof RemoteException) { ce = ce.getCause(); } if (!(ce instanceof OutdatedTopologyException) && !(ce instanceof SuspectException)) throw t; int currentTopologyId = currentTopologyId(); if (trace) log.tracef("Retrying command because of topology change, current topology is %d: %s", currentTopologyId(), rCommand); AbstractTopologyAffectedCommand cmd = (AbstractTopologyAffectedCommand) rCommand; int newTopologyId = Math.max(currentTopologyId(), cmd.getTopologyId() + 1); cmd.setTopologyId(newTopologyId); waitForTopology(newTopologyId); return handleReadCommand(rCtx, cmd); }); }

Target:
private InvocationStage handleReadCommand(InvocationContext ctx, AbstractTopologyAffectedCommand command) throws Throwable { if (isLocalOnly(command)) { return invokeNext(ctx, command); } updateTopologyId(command); return invokeNext(ctx, command).compose(this::handleReadCommandReturn); }
Source:
public void setUp() throws Exception { User.disableStorage(); }

Target:
public void setUp() { User.disableStorage(); }
Source:
public void verifyPinResetConfirmationCode(UUID userId, String userProvidedConfirmationCode) { User userEntity = userService.getUserEntityById(userId); logger.info("User with mobile number '{}' and ID '{}' requested to verify the pin reset confirmation code", userEntity.getMobileNumber(), userId); Optional<ConfirmationCode> confirmationCodeOpt = userEntity.getPinResetConfirmationCode(); Require.that(isValidConfirmationCode(confirmationCodeOpt), () -> PinResetRequestConfirmationException.confirmationCodeNotSet(userEntity.getMobileNumber())); ConfirmationCode confirmationCode = confirmationCodeOpt.get(); int remainingAttempts = yonaProperties.getSecurity().getConfirmationCodeMaxAttempts() - confirmationCode.getAttempts(); Require.that(remainingAttempts > 0, () -> PinResetRequestConfirmationException.tooManyAttempts(userEntity.getMobileNumber())); if (!userProvidedConfirmationCode.equals(confirmationCode.getCode())) { userService.registerFailedAttempt(userEntity, confirmationCode); throw PinResetRequestConfirmationException.confirmationCodeMismatch(userEntity.getMobileNumber(), userProvidedConfirmationCode, remainingAttempts - 1); } }

Target:
public void verifyPinResetConfirmationCode(UUID userId, String userProvidedConfirmationCode) { User user = userService.lockUserForUpdate(userId); logger.info("User with mobile number '{}' and ID '{}' requested to verify the pin reset confirmation code", user.getMobileNumber(), userId); Optional<ConfirmationCode> confirmationCodeOpt = user.getPinResetConfirmationCode(); Require.that(isValidConfirmationCode(confirmationCodeOpt), () -> PinResetRequestConfirmationException.confirmationCodeNotSet(user.getMobileNumber())); ConfirmationCode confirmationCode = confirmationCodeOpt.get(); int remainingAttempts = yonaProperties.getSecurity().getConfirmationCodeMaxAttempts() - confirmationCode.getAttempts(); Require.that(remainingAttempts > 0, () -> PinResetRequestConfirmationException.tooManyAttempts(user.getMobileNumber())); if (!userProvidedConfirmationCode.equals(confirmationCode.getCode())) { confirmationCode.incrementAttempts(); throw PinResetRequestConfirmationException.confirmationCodeMismatch(user.getMobileNumber(), userProvidedConfirmationCode, remainingAttempts - 1); } }
Source:
public void notLeader() { _log.info("Not assuming leader role. Probably there is another PinManager that already is entitled to the leader role."); expirationFuture.cancel(false); unpinFuture.cancel(true); }

Target:
public void notLeader() { _log.info("Dropping leader role. Cancelling Expiration and Unpin tasks."); expirationFuture.cancel(false); unpinFuture.cancel(true); }
Source:
public String getComponentType() { return (this.getExpectReply() ? "http:outbound-reactive-gateway" : "http:outbound-reactive-channel-adapter"); }

Target:
public String getComponentType() { return (isExpectReply() ? "http:outbound-reactive-gateway" : "http:outbound-reactive-channel-adapter"); }
Source:
LineReader(Reader reader, LineDelimiter lineDelimiter, int bufferSize) { super(reader); this.lineDelimiter = lineDelimiter; this.buffer = new char[bufferSize]; this.offset = UNREAD; this.charsRead = 0; }

Target:
private LineReader(Reader reader, LineDelimiter lineDelimiter, int bufferSize) { super(reader); this.lineDelimiter = lineDelimiter; this.buffer = new char[bufferSize]; this.offset = UNREAD; this.charsRead = 0; }
Source:
private int getBarcodeValue(final SAMRecord record) { if (null == BARCODE_TAG) return 0; final String tag = record.getStringAttribute(BARCODE_TAG); if (null == tag) return 0; else return tag.hashCode(); }

Target:
private int getBarcodeValue(final SAMRecord record) { return EstimateLibraryComplexity.getReadBarcodeValue(record, BARCODE_TAG); }
Source:
public BufferableHandle getParamValue() { return (BufferableHandle) paramValue; }

Target:
public AbstractWriteHandle getParamValue() { return paramValue; }
Source:
private void testSelectForUpdateConcurrency() throws SQLException { Connection conn = getConnection(url); conn.setAutoCommit(false); String sql = "CREATE TABLE test (" + "entity_id INTEGER NOT NULL PRIMARY KEY, " + "lastUpdated INTEGER NOT NULL)"; Statement smtm = conn.createStatement(); smtm.executeUpdate(sql); PreparedStatement ps = conn.prepareStatement( "INSERT INTO test (entity_id, lastUpdated) VALUES (?, ?)"); ps.setInt(1, 1); ps.setInt(2, 100); ps.executeUpdate(); conn.commit(); for (int i = 0; i < 100; i++) new SelectForUpdate().start(); }

Target:
private void testSelectForUpdateConcurrency() throws SQLException { deleteDb(getTestName()); Connection conn = getConnection(getTestName() + url); conn.setAutoCommit(false); String sql = "CREATE TABLE testmvccmultithreaded2 (" + "entity_id INTEGER NOT NULL PRIMARY KEY, " + "lastUpdated INTEGER NOT NULL)"; Statement smtm = conn.createStatement(); smtm.executeUpdate(sql); PreparedStatement ps = conn.prepareStatement( "INSERT INTO testmvccmultithreaded2 (entity_id, lastUpdated) VALUES (?, ?)"); ps.setInt(1, 1); ps.setInt(2, 100); ps.executeUpdate(); conn.commit(); int howManyThreads = 100; Thread[] threads = new SelectForUpdate[howManyThreads]; for (int i = 0; i < howManyThreads; i++) { threads[i] = new SelectForUpdate(); threads[i].start(); } try { for (int i = 0; i < howManyThreads; i++) { threads[i].join(); } } catch (InterruptedException e) { e.printStackTrace(); } smtm = conn.createStatement(); smtm.execute("DROP TABLE testmvccmultithreaded2"); if (conn != null) { try { conn.close(); } catch (SQLException e1) { e1.printStackTrace(); } } }
Source:
public Path getAssetsDirectory() { return fileAssets.toPath(); }

Target:
public Path getAssetsDirectory() { return this.fileAssets.toPath(); }
Source:
private static List<String> toLonLatStrings(GeoPoint point) { if (point == null) { return null; } return Arrays.asList(String.valueOf(point.getLongitude()), String.valueOf(point.getLatitude())); }

Target:
private static List<String> toLonLatStrings(GeoPoint point) { Objects.requireNonNull(point); return Arrays.asList(String.valueOf(point.getLongitude()), String.valueOf(point.getLatitude())); }
Source:
public void oneDelayed() { Flowable.just(1, 2, 3, 4, 5) .concatMapEager(new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer i) throws Exception { System.out.println("Processing " + i); return i == 3 ? Flowable.just(i) : Flowable .just(i) .delay(1, TimeUnit.MILLISECONDS, Schedulers.io()); } }) .observeOn(Schedulers.io()) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(1, 2, 3, 4, 5) ; }

Target:
public void oneDelayed() { Flowable.just(1, 2, 3, 4, 5) .concatMapEager(new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer i) throws Exception { return i == 3 ? Flowable.just(i) : Flowable .just(i) .delay(1, TimeUnit.MILLISECONDS, Schedulers.io()); } }) .observeOn(Schedulers.io()) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(1, 2, 3, 4, 5) ; }
Source:
public static FillStatus drainContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot, boolean doDrain) { ItemStack input = inv.getStackInSlot(inputSlot); if (input.isEmpty()) { return FillStatus.INVALID_INPUT; } ItemStack outputStack = inv.getStackInSlot(outputSlot); FluidActionResult drainedResultSimulated = FluidUtil.tryEmptyContainer(input, fluidHandler, Fluid.BUCKET_VOLUME, null, false); if (!drainedResultSimulated.isSuccess()) { return FillStatus.INVALID_INPUT; } ItemStack drainedItemSimulated = drainedResultSimulated.getResult(); if (outputStack.isEmpty() || drainedItemSimulated.isEmpty() || ItemStackUtil.isIdenticalItem(outputStack, drainedItemSimulated) && outputStack.getCount() + drainedItemSimulated.getCount() < outputStack.getMaxStackSize()) { if (doDrain) { FluidActionResult drainedResult = FluidUtil.tryEmptyContainer(input, fluidHandler, Fluid.BUCKET_VOLUME, null, true); if (drainedResult.isSuccess()) { ItemStack drainedItem = drainedResult.getResult(); if (!drainedItem.isEmpty()) { ItemStack newStack = drainedItem.copy(); if (!outputStack.isEmpty()) { newStack.grow(outputStack.getCount()); } if (!isFillableContainer(newStack) || isFillableContainerAndEmpty(newStack)) { inv.setInventorySlotContents(outputSlot, newStack); inv.decrStackSize(inputSlot, 1); } if(!isFillableEmptyContainer(newStack) && isFillableContainerWithRoom(newStack)) { inv.setInventorySlotContents(inputSlot, newStack.copy()); } } else { inv.decrStackSize(inputSlot, 1); } return FillStatus.SUCCESS; } } return FillStatus.SUCCESS; } return FillStatus.NO_SPACE; }

Target:
public static FillStatus drainContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot, boolean doDrain) { ItemStack input = inv.getStackInSlot(inputSlot); if (input.isEmpty()) { return FillStatus.INVALID_INPUT; } ItemStack outputStack = inv.getStackInSlot(outputSlot); FluidActionResult drainedResultSimulated = FluidUtil.tryEmptyContainer(input, fluidHandler, Fluid.BUCKET_VOLUME, null, false); if (!drainedResultSimulated.isSuccess()) { return FillStatus.INVALID_INPUT; } ItemStack drainedItemSimulated = drainedResultSimulated.getResult(); if (outputStack.isEmpty() || drainedItemSimulated.isEmpty() || ItemStackUtil.isIdenticalItem(outputStack, drainedItemSimulated) && outputStack.getCount() + drainedItemSimulated.getCount() < outputStack.getMaxStackSize()) { if (doDrain) { FluidActionResult drainedResult = FluidUtil.tryEmptyContainer(input, fluidHandler, Fluid.BUCKET_VOLUME, null, true); if (drainedResult.isSuccess()) { ItemStack drainedItem = drainedResult.getResult(); if (!drainedItem.isEmpty()) { ItemStack newStack = drainedItem.copy(); if (!outputStack.isEmpty()) { newStack.grow(outputStack.getCount()); } if (!isFillableContainer(newStack) || isFillableContainerAndEmpty(newStack)) { inv.setInventorySlotContents(outputSlot, newStack); inv.decrStackSize(inputSlot, 1); } if (isDrainableContainer(newStack) && !isEmpty(newStack)) { inv.setInventorySlotContents(inputSlot, newStack); } } else { inv.decrStackSize(inputSlot, 1); } return FillStatus.SUCCESS; } } return FillStatus.SUCCESS; } return FillStatus.NO_SPACE; }
Source:
public void testDefaultMethodInterception() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bindInterceptor( Matchers.any(), Matchers.annotatedWith(Grounded.class), new CountingInterceptor()); } }); assertEquals(0, count.get()); assertEquals("I am a horse.", injector.getInstance(Unicorn.class).identifyMyself()); assertEquals(1, count.get()); assertEquals("I am a flying horse.", injector.getInstance(Pegasus.class).identifyMyself()); assertEquals(1, count.get()); }

Target:
public void testDefaultMethodInterception() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bindInterceptor( Matchers.any(), Matchers.annotatedWith(Grounded.class), new CountingInterceptor()); } }); assertEquals(0, count.get()); assertEquals("I am a horse.", injector.getInstance(Unicorn.class).identifyMyself()); assertEquals(1, count.get()); count.set(0); assertEquals(0, count.get()); assertEquals("I am a flying horse.", injector.getInstance(Pegasus.class).identifyMyself()); assertEquals(0, count.get()); }
Source:
private void updatePartitionLeadershipMap() { Optional.ofNullable(_consumer.listTopics(_consumerRequestTimeout)).ifPresent(response -> response.values().stream() .filter(Objects::nonNull) .flatMap(Collection::stream) .filter(partitionInfo -> partitionInfo != null && partitionInfo.topic() != null && partitionInfo.leader() != null) .forEach(partitionInfo -> { final TopicPartition topicPartition = new TopicPartition(partitionInfo.topic(), partitionInfo.partition()); final Node leader = partitionInfo.leader(); _partitionLeadershipMap.put(topicPartition, leader); })); }

Target:
private void updatePartitionLeadershipMap() { LOG.debug("Updating partition leadership map"); Optional.ofNullable(_consumer.listTopics(_consumerRequestTimeout)).ifPresent(response -> { Map<TopicPartition, Node> updateMap = response.values().stream() .filter(Objects::nonNull) .flatMap(Collection::stream) .filter(partitionInfo -> partitionInfo != null && partitionInfo.topic() != null && partitionInfo.leader() != null) .collect(Collectors.toMap( partitionInfo -> new TopicPartition(partitionInfo.topic(), partitionInfo.partition()), PartitionInfo::leader)); _partitionLeadershipMap.keySet().retainAll(updateMap.keySet()); _partitionLeadershipMap.putAll(updateMap); }); }
Source:
public Comparator getComparator() { throw new UnsupportedOperationException(); }

Target:
public Comparator getComparator() { return ArithmeticPostAggregator.DEFAULT_COMPARATOR; }