auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>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) { <START> log.info("Tried more than 10, stop it NOW!"); <END> StandardJMeterEngine.stopEngineNow(); } else if (stopTries > 5) { log.info("Tried more than 5, stop it!"); StandardJMeterEngine.stopEngine(); } else { JMeterContextService.getContext().getEngine().askThreadsToStop(); } }</code><technical_language>English-wise, original message correct, please revert</technical_language>

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:
<code><START> private StackExchangeApi() { <END> }</code><technical_language>protected. fault API constructors private. I fixed that. In master branch API constructors protected, extend API in code if want. instantiate directly, forcing singleton</technical_language>

Target:
protected StackExchangeApi() { }
Source:
<code>public static ErrorMessageFactory shouldContain(Throwable actual, CharSequence sequence) { String format = "%n" + <START> "Expecting:%n" + <END> " <%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()); }</code><technical_language>I reword this "Expecting throwable message:%n" string is string a throwable message</technical_language>

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:
<code>protected void doExecute() { configUserThread(); CoreSetup.setup(config); addCapabilities(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { gracefulShutDown(() -> log.info("gracefulShutDown complete")); <START> }, "Monitor Shutdown Hook ") <END> ); launchApplication(); }</code><technical_language>Is a reason labeled Monitor Shutdown Hook ? suggestion }, "BisqExecutable Shutdown Hook")</technical_language>

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:
<code>protected String getLink() { Method method = getMethod(); <START> return getContextPath() + router.urlFor(controller, method, getArgs(method)); <END> }</code><technical_language>change controller getController()</technical_language>

Target:
protected String getLink() { Method method = getMethod(); return getPrefix() + router.urlFor(controller, method, getArgs(method)); }
Source:
<code>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()) <START> .addAfter(ctxName, "stompDecoder", new StompSubframeDecoder()) <END> .remove(StompWebSocketClientPageHandler.INSTANCE); } else { super.userEventTriggered(ctx, evt); } }</code><technical_language>a name adding pipeline ? Consider this</technical_language>

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:
<code>private void jumpToNode() { <START> String inputText = jumpTo.getCharacters().toString(); <END> 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(); } }</code><technical_language>@gfokkema another solution for this, he</technical_language>

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:
<code>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); <START> item.setIcon(player.isMuted() <END> ? getResources().getDrawable(ThemeHelper.resolveResourceIdFromAttr(getApplicationContext(), R.attr.ic_volume_off)) : getResources().getDrawable(R.drawable.ic_volume_off_gray_24dp)); } }</code><technical_language>I tested code ok</technical_language>

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:
<code>public DiscoveryResult createResult(ServiceInfo service) { <START> if (service.getType().equals(getServiceType())) { <END> 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; }</code><technical_language>Do need this check? I thought framework ensures asked for service types registered for</technical_language>

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:
<code>public <T> ModelAdaptor<? super T> getModelAdaptor(Class<T> attributeType) { <START> return (ModelAdaptor<T>) adaptors.get(attributeType); <END> }</code><technical_language>suggestion return (ModelAdaptor<? super T>) adaptors.get(attributeType);</technical_language>

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

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:
<code>private String userKey(User user) { User.Profile profile = user.getUserProfiles().get(TokenType.GOOGLE_COM.toString()); String email = profile == null ? null : profile.email; <START> return email == null ? user.getUsername() : email; <END> }</code><technical_language>simplify. sure, is this just? if (profile == null || profile.email == null) { return user.getUsername(); } return profile.email;</technical_language>

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:
<code>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()); <START> driver = new IOSDriver<>(new URL("http://" + ipAddress + ":4723/wd/hub"), capabilities); <END> }</code><technical_language>port number is hardcoded</technical_language>

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:
<code>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; <START> this.outstandingConsumptionRequests = Collections.newSetFromMap(new ConcurrentHashMap()); <END> this.periodicCommitInterval = periodicCommitInterval; this.nextOffsetsCommitTSGlobal = nextOffsetsCommitTSGlobal; this.nextOffsetsCommitTSThreadLocal = this.nextOffsetsCommitTSGlobal.get(); this.coordinator = null; this.hasStopped = async.future(); }</code><technical_language>of raw class, new ConcurrentHashMap<Long, Boolean>()</technical_language>

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:
<code>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; <START> expectedState = nextExpectedState; <END> 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); } } }</code><technical_language>setting expectedState ? (it if expected is false)</technical_language>

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:
<code>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()); <START> } <END> } }</code><technical_language>Wtf</technical_language>

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:
<code>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; <START> if(region instanceof CuboidRegion) { <END> 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; }</code><technical_language>a space if. java if (statement)</technical_language>

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:
<code>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(), <START> ex.toString())); <END> } } }); } } catch (CloneNotSupportedException ex) { _logger.error(String.format("Failed to take snapshot for %s metric %s", metric.getClass().getName(), ex.toString())); } } }</code><technical_language>is call toString() method. logger.error prints out entire stack trace</technical_language>

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:
<code>protected List<VmStatic> filterVmsInClusterNeedUpdate() { <START> if (Objects.equals(oldCluster.getCompatibilityVersion(), getCluster().getCompatibilityVersion())) { return Collections.emptyList(); } <END> return vmStaticDao.getAllByCluster(getCluster().getId()).stream() .filter(vm -> vm.getOrigin() != OriginType.EXTERNAL && !vm.isHostedEngine()) .filter(vm -> vm.getCustomCompatibilityVersion() == null) .sorted() .collect(Collectors.toList()); }</code><technical_language>this is redundant, right</technical_language>

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:
<code>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()); <START> if (upgradeStack.equals(stackToFind) && upgradePack.getType().equals(upgradeType)) { <END> 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; }</code><technical_language>== for enums</technical_language>

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:
<code>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); <START> int fltmapid = (int) rowIdx; <END> assertEquals(ngram, result.getString(0, batchIdx)); assertEquals(fltmapid, result.getInt(1, batchIdx)); } } } assertEquals(EXPECTED_RESULTS, rowIdx); apply.close(); }</code><technical_language>typo, nit-picking: fine declare rowIdx int</technical_language>

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:
<code>public void should_associate_all_quality_gates_to_default_organization() throws SQLException { <START> String orgUuid1 = uuidFactory.create(); <END> 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) ); }</code><technical_language>Rename defaultOrgUuid => improve readability</technical_language>

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:
<code>public WeekDiffFunction(String template) { <START> super("day_diff", template); <END> }</code><technical_language>day_diff</technical_language>

Target:
public WeekDiffFunction(String template) { super("week_diff", template); }
Source:
<code>public void centerMapToPlace(Place place) { if (nearbyMapFragment == null) { <START> nearbyMapFragment.nearbyplace = place; <END> } else { nearbyMapFragment.centerMapToPlace(place); } }</code><technical_language>@sp2710 , this line crash NPE if nearbyMapFragment is null. explain aim achieve here</technical_language>

Target:
public void centerMapToPlace(Place place) { if (nearbyMapFragment != null) { nearbyMapFragment.centerMapToPlace(place); } }
Source:
<code>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; } <START> return true; <END> }</code><technical_language>consider change return validate(validator.isDomainExistAndActive()) && validate(validator.isDataDomain())</technical_language>

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:
<code>public boolean canSubmit() { <START> if ("refs/meta/config".equals(refName)) { <END> return getProjectControl().isOwner(); } return canPerform(Permission.SUBMIT); }</code><technical_language>This GitRepositoryManager.REF_CONFIG constant. fix cherry-pick I submit this topic, thanks</technical_language>

Target:
public boolean canSubmit() { if (GitRepositoryManager.REF_CONFIG.equals(refName)) { return getProjectControl().isOwner(); } return canPerform(Permission.SUBMIT); }
Source:
<code>private void replicateProjectLocally(final Project.NameKey projectName, final URIish replicateURI, final String head) { Repository repo = null; try { <START> repo = gitRepositoryManager.openRepository(projectName); <END> 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(); } } }</code><technical_language>I if move this try, eliminate null check 301</technical_language>

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:
<code>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"); <START> } <END> }</code><technical_language>validateItemType is meant detect current itemType in case complain incompatibilities. Please move parsing validation code processBindingConfiguration</technical_language>

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:
<code>private void terminateTasks(final SchedulingService service) { if (tasksToTerminate.values().isEmpty()) { return; } <START> ExecutorService parallelTerminationService = Executors.newFixedThreadPool(tasksToTerminate.values().size()); <END> 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); } }</code><technical_language>executor service shutdown end of this method, leave alive threads</technical_language>

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:
<code>public void setupDocument(IDocument newDocument) { if (newDocument != null) { fLineBackgroundListener.setCurrentDocument(newDocument); if(positionUpdaterAddedDocuments.contains(newDocument)) { return; } <START> newDocument.addPositionCategory(PresentationReconcilerCPP.SEMANTIC_HIGHLIGHTING_POSITION_CATEGORY); <END> 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); } }</code><technical_language>PresentationReconcilerCPP prefix is necessary</technical_language>

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:
<code>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(); <START> assertThat("Expected to find link with rel " + rel + " but found none in " + s, END> getDiscoverer(response).findLinkWithRel(rel, s), notNullValue()); } }; }</code><technical_language>Please, AssertJ</technical_language>

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:
<code>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); <START> if (compareRows(firstSplit.split.getStartRow(), scanStartRow) != 0 || compareRows(lastSplit.split.getEndRow(), scanStopRow) != 0) { <END> return true; } } return false; }</code><technical_language>This check is correct, a scan start key = 1000 partition key = 500. check firstSplit.split.getStartRow() <= scanStartRow lastSplit.split.getEndRow() >= scanStopRow (or lastSplit.split.getEndRow().isEmpty())</technical_language>

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:
<code>public String toBase64(int jpegQualityPercent) { <START> return Base64.encodeToString(toJpeg(currentRepresentation, jpegQualityPercent), Base64.DEFAULT); <END> }</code><technical_language>is this a breaking change</technical_language>

Target:
public String toBase64(int jpegQualityPercent) { return Base64.encodeToString(toJpeg(currentRepresentation, jpegQualityPercent), Base64.NO_WRAP); }
Source:
<code>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)); <START> message = MessageBuilder.withPayload(this.createPerson("Tom", 40)).build(); <END> 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()); }</code><technical_language>this. for method calls</technical_language>

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:
<code>public static String getContext() { <START> return Bugsnag.getClient().getContext(); <END> }</code><technical_language>Ah - guessing static Bugsnag this interface possible. workarounds of avoid depending static class</technical_language>

Target:
public static String getContext() { return getClient().getContext(); }
Source:
<code>public long getLatestEstimate() { <START> return 0; <END> }</code><technical_language>return actual estimate</technical_language>

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:
<code>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) { <START> Integer targetCRSEpsgCode = CRS.lookupEpsgCode(crs, true); <END> 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; }</code><technical_language>is a full scan... is this intended</technical_language>

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; }