auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void stopTest() { if (stopTries > 30) { throw new IllegalStateException("More than 30 retries - stopping with exception"); } if (lastStopTry == time) { return; } log.info("No further RPS schedule, asking threads to stop..."); lastStopTry = time; stopTries++; if (stopTries > 10) { log.info("Tried more than 10, stop it NOW!"); StandardJMeterEngine.stopEngineNow(); } else if (stopTries > 5) { log.info("Tried more than 5, stop it!"); StandardJMeterEngine.stopEngine(); } else { JMeterContextService.getContext().getEngine().askThreadsToStop(); } }

Target:
protected void stopTest() { if (stopTries > 30) { throw new IllegalStateException("More than 30 retries - stopping with exception"); } if (lastStopTry == time) { return; } log.info("No further RPS schedule, asking threads to stop..."); lastStopTry = time; stopTries++; if (stopTries > 10) { log.info("Tries more than 10, stopping engine NOW!"); StandardJMeterEngine.stopEngineNow(); } else if (stopTries > 5) { log.info("Tries more than 5, shutting down engine!"); StandardJMeterEngine.stopEngine(); } else { JMeterContextService.getContext().getEngine().askThreadsToStop(); } }
Source:
private StackExchangeApi() { }

Target:
protected StackExchangeApi() { }
Source:
public static ErrorMessageFactory shouldContain(Throwable actual, CharSequence sequence) { String format = "%n" + "Expecting:%n" + " <%s>%n" + "to contain:%n" + " <%s>%n" + "but did not.%n" + "%n" + "Throwable that failed the check:%n" + "%n" + escapePercent(getStackTrace(actual)); return new ShouldContainCharSequence(format, actual.getMessage(), sequence, StandardComparisonStrategy.instance()); }

Target:
public static ErrorMessageFactory shouldContain(Throwable actual, CharSequence sequence) { String format = "%n" + "Expecting throwable message:%n" + " <%s>%n" + "to contain:%n" + " <%s>%n" + "but did not.%n" + "%n" + "Throwable that failed the check:%n" + "%n" + escapePercent(getStackTrace(actual)); return new ShouldContainCharSequence(format, actual.getMessage(), sequence, StandardComparisonStrategy.instance()); }
Source:
protected void doExecute() { configUserThread(); CoreSetup.setup(config); addCapabilities(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { gracefulShutDown(() -> log.info("gracefulShutDown complete")); }, "Monitor Shutdown Hook ") ); launchApplication(); }

Target:
protected void doExecute() { configUserThread(); CoreSetup.setup(config); addCapabilities(); Signal.handle(new Signal("INT"), signal -> { gracefulShutDown(() -> { }); }); Signal.handle(new Signal("TERM"), signal -> { gracefulShutDown(() -> { }); }); launchApplication(); }
Source:
protected String getLink() { Method method = getMethod(); return getContextPath() + router.urlFor(controller, method, getArgs(method)); }

Target:
protected String getLink() { Method method = getMethod(); return getPrefix() + router.urlFor(controller, method, getArgs(method)); }
Source:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) { StompVersion stompVersion = StompVersion.findBySubProtocol(((HandshakeComplete) evt).selectedSubprotocol()); ctx.channel().attr(StompVersion.CHANNEL_ATTRIBUTE_KEY).set(stompVersion); String ctxName = ctx.name(); ctx.pipeline() .addAfter(ctxName, "stompChatHandler", stompChatHandler) .addAfter(ctxName, "stompAggregator", new StompSubframeAggregator(65536)) .addAfter(ctxName, "stompEncoder", new StompSubframeEncoder()) .addAfter(ctxName, "stompDecoder", new StompSubframeDecoder()) .remove(StompWebSocketClientPageHandler.INSTANCE); } else { super.userEventTriggered(ctx, evt); } }

Target:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) { StompVersion stompVersion = StompVersion.findBySubProtocol(((HandshakeComplete) evt).selectedSubprotocol()); ctx.channel().attr(StompVersion.CHANNEL_ATTRIBUTE_KEY).set(stompVersion); ctx.pipeline() .addLast(new StompSubframeDecoder()) .addLast(new StompSubframeEncoder()) .addLast(new StompSubframeAggregator(65536)) .addLast(stompChatHandler) .remove(StompWebSocketClientPageHandler.INSTANCE); } else { super.userEventTriggered(ctx, evt); } }
Source:
private void jumpToNode() { String inputText = jumpTo.getCharacters().toString(); if (isInteger(inputText) && curGraph.getNode(inputText) != null) { EnrichedSequenceNode reqNode = curGraph.getNode(inputText); resetPromptText(NODE); strainView.gotoRank(reqNode.getRank()); if (strainView.getStrain().getClusters().get(inputText) != null) { strainView.centerNode(inputText); } } else { promptInvalid(); } }

Target:
private void jumpToNode() { String inputText = jumpTo.getCharacters().toString(); if (isInteger(inputText) && curGraph.getNode(inputText) != null) { EnrichedSequenceNode reqNode = curGraph.getNode(inputText); resetPromptText(NODE); strainView.gotoRank(reqNode.getRank()); if (strainView.getStrain().getClusters().get(inputText) != null) { strainView.centerNodeVertically(inputText); } } else { promptInvalid(); } }
Source:
private void onMaybeMuteChanged() { if (menu != null && player != null) { MenuItem item = menu.findItem(R.id.action_mute); item.setTitle(player.isMuted() ? R.string.unmute : R.string.mute); item.setIcon(player.isMuted() ? getResources().getDrawable(ThemeHelper.resolveResourceIdFromAttr(getApplicationContext(), R.attr.ic_volume_off)) : getResources().getDrawable(R.drawable.ic_volume_off_gray_24dp)); } }

Target:
private void onMaybeMuteChanged() { if (menu != null && player != null) { MenuItem item = menu.findItem(R.id.action_mute); item.setTitle(player.isMuted() ? R.string.unmute : R.string.mute); item.setIcon(player.isMuted() ? ThemeHelper.resolveResourceIdFromAttr(rootView.getContext(), R.attr.ic_volume_off) : ThemeHelper.resolveResourceIdFromAttr(rootView.getContext(), R.attr.ic_volume_up)); } }
Source:
public DiscoveryResult createResult(ServiceInfo service) { if (service.getType().equals(getServiceType())) { if (service.getHostAddresses() != null && service.getHostAddresses().length > 0 && !service.getHostAddresses()[0].isEmpty()) { String ip = service.getHostAddresses()[0]; ThingUID thingUID = getThingUID(service); if (thingUID != null) { logger.debug("Discovered Tradfri gateway: {}", service); Map<String, Object> properties = new HashMap<>(4); properties.put(Thing.PROPERTY_VENDOR, "IKEA of Sweden"); properties.put(GatewayConfig.HOST, ip); properties.put(GatewayConfig.PORT, service.getPort()); String fwVersion = service.getPropertyString("version"); if (fwVersion != null) { properties.put(Thing.PROPERTY_FIRMWARE_VERSION, fwVersion); } return DiscoveryResultBuilder.create(thingUID).withProperties(properties).withLabel("TRÅDFRI Gateway") .withRepresentationProperty(GatewayConfig.HOST).build(); } } else { logger.warn("Discovered ServiceInfo doesn't have ip address: {}", service); } } return null; }

Target:
public DiscoveryResult createResult(ServiceInfo service) { ThingUID thingUID = getThingUID(service); if (thingUID != null) { if (service.getHostAddresses() != null && service.getHostAddresses().length > 0 && !service.getHostAddresses()[0].isEmpty()) { logger.debug("Discovered Tradfri gateway: {}", service); Map<String, Object> properties = new HashMap<>(4); properties.put(PROPERTY_VENDOR, "IKEA of Sweden"); properties.put(GATEWAY_CONFIG_HOST, service.getHostAddresses()[0]); properties.put(GATEWAY_CONFIG_PORT, service.getPort()); String fwVersion = service.getPropertyString("version"); if (fwVersion != null) { properties.put(PROPERTY_FIRMWARE_VERSION, fwVersion); } return DiscoveryResultBuilder.create(thingUID).withProperties(properties).withLabel("TRÅDFRI Gateway") .withRepresentationProperty(GATEWAY_CONFIG_HOST).build(); } else { logger.warn("Discovered Tradfri gateway doesn't have an IP address: {}", service); } } return null; }
Source:
public <T> ModelAdaptor<? super T> getModelAdaptor(Class<T> attributeType) { return (ModelAdaptor<T>) adaptors.get(attributeType); }

Target:
public <T> ModelAdaptor<? super T> getModelAdaptor(Class<T> attributeType) { return (ModelAdaptor<? super T>) adaptors.get(attributeType); }
Source:
protected ClientProxyImpl createClientProxy(ClassResourceInfo cri, boolean isRoot, ClientState actualState, Object[] varValues) { CDIInterceptorWrapper interceptorWrapper = CDIInterceptorWrapper.createWrapper(getServiceClass()); MicroProfileClientProxyImpl impl; if (actualState == null) { impl = new MicroProfileClientProxyImpl(URI.create(getAddress()), proxyLoader, cri, isRoot, inheritHeaders, executorService, configuration, interceptorWrapper, varValues); } else { impl = new MicroProfileClientProxyImpl(actualState, proxyLoader, cri, isRoot, inheritHeaders, executorService, configuration, interceptorWrapper, varValues); } return impl; }

Target:
protected ClientProxyImpl createClientProxy(ClassResourceInfo cri, boolean isRoot, ClientState actualState, Object[] varValues) { CDIInterceptorWrapper interceptorWrapper = CDIInterceptorWrapper.createWrapper(getServiceClass()); if (actualState == null) { return new MicroProfileClientProxyImpl(URI.create(getAddress()), proxyLoader, cri, isRoot, inheritHeaders, executorService, configuration, interceptorWrapper, varValues); } else { return new MicroProfileClientProxyImpl(actualState, proxyLoader, cri, isRoot, inheritHeaders, executorService, configuration, interceptorWrapper, varValues); } }
Source:
private String userKey(User user) { User.Profile profile = user.getUserProfiles().get(TokenType.GOOGLE_COM.toString()); String email = profile == null ? null : profile.email; return email == null ? user.getUsername() : email; }

Target:
private String userKey(User user) { User.Profile profile = user.getUserProfiles().get(TokenType.GOOGLE_COM.toString()); if (profile == null || profile.email == null) { return user.getUsername(); } else { return profile.email; } }
Source:
public static void beforeClass() throws UnknownHostException, MalformedURLException { String ipAddress = startAppiumServer(); if (service == null || !service.isRunning()) { throw new AppiumServerHasNotBeenStartedLocallyException( "An appium server node is not started!"); } File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "UICatalog.app.zip"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "9.2"); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone 6"); capabilities.setCapability(IOSMobileCapabilityType.LAUNCH_TIMEOUT, 500000); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); driver = new IOSDriver<>(new URL("http://" + ipAddress + ":4723/wd/hub"), capabilities); }

Target:
public static void beforeClass() throws UnknownHostException, MalformedURLException { String ipAddress = startAppiumServer(); if (service == null || !service.isRunning()) { throw new AppiumServerHasNotBeenStartedLocallyException( "An appium server node is not started!"); } File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "UICatalog.app.zip"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, ""); capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "9.2"); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone 6"); capabilities.setCapability(IOSMobileCapabilityType.LAUNCH_TIMEOUT, 500000); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); driver = new IOSDriver<>(new URL("http://" + ipAddress + ":" + PORT + "/wd/hub"), capabilities); }
Source:
public ConsumerThread( final AsyncFramework async, final String name, final ConsumerReporter reporter, final KafkaStream<byte[], byte[]> stream, final ConsumerSchema.Consumer schema, final AtomicInteger active, final AtomicLong errors, final LongAdder consumed, final boolean enablePeriodicCommit, final long periodicCommitInterval, final AtomicLong nextOffsetsCommitTSGlobal ) { super(String.format("%s: %s", ConsumerThread.class.getCanonicalName(), name)); this.async = async; this.name = name; this.reporter = reporter; this.stream = stream; this.schema = schema; this.active = active; this.errors = errors; this.consumed = consumed; this.enablePeriodicCommit = enablePeriodicCommit; this.outstandingConsumptionRequests = Collections.newSetFromMap(new ConcurrentHashMap()); this.periodicCommitInterval = periodicCommitInterval; this.nextOffsetsCommitTSGlobal = nextOffsetsCommitTSGlobal; this.nextOffsetsCommitTSThreadLocal = this.nextOffsetsCommitTSGlobal.get(); this.coordinator = null; this.hasStopped = async.future(); }

Target:
public ConsumerThread( final AsyncFramework async, final String name, final ConsumerReporter reporter, final KafkaStream<byte[], byte[]> stream, final ConsumerSchema.Consumer schema, final AtomicInteger active, final AtomicLong errors, final LongAdder consumed, final boolean enablePeriodicCommit, final long periodicCommitInterval, final AtomicLong nextOffsetsCommitTSGlobal ) { super(String.format("%s: %s", ConsumerThread.class.getCanonicalName(), name)); this.async = async; this.name = name; this.reporter = reporter; this.stream = stream; this.schema = schema; this.active = active; this.errors = errors; this.consumed = consumed; this.enablePeriodicCommit = enablePeriodicCommit; this.outstandingConsumptionRequests = new ConcurrentHashMap<Long, Boolean>(); this.periodicCommitInterval = periodicCommitInterval; this.nextOffsetsCommitTSGlobal = nextOffsetsCommitTSGlobal; this.nextOffsetsCommitTSThreadLocal = this.nextOffsetsCommitTSGlobal.get(); this.coordinator = null; this.hasStopped = async.future(); }
Source:
protected void expectMessage(DTLSMessage message) throws HandshakeException { if (useStateValidation && states != null) { if (statesIndex >= states.length) { LOGGER.warn("Cannot process message from peer [{}], no more expected!", HandshakeState.toString(message), getSession().getPeer()); AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.INTERNAL_ERROR, session.getPeer()); throw new HandshakeException("Cannot process " + HandshakeState.toString(message) + " handshake message, no more expected!", alert); } HandshakeState expectedState = states[statesIndex]; boolean expected = expectedState.expect(message); if (!expected && expectedState.isOptional()) { if (statesIndex + 1 < states.length) { HandshakeState nextExpectedState = states[statesIndex + 1]; if (nextExpectedState.expect(message)) { ++statesIndex; expectedState = nextExpectedState; expected = true; } } } if (!expected) { LOGGER.warn("Cannot process message from peer [{}], expected!", HandshakeState.toString(message), getSession().getPeer(), expectedState); AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.INTERNAL_ERROR, session.getPeer()); throw new HandshakeException("Cannot process " + HandshakeState.toString(message) + " handshake message, " + expectedState + " expected!", alert); } } }

Target:
protected void expectMessage(DTLSMessage message) throws HandshakeException { if (useStateValidation && states != null) { if (statesIndex >= states.length) { LOGGER.warn("Cannot process message from peer [{}], no more expected!", HandshakeState.toString(message), getSession().getPeer()); AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.INTERNAL_ERROR, session.getPeer()); throw new HandshakeException("Cannot process " + HandshakeState.toString(message) + " handshake message, no more expected!", alert); } HandshakeState expectedState = states[statesIndex]; boolean expected = expectedState.expect(message); if (!expected && expectedState.isOptional()) { if (statesIndex + 1 < states.length) { HandshakeState nextExpectedState = states[statesIndex + 1]; if (nextExpectedState.expect(message)) { ++statesIndex; expected = true; } } } if (!expected) { LOGGER.warn("Cannot process message from peer [{}], expected!", HandshakeState.toString(message), getSession().getPeer(), expectedState); AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.INTERNAL_ERROR, session.getPeer()); throw new HandshakeException("Cannot process " + HandshakeState.toString(message) + " handshake message, " + expectedState + " expected!", alert); } } }
Source:
public void handle(Willie bot, Channel channel, User sender, String[] args) { String cmdPrefix = bot.getConfig().getCommandPrefix(); for (Command command : bot.commandManager.getCommands()) { if (command.isAdminOnly() && channel.getOps().contains(sender)) { sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); } else { sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); } } }

Target:
public void handle(Willie bot, Channel channel, User sender, String[] args) { String cmdPrefix = bot.getConfig().getCommandPrefix(); for (Command command : bot.commandManager.getCommands()) { if (command.isAdminOnly()) { if (channel.getOps().contains(sender)) { sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); } } else { sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); } } }
Source:
public int line(Actor actor, EditSession editSession, @Selection Region region, @Arg(desc = "The pattern of blocks to place") Pattern pattern, @Arg(desc = "The thickness of the line", def = "0") int thickness, @Switch(name = 'h', desc = "Generate only a shell") boolean shell) throws WorldEditException { if (!((region instanceof CuboidRegion) || (region instanceof ConvexPolyhedralRegion))) { actor.printError(" return 0; } checkCommandArgument(thickness >= 0, "Thickness must be >= 0"); List<BlockVector3> vectors; if(region instanceof CuboidRegion) { CuboidRegion cuboidregion = (CuboidRegion) region; vectors = Lists.newArrayList(cuboidregion.getPos1(), cuboidregion.getPos2()); } else { ConvexPolyhedralRegion convexregion = (ConvexPolyhedralRegion) region; vectors = new ArrayList<>(convexregion.getVertices()); } int blocksChanged = editSession.drawLine(pattern, vectors, thickness, !shell); actor.print(blocksChanged + " block(s) have been changed."); return blocksChanged; }

Target:
public int line(Actor actor, EditSession editSession, @Selection Region region, @Arg(desc = "The pattern of blocks to place") Pattern pattern, @Arg(desc = "The thickness of the line", def = "0") int thickness, @Switch(name = 'h', desc = "Generate only a shell") boolean shell) throws WorldEditException { if (!((region instanceof CuboidRegion) || (region instanceof ConvexPolyhedralRegion))) { actor.printError(" return 0; } checkCommandArgument(thickness >= 0, "Thickness must be >= 0"); List<BlockVector3> vectors; if (region instanceof CuboidRegion) { CuboidRegion cuboidRegion = (CuboidRegion) region; vectors = ImmutableList.of(cuboidRegion.getPos1(), cuboidRegion.getPos2()); } else { ConvexPolyhedralRegion convexRegion = (ConvexPolyhedralRegion) region; vectors = ImmutableList.copyOf(convexRegion.getVertices()); } int blocksChanged = editSession.drawLine(pattern, vectors, thickness, !shell); actor.print(blocksChanged + " block(s) have been changed."); return blocksChanged; }
Source:
public void reportMetric(final IMetric<?> metric) { if (metric != null && isAvailable()) { try { final IMetric<?> metricSnapshot; synchronized (metric) { metricSnapshot = metric.getSnapshot(); } _logger.debug(String.format("Submitting %s metric for metric emission pool", metricSnapshot.getName())); for (final IMetricEmitter metricEmitter : _metricEmitters) { _executorService.submit(new Runnable() { @Override public void run() { try { metricEmitter.reportMetric(metricSnapshot); } catch (Exception ex) { _logger.error(String.format("Failed to report %s metric due to %s", metricSnapshot.getName(), ex.toString())); } } }); } } catch (CloneNotSupportedException ex) { _logger.error(String.format("Failed to take snapshot for %s metric %s", metric.getClass().getName(), ex.toString())); } } }

Target:
public void reportMetric(final IMetric<?> metric) { if (metric != null && isAvailable()) { try { final IMetric<?> metricSnapshot; synchronized (metric) { metricSnapshot = metric.getSnapshot(); } logger.debug(String.format("Submitting %s metric for metric emission pool", metricSnapshot.getName())); for (final IMetricEmitter metricEmitter : metricEmitters) { executorService.submit(new Runnable() { @Override public void run() { try { metricEmitter.reportMetric(metricSnapshot); } catch (Exception ex) { logger.error(String.format("Failed to report %s metric due to ", metricSnapshot.getName()), ex); } } }); } } catch (CloneNotSupportedException ex) { logger.error(String.format("Failed to take snapshot for %s metric", metric.getClass().getName()), ex); } } }
Source:
protected List<VmStatic> filterVmsInClusterNeedUpdate() { if (Objects.equals(oldCluster.getCompatibilityVersion(), getCluster().getCompatibilityVersion())) { return Collections.emptyList(); } return vmStaticDao.getAllByCluster(getCluster().getId()).stream() .filter(vm -> vm.getOrigin() != OriginType.EXTERNAL && !vm.isHostedEngine()) .filter(vm -> vm.getCustomCompatibilityVersion() == null) .sorted() .collect(Collectors.toList()); }

Target:
protected List<VmStatic> filterVmsInClusterNeedUpdate() { return vmStaticDao.getAllByCluster(getCluster().getId()).stream() .filter(vm -> vm.getOrigin() != OriginType.EXTERNAL && !vm.isHostedEngine()) .filter(vm -> vm.getCustomCompatibilityVersion() == null) .sorted() .collect(Collectors.toList()); }
Source:
private UpgradePack findUpgradePack(StackId sourceStack, StackId stackToFind, UpgradeType upgradeType, boolean compareToSource) throws AmbariException { Map<String, UpgradePack> packs = m_ambariMetaInfoProvider.get().getUpgradePacks( sourceStack.getStackName(), sourceStack.getStackVersion()); UpgradePack result = null; for (UpgradePack upgradePack : packs.values()) { StackId upgradeStack = compareToSource ? new StackId(upgradePack.getSourceStack()) : new StackId(upgradePack.getTargetStack()); if (upgradeStack.equals(stackToFind) && upgradePack.getType().equals(upgradeType)) { if (null == result) { result = upgradePack; } else { throw new AmbariException( String.format( "Unable to resolve upgrade pack. Found multiple upgrade packs for type %s and stack %s", upgradeType.toString(), stackToFind)); } } } return result; }

Target:
private UpgradePack findUpgradePack(StackId sourceStack, StackId stackToFind, UpgradeType upgradeType, boolean compareToSource) throws AmbariException { Map<String, UpgradePack> packs = m_ambariMetaInfoProvider.get().getUpgradePacks( sourceStack.getStackName(), sourceStack.getStackVersion()); UpgradePack result = null; for (UpgradePack upgradePack : packs.values()) { StackId upgradeStack = compareToSource ? new StackId(upgradePack.getSourceStack()) : new StackId(upgradePack.getTargetStack()); if (upgradeStack.equals(stackToFind) && upgradePack.getType() == upgradeType) { if (null == result) { result = upgradePack; } else { throw new AmbariException( String.format( "Unable to resolve upgrade pack. Found multiple upgrade packs for type %s and stack %s", upgradeType.toString(), stackToFind)); } } } return result; }
Source:
public void testApplywithCounter() throws DbException { final Schema schema = Schema.ofFields("char_sequence", Type.STRING_TYPE); final Schema expectedResultSchema = Schema.ofFields("ngrams", Type.STRING_TYPE, "flatmapid", Type.INT_TYPE); final TupleBatchBuffer input = new TupleBatchBuffer(schema); StringBuilder sb = new StringBuilder(); for (int i = 0; i < CHAR_SEQ_LEN; ++i) { sb.append((char) i); } input.putString(0, sb.toString()); ImmutableList.Builder<Expression> expressions = ImmutableList.builder(); ExpressionOperator colIdx = new VariableExpression(0); ExpressionOperator ngramLen = new ConstantExpression(NGRAM_LEN); ExpressionOperator split = new NgramExpression(colIdx, ngramLen); Expression expr = new Expression("ngrams", split); expressions.add(expr); Apply apply = new Apply(new BatchTupleSource(input), expressions.build(), true); apply.open(TestEnvVars.get()); long rowIdx = 0; while (!apply.eos()) { TupleBatch result = apply.nextReady(); if (result != null) { assertEquals(expectedResultSchema, result.getSchema()); for (int batchIdx = 0; batchIdx < result.numTuples(); ++batchIdx, ++rowIdx) { char[] ngramChars = new char[] {(char) rowIdx, (char) (rowIdx + 1), (char) (rowIdx + 2)}; String ngram = new String(ngramChars); int fltmapid = (int) rowIdx; assertEquals(ngram, result.getString(0, batchIdx)); assertEquals(fltmapid, result.getInt(1, batchIdx)); } } } assertEquals(EXPECTED_RESULTS, rowIdx); apply.close(); }

Target:
public void testApplywithCounter() throws DbException { final Schema schema = Schema.ofFields("char_sequence", Type.STRING_TYPE); final Schema expectedResultSchema = Schema.ofFields("ngrams", Type.STRING_TYPE, "flatmapid", Type.INT_TYPE); final TupleBatchBuffer input = new TupleBatchBuffer(schema); StringBuilder sb = new StringBuilder(); for (int i = 0; i < CHAR_SEQ_LEN; ++i) { sb.append((char) i); } input.putString(0, sb.toString()); ImmutableList.Builder<Expression> expressions = ImmutableList.builder(); ExpressionOperator colIdx = new VariableExpression(0); ExpressionOperator ngramLen = new ConstantExpression(NGRAM_LEN); ExpressionOperator split = new NgramExpression(colIdx, ngramLen); Expression expr = new Expression("ngrams", split); expressions.add(expr); Apply apply = new Apply(new BatchTupleSource(input), expressions.build(), true); apply.open(TestEnvVars.get()); int rowIdx = 0; while (!apply.eos()) { TupleBatch result = apply.nextReady(); if (result != null) { assertEquals(expectedResultSchema, result.getSchema()); for (int batchIdx = 0; batchIdx < result.numTuples(); ++batchIdx, ++rowIdx) { char[] ngramChars = new char[] {(char) rowIdx, (char) (rowIdx + 1), (char) (rowIdx + 2)}; String ngram = new String(ngramChars); int fltmapid = rowIdx; assertEquals(ngram, result.getString(0, batchIdx)); assertEquals(fltmapid, result.getInt(1, batchIdx)); } } } assertEquals(EXPECTED_RESULTS, rowIdx); apply.close(); }
Source:
public void should_associate_all_quality_gates_to_default_organization() throws SQLException { String orgUuid1 = uuidFactory.create(); String orgUuid2 = uuidFactory.create(); insertOrganization(orgUuid1); insertOrganization(orgUuid2); String qgUuid1 = uuidFactory.create(); String qgUuid2 = uuidFactory.create(); String qgUuid3 = uuidFactory.create(); insertQualityGate(qgUuid1, "QualityGate1", false); insertQualityGate(qgUuid2, "QualityGate2", false); insertQualityGate(qgUuid3, "QualityGate3", true); insertDefaultOrgProperty(orgUuid1); underTest.execute(); assertThat(selectAllOrgQualityGates()) .extracting(map -> map.get("ORGANIZATION_UUID"), map -> map.get("QUALITY_GATE_UUID")) .containsExactlyInAnyOrder( tuple(orgUuid1, qgUuid1), tuple(orgUuid1, qgUuid2) ); }

Target:
public void should_associate_all_quality_gates_to_default_organization() throws SQLException { String defaultOrgUuid = uuidFactory.create(); String anotherOrgUuid = uuidFactory.create(); insertOrganization(defaultOrgUuid); insertOrganization(anotherOrgUuid); String qgUuid1 = uuidFactory.create(); String qgUuid2 = uuidFactory.create(); String qgUuid3 = uuidFactory.create(); insertQualityGate(qgUuid1, "QualityGate1", false); insertQualityGate(qgUuid2, "QualityGate2", false); insertQualityGate(qgUuid3, "QualityGate3", true); insertDefaultOrgProperty(defaultOrgUuid); underTest.execute(); assertThat(selectAllOrgQualityGates()) .extracting(map -> map.get("ORGANIZATION_UUID"), map -> map.get("QUALITY_GATE_UUID")) .containsExactlyInAnyOrder( tuple(defaultOrgUuid, qgUuid1), tuple(defaultOrgUuid, qgUuid2) ); }
Source:
public WeekDiffFunction(String template) { super("day_diff", template); }

Target:
public WeekDiffFunction(String template) { super("week_diff", template); }
Source:
public void centerMapToPlace(Place place) { if (nearbyMapFragment == null) { nearbyMapFragment.nearbyplace = place; } else { nearbyMapFragment.centerMapToPlace(place); } }

Target:
public void centerMapToPlace(Place place) { if (nearbyMapFragment != null) { nearbyMapFragment.centerMapToPlace(place); } }
Source:
protected boolean validateLeaseStorageDomain(Guid leaseStorageDomainId) { StorageDomain domain = storageDomainDao.getForStoragePool(leaseStorageDomainId, getStoragePoolId()); StorageDomainValidator validator = new StorageDomainValidator(domain); if (!validate(validator.isDomainExistAndActive()) || !validate(validator.isDataDomain())) { return false; } return true; }

Target:
protected boolean validateLeaseStorageDomain(Guid leaseStorageDomainId) { StorageDomain domain = storageDomainDao.getForStoragePool(leaseStorageDomainId, getStoragePoolId()); StorageDomainValidator validator = new StorageDomainValidator(domain); return (validate(validator.isDomainExistAndActive()) && validate(validator.isDataDomain())); }
Source:
public boolean canSubmit() { if ("refs/meta/config".equals(refName)) { return getProjectControl().isOwner(); } return canPerform(Permission.SUBMIT); }

Target:
public boolean canSubmit() { if (GitRepositoryManager.REF_CONFIG.equals(refName)) { return getProjectControl().isOwner(); } return canPerform(Permission.SUBMIT); }
Source:
private void replicateProjectLocally(final Project.NameKey projectName, final URIish replicateURI, final String head) { Repository repo = null; try { repo = gitRepositoryManager.openRepository(projectName); FileUtils.copyDirectory(repo.getDirectory(), new File(replicateURI.getPath())); } catch (RepositoryNotFoundException e) { log.error("Failed to replicate project locally: " + replicateURI.toString()); } catch (IOException e) { log.error("Failed to replicate project locally: " + replicateURI.toString()); } finally { if (repo != null) { repo.close(); } } }

Target:
private void replicateProjectLocally(final Project.NameKey projectName, final URIish replicateURI, final String head) { try { final Repository repo = gitRepositoryManager.openRepository(projectName); try { FileUtils.copyDirectory(repo.getDirectory(), new File(replicateURI.getPath())); } catch (IOException e) { log.error("Failed to replicate project locally: " + replicateURI.toString()); } finally { repo.close(); } } catch (RepositoryNotFoundException e) { log.error("Failed to replicate project locally: " + replicateURI.toString()); } }
Source:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { logger.debug("Validate "+item+" bind:"+bindingConfig); String[] configParts = bindingConfig.trim().split(":"); if (configParts.length < 1) { throw new BindingConfigParseException( "Tellstick binding must contain two parts separated by ':'"); } TellstickDevice device; try { device = findDevice(configParts[0].trim()); } catch (SupportedMethodsException e) { throw new BindingConfigParseException(e.getMessage()); } if (device == null && !StringUtils.isNumeric(configParts[0].trim())) { throw new BindingConfigParseException("item '" + item.getName() + "' telldus device "+configParts[0].trim()+" not found"); } if (configParts.length > 3 && !StringUtils.isNumeric(configParts[3].trim())) { throw new BindingConfigParseException("item '" + item.getName() + "' resend config wrong"+configParts[3].trim()+" not a number"); } }

Target:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (!(item instanceof SwitchItem || item instanceof NumberItem || item instanceof DimmerItem)) { throw new BindingConfigParseException( "item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() + "', only Number and Switch- and DimmerItems are allowed - please check your *.items configuration"); } }
Source:
private void terminateTasks(final SchedulingService service) { if (tasksToTerminate.values().isEmpty()) { return; } ExecutorService parallelTerminationService = Executors.newFixedThreadPool(tasksToTerminate.values().size()); try { List<Callable<Void>> callables = new ArrayList<>(tasksToTerminate.values().size()); for (final TaskTerminationData taskToTerminate : tasksToTerminate.values()) { callables.add(new Callable<Void>() { @Override public Void call() throws Exception { try { RunningTaskData taskData = taskToTerminate.taskData; if (taskToTerminate.terminatedWhileRunning()) { terminateRunningTask(service, taskToTerminate, taskData); } } catch (Throwable e) { logger.error("Failed to terminate task " + taskToTerminate.taskData.getTask().getName(), e); throw new RuntimeException(e); } return null; } }); } parallelTerminationService.invokeAll(callables); } catch (Exception e) { logger.error("Failed to terminate tasks ", e); } }

Target:
private void terminateTasks(final SchedulingService service) { if (tasksToTerminate.values().isEmpty()) { return; } ExecutorService parallelTerminationService = Executors.newFixedThreadPool(tasksToTerminate.values().size()); try { List<Callable<Void>> callables = new ArrayList<>(tasksToTerminate.values().size()); for (final TaskTerminationData taskToTerminate : tasksToTerminate.values()) { callables.add(new Callable<Void>() { @Override public Void call() throws Exception { try { RunningTaskData taskData = taskToTerminate.taskData; if (taskToTerminate.terminatedWhileRunning()) { terminateRunningTask(service, taskToTerminate, taskData); } } catch (Throwable e) { logger.error("Failed to terminate task " + taskToTerminate.taskData.getTask().getName(), e); throw new RuntimeException(e); } return null; } }); } parallelTerminationService.invokeAll(callables); } catch (Exception e) { logger.error("Failed to terminate tasks ", e); } finally { parallelTerminationService.shutdown(); } }
Source:
public void setupDocument(IDocument newDocument) { if (newDocument != null) { fLineBackgroundListener.setCurrentDocument(newDocument); if(positionUpdaterAddedDocuments.contains(newDocument)) { return; } newDocument.addPositionCategory(PresentationReconcilerCPP.SEMANTIC_HIGHLIGHTING_POSITION_CATEGORY); DefaultPositionUpdater semanticPositionUpdater = new DefaultPositionUpdater(SEMANTIC_HIGHLIGHTING_POSITION_CATEGORY); newDocument.addPositionUpdater(semanticPositionUpdater); newDocument.addPositionCategory(PresentationReconcilerCPP.INACTIVE_CODE_HIGHLIGHTING_POSITION_CATEGORY); DefaultPositionUpdater inactiveCodePositionUpdater = new DefaultPositionUpdater(INACTIVE_CODE_HIGHLIGHTING_POSITION_CATEGORY); newDocument.addPositionUpdater(inactiveCodePositionUpdater); positionUpdaterAddedDocuments.add(newDocument); } }

Target:
public void setupDocument(IDocument newDocument) { if (newDocument != null) { fLineBackgroundListener.setCurrentDocument(newDocument); newDocument.addPositionCategory(SEMANTIC_HIGHLIGHTING_POSITION_CATEGORY); semanticHighlightingPositionUpdater = new DefaultPositionUpdater(SEMANTIC_HIGHLIGHTING_POSITION_CATEGORY); newDocument.addPositionUpdater(semanticHighlightingPositionUpdater); newDocument.addPositionCategory(INACTIVE_CODE_HIGHLIGHTING_POSITION_CATEGORY); DefaultPositionUpdater inactiveCodeHighlightingPositionUpdater = new DefaultPositionUpdater(INACTIVE_CODE_HIGHLIGHTING_POSITION_CATEGORY); newDocument.addPositionUpdater(inactiveCodeHighlightingPositionUpdater); } }
Source:
public ResultMatcher hasLinkWithRel(final String rel) { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { MockHttpServletResponse response = result.getResponse(); String s = response.getContentAsString(); assertThat("Expected to find link with rel " + rel + " but found none in " + s, getDiscoverer(response).findLinkWithRel(rel, s), notNullValue()); } }; }

Target:
public ResultMatcher hasLinkWithRel(final String rel) { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { MockHttpServletResponse response = result.getResponse(); String s = response.getContentAsString(); assertThat(getDiscoverer(response).findLinkWithRel(rel, s)) .describedAs("Expected to find link with rel " + rel + " but found none in " + s) .isNotNull(); } }; }
Source:
protected boolean isRefreshNeeded(List<InputSplit> inputSplits, byte[] scanStartRow, byte[] scanStopRow) { assert inputSplits.stream().allMatch(is -> (is instanceof SMSplit)) : "items expected to be instanceof SMSplit"; if (inputSplits.size() < 2) { return !splitContainsScan((SMSplit) inputSplits.get(0), scanStartRow, scanStopRow); } else { inputSplits.sort(new Comparator<InputSplit>() { @Override public int compare(InputSplit o1, InputSplit o2) { SMSplit smSplit1 = (SMSplit) o1; SMSplit smSplit2 = (SMSplit) o2; return compareRows(smSplit1.split.getStartRow(), smSplit2.split.getStartRow()); } }); for (int i = 1; i < inputSplits.size(); i++) { byte currentStartRow[] = ((SMSplit) inputSplits.get(i)).split.getStartRow(); byte prevEndRow[] = ((SMSplit) inputSplits.get(i - 1)).split.getEndRow(); if (compareRows(currentStartRow, prevEndRow) != 0) { LOG.warn("The gap in splits is found: current split [" + inputSplits.get(i) + "], previous split [" + inputSplits.get(i - 1) + "]"); return true; } } SMSplit firstSplit = (SMSplit) inputSplits.get(0); SMSplit lastSplit = (SMSplit) inputSplits.get(inputSplits.size() - 1); if (compareRows(firstSplit.split.getStartRow(), scanStartRow) != 0 || compareRows(lastSplit.split.getEndRow(), scanStopRow) != 0) { return true; } } return false; }

Target:
protected boolean isRefreshNeeded(List<InputSplit> inputSplits, byte[] scanStartRow, byte[] scanStopRow) { assert inputSplits.stream().allMatch(is -> (is instanceof SMSplit)) : "items expected to be instanceof SMSplit"; if (inputSplits.size() < 2) { return !splitContainsScan((SMSplit) inputSplits.get(0), scanStartRow, scanStopRow); } else { inputSplits.sort(new Comparator<InputSplit>() { @Override public int compare(InputSplit o1, InputSplit o2) { SMSplit smSplit1 = (SMSplit) o1; SMSplit smSplit2 = (SMSplit) o2; return compareRows(smSplit1.split.getStartRow(), smSplit2.split.getStartRow()); } }); for (int i = 1; i < inputSplits.size(); i++) { byte currentStartRow[] = ((SMSplit) inputSplits.get(i)).split.getStartRow(); byte prevEndRow[] = ((SMSplit) inputSplits.get(i - 1)).split.getEndRow(); if (compareRows(currentStartRow, prevEndRow) != 0) { LOG.warn("The gap in splits is found: current split [" + inputSplits.get(i) + "], previous split [" + inputSplits.get(i - 1) + "]"); return true; } } SMSplit firstSplit = (SMSplit) inputSplits.get(0); SMSplit lastSplit = (SMSplit) inputSplits.get(inputSplits.size() - 1); if (compareRows(firstSplit.split.getStartRow(), scanStartRow) > 0 || (lastSplit.split.getEndRow().length != 0 && compareRows(lastSplit.split.getEndRow(), scanStopRow) < 0)) { return true; } } return false; }
Source:
public String toBase64(int jpegQualityPercent) { return Base64.encodeToString(toJpeg(currentRepresentation, jpegQualityPercent), Base64.DEFAULT); }

Target:
public String toBase64(int jpegQualityPercent) { return Base64.encodeToString(toJpeg(currentRepresentation, jpegQualityPercent), Base64.NO_WRAP); }
Source:
public void testAnyOtherObjectQueryExpression() { R2dbcMessageHandler handler = new R2dbcMessageHandler(this.entityTemplate); handler.setBeanFactory(mock(BeanFactory.class)); handler.setApplicationContext(mock(ApplicationContext.class, Answers.RETURNS_MOCKS)); handler.afterPropertiesSet(); Message<Person> message = MessageBuilder.withPayload(this.createPerson("Bob", 35)).build(); waitFor(handler.handleMessage(message)); message = MessageBuilder.withPayload(this.createPerson("Tom", 40)).build(); waitFor(handler.handleMessage(message)); R2dbcMessageSource messageSource = new R2dbcMessageSource(this.entityTemplate, new ValueExpression<>(new Object())); messageSource.setBeanFactory(mock(BeanFactory.class)); messageSource.afterPropertiesSet(); messageSource.setPayloadType(Person.class); messageSource.setExpectSingleResult(true); Assertions.assertThrows(IllegalStateException.class, () -> messageSource.receive().getPayload()); }

Target:
public void testAnyOtherObjectQueryExpression() { StepVerifier.create((Flux<?>) r2dbcMessageSourceError.receive().getPayload()) .expectErrorMatches(throwable -> throwable instanceof IllegalStateException && throwable.getMessage().contains("'queryExpression' must evaluate to String or")) .verify(); }
Source:
public static String getContext() { return Bugsnag.getClient().getContext(); }

Target:
public static String getContext() { return getClient().getContext(); }
Source:
public long getLatestEstimate() { return 0; }

Target:
public long getLatestEstimate() { synchronized (critSect) { long bitrateBps; if (!remoteRate.isValidEstimate()) { return -1; } if (ssrcs_.isEmpty()) { bitrateBps = 0; } else { bitrateBps = remoteRate.getLatestEstimate(); } return bitrateBps; } }
Source:
public static boolean isSupportedCRS(GridCoverage2DReader reader, CoordinateReferenceSystem crs) throws FactoryException, IOException { String multiCrsReader = reader.getMetadataValue(AbstractGridCoverage2DReader.MULTICRS_READER); boolean isMultiCRS = multiCrsReader != null && Boolean.valueOf(multiCrsReader); String supportedEpsgCodes = ""; if (isMultiCRS) { supportedEpsgCodes = reader.getMetadataValue(AbstractGridCoverage2DReader.MULTICRS_EPSGCODES); } if (!StringUtils.isBlank(supportedEpsgCodes) && crs != null) { Integer targetCRSEpsgCode = CRS.lookupEpsgCode(crs, true); if (targetCRSEpsgCode != null) { String code = String.valueOf(targetCRSEpsgCode); supportedEpsgCodes = supportedEpsgCodes.replaceAll("[^0-9,]", ""); String[] epsgCodes = supportedEpsgCodes.split(","); for (String epsgCode : epsgCodes) { if (code.equalsIgnoreCase(epsgCode)) { return true; } } } } return false; }

Target:
public static boolean isSupportedCRS(GridCoverage2DReader reader, CoordinateReferenceSystem crs) throws FactoryException, IOException { String multiCrsReader = reader.getMetadataValue(AbstractGridCoverage2DReader.MULTICRS_READER); boolean isMultiCRS = multiCrsReader != null && Boolean.valueOf(multiCrsReader); String supportedEpsgCodes = ""; if (isMultiCRS) { supportedEpsgCodes = reader.getMetadataValue(AbstractGridCoverage2DReader.MULTICRS_EPSGCODES); } if (!StringUtils.isBlank(supportedEpsgCodes) && crs != null) { Integer targetCRSEpsgCode = CRS.lookupEpsgCode(crs, false); if (targetCRSEpsgCode != null) { String code = String.valueOf(targetCRSEpsgCode); supportedEpsgCodes = supportedEpsgCodes.replaceAll("[^0-9,]", ""); String[] epsgCodes = supportedEpsgCodes.split(","); for (String epsgCode : epsgCodes) { if (code.equalsIgnoreCase(epsgCode)) { return true; } } } } return false; }
Source:
private static <R extends Named> ImmutableList<NamedLookup<R>> parseProviders( IniFile config, Class<R> enumType) { if (!config.contains("providers")) { return ImmutableList.of(); } PropertySet section = config.getSection("providers"); ImmutableList.Builder<NamedLookup<R>> builder = ImmutableList.builder(); for (String key : section.keys()) { Class<?> cls; try { cls = RenameHandler.INSTANCE.lookupType(key); } catch (Exception ex) { throw new IllegalArgumentException("Unable to find enum provider class: " + key, ex); } String value = section.getValue(key); if (value.equals("constants")) { builder.add(parseConstants(enumType, cls)); } else if (value.equals("lookup")) { if (!NamedLookup.class.isAssignableFrom(cls)) { throw new IllegalArgumentException("Enum provider class must implement NamedLookup " + cls.getName()); } try { Constructor<?> cons = cls.getDeclaredConstructor(); if (Modifier.isPublic(cls.getModifiers()) == false) { cons.setAccessible(true); } builder.add((NamedLookup<R>) cons.newInstance()); } catch (Exception ex) { throw new IllegalArgumentException("Invalid enum provider constructor: new " + cls.getName() + "()", ex); } } else { throw new IllegalArgumentException("Provider value must be either 'constants' or 'lookup'"); } } return builder.build(); }

Target:
private static <R extends Named> ImmutableList<NamedLookup<R>> parseProviders( IniFile config, Class<R> enumType) { if (!config.contains(PROVIDERS_SECTION)) { return ImmutableList.of(); } PropertySet section = config.getSection(PROVIDERS_SECTION); ImmutableList.Builder<NamedLookup<R>> builder = ImmutableList.builder(); for (String key : section.keys()) { Class<?> cls; try { cls = RenameHandler.INSTANCE.lookupType(key); } catch (Exception ex) { throw new IllegalArgumentException("Unable to find enum provider class: " + key, ex); } String value = section.getValue(key); if (value.equals("constants")) { builder.add(parseConstants(enumType, cls)); } else if (value.equals("lookup")) { if (!NamedLookup.class.isAssignableFrom(cls)) { throw new IllegalArgumentException("Enum provider class must implement NamedLookup " + cls.getName()); } try { Constructor<?> cons = cls.getDeclaredConstructor(); if (Modifier.isPublic(cls.getModifiers()) == false) { cons.setAccessible(true); } builder.add((NamedLookup<R>) cons.newInstance()); } catch (Exception ex) { throw new IllegalArgumentException("Invalid enum provider constructor: new " + cls.getName() + "()", ex); } } else { throw new IllegalArgumentException("Provider value must be either 'constants' or 'lookup'"); } } return builder.build(); }
Source:
private void runParallelLoad(final RDFFormat rdfFormat, final String baseURI, final String defaultGraph, BigdataSailConnection conn, List<File> files) throws InterruptedException, SailException { BlockingQueue<File> fileQueue = new LinkedBlockingDeque<>(files); BlockingQueue<TmpStore> tmpStoreQueue = new LinkedBlockingDeque<>(); Collection<Callable<Integer>> allTasks = new ArrayList<>(); AbstractTripleStore db = conn.getTripleStore(); ExecutorService executorService = db.getExecutorService(); Semaphore tmpQueueSemaphore = new Semaphore(tmpQueueLimit); for (int i = 0; i < fileReadersCount; i++) { allTasks.add(new FileReaderTask(fileQueue, tmpStoreQueue, tmpQueueSemaphore, db, baseURI, rdfFormat, defaultGraph, maxTmpStatementsSize)); } for (int i = 0; i < mergersCount; i++) { allTasks.add(new MergerTask(fileQueue, tmpStoreQueue, tmpQueueSemaphore, db, maxTmpStatementsSize)); } long startTime = System.currentTimeMillis(); List<Future<Integer>> results = executorService.invokeAll(allTasks); int merges = results.stream().collect(Collectors.summingInt(f -> { try { return f.get(); } catch (InterruptedException | ExecutionException e) { log.error("Error collecting stats", e); return 0; } })); log.info("allTasks completed in with merges, dbsize {}", System.currentTimeMillis() - startTime, merges, db.getStatementCount(true)); conn.commit(); log.info("CONN commit."); }

Target:
private void runParallelLoad(final RDFFormat rdfFormat, final String baseURI, final String defaultGraph, BigdataSailConnection conn, List<File> files) throws InterruptedException, SailException { BlockingQueue<File> fileQueue = new LinkedBlockingDeque<>(files); BlockingQueue<TmpStore> tmpStoreQueue = new LinkedBlockingDeque<>(); Collection<Callable<Integer>> allTasks = new ArrayList<>(); AbstractTripleStore db = conn.getTripleStore(); ExecutorService executorService = db.getExecutorService(); Semaphore tmpQueueSemaphore = new Semaphore(tmpQueueLimit); for (int i = 0; i < fileReadersCount; i++) { allTasks.add(new FileReaderTask(fileQueue, tmpStoreQueue, tmpQueueSemaphore, db, baseURI, rdfFormat, defaultGraph, maxTmpStatementsSize)); } for (int i = 0; i < mergersCount; i++) { allTasks.add(new MergerTask(fileQueue, tmpStoreQueue, tmpQueueSemaphore, db, maxTmpStatementsSize)); } long startTime = System.currentTimeMillis(); List<Future<Integer>> results = executorService.invokeAll(allTasks); int merges = results.stream().collect(Collectors.summingInt(f -> { try { return f.get(); } catch (InterruptedException | ExecutionException e) { log.error("Error collecting stats", e); return 0; } })); log.info("allTasks completed in with merges, dbsize {}", System.currentTimeMillis() - startTime, merges, db.getStatementCount(true)); }
Source:
public void testVerseTwo() { String expectedVerseTwo = "On the second day of Christmas my true love gave to me, " + "two Turtle Doves, " + "and a Partridge in a Pear Tree.\n"; assertEquals(expectedVerseTwo, twelveDays.verse(2)); }

Target:
public void testVerseTwo() { String expectedVerseTwo = "On the second day of Christmas my true love gave to me, two Turtle Doves, " + "and a Partridge in a Pear Tree.\n"; assertEquals(expectedVerseTwo, twelveDays.verse(2)); }