auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public HttpContent readChunk(ByteBufAllocator allocator) throws Exception { long chunkDispenseStartTime = System.currentTimeMillis(); logger.trace("Servicing request for next chunk on channel {}", ctx.channel()); HttpContent content = null; Chunk chunk = chunksToWrite.poll(); if (chunk != null) { chunk.onDequeue(); progress.addAndGet(chunk.buffer.readableBytes()); chunksAwaitingCallback.add(chunk); if (chunk.isLast) { <START> content = new DefaultLastHttpContent(chunk.buffer); <END> sentLastChunk = true; } else { content = new DefaultHttpContent(chunk.buffer); } } else if (allChunksWritten() && !sentLastChunk) { sentLastChunk = true; content = LastHttpContent.EMPTY_LAST_CONTENT; logger.trace("Last chunk was sent on channel {}", ctx.channel()); } nettyMetrics.chunkDispenseTimeInMs.update(System.currentTimeMillis() - chunkDispenseStartTime); return content; }</code><technical_language>buffers retained sending content? If chunk callback called operationProgressed releases buffer content object is released downstream channel handlers (not if this part not), get IllegalReferenceCountException</technical_language>

Target:
public HttpContent readChunk(ByteBufAllocator allocator) throws Exception { long chunkDispenseStartTime = System.currentTimeMillis(); logger.trace("Servicing request for next chunk on channel {}", ctx.channel()); HttpContent content = null; Chunk chunk = chunksToWrite.poll(); if (chunk != null) { chunk.onDequeue(); progress.addAndGet(chunk.buffer.readableBytes()); chunksAwaitingCallback.add(chunk); if (chunk.isLast) { content = new DefaultLastHttpContent(chunk.buffer.retainedDuplicate()); sentLastChunk = true; } else { content = new DefaultHttpContent(chunk.buffer.retainedDuplicate()); } } else if (allChunksWritten() && !sentLastChunk) { sentLastChunk = true; content = LastHttpContent.EMPTY_LAST_CONTENT; logger.trace("Last chunk was sent on channel {}", ctx.channel()); } nettyMetrics.chunkDispenseTimeInMs.update(System.currentTimeMillis() - chunkDispenseStartTime); return content; }
Source:
<code>public static OverridePolicy get(String aLiteral) { for (OverridePolicy <START> element : <END> ENUM_ARRAY) { if (element.getLiteral().equals(aLiteral)) { return element; } } return InvokeAlwaysRegardlessOfSuppressedExt; }</code><technical_language>rename 'policy'</technical_language>

Target:
public static OverridePolicy get(String aLiteral) { for (OverridePolicy policy : ENUM_ARRAY) { if (policy.getLiteral().equals(aLiteral)) { return policy; } } return InvokeAlwaysRegardlessOfSuppressedExt; }
Source:
<code><START> protected boolean isConnectorIsOnPool(final Connector connector) { <END> if (connector.eContainer() instanceof Pool) { return true; } return false; }</code><technical_language>return connector.eContainer() instanceof Pool;</technical_language>

Target:
protected boolean isConnectorIsOnPool(final Connector connector) { return connector.eContainer() instanceof Pool; }
Source:
<code>private String getActivationLinkFromMail(String email, String password, String language) { String mailSubject; <START> if (language == "ja") { <END> mailSubject = "メールアドレスの認証を行ってウィキアを始めよう！"; } else { mailSubject = "Confirm your email and get started on Wikia!"; } String www = MailFunctions.getActivationLinkFromEmailContent( MailFunctions.getFirstEmailContent(email, password, mailSubject)); PageObjectLogging.log("getActivationLinkFromMail", "activation link is visible in email content: " + www, true); return www; }</code><technical_language>String is object, for String comparison please use: language.equals("ja")</technical_language>

Target:
private String getActivationLinkFromMail(String email, String password, String language) { String mailSubject; if (language.equals("ja")) { mailSubject = "メールアドレスの認証を行ってウィキアを始めよう！"; } else { mailSubject = "Confirm your email and get started on Wikia!"; } String www = MailFunctions.getActivationLinkFromEmailContent( MailFunctions.getFirstEmailContent(email, password, mailSubject)); PageObjectLogging.log("getActivationLinkFromMail", "activation link is visible in email content: " + www, true); return www; }
Source:
<code>public void testInvalidConfig() throws Exception { String inputTable = "input-xpath-with-multiple-elements"; ETLStage source = new ETLStage("source", MockSource.getPlugin(inputTable)); Map<String, String> sourceProperties = new ImmutableMap.Builder<String, String>() .put("input", "body") .put("encoding", "UTF-8") .put("xpathMappings", "category://book/@category,title://book/title,year:/bookstore/book[price>35.00]/year," + "price:/bookstore/book[price>35.00]/price,subcategory://book/subcategory") .put("fieldTypeMapping", "category:,title:string,price:double,year:int,subcategory:string") .put("processOnError", "Exit on error") .build(); ETLStage transform = new ETLStage("transform", new ETLPlugin("XMLParser", Transform.PLUGIN_TYPE, sourceProperties, null)); String sinkTable = "output-xpath-with-multiple-elements"; ETLStage sink = new ETLStage("sink", MockSink.getPlugin(sinkTable)); ETLBatchConfig etlConfig = ETLBatchConfig.builder("* * * * *") .addStage(source) .addStage(transform) .addStage(sink) .addConnection(source.getName(), transform.getName()) .addConnection(transform.getName(), sink.getName()) .build(); AppRequest<ETLBatchConfig> appRequest = new AppRequest<>(ETLBATCH_ARTIFACT, etlConfig); ApplicationId appId = NamespaceId.DEFAULT.app("XMLReaderTest"); try { deployApplication(appId.toId(), appRequest); Assert.fail(); <START> } catch (IllegalStateException e) { <END> } }</code><technical_language>in error message of this exception check against</technical_language>

Target:
public void testInvalidConfig() throws Exception { XMLParser.Config config = new XMLParser.Config("body", "UTF-8", "category://book/@category,title://book/title," + "year:/bookstore/book[price>35.00]/year,price:/bookstore/book[price>35.00]/price,subcategory://book/subcategory", "category:,title:string,price:double,year:int,subcategory:string", "Exit on error"); MockPipelineConfigurer configurer = new MockPipelineConfigurer(INPUT); try { new XMLParser(config).configurePipeline(configurer); Assert.fail(); } catch (IllegalArgumentException e) { Assert.assertEquals("Type cannot be null. Please specify type for category", e.getMessage()); } }
Source:
<code>private void alterTableDropPartition(TableWriter writer) throws SqlException { CharSequence tok = expectToken(lexer, "'list' or 'where'"); if (SqlKeywords.isListKeyword(tok)) { alterTableDropPartitionByList(writer); } else if (SqlKeywords.isWhereKeyword(tok)) { ExpressionNode expr = parser.expr(lexer, (QueryModel) null); int timestampIndex = writer.getMetadata().getTimestampIndex(); if (timestampIndex != -1) { String timestampColumnName = writer.getMetadata().getColumnName(timestampIndex); Function function = functionParser.parseFunction(expr, new SingleTimestampColumnRecordMetadata(timestampColumnName), currentExecutionContext); if (function != null && function.getType() == ColumnType.BOOLEAN) { writer.removePartition(function); } else { throw SqlException.$(lexer.lastTokenPosition(), "boolean expression expected"); } } } else { throw SqlException.$(lexer.lastTokenPosition(), "'list' or 'where' expected"); <START> } <END> }</code><technical_language>is feedback if timestamp column is defined</technical_language>

Target:
private void alterTableDropPartition(TableWriter writer) throws SqlException { CharSequence tok = expectToken(lexer, "'list' or 'where'"); if (SqlKeywords.isListKeyword(tok)) { alterTableDropPartitionByList(writer); } else if (SqlKeywords.isWhereKeyword(tok)) { ExpressionNode expr = parser.expr(lexer, (QueryModel) null); String designatedTimestampColumnName = writer.getDesignatedTimestampColumnName(); if (designatedTimestampColumnName != null) { GenericRecordMetadata metadata = new GenericRecordMetadata(); metadata.add(new TableColumnMetadata(designatedTimestampColumnName, ColumnType.TIMESTAMP)); Function function = functionParser.parseFunction(expr, metadata, currentExecutionContext); if (function != null && function.getType() == ColumnType.BOOLEAN) { writer.removePartition(function); } else { throw SqlException.$(lexer.lastTokenPosition(), "boolean expression expected"); } } else { throw SqlException.$(lexer.lastTokenPosition(), "this table does not have a designated timestamp column"); } } else { throw SqlException.$(lexer.lastTokenPosition(), "'list' or 'where' expected"); } }
Source:
<code>private Set<String> getDefaultAllowedOrigins() throws ServletException { GetDefaultAllowedOriginsQueryParameters parameters = new GetDefaultAllowedOriginsQueryParameters(); parameters.addSuffixes(defaultOriginsSuffixes); VdcQueryReturnValue value = backend.runPublicQuery(VdcQueryType.GetDefaultAllowedOrigins, parameters); if (!value.getSucceeded()) { throw new ServletException("Can't get list of default origins"); } log.debug("Origins allowed by default: {}", <START> StringUtils.join((Set<String>)value.getReturnValue(), ',')); <END> return value.getReturnValue(); }</code><technical_language>This is expensive, avoid running request</technical_language>

Target:
private Set<String> getDefaultAllowedOrigins() throws ServletException { GetDefaultAllowedOriginsQueryParameters parameters = new GetDefaultAllowedOriginsQueryParameters(); parameters.addSuffixes(defaultOriginsSuffixes); VdcQueryReturnValue value = backend.runPublicQuery(VdcQueryType.GetDefaultAllowedOrigins, parameters); if (!value.getSucceeded()) { throw new ServletException("Can't get list of default origins"); } if (log.isDebugEnabled()) { log.debug("Origins allowed by default: {}", StringUtils.join((Set<String>) value.getReturnValue(), ',')); } return value.getReturnValue(); }
Source:
<code>public static K parseWithDef(CharSequence theTextToParse, String mainModule, String startSymbol, org.kframework.kore.outer.Definition definition) { <START> Module kastModule = definition.getModule(mainModule).get(); <END> Grammar kastGrammar = KSyntax2GrammarStatesFilter.getGrammar(kastModule); Parser parser = new Parser(theTextToParse); Term parsed = parser.parse(kastGrammar.get(startSymbol), 0); if (parsed.equals(Ambiguity.apply())) { Parser.ParseError errors = parser.getErrors(); throw new AssertionError("There are parsing errors: " + errors.toString()); } Term cleaned = new TreeCleanerVisitor().apply(parsed); cleaned = new PreferAvoidVisitor().apply(cleaned); cleaned = new PriorityVisitor(kastModule.priorities(), kastModule.leftAssoc(), kastModule.rightAssoc()).apply(cleaned); return TreeNodesToKORE.apply(cleaned); }</code><technical_language>please factor this step a parseWithGrammar function takes a CharSequence, a Grammar, a start symbol? factor out code generates a grammar a Definition. In particular, for performance reasons is necessary grammar computed for multiple executions of krun</technical_language>

Target:
public static K parseWithDef(CharSequence theTextToParse, String mainModule, String startSymbol, org.kframework.kore.outer.Definition definition) { Module kastModule = definition.getModule(mainModule).get(); Grammar kastGrammar = KSyntax2GrammarStatesFilter.getGrammar(kastModule); return parseWithGrammar(theTextToParse, startSymbol, kastModule, kastGrammar); }
Source:
<code>public String templateCommand(TemplateEngine templateEngine, Config params, String aliasKey, Charset fileCharset) { if (params.has("_command")) { Config nested; try { nested = params.getNested("_command"); } catch (ConfigException notNested) { String command = params.get("_command", String.class); try { return templateFile(templateEngine, command, fileCharset, params); } catch (ConfigException ex) { throw ex; } catch (TemplateException ex) { throw new ConfigException("" + ex.getMessage() + " in " + command, ex); } catch (FileNotFoundException | NoSuchFileException ex) { throw new ConfigException("File not found: " + ex.getMessage(), ex); } catch (IOException ex) { throw new ConfigException("Failed to read a template file: " + command + ": " + ex.getClass(), ex); } catch (RuntimeException ex) { <START> throw new ConfigException("" + ex.getMessage() + ": " + command, ex); <END> } } return nested.get("data", String.class); } else if (aliasKey != null) { return params.get(aliasKey, String.class); } else { return params.get("_command", String.class); } }</code><technical_language>[minor] Throwable#getMessage returns String, remove empty string literal</technical_language>

Target:
public String templateCommand(TemplateEngine templateEngine, Config params, String aliasKey, Charset fileCharset) { if (params.has("_command")) { Config nested; try { nested = params.getNested("_command"); } catch (ConfigException notNested) { String fileName = params.get("_command", String.class); try { return templateFile(templateEngine, fileName, fileCharset, params); } catch (ConfigException ex) { throw ex; } catch (TemplateException ex) { throw new ConfigException( String.format(ENGLISH, "%s in %s", ex.getMessage(), fileName), ex); } catch (FileNotFoundException | NoSuchFileException ex) { throw new ConfigException( String.format(ENGLISH, "File not found: %s", ex.getMessage()), ex); } catch (IOException ex) { throw new ConfigException( String.format(ENGLISH, "Failed to read a template file: %s: %s", fileName, ex.getClass()), ex); } catch (RuntimeException ex) { throw new ConfigException( String.format(ENGLISH, "%s: %s", ex.getMessage(), fileName), ex); } } return nested.get("data", String.class); } else if (aliasKey != null) { return params.get(aliasKey, String.class); } else { return params.get("_command", String.class); } }
Source:
<code>private static boolean classHasInheritance(PyClassDefTree classDef) { PyArgListTree args = classDef.args(); <START> if(args == null) { <END> return false; } List<Tree> children = args.children(); if(children.isEmpty()) { return false; } return children.size() != 1 || !"object".equals(children.get(0).firstToken().getValue()); }</code><technical_language>formatting</technical_language>

Target:
private static boolean classHasInheritance(PyClassDefTree classDef) { PyArgListTree argList = classDef.args(); if (argList == null) { return false; } List<PyArgumentTree> arguments = argList.arguments(); if (arguments.isEmpty()) { return false; } return arguments.size() != 1 || !"object".equals(arguments.get(0).firstToken().getValue()); }
Source:
<code>public void testLifeCycleReverse() throws Exception { <START> deployContrib(CoreUTConstants.CORE_TESTS_BUNDLE, "LifeCycleManagerReverseTestExtensions.xml"); <END> applyInlineDeployments(); postSetUp(); LifeCycle lifeCycle = lifeCycleService.getLifeCycleByName("defaultReverse"); LifeCycleState workState = lifeCycle.getStateByName("work"); assertEquals("work", workState.getName()); Collection<String> transitions = workState.getAllowedStateTransitions(); assertEquals(3, transitions.size()); assertTrue(transitions.contains("approve")); assertTrue(transitions.contains("cancel")); assertTrue(transitions.contains("obsolete")); workState = lifeCycle.getStateByName("approved"); transitions = workState.getAllowedStateTransitions(); assertEquals(1, transitions.size()); assertTrue(transitions.contains("obsolete")); workState = lifeCycle.getStateByName("cancelled"); assertEquals("cancelled", workState.getName()); transitions = workState.getAllowedStateTransitions(); assertEquals(1, transitions.size()); assertTrue(transitions.contains("backToWork")); workState = lifeCycle.getStateByName("obsolete"); assertEquals("obsolete", workState.getName()); transitions = workState.getAllowedStateTransitions(); assertEquals(0, transitions.size()); LifeCycleTransition transition = lifeCycle.getTransitionByName("approve"); assertNotNull(transition); String destinationName = transition.getDestinationStateName(); assertEquals("approved", destinationName); }</code><technical_language>postSetUp called applyInlineDeployments - pushInlineDeployments ? - of deployContrib a test bundle</technical_language>

Target:
public void testLifeCycleReverse() throws Exception { pushInlineDeployments(CoreUTConstants.CORE_TESTS_BUNDLE + ":LifeCycleManagerReverseTestExtensions.xml"); LifeCycle lifeCycle = lifeCycleService.getLifeCycleByName("defaultReverse"); LifeCycleState workState = lifeCycle.getStateByName("work"); assertEquals("work", workState.getName()); Collection<String> transitions = workState.getAllowedStateTransitions(); assertEquals(3, transitions.size()); assertTrue(transitions.contains("approve")); assertTrue(transitions.contains("cancel")); assertTrue(transitions.contains("obsolete")); workState = lifeCycle.getStateByName("approved"); transitions = workState.getAllowedStateTransitions(); assertEquals(1, transitions.size()); assertTrue(transitions.contains("obsolete")); workState = lifeCycle.getStateByName("cancelled"); assertEquals("cancelled", workState.getName()); transitions = workState.getAllowedStateTransitions(); assertEquals(1, transitions.size()); assertTrue(transitions.contains("backToWork")); workState = lifeCycle.getStateByName("obsolete"); assertEquals("obsolete", workState.getName()); transitions = workState.getAllowedStateTransitions(); assertEquals(0, transitions.size()); LifeCycleTransition transition = lifeCycle.getTransitionByName("approve"); assertNotNull(transition); String destinationName = transition.getDestinationStateName(); assertEquals("approved", destinationName); }
Source:
<code>private void loadLocale() throws IOException, NoticeException { for (DataRow row : queryResults("SELECT name, setting FROM pg_settings WHERE name IN ('lc_numeric', 'lc_time')")) { String localeSpec = row.getColumn(1).toString(); switch (localeSpec.toUpperCase(Locale.US)) { case "C": case "POSIX": localeSpec = "en_US"; break; } if (Locales.getJavaCompatibleLocale(localeSpec.split("\\.")[0]) != null) { <START> localeSpec = Locales.getJavaCompatibleLocale(localeSpec.split("\\.")[0]); <END> } String[] localeIds = localeSpec.split("_|\\."); switch (row.getColumn(0).toString()) { case "lc_numeric": Locale numLocale = new Locale.Builder().setLanguageTag(localeIds[0]).setRegion(localeIds[1]).build(); decimalFormatter = (DecimalFormat) DecimalFormat.getNumberInstance(numLocale); decimalFormatter.setParseBigDecimal(true); currencyFormatter = (DecimalFormat) NumberFormat.getCurrencyInstance(numLocale); currencyFormatter.setParseBigDecimal(true); break; case "lc_time": Locale timeLocale = new Locale.Builder().setLanguageTag(localeIds[0]).setRegion(localeIds[1]).build(); } row.release(); } }</code><technical_language>Hi, extract a variable avoid operation (and making mistake in future)</technical_language>

Target:
private void loadLocale() throws IOException, NoticeException { for (DataRow row : queryResults("SELECT name, setting FROM pg_settings WHERE name IN ('lc_numeric', 'lc_time')")) { String localeSpec = row.getColumn(1).toString(); switch (localeSpec.toUpperCase(Locale.US)) { case "C": case "POSIX": localeSpec = "en_US"; break; } String windowsLocale = localeSpec.split("\\.")[0]; if (Locales.getJavaCompatibleLocale(windowsLocale) != null) { localeSpec = Locales.getJavaCompatibleLocale(windowsLocale); } String[] localeIds = localeSpec.split("_|\\."); switch (row.getColumn(0).toString()) { case "lc_numeric": Locale numLocale = new Locale.Builder().setLanguageTag(localeIds[0]).setRegion(localeIds[1]).build(); decimalFormatter = (DecimalFormat) DecimalFormat.getNumberInstance(numLocale); decimalFormatter.setParseBigDecimal(true); currencyFormatter = (DecimalFormat) NumberFormat.getCurrencyInstance(numLocale); currencyFormatter.setParseBigDecimal(true); break; case "lc_time": Locale timeLocale = new Locale.Builder().setLanguageTag(localeIds[0]).setRegion(localeIds[1]).build(); } row.release(); } }
Source:
<code><START> public JDynamicCastOperation(@Nonnull SourceInfo info, @Nonnull JExpression expr, <END> @Nonnull JType... castTypes) { super(info, expr); this.castTypes = Arrays.asList(castTypes); assert !this.castTypes.isEmpty(); }</code><technical_language>Assert is JPrimitiveType in types</technical_language>

Target:
public JDynamicCastOperation(@Nonnull SourceInfo info, @Nonnull JExpression expr, @Nonnull JType... castTypes) { super(info, expr); this.castTypes = Arrays.asList(castTypes); assert !this.castTypes.isEmpty(); assert this.castTypes.size() == 1 || !hasJPrimitiveType(); }
Source:
<code>public void removeAllOwnerContacts(PerunSession sess, Owner owner) throws InternalErrorException { try { List<ContactGroup> contactGroups = getFacilityContactGroups(sess, owner); for (ContactGroup contactGroup : contactGroups) { <START> sess.getPerun().getAuditer().log(sess, "User/owner (" + owner.getId() + ") removed from facility contacts " + contactGroup.toString() + "."); <END> } jdbc.update("delete from facility_contacts where owner_id=?", owner.getId()); log.info("All owner's facilities contacts deleted.", owner); } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }</code><technical_language>owner, user</technical_language>

Target:
public void removeAllOwnerContacts(PerunSession sess, Owner owner) throws InternalErrorException { try { jdbc.update("delete from facility_contacts where owner_id=?", owner.getId()); log.info("All owner's facilities contacts deleted.", owner); } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
<code>public CellBaseIterator<Gene> iterator(GeneQuery query) { Bson bson = parseQuery(query); QueryOptions queryOptions = query.toQueryOptions(); Bson projection = getProjection(query); GenericDocumentComplexConverter<Gene> converter = new GenericDocumentComplexConverter<>(Gene.class); MongoDBIterator<Gene> iterator = null; if (query.getSource() != null && !query.getSource().isEmpty() && "refseq".equalsIgnoreCase(query.getSource().get(0))) { iterator = refseqCollection.iterator(null, bson, projection, converter, queryOptions); } else { <START> iterator = mongoDBCollection.iterator(null, bson, projection, converter, queryOptions); <END> } return new CellBaseIterator<>(iterator); }</code><technical_language>rename mongoDBCollection ensemblCollection</technical_language>

Target:
public CellBaseIterator<Gene> iterator(GeneQuery query) { Bson bson = parseQuery(query); QueryOptions queryOptions = query.toQueryOptions(); Bson projection = getProjection(query); GenericDocumentComplexConverter<Gene> converter = new GenericDocumentComplexConverter<>(Gene.class); MongoDBIterator<Gene> iterator = null; if (query.getSource() != null && !query.getSource().isEmpty() && VariantDBAdaptor.QueryParams.REFSEQ.key() .equalsIgnoreCase(query.getSource().get(0))) { iterator = refseqCollection.iterator(null, bson, projection, converter, queryOptions); } else { iterator = ensemblCollection.iterator(null, bson, projection, converter, queryOptions); } return new CellBaseIterator<>(iterator); }
Source:
<code>protected void addVmPermission() { if ((getParameters()).isMakeCreatorExplicitOwner()) { permissions perms = new permissions(getCurrentUser().getUserId(), PredefinedRoles.VM_OPERATOR.getId(), getVmId(), VdcObjectType.VM); MultiLevelAdministrationHandler.addPermission(perms); getCompensationContext().snapshotNewEntity(perms); } <START> if (getParameters().isCopyTemplatePermissions() && getVmTemplateId() != null && !getVmTemplateId().equals(Guid.Empty)) { <END> copyTemplatePermissions(); } }</code><technical_language>please VmTemplateHandler.BlankVmTemplateId (i guess this is meant..)</technical_language>

Target:
protected void addVmPermission() { if ((getParameters()).isMakeCreatorExplicitOwner()) { permissions perms = new permissions(getCurrentUser().getUserId(), PredefinedRoles.VM_OPERATOR.getId(), getVmId(), VdcObjectType.VM); MultiLevelAdministrationHandler.addPermission(perms); getCompensationContext().snapshotNewEntity(perms); } if (getParameters().isCopyTemplatePermissions() && !getVmTemplateId().equals(VmTemplateHandler.BlankVmTemplateId)) { copyTemplatePermissions(); } }
Source:
<code>protected Mono<Authentication> attemptSwitchUser(Authentication currentAuthentication, String userName) { Assert.notNull(userName, "The userName can not be null."); if (this.logger.isDebugEnabled()) { this.logger.debug("Attempt to switch to user [" + userName + "]"); } <START> <END> return userDetailsService.findByUsername(userName) .switchIfEmpty(Mono.error(this::noTargetAuthenticationException)) .doOnNext(userDetailsChecker::check) .map(userDetails -> createSwitchUserToken(userDetails, currentAuthentication)); }</code><technical_language>explain switchUser attemptSwitchUser split this way? sense combine a single method? Similar question for exitSwitchUser attemptExitUser</technical_language>

Target:
private Mono<Authentication> attemptSwitchUser(Authentication currentAuthentication, String userName) { Assert.notNull(userName, "The userName can not be null."); if (this.logger.isDebugEnabled()) { this.logger.debug("Attempt to switch to user [" + userName + "]"); } return userDetailsService.findByUsername(userName) .switchIfEmpty(Mono.error(this::noTargetAuthenticationException)) .doOnNext(userDetailsChecker::check) .map(userDetails -> createSwitchUserToken(userDetails, currentAuthentication)); }
Source:
<code>private void deleteMail(Account.Id id, final String mailAddress) throws UnloggedFailure { if (mailAddress.equals("ALL")) { ResultSet<AccountExternalId> ids; try { ids = db.accountExternalIds().byAccount(id); } catch (OrmException e) { throw die("Could not query database: " + e.getMessage()); } for (AccountExternalId extId : ids) { <START> unlink(id, extId.getEmailAddress()); <END> } } else { unlink(id, mailAddress); } }</code><technical_language>id record email address</technical_language>

Target:
private void deleteMail(Account.Id id, final String mailAddress) throws UnloggedFailure { if (mailAddress.equals("ALL")) { ResultSet<AccountExternalId> ids; try { ids = db.accountExternalIds().byAccount(id); } catch (OrmException e) { throw die("Could not query database: " + e.getMessage()); } for (AccountExternalId extId : ids) { if (extId.getEmailAddress() != null) { unlink(id, extId.getEmailAddress()); } } } else { unlink(id, mailAddress); } }
Source:
<code>public boolean isDirty() { if (getTrace() == null) { return false; } TmfTraceContext ctx = TmfTraceManager.getInstance().getCurrentTraceContext(); long startTime = ctx.getWindowRange().getStartTime().toNanos(); long endTime = ctx.getWindowRange().getEndTime().toNanos(); <START> if (getWindowStartTime() != startTime || getWindowEndTime() != endTime) { <END> return true; } return false; }</code><technical_language>a single return instead of if</technical_language>

Target:
public boolean isDirty() { if (getTrace() == null) { return false; } TmfTraceContext ctx = TmfTraceManager.getInstance().getCurrentTraceContext(); long startTime = ctx.getWindowRange().getStartTime().toNanos(); long endTime = ctx.getWindowRange().getEndTime().toNanos(); return (getWindowStartTime() != startTime || getWindowEndTime() != endTime); }
Source:
<code>private boolean getOldChildStale(IObservable child) { Boolean oldChildValue = staleMap.get(child); boolean oldChildStale = <START> oldChildValue == null ? false : oldChildValue .booleanValue(); <END> return oldChildStale; }</code><technical_language>Simpler: oldChildValue != && oldChildValue.booleanValue()</technical_language>

Target:
private boolean getOldChildStale(IObservable child) { Boolean oldChildValue = staleMap.get(child); boolean oldChildStale = oldChildValue != null && oldChildValue; return oldChildStale; }
Source:
<code>public Result<TopNResultValue> build() { final DimValHolder[] holderValueArray = pQueue.toArray(new DimValHolder[0]); Arrays.sort( holderValueArray, new Comparator<DimValHolder>() { @Override public int compare(DimValHolder d1, DimValHolder d2) { <START> int retVal = -metricComparator.compare(d1.getTopNMetricVal(), d2.getTopNMetricVal()); <END> if (retVal == 0) { retVal = dimNameComparator.compare(d1.getDimName(), d2.getDimName()); } return retVal; } } ); List<DimValHolder> holderValues = Arrays.asList(holderValueArray); final List<Map<String, Object>> values = Lists.transform( holderValues, new Function<DimValHolder, Map<String, Object>>() { @Override public Map<String, Object> apply(DimValHolder valHolder) { return valHolder.getMetricValues(); } } ); return new Result<TopNResultValue>( timestamp, new TopNResultValue(values) ); }</code><technical_language>Negating a comparator is bad, if returned Int.MinValue get result expect. Simply switch arguments instead</technical_language>

Target:
public Result<TopNResultValue> build() { final DimValHolder[] holderValueArray = pQueue.toArray(new DimValHolder[0]); Arrays.sort( holderValueArray, new Comparator<DimValHolder>() { @Override public int compare(DimValHolder d1, DimValHolder d2) { int retVal = metricComparator.compare(d2.getTopNMetricVal(), d1.getTopNMetricVal()); if (retVal == 0) { retVal = dimNameComparator.compare(d1.getDimName(), d2.getDimName()); } return retVal; } } ); List<DimValHolder> holderValues = Arrays.asList(holderValueArray); final List<Map<String, Object>> values = Lists.transform( holderValues, new Function<DimValHolder, Map<String, Object>>() { @Override public Map<String, Object> apply(DimValHolder valHolder) { return valHolder.getMetricValues(); } } ); return new Result<TopNResultValue>( timestamp, new TopNResultValue(values) ); }
Source:
<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == Activity.RESULT_OK) { btStatusTextView.setText(getString(R.string.status_bluetooth_connected)); } else { <START> Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG).show(); <END> } } super.onActivityResult(requestCode, resultCode, data); }</code><technical_language>reuse getString(R.string.text_bluetooth_disabled)</technical_language>

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == Activity.RESULT_OK) { btStatusTextView.setText(getString(R.string.status_bluetooth_connected)); } else { Toast.makeText(this, R.string.text_bluetooth_disabled, Toast.LENGTH_LONG).show(); } } super.onActivityResult(requestCode, resultCode, data); }
Source:
<code>public void visitAnonymousClass(AnonymousClassTree tree) { enterScope(tree); classScope = currentScope; tree.arguments().stream() .filter(arg -> arg.is(Kind.VARIABLE_IDENTIFIER)) .map(VariableIdentifierTree.class::cast) <START> .forEach(arg -> createSymbol(currentScope.outer(), arg, Symbol.Kind.VARIABLE)); <END> createMemberSymbols(tree); super.visitAnonymousClass(tree); classScope = null; leaveScope(); }</code><technical_language>avoid creating new createSymbol method if moved this statement beginning of visitAnonymousClass</technical_language>

Target:
public void visitAnonymousClass(AnonymousClassTree tree) { scan(tree.arguments()); enterScope(tree); classScope = currentScope; createMemberSymbols(tree); NamespaceNameTree superClass = tree.superClass(); if (superClass != null) { scan(superClass); } scan(tree.superInterfaces()); scan(tree.members()); classScope = null; leaveScope(); }
Source:
<code>public static String macToString(byte[] mac) throws KuraException { if ((mac == null) || (mac.length != 6)) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); <START> } <END> String[] items = new String[6]; for (int i = 0; i < 6; i++) { String octet = Integer.toHexString(mac[i] & 0xFF).toUpperCase(); if (octet.length() == 1) { octet = "0" + octet; } items[i] = octet; } String macString = String.join(":", items); return macString; }</code><technical_language>Runtime Exception</technical_language>

Target:
public static String macToString(byte[] mac) { if ((mac == null) || (mac.length != 6)) { throw new IllegalArgumentException("mac is null or invalid"); } String[] items = new String[6]; for (int i = 0; i < 6; i++) { String octet = Integer.toHexString(mac[i] & 0xFF).toUpperCase(); if (octet.length() == 1) { octet = "0" + octet; } items[i] = octet; } return String.join(":", items); }
Source:
<code>public void setup() throws CommandLineException { cliOut = new ByteArrayOutputStream(); System.setProperty("aesh.ansi","false"); System.setProperty("aesh.terminal","org.jboss.aesh.terminal.TestTerminal"); CLITestUtil.setJBossCliConfig(); config = new CommandContextConfiguration.Builder() .setController(CLITestUtil.constructUri(null, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort())) .setUsername(null) .setPassword(null) .setConsoleInput(null) .setConsoleOutput(cliOut) .setDisableLocalAuth(false) .setInitConsole(true) .build(); ctx = CommandContextFactory.getInstance().newCommandContext(config); ctx.handle("set " + FOO_NAME + "=" + FOO_VALUE); ctx.handle("set " + FOOBAR_NAME + "=" + FOOBAR_VALUE); cliOut.reset(); ctx.handle("echo $" + FOO_NAME); assertTrue(cliOut.toString().contains(FOO_VALUE)); ctx.handle("echo $" + FOOBAR_NAME); assertTrue(cliOut.toString().contains(FOOBAR_VALUE)); <START> ctx.handle("connect"); END> }</code><technical_language>class CLIWrapper call constructor CLIWrapper(true). do setup for ;-)</technical_language>

Target:
public void setup() throws Exception { cli = new CLIWrapper(true, null, System.in); assertTrue(cli.isConnected()); cli.sendLine("set " + FOO_NAME + "=" + FOO_VALUE); cli.sendLine("set " + FOOBAR_NAME + "=" + FOOBAR_VALUE); cli.sendLine("echo $" + FOO_NAME); assertTrue(cli.readOutput().contains(FOO_VALUE)); cli.sendLine("echo $" + FOOBAR_NAME); assertTrue(cli.readOutput().contains(FOOBAR_VALUE)); }
Source:
<code>public void testExecuteBatchPreparedStatementFailOne() throws Exception { try (Connection conn = DriverManager.getConnection(connectionStr)) { PreparedStatement stmt = conn.prepareStatement("insert into test (id, string_field) values (?, ?)"); stmt.setInt(1, 2); <START> stmt.setString(2, "foo"); <END> stmt.addBatch(); stmt.setInt(1, 3); stmt.setString(2, "bar"); stmt.addBatch(); stmt.setInt(1, 1); stmt.setObject(2, "baz"); stmt.addBatch(); int[] results = stmt.executeBatch(); assertArrayEquals(new int[]{1, 1, Statement.EXECUTE_FAILED}, results); conn.createStatement().execute("refresh table test"); ResultSet resultSet = conn.createStatement().executeQuery("select count(*) from test"); assertThat(resultSet.next(), is(true)); assertThat(resultSet.getLong(1), is(3L)); } }</code><technical_language>here, try tests simple pls</technical_language>

Target:
public void testExecuteBatchPreparedStatementFailOne() throws Exception { try (Connection conn = DriverManager.getConnection(connectionString)) { PreparedStatement stmt = conn.prepareStatement("insert into test (id, string_field) values (?, ?)"); stmt.setInt(1, 2); stmt.setString(2, "foo"); stmt.addBatch(); stmt.setInt(1, 1); stmt.setObject(2, "baz"); stmt.addBatch(); int[] results = stmt.executeBatch(); assertArrayEquals(new int[]{1, Statement.EXECUTE_FAILED}, results); conn.createStatement().execute("refresh table test"); ResultSet resultSet = conn.createStatement().executeQuery("select count(*) from test"); assertThat(resultSet.next(), is(true)); assertThat(resultSet.getLong(1), is(2L)); } }
Source:
<code>public KafkaOffsetProvider(KafkaConfigProvider configProvider) { <START> this.configProvider = configProvider; <END> }</code><technical_language>configProvider is required, it? If so, Objects.requireNonNull(...) a NotNull check</technical_language>

Target:
public KafkaOffsetProvider(KafkaConfigProvider configProvider) { this.configProvider = Objects.requireNonNull(configProvider); }
Source:
<code>public void testNoMessageBody() throws Exception { when(msg.getBody()).thenReturn(null); processor.process(exchange); <START> verify(messageSender, never()).sendIndexingOperation(anyString(), any(Collection.class), <END> any(IndexingActionType.class)); }</code><technical_language>If anyCollectionOf(PID.class) skip warning suppression</technical_language>

Target:
public void testNoMessageBody() throws Exception { when(msg.getBody()).thenReturn(null); processor.process(exchange); verify(messageSender, never()).sendIndexingOperation(anyString(), any(PID.class), any(IndexingActionType.class)); }
Source:
<code>PinotExpression(String definition, Origin origin) { <START> this.definition = requireNonNull(definition, "definition"); <END> this.origin = requireNonNull(origin, "origin"); }</code><technical_language>message "definition is null". for other requireNonNulls</technical_language>

Target:
PinotExpression(String definition, Origin origin) { this.definition = requireNonNull(definition, "definition is null"); this.origin = requireNonNull(origin, "origin is null"); }
Source:
<code>public void reTakeLabelLockForQueryWithIndexUsagesWhenSchemaStateWasUpdatedDuringLockOperations() throws Exception { String labelName = "Robot"; Label human = Label.label( labelName ); String propertyKey = "name"; createIndex( human, propertyKey ); try ( Transaction transaction = databaseRule.beginTx() ) { Node node = databaseRule.createNode( human ); node.setProperty( propertyKey, RandomStringUtils.randomAscii( 10 ) ); transaction.success(); <START> } <END> String query = "MATCH (n:" + labelName + ") where n." + propertyKey + " = \"Bender\" RETURN n "; LockOperationListener lockOperationListener = new OnceSchemaFlushListener(); List<LockOperationRecord> lockOperationRecords = traceQueryLocks( query, lockOperationListener ); assertThat( "Observed list of lock operations is: " + lockOperationRecords, lockOperationRecords, hasSize( 3 ) ); LockOperationRecord operationRecord = lockOperationRecords.get( 0 ); assertTrue( operationRecord.acquisition ); assertFalse( operationRecord.exclusive ); assertEquals( ResourceTypes.LABEL, operationRecord.resourceType ); LockOperationRecord operationRecord1 = lockOperationRecords.get( 1 ); assertFalse( operationRecord1.acquisition ); assertFalse( operationRecord1.exclusive ); assertEquals( ResourceTypes.LABEL, operationRecord1.resourceType ); LockOperationRecord operationRecord2 = lockOperationRecords.get( 2 ); assertTrue( operationRecord2.acquisition ); assertFalse( operationRecord2.exclusive ); assertEquals( ResourceTypes.LABEL, operationRecord2.resourceType ); }</code><technical_language>Small nit, variable name Bender is human (which happen in episode)</technical_language>

Target:
public void reTakeLabelLockForQueryWithIndexUsagesWhenSchemaStateWasUpdatedDuringLockOperations() throws Exception { String labelName = "Robot"; Label robot = Label.label( labelName ); String propertyKey = "name"; createIndex( robot, propertyKey ); try ( Transaction transaction = databaseRule.beginTx() ) { Node node = databaseRule.createNode( robot ); node.setProperty( propertyKey, RandomStringUtils.randomAscii( 10 ) ); transaction.success(); } String query = "MATCH (n:" + labelName + ") where n." + propertyKey + " = \"Bender\" RETURN n "; LockOperationListener lockOperationListener = new OnceSchemaFlushListener(); List<LockOperationRecord> lockOperationRecords = traceQueryLocks( query, lockOperationListener ); assertThat( "Observed list of lock operations is: " + lockOperationRecords, lockOperationRecords, hasSize( 3 ) ); LockOperationRecord operationRecord = lockOperationRecords.get( 0 ); assertTrue( operationRecord.acquisition ); assertFalse( operationRecord.exclusive ); assertEquals( ResourceTypes.LABEL, operationRecord.resourceType ); LockOperationRecord operationRecord1 = lockOperationRecords.get( 1 ); assertFalse( operationRecord1.acquisition ); assertFalse( operationRecord1.exclusive ); assertEquals( ResourceTypes.LABEL, operationRecord1.resourceType ); LockOperationRecord operationRecord2 = lockOperationRecords.get( 2 ); assertTrue( operationRecord2.acquisition ); assertFalse( operationRecord2.exclusive ); assertEquals( ResourceTypes.LABEL, operationRecord2.resourceType ); }
Source:
<code>Container(JSONObject metadata) throws JSONException { if (metadata == null) { throw new IllegalArgumentException("metadata cannot be null."); } short metadataVersion = (short) metadata.getInt(CONTAINER_METADATA_VERSION_KEY); switch (metadataVersion) { case CONTAINER_METADATA_VERSION_1: <START> this.id = (short) metadata.getInt(CONTAINER_ID_KEY); <END> this.name = metadata.getString(CONTAINER_NAME_KEY); this.status = ContainerStatus.valueOf(metadata.getString(CONTAINER_STATUS_KEY)); this.description = metadata.optString(CONTAINER_DESCRIPTION_KEY); this.isPrivate = metadata.getBoolean(CONTAINER_IS_PRIVATE_KEY); this.parentAccountId = (short) metadata.getInt(CONTAINER_PARENT_ACCOUNT_ID_KEY); checkRequiredFields(); break; default: throw new IllegalStateException("Unsupported container metadata version=" + metadataVersion); } }</code><technical_language>call other constructor fields</technical_language>

Target:
private Container(JSONObject metadata) throws JSONException { if (metadata == null) { throw new IllegalArgumentException("metadata cannot be null."); } short metadataVersion = (short) metadata.getInt(JSON_VERSION_KEY); switch (metadataVersion) { case JSON_VERSION_1: this.id = (short) metadata.getInt(CONTAINER_ID_KEY); this.name = metadata.getString(CONTAINER_NAME_KEY); this.status = ContainerStatus.valueOf(metadata.getString(STATUS_KEY)); this.description = metadata.optString(DESCRIPTION_KEY); this.isPrivate = metadata.getBoolean(IS_PRIVATE_KEY); this.parentAccountId = (short) metadata.getInt(PARENT_ACCOUNT_ID_KEY); checkRequiredFields(); break; default: throw new IllegalStateException("Unsupported container json version=" + metadataVersion); } }
Source:
<code>public List<Resource> getResourcesWhereUserIsAdmin(PerunSession sess, Vo vo, User authorizedUser) throws InternalErrorException, PrivilegeException, UserNotExistsException, VoNotExistsException { Utils.checkPerunSession(sess); getPerunBl().getVosManagerBl().checkVoExists(sess, vo); getPerunBl().getUsersManagerBl().checkUserExists(sess, authorizedUser); List<Resource> resources = getResourcesManagerBl().getResourcesWhereUserIsAdmin(sess, vo, authorizedUser); if(AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo) || AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)){ return resources; } if(AuthzResolver.isAuthorized(sess, Role.RESOURCEADMIN)) { return filterNotAuthorizedResource(sess, resources); } else { <START> throw new PrivilegeException(sess, "getResourcesByResourceManager"); <END> } }</code><technical_language>This String correspond name of called method. suggestion throw new PrivilegeException(sess, "getResourcesWhereUserIsAdmin");</technical_language>

Target:
public List<Resource> getResourcesWhereUserIsAdmin(PerunSession sess, Vo vo, User authorizedUser) throws InternalErrorException, PrivilegeException, UserNotExistsException, VoNotExistsException { Utils.checkPerunSession(sess); getPerunBl().getVosManagerBl().checkVoExists(sess, vo); getPerunBl().getUsersManagerBl().checkUserExists(sess, authorizedUser); List<Resource> resources = getResourcesManagerBl().getResourcesWhereUserIsAdmin(sess, vo, authorizedUser); if(AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo) || AuthzResolver.isAuthorized(sess, Role.VOOBSERVER, vo) || AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)){ return resources; } if(AuthzResolver.isAuthorized(sess, Role.RESOURCEADMIN)) { return filterNotAuthorizedResource(sess, resources); } else { throw new PrivilegeException(sess, "getResourcesWhereUserIsAdmin"); } }
Source:
<code>@Test void testRowCountRightJoinEmptyFinite() { final String sql = "select * from (select * from emp limit 4) as emp\n" + "right join (select * from dept limit 0) as dept\n" + "on emp.deptno = dept.deptno"; checkRowCount(sql, 1D, <START> 0D, 0D); END> }</code><technical_language>name of I thinking this test intended test empty join right? (now is changed test left join empty</technical_language>

Target:
@Test void testRowCountRightJoinEmptyFinite() { final String sql = "select * from (select * from emp limit 0) as emp\n" + "right join (select * from dept limit 4) as dept\n" + "on emp.deptno = dept.deptno"; checkRowCount(sql, 4D, 0D, 4D); }
Source:
<code>public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ProcessorData other = (ProcessorData) obj; <START> return processorId.equals(other.processorId) && host.equals(other.host); <END> }</code><technical_language>I comparing host for equality. processors. For example, a case duplicate processorId a host, is a duplicate partitioning/grouping is concerned. Please correct if I wrong</technical_language>

Target:
public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ProcessorData other = (ProcessorData) obj; return Objects.equals(processorId, other.processorId) && Objects.equals(host, other.host); }
Source:
<code>public String getServerVersion() <START> throws SecurityException, TransactionException, TException { <END> return Version.getVersion(ConcourseServer.class).toString(); }</code><technical_language>this need declare throws exceptions, now</technical_language>

Target:
public String getServerVersion() { return Version.getVersion(ConcourseServer.class).toString(); }
Source:
<code>private Guid getVdsToRunOn(Iterable<VDS> vdss) { final List<VDS> readyToRun = new ArrayList<VDS>(); <START> final List<VmNetworkInterface> vmNetworks = getVmNetworkInterfaceDAO().getAllForVm(getVm().getId()); <END> for (VDS curVds : vdss) { if (!curVds.getvds_group_id().equals(getVm().getvds_group_id())) continue; if (curVds.getstatus() != VDSStatus.Up) continue; if (!RunVmCommandBase.hasMemoryToRunVM(curVds, getVm())) continue; if ((getVm().getrun_on_vds() != null && getVm().getrun_on_vds().equals(curVds.getId())) || isVdsFailedToRunVm(curVds.getId()) || !RunVmCommandBase.hasCapacityToRunVM(curVds)) continue; if (curVds.getcpu_cores() != null && getVm().getnum_of_cpus() > curVds.getcpu_cores()) { continue; } if (!IsVMSwapValueLegal(curVds)) continue; if(!areRequiredNetworksAvailable(vmNetworks, getInterfaceDAO().getAllInterfacesForVds(curVds.getId()))) continue; readyToRun.add(curVds); } return readyToRun.isEmpty() ? Guid.Empty : getBestVdsToRun(readyToRun); }</code><technical_language>This is a list of vm's NICs naming vmNetworks is misleading</technical_language>

Target:
private Guid getVdsToRunOn(Iterable<VDS> vdss) { final List<VDS> readyToRun = new ArrayList<VDS>(); final List<VmNetworkInterface> vmNICs = getVmNetworkInterfaceDAO().getAllForVm(getVm().getId()); for (VDS curVds : vdss) { if (!curVds.getvds_group_id().equals(getVm().getvds_group_id())) continue; if (curVds.getstatus() != VDSStatus.Up) continue; if (!RunVmCommandBase.hasMemoryToRunVM(curVds, getVm())) continue; if ((getVm().getrun_on_vds() != null && getVm().getrun_on_vds().equals(curVds.getId())) || isVdsFailedToRunVm(curVds.getId()) || !RunVmCommandBase.hasCapacityToRunVM(curVds)) continue; if (curVds.getcpu_cores() != null && getVm().getnum_of_cpus() > curVds.getcpu_cores()) { continue; } if (!IsVMSwapValueLegal(curVds)) continue; if(!areRequiredNetworksAvailable(vmNICs, getInterfaceDAO().getAllInterfacesForVds(curVds.getId()))) continue; readyToRun.add(curVds); } return readyToRun.isEmpty() ? Guid.Empty : getBestVdsToRun(readyToRun); }