auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> protected void implementNetworkElements(final DeployDestination dest, final ReservationContext context, final Network network, final NetworkOffering offering, final List<Provider> providersToImplement) <END> throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { for (NetworkElement element : networkElements) { if (providersToImplement.contains(element.getProvider())) { if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) { throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Asking " + element.getName() + " to implemenet " + network); } if (!element.implement(network, offering, dest, context)) { CloudRuntimeException ex = new CloudRuntimeException("Failed to implement provider " + element.getProvider().getName() + " for network with specified id"); ex.addProxyObject(network.getUuid(), "networkId"); throw ex; } } } }</code><technical_language>Is a reason for this method protected? do making private</technical_language>

Target:
private void implementNetworkElements(final DeployDestination dest, final ReservationContext context, final Network network, final NetworkOffering offering, final List<Provider> providersToImplement) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { for (NetworkElement element : networkElements) { if (providersToImplement.contains(element.getProvider())) { if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) { throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Asking " + element.getName() + " to implemenet " + network); } if (!element.implement(network, offering, dest, context)) { CloudRuntimeException ex = new CloudRuntimeException("Failed to implement provider " + element.getProvider().getName() + " for network with specified id"); ex.addProxyObject(network.getUuid(), "networkId"); throw ex; } } } }
Source:
<code><START> public List<TypeDeclaration> parentTypes() { <END> List<TypeDeclaration> nodes = new ArrayList<>(); Set<String> parentNames = new HashSet<>(); Node parents = resolvedType.getTypeDeclarationNode().get("type"); if ( parents == null) { return nodes; } List<Node> parentTypeNodes = parents.getChildren(); for (Node parentTypeNode : parentTypeNodes) { NamedTypeExpressionNode parent = (NamedTypeExpressionNode) parentTypeNode; parentNames.add(parent.getValue()); } Node nn = node.getRootNode().get("types"); if ( nn == null ) { return nodes; } TypeDeclarationModelFactory factory = new TypeDeclarationModelFactory(); List<TypeDeclarationNode> typeDeclarationNodes = nn.findDescendantsWith(TypeDeclarationNode.class); for (TypeDeclarationNode declarationNode : typeDeclarationNodes) { if ( parentNames.contains(declarationNode.getTypeName()) ) { TypeDeclaration decl = factory.create(declarationNode); nodes.add(decl); } } return nodes; }</code><technical_language>running mvn fix code formatting</technical_language>

Target:
public List<TypeDeclaration<?>> parentTypes() { List<TypeDeclaration<?>> result = new ArrayList<>(); Node typeNode = getTypeNode(); if (typeNode instanceof ArrayNode) { List<Node> children = typeNode.getChildren(); for (Node child : children) { result.add(toTypeDeclaration(((NamedTypeExpressionNode) child).getRefNode())); } } else { if (typeNode instanceof NamedTypeExpressionNode) { result.add(toTypeDeclaration(((NamedTypeExpressionNode) typeNode).getRefNode())); } } return result; }
Source:
<code>private CommandLineCompleter getCompleter(final Map<String, CommandLineCompleterFactory> globalOpProps, final Property prop, CommandContext ctx, String operationName, OperationRequestAddress address) throws IllegalArgumentException { CommandLineCompleter propCompleter = null; final CommandLineCompleterFactory factory = globalOpProps == null ? null : globalOpProps.get(prop.getName()); if (factory != null) { final String propName = ctx.getParsedCommandLine().getPropertyValue(Util.NAME); <START> if (Util.WRITE_ATTRIBUTE.equals(operationName) && propName != null) { <END> return getFilenameCompleter(ctx, address, propName); } if (propCompleter == null) { propCompleter = factory.createCompleter(address); } } if (propCompleter == null) { final ModelNode typeNode = prop.getValue().get(Util.TYPE); if (typeNode.isDefined() && ModelType.BOOLEAN.equals(typeNode.asType())) { return SimpleTabCompleter.BOOLEAN; } if (prop.getValue().get(Util.FILESYSTEM_PATH).asBoolean()) { return Util.isWindows() ? new WindowsFilenameTabCompleter(ctx) : new DefaultFilenameTabCompleter(ctx); } if (prop.getValue().has(Util.VALUE_TYPE)) { final ModelNode valueTypeNode = prop.getValue().get(Util.VALUE_TYPE); try { valueTypeNode.asType(); if (prop.getValue().has(Util.ALLOWED)) { return getAllowedCompleter(prop); } } catch (IllegalArgumentException e) { return new ValueTypeCompleter(prop.getValue()); } } if (prop.getValue().has(Util.ALLOWED)) { return getAllowedCompleter(prop); } } return propCompleter; }</code><technical_language>"add" well</technical_language>

Target:
private CommandLineCompleter getCompleter(final Map<String, CommandLineCompleterFactory> globalOpProps, final Property prop, CommandContext ctx, String operationName, OperationRequestAddress address) throws IllegalArgumentException { CommandLineCompleter propCompleter = null; final CommandLineCompleterFactory factory = globalOpProps == null ? null : globalOpProps.get(prop.getName()); if (factory != null) { propCompleter = factory.createCompleter(ctx, address); } if (propCompleter == null) { final ModelNode typeNode = prop.getValue().get(Util.TYPE); if (typeNode.isDefined() && ModelType.BOOLEAN.equals(typeNode.asType())) { return SimpleTabCompleter.BOOLEAN; } if (prop.getValue().get(Util.FILESYSTEM_PATH).asBoolean()) { return Util.isWindows() ? new WindowsFilenameTabCompleter(ctx) : new DefaultFilenameTabCompleter(ctx); } if (prop.getValue().has(Util.VALUE_TYPE)) { final ModelNode valueTypeNode = prop.getValue().get(Util.VALUE_TYPE); try { valueTypeNode.asType(); if (prop.getValue().has(Util.ALLOWED)) { return getAllowedCompleter(prop); } } catch (IllegalArgumentException e) { return new ValueTypeCompleter(prop.getValue()); } } if (prop.getValue().has(Util.ALLOWED)) { return getAllowedCompleter(prop); } } return propCompleter; }
Source:
<code>public static CaseUserTaskWithVariablesList convertToCaseUserTaskWithVariablesList(List<UserTaskInstanceWithPotOwnerDesc> queryUserTasksByVariables) { List<CaseUserTaskWithVariables> data = new ArrayList<>(); for (UserTaskInstanceWithPotOwnerDesc desc : queryUserTasksByVariables) { CaseUserTaskWithVariables var = new CaseUserTaskWithVariables(); var.setId(desc.getTaskId()); var.setName(desc.getName()); var.setProcessInstanceId(desc.getProcessInstanceId()); var.setCorrelationKey(desc.getCorrelationKey()); var.setActualOwner(desc.getActualOwner()); var.setCaseDefinitionId(desc.getProcessId()); var.setPotentialOwners(desc.getPotentialOwners()); var.setCaseId(desc.getCorrelationKey()); var.setProcessVariables(desc.getProcessVariables()); var.setInputVariables(desc.getInputdata()); var.setCaseVariables(desc.getExtraData()); data.add(var); } CaseUserTaskWithVariablesList result = new CaseUserTaskWithVariablesList(); <START> result.setCaseUserTaskWithVariables(data.parallelStream().toArray(CaseUserTaskWithVariables[]::new)); <END> return result; }</code><technical_language>parallelStream here</technical_language>

Target:
public static CaseUserTaskWithVariablesList convertToCaseUserTaskWithVariablesList(List<UserTaskInstanceWithPotOwnerDesc> queryUserTasksByVariables) { List<CaseUserTaskWithVariables> data = new ArrayList<>(); for (UserTaskInstanceWithPotOwnerDesc desc : queryUserTasksByVariables) { CaseUserTaskWithVariables var = new CaseUserTaskWithVariables(); var.setId(desc.getTaskId()); var.setName(desc.getName()); var.setProcessInstanceId(desc.getProcessInstanceId()); var.setCorrelationKey(desc.getCorrelationKey()); var.setActualOwner(desc.getActualOwner()); var.setCaseDefinitionId(desc.getProcessId()); var.setPotentialOwners(desc.getPotentialOwners()); var.setCaseId(desc.getCorrelationKey()); var.setProcessVariables(desc.getProcessVariables()); var.setInputVariables(desc.getInputdata()); var.setCaseVariables(desc.getExtraData()); data.add(var); } CaseUserTaskWithVariablesList result = new CaseUserTaskWithVariablesList(); result.setCaseUserTaskWithVariables(data.stream().toArray(CaseUserTaskWithVariables[]::new)); return result; }
Source:
<code>public static void main(String[] args) throws NamingException, JMSException { QueueConsumer queueConsumer = new QueueConsumer("Transactional-Queue"); TransactionalQueuePublisher transactionalQueuePublisher = new TransactionalQueuePublisher("Transactional-Queue"); log.info("------Sample for Message Sending and Committing.------"); transactionalQueuePublisher.sendMessage("My First Message."); queueConsumer.receiveMessage(); transactionalQueuePublisher.sendMessage("My Second Message."); transactionalQueuePublisher.commitMessages(); queueConsumer.receiveMessage(); queueConsumer.receiveMessage(); log.info("------Sample for Message Sending, Rollback and Committing.------"); <START> transactionalQueuePublisher.sendMessage("My Unique Message."); <END> queueConsumer.receiveMessage(); transactionalQueuePublisher.rollbackMessages(); transactionalQueuePublisher.sendMessage("My Unique Message."); transactionalQueuePublisher.commitMessages(); queueConsumer.receiveMessage(); queueConsumer.receiveMessage(); System.exit(0); }</code><technical_language>a string? messages for rollbacked committed message IMO</technical_language>

Target:
public static void main(String[] args) throws NamingException, JMSException { QueueConsumer queueConsumer = new QueueConsumer("Transactional-Queue"); TransactionalQueuePublisher transactionalQueuePublisher = new TransactionalQueuePublisher("Transactional-Queue"); log.info("------Sample for Message Sending and Committing.------"); transactionalQueuePublisher.sendMessage("My First Message."); queueConsumer.receiveMessage(); transactionalQueuePublisher.sendMessage("My Second Message."); transactionalQueuePublisher.commitMessages(); queueConsumer.receiveMessage(); queueConsumer.receiveMessage(); log.info("------Sample for Message Sending, Rollback and Committing.------"); transactionalQueuePublisher.sendMessage("My Third Message."); queueConsumer.receiveMessage(); transactionalQueuePublisher.rollbackMessages(); transactionalQueuePublisher.sendMessage("My Forth Message."); transactionalQueuePublisher.commitMessages(); queueConsumer.receiveMessage(); queueConsumer.receiveMessage(); System.exit(0); }
Source:
<code><START> public static void wipeDataBase() { <END> Delete.tables( EventFlow.class, TrackedEntityDataValueFlow.class, DataElementFlow.class, ProgramFlow.class, AttributeFlow.class, AttributeValueFlow.class, ModelLinkFlow.class, OptionSetFlow.class, OptionFlow.class, OrganisationUnitFlow.class, OrganisationUnitLevelFlow.class, OrganisationUnitToProgramRelationFlow.class, ProgramStageDataElementFlow.class, ProgramStageSectionFlow.class, ProgramStageFlow.class, FailedItemFlow.class, StateFlow.class, FailedItemFlow.class ); }</code><technical_language>@idelcano is practice in this case convert static this method PullDhisSDKDataSource is a class state. refactor extract this method other place</technical_language>

Target:
public void wipeDataBase() { Delete.tables( EventFlow.class, TrackedEntityDataValueFlow.class, DataElementFlow.class, ProgramFlow.class, AttributeFlow.class, AttributeValueFlow.class, ModelLinkFlow.class, OptionSetFlow.class, OptionFlow.class, OrganisationUnitFlow.class, OrganisationUnitLevelFlow.class, OrganisationUnitToProgramRelationFlow.class, ProgramStageDataElementFlow.class, ProgramStageSectionFlow.class, ProgramStageFlow.class, FailedItemFlow.class, StateFlow.class, FailedItemFlow.class ); }
Source:
<code>public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) { context = ObjectUtil.nvl(context, new EvaluationContext()); SqlCohortDefinition sqlCohortDefinition = (SqlCohortDefinition) cohortDefinition; EvaluatedCohort ret = new EvaluatedCohort(sqlCohortDefinition, context); if (context.getBaseCohort() != null && context.getBaseCohort().isEmpty()) { return ret; <START> } <END> final Boolean includeChildLocations = (Boolean) context.getParameterValue("includeChildLocations"); if (includeChildLocations != null && includeChildLocations) { final List<Location> locationList = (List<Location>) context.getParameterValue("locationList"); final Map<String, Object> parameterValues = context.getParameterValues(); parameterValues.put("locationList", getLocationsIncludingChildLocations(locationList)); context.setParameterValues(parameterValues); } SqlQueryBuilder qb = new SqlQueryBuilder(sqlCohortDefinition.getQuery(), context.getParameterValues()); if (sqlCohortDefinition.getQuery().contains(":patientIds")) { qb.addParameter("patientIds", context.getBaseCohort()); } List<Integer> l = evaluationService.evaluateToList(qb, Integer.class, context); if (context.getBaseCohort() != null) { l.retainAll(context.getBaseCohort().getMemberIds()); } ret.setMemberIds(new HashSet<Integer>(l)); return ret; }</code><technical_language>I is need modify parameter values in context here. SqlQueryBuilder simply takes in a Map<String, Object>. clone parameter values of context start, modify this Map of parameter values list of locations if necessary, pass this query builder. If modify context, affect of invalidating cache, other side effects, is avoid if is needed</technical_language>

Target:
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) { context = ObjectUtil.nvl(context, new EvaluationContext()); SqlCohortDefinition sqlCohortDefinition = (SqlCohortDefinition) cohortDefinition; EvaluatedCohort ret = new EvaluatedCohort(sqlCohortDefinition, context); if (context.getBaseCohort() != null && context.getBaseCohort().isEmpty()) { return ret; } final Boolean includeChildLocations = (Boolean) context.getParameterValue("includeChildLocations"); Map<String, Object> parameterValues; if (includeChildLocations != null && includeChildLocations) { final List<Location> locationList = (List<Location>) context.getParameterValue("locationList"); parameterValues = new HashMap<String, Object>(context.getParameterValues()); parameterValues.put("locationList", getLocationsIncludingChildLocations(locationList)); } else { parameterValues = context.getParameterValues(); } SqlQueryBuilder qb = new SqlQueryBuilder(sqlCohortDefinition.getQuery(), parameterValues); if (sqlCohortDefinition.getQuery().contains(":patientIds")) { qb.addParameter("patientIds", context.getBaseCohort()); } List<Integer> l = evaluationService.evaluateToList(qb, Integer.class, context); if (context.getBaseCohort() != null) { l.retainAll(context.getBaseCohort().getMemberIds()); } ret.setMemberIds(new HashSet<Integer>(l)); return ret; }
Source:
<code>public static VMImage create(String name, String label, String category, String description, OSDiskConfiguration osDiskConfiguration, List<DataVirtualHardDisk> dataDiskConfiguration, String serviceName, String deploymentName, String roleName, String location, String affinityGroup, Date createdTime, Date modifiedTime, String language, String imageFamily, RoleSize.Type recommendedVMSize, Boolean isPremium, String eula, URI iconUri, URI smallIconUri, URI privacyUri, Date publishedDate) { <START> return new AutoValue_VMImage(name, label, category, description, osDiskConfiguration, dataDiskConfiguration, <END> serviceName, deploymentName, roleName, location, affinityGroup, createdTime, modifiedTime, language, imageFamily, recommendedVMSize, isPremium, eula, iconUri, smallIconUri, privacyUri, publishedDate); }</code><technical_language>ImmutableList.copyOf(dataDiskConfiguration)</technical_language>

Target:
public static VMImage create(String name, String label, String category, String description, OSDiskConfiguration osDiskConfiguration, List<DataVirtualHardDisk> dataDiskConfiguration, String serviceName, String deploymentName, String roleName, String location, String affinityGroup, Date createdTime, Date modifiedTime, String language, String imageFamily, RoleSize.Type recommendedVMSize, Boolean isPremium, String eula, URI iconUri, URI smallIconUri, URI privacyUri, Date publishedDate) { return new AutoValue_VMImage(name, label, category, description, osDiskConfiguration, copyOf(dataDiskConfiguration), serviceName, deploymentName, roleName, location, affinityGroup, createdTime, modifiedTime, language, imageFamily, recommendedVMSize, isPremium, eula, iconUri, smallIconUri, privacyUri, publishedDate); }
Source:
<code>private void createDropDownPopup() { if (dropDownPopup == null) { dropDownPopup = new FilterDropdownListBox<ListType>(resources); dropDownPopup.setStyleName(this.resources.filterDropdownStyle().dropDownPopUpContainer()); dropDownPopup.setPopupPosition(this.getAbsoluteLeft(), this.getAbsoluteTop() + this.getOffsetHeight()); <START> dropDownPopup.setWidth(this.getOffsetWidth() + "px"); <END> dropDownPopup.show(); dropDownPopup.addCloseHandler(new CloseHandler<PopupPanel>() { @Override public void onClose(CloseEvent<PopupPanel> event) { dropDownPopup = null; } }); } }</code><technical_language>Unit.PX constant</technical_language>

Target:
private void createDropDownPopup() { if (dropDownPopup == null) { dropDownPopup = new FilterDropdownListBox<ListType>(resources); dropDownPopup.setStyleName(this.resources.filterDropdownStyle().dropDownPopUpContainer()); dropDownPopup.setPopupPosition(this.getAbsoluteLeft(), this.getAbsoluteTop() + this.getOffsetHeight()); dropDownPopup.setWidth(this.getOffsetWidth() + Unit.PX.getType()); dropDownPopup.show(); dropDownPopup.addCloseHandler(new CloseHandler<PopupPanel>() { @Override public void onClose(CloseEvent<PopupPanel> event) { dropDownPopup = null; } }); } }
Source:
<code>public void build(@NotNull ErlangTarget target, @NotNull DirtyFilesHolder<ErlangSourceRootDescriptor, ErlangTarget> holder, @NotNull BuildOutputConsumer outputConsumer, @NotNull CompileContext context) throws ProjectBuildException, IOException { JpsModule module = target.getModule(); JpsProject project = module.getProject(); ErlangCompilerOptions compilerOptions = JpsErlangCompilerOptionsExtension.getOrCreateExtension(project).getOptions(); if (compilerOptions.myUseRebarCompiler) return; LOG.info("Starting build for " + target.getPresentableName()); File sourceOutput = getBuildOutputDirectory(module, false, context); File testOutput = getBuildOutputDirectory(module, true, context); if (holder.hasRemovedFiles()) { LOG.debug("Remove invalid .beam and .app files."); <START> removeOutputFiles(holder.getRemovedFiles(target), sourceOutput, testOutput); <END> } buildSources(target, context, compilerOptions, outputConsumer, sourceOutput, false); buildSources(target, context, compilerOptions, outputConsumer, testOutput, true); processAppConfigFiles(holder, outputConsumer, context, sourceOutput, testOutput); }</code><technical_language>lying - .app files get removed a result of this method call</technical_language>

Target:
public void build(@NotNull ErlangTarget target, @NotNull DirtyFilesHolder<ErlangSourceRootDescriptor, ErlangTarget> holder, @NotNull BuildOutputConsumer outputConsumer, @NotNull CompileContext context) throws ProjectBuildException, IOException { JpsModule module = target.getModule(); JpsProject project = module.getProject(); ErlangCompilerOptions compilerOptions = JpsErlangCompilerOptionsExtension.getOrCreateExtension(project).getOptions(); if (compilerOptions.myUseRebarCompiler) return; LOG.info("Build module " + target.getPresentableName()); File sourceOutput = getBuildOutputDirectory(module, false, context); File testOutput = getBuildOutputDirectory(module, true, context); if (holder.hasRemovedFiles()) { LOG.debug("Remove invalid .beam and .app files."); removeOutputFiles(holder.getRemovedFiles(target), sourceOutput, testOutput); } buildSources(target, context, compilerOptions, outputConsumer, sourceOutput, false); buildSources(target, context, compilerOptions, outputConsumer, testOutput, true); processAppConfigFiles(holder, outputConsumer, context, sourceOutput, testOutput); }
Source:
<code>public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config == null) { throw new ConfigurationException("influxdb", "The configuration for influxdb is missing fix openhab.cfg"); } url = (String) config.get("url"); if (StringUtils.isBlank(url)) { throw new ConfigurationException("influxdb:url", "The database URL is missing - please configure the url parameter in openhab.cfg"); } user = (String) config.get("user"); if (StringUtils.isBlank(user)) { throw new ConfigurationException("influxdb:user", "The user is missing - please configure the user parameter in openhab.cfg"); } password = (String) config.get("password"); if (StringUtils.isBlank(password)) { throw new ConfigurationException("influxdb:password", "The password is missing. To specify a password configure the password parameter in openhab.cfg."); } dbName = (String) config.get("db"); <START> if (StringUtils.isBlank(dbName)) { <END> throw new ConfigurationException("influxdb:db", "The db name is missing. To specify a db name configure the db parameter in openhab.cfg."); } disconnect(); connect(); isProperlyConfigured = true; }</code><technical_language>a reasonable default value? (if yes, please mentioned this default in openhab_default.cfg)</technical_language>

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { disconnect(); if (config == null) { throw new ConfigurationException("influxdb", "The configuration for influxdb is missing fix openhab.cfg"); } url = (String) config.get("url"); if (StringUtils.isBlank(url)) { url = DEFAULT_URL; logger.debug("using default url {}", DEFAULT_URL); } user = (String) config.get("user"); if (StringUtils.isBlank(user)) { user = DEFAULT_USER; logger.debug("using default user {}", DEFAULT_USER); } password = (String) config.get("password"); if (StringUtils.isBlank(password)) { throw new ConfigurationException("influxdb:password", "The password is missing. To specify a password configure the password parameter in openhab.cfg."); } dbName = (String) config.get("db"); if (StringUtils.isBlank(dbName)) { dbName = DEFAULT_DB; logger.debug("using default db name {}", DEFAULT_DB); } isProperlyConfigured = true; connect(); if ( ! checkConnection()){ logger.error("database connection does not work for now, will retry to use the database."); } }
Source:
<code>public void testRandomPatterns() throws <START> UnsupportedEncodingException, IOException, IllegalStateException, GitAPIException, InterruptedException { <END> File gitDir = Files.createTempDirectory("jgit").toFile(); Git.init().setDirectory(gitDir).call(); PseudoRandomPatternGenerator generator = new PseudoRandomPatternGenerator(); for (int i = 0; i < NB_PATTERN; i++) { String pattern = generator.nextRandomString(); FastIgnoreRule jgitIgnoreRule = new FastIgnoreRule(pattern); CGitIgnoreRule cgitIgnoreRule = new CGitIgnoreRule(gitDir, pattern); assertCgitAndJgitMatch(pattern, jgitIgnoreRule, cgitIgnoreRule, pattern); for (int p = 0; p < PATH_PER_PATTERN; p++) { String path = generator.nextRandomString(); assertCgitAndJgitMatch(pattern, jgitIgnoreRule, cgitIgnoreRule, path); } } }</code><technical_language>handle exceptions declare "throws Exception" in test cases</technical_language>

Target:
public void testRandomPatterns() throws Exception { File gitDir = Files.createTempDirectory("jgit").toFile(); Git.init().setDirectory(gitDir).call(); PseudoRandomPatternGenerator generator = new PseudoRandomPatternGenerator(); for (int i = 0; i < NB_PATTERN; i++) { String pattern = generator.nextRandomString(); FastIgnoreRule jgitIgnoreRule = new FastIgnoreRule(pattern); CGitIgnoreRule cgitIgnoreRule = new CGitIgnoreRule(gitDir, pattern); assertCgitAndJgitMatch(pattern, jgitIgnoreRule, cgitIgnoreRule, pattern); for (int p = 0; p < PATH_PER_PATTERN; p++) { String path = generator.nextRandomString(); assertCgitAndJgitMatch(pattern, jgitIgnoreRule, cgitIgnoreRule, path); } } }
Source:
<code>public final NamedInputStream getIndexScript() { <START> return getScriptAsStream(indexScript); <END> }</code><technical_language>default "index_generic.sql" subclasses override this id appropriate</technical_language>

Target:
public ScriptRunner getIndexScript() throws IOException { return getScriptRunner("index_generic.sql"); }
Source:
<code>private static Map<String, Object> parseArgs(String[] args) throws Exception { if(args.length < 1) { throw new IllegalArgumentException("Please provide module. To list existing modules use --help argument."); } return new ParametersParser( CoreUtil.loadProperties(ExtensionsToolExecutor.class, "arguments.properties"), <START> CoreUtil.loadProperties(ExtensionsToolExecutor.class, "defaults.properties") <END> ).parse(args); }</code><technical_language>defaults loaded parameters parser here, I understand defaults :)</technical_language>

Target:
private static Map<String, Object> parseArgs(String[] args) throws Exception { if(args.length < 1) { throw new IllegalArgumentException("Please provide module. To list existing modules use --help argument."); } return new ParametersParser( CoreUtil.loadProperties(ExtensionsToolExecutor.class, "arguments.properties") ).parse(args); }
Source:
<code>public void updateParentCommits(IRepository parent, IReview review, ChangeDetailX detail) { Map<Integer, CommitInfo[]> parents = detail.getParents(); if (parents == null) { return; } List<IReviewItemSet> sets = review.getSets(); for (Entry<Integer, CommitInfo[]> parentCommit : parents.entrySet()) { IReviewItemSet reviewItemSet = sets.get(parentCommit.getKey() - 1); for (CommitInfo gerritCommit : parentCommit.getValue()) { <START> ICommit commit = IReviewsFactory.INSTANCE.createCommit(); <END> commit.setId(gerritCommit.getCommit()); IUser commitAuthor = IReviewsFactory.INSTANCE.createUser(); GitPersonalInfo author = gerritCommit.getAuthor(); if (author != null) { commitAuthor.setId(author.getName()); commitAuthor.setDisplayName(author.getName()); commitAuthor.setEmail(author.getEmail()); commit.setAuthor(commitAuthor); } commit.setSubject(gerritCommit.getSubject()); commit.setMessage(gerritCommit.getMessage()); commit.setId(gerritCommit.getCommit()); reviewItemSet.getParentCommits().add(commit); } } }</code><technical_language>out of model</technical_language>

Target:
public void updateParentCommits(IRepository parent, IReview review, ChangeDetailX detail) { Map<Integer, CommitInfo[]> parents = detail.getParents(); if (parents == null) { return; } List<IReviewItemSet> sets = review.getSets(); for (Entry<Integer, CommitInfo[]> parentCommit : parents.entrySet()) { IReviewItemSet reviewItemSet = sets.get(parentCommit.getKey() - 1); for (CommitInfo gerritCommit : parentCommit.getValue()) { ICommit commit = IReviewsFactory.INSTANCE.createCommit(); commit.setId(gerritCommit.getCommit()); commit.setSubject(gerritCommit.getSubject()); IUser commitAuthor = IReviewsFactory.INSTANCE.createUser(); GitPersonalInfo author = gerritCommit.getAuthor(); if (author != null) { commitAuthor.setId(author.getName()); commitAuthor.setDisplayName(author.getName()); commitAuthor.setEmail(author.getEmail()); commit.setAuthor(commitAuthor); } commit.setMessage(gerritCommit.getMessage()); List<ICommit> parentCommits = reviewItemSet.getParentCommits(); if (!hasCommit(parentCommits, commit)) { parentCommits.add(commit); } } } }
Source:
<code>public void delete(IProgressMonitor progressMonitor, boolean overwriting, boolean closeEditors) throws CoreException { if (closeEditors) { Display.getDefault().syncExec(new Runnable() { @Override <START> public void run() { <END> closeEditors(); } }); } IPath path = getResource().getLocation(); if (path != null) { if (getParent() instanceof TmfTraceFolder) { TmfExperimentFolder experimentFolder = getProject().getExperimentsFolder(); if (experimentFolder != null && !overwriting) { for (TmfExperimentElement experiment : experimentFolder.getExperiments()) { List<TmfTraceElement> toRemove = new LinkedList<>(); for (TmfTraceElement trace : experiment.getTraces()) { if (trace.getElementPath().equals(getElementPath())) { toRemove.add(trace); } } for (TmfTraceElement child : toRemove) { experiment.removeTrace(child); } if (!toRemove.isEmpty() && experiment.getTraces().isEmpty()) { experiment.deleteSupplementaryFolder(); experiment.getResource().delete(true, progressMonitor); } } } if (overwriting) { deleteSupplementaryResources(); } else { deleteSupplementaryFolder(); } } else if (getParent() instanceof TmfExperimentElement) { TmfExperimentElement experimentElement = (TmfExperimentElement) getParent(); experimentElement.removeTrace(this); } } getResource().delete(true, progressMonitor); }</code><technical_language>get a method reference here</technical_language>

Target:
public void delete(IProgressMonitor progressMonitor, boolean overwriting, boolean closeEditors) throws CoreException { if (closeEditors) { Display.getDefault().syncExec(this::closeEditors); } IPath path = getResource().getLocation(); if (path != null) { if (getParent() instanceof TmfTraceFolder) { TmfExperimentFolder experimentFolder = getProject().getExperimentsFolder(); if (experimentFolder != null && !overwriting) { for (TmfExperimentElement experiment : experimentFolder.getExperiments()) { List<TmfTraceElement> toRemove = new LinkedList<>(); for (TmfTraceElement trace : experiment.getTraces()) { if (trace.getElementPath().equals(getElementPath())) { toRemove.add(trace); } } for (TmfTraceElement child : toRemove) { experiment.removeTrace(child, false); } if (!toRemove.isEmpty() && experiment.getTraces().isEmpty()) { experiment.deleteSupplementaryFolder(); experiment.getResource().delete(true, progressMonitor); } } } if (overwriting) { deleteSupplementaryResources(); } else { deleteSupplementaryFolder(); } } else if (getParent() instanceof TmfExperimentElement) { TmfExperimentElement experimentElement = (TmfExperimentElement) getParent(); experimentElement.removeTrace(this, false); } } getResource().delete(true, progressMonitor); }
Source:
<code>public ActionResult execute() { String studentId = getNonNullRequestParamValue(Const.ParamsNames.STUDENT_ID); try { <START> StudentProfileAttributes studentProfile = extractProfileData(studentId); <END> logic.updateOrCreateStudentProfile(sanitizeProfile(studentProfile)); return new JsonResult(Const.StatusMessages.STUDENT_PROFILE_EDITED, HttpStatus.SC_ACCEPTED); } catch (InvalidParametersException ipe) { return new JsonResult(ipe.getMessage(), HttpStatus.SC_BAD_REQUEST); } }</code><technical_language>Similarly here; access control check broken</technical_language>

Target:
public ActionResult execute() { String studentId = getNonNullRequestParamValue(Const.ParamsNames.STUDENT_ID); if (!studentId.equals(userInfo.id) && !isMasqueradeMode()) { return new JsonResult("You are not authorized to update this student's profile.", HttpStatus.SC_FORBIDDEN); } try { StudentProfileAttributes studentProfile = extractProfileData(studentId); logic.updateOrCreateStudentProfile(sanitizeProfile(studentProfile)); return new JsonResult(Const.StatusMessages.STUDENT_PROFILE_EDITED, HttpStatus.SC_ACCEPTED); } catch (InvalidParametersException ipe) { return new JsonResult(ipe.getMessage(), HttpStatus.SC_BAD_REQUEST); } }
Source:
<code>public void addPermission(Permission permission) throws PermissionException { <START> log.debug("Add permission " + permission); <END> this.getPermissionsDAO().addPermission(permission); }</code><technical_language>add isDebugEnabled check a string concatenation</technical_language>

Target:
public void addPermission(Permission permission) throws PermissionException { if (log.isDebugEnabled()) { log.debug("Add permission " + permission); } this.getPermissionsDAO().addPermission(permission); }
Source:
<code>private void handleSendImage(Intent intent) { Uri selectedImage = null; ArrayList<Uri> selectedImagesArray = new ArrayList<>(); selectedImage = intent.getParcelableExtra(Intent.EXTRA_STREAM); <START> selectedImagesArray.add(selectedImage); <END> chooseDialog(selectedImagesArray); }</code><technical_language>remove check if (selectedImage != null) {.... Is usefull</technical_language>

Target:
private void handleSendImage(Intent intent) { Uri selectedImage = null; ArrayList<Uri> selectedImagesArray = new ArrayList<>(); selectedImage = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (selectedImage != null) { selectedImagesArray.add(selectedImage); chooseDialog(selectedImagesArray); } }
Source:
<code>public void onEvent(RowData event, long eventTimestamp, WatermarkOutput output) { try { Long watermark = innerWatermarkGenerator.currentWatermark(event); if (watermark != null) { <START> currentWatermark = innerWatermarkGenerator.currentWatermark(event); <END> } } catch (Exception e) { throw new RuntimeException( String.format("Generated WatermarkGenerator fails to generate for row: %s.", event), e); } }</code><technical_language>Do calculate again</technical_language>

Target:
public void onEvent(RowData event, long eventTimestamp, WatermarkOutput output) { try { Long watermark = innerWatermarkGenerator.currentWatermark(event); if (watermark != null) { currentWatermark = watermark; } } catch (Exception e) { throw new RuntimeException( String.format("Generated WatermarkGenerator fails to generate for row: %s.", event), e); } }
Source:
<code>Collection<NotificationFilter> getAllFilters(boolean allWikis) throws NotificationException; Collection<NotificationFilter> getAllFilters(DocumentReference user, boolean onlyEnabled) throws NotificationException; default Collection<NotificationFilter> getAllFilters(DocumentReference user, boolean onlyEnabled, <START> Set<NotificationFilter.FilteringMoment> filteringMoments) <END> throws NotificationException { return getAllFilters(user, onlyEnabled); }</code><technical_language>I understand need a Set here. I feels this method get filters for: * pre filtering * post filtering * this expressed a single FilteringMoment parameter already</technical_language>

Target:
Collection<NotificationFilter> getAllFilters(boolean allWikis) throws NotificationException; Collection<NotificationFilter> getAllFilters(DocumentReference user, boolean onlyEnabled) throws NotificationException; @Unstable default Collection<NotificationFilter> getAllFilters(DocumentReference user, boolean onlyEnabled, NotificationFilter.FilteringPhase filteringPhase) throws NotificationException { return getAllFilters(user, onlyEnabled); }
Source:
<code>public boolean isAPIThrottled(String apiKey){ boolean isThrottled = this.throttledAPIKeysMap.containsKey(apiKey); if(isThrottled) { long currentTime = System.currentTimeMillis(); long timestamp = this.throttledAPIKeysMap.get(apiKey); if(timestamp >= currentTime) { return isThrottled; } else { this.throttledAPIKeysMap.remove(apiKey); this.conditionDtoMap.remove(apiKey); return false; <START> }APIUtil <END> } else { return isThrottled; } }</code><technical_language>remove APIUtil</technical_language>

Target:
public boolean isAPIThrottled(String apiKey){ boolean isThrottled = this.throttledAPIKeysMap.containsKey(apiKey); if(isThrottled) { long currentTime = System.currentTimeMillis(); long timestamp = this.throttledAPIKeysMap.get(apiKey); if(timestamp >= currentTime) { return isThrottled; } else { this.throttledAPIKeysMap.remove(apiKey); this.conditionDtoMap.remove(apiKey); return false; } } else { return isThrottled; } }
Source:
<code>public TactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View tactContent; switch (viewType) { <START> case 1: <END> tactContent = LayoutInflater.from(parent.getContext()).inflate(R.layout.pocketmusic_add_tact_button, parent, false); tactContent.setLayoutParams(tactViewParams); tactContent.setOnClickListener(addTactClickListener); break; case 2: tactContent = LayoutInflater.from(parent.getContext()).inflate(R.layout.pocketmusic_empty_view, parent, false); tactContent.setLayoutParams(tactViewParams); break; default: tactContent = new TrackView(getContext(), trackGrid); tactContent.setLayoutParams(tactViewParams); break; } return new TactViewHolder(tactContent); }</code><technical_language>Please PLUS_VIEW_TYPE here</technical_language>

Target:
public TactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View tactContent; switch (viewType) { case PLUS_VIEW_TYPE: tactContent = LayoutInflater.from(parent.getContext()).inflate(R.layout.pocketmusic_add_tact_button, parent, false); tactContent.setLayoutParams(tactViewParams); tactContent.setOnClickListener(addTactClickListener); break; case EMPTY_VIEW_TYPE: tactContent = LayoutInflater.from(parent.getContext()).inflate(R.layout.pocketmusic_empty_view, parent, false); tactContent.setLayoutParams(tactViewParams); break; default: tactContent = new TrackView(getContext(), trackGrid); tactContent.setLayoutParams(tactViewParams); break; } return new TactViewHolder(tactContent); }
Source:
<code>public void onCreate() { super.onCreate(); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); log.info("WalletApplication.onCreate()"); config = new Configuration(PreferenceManager.getDefaultSharedPreferences(this), getResources()); autoLogout = new AutoLogout(config); <START> myPackageReplaced = false; <END> registerActivityLifecycleCallbacks(new ActivitiesTracker() { @Override protected void onStartedFirst(Activity activity) { autoLogout.setAppInBackground(false); if (wallet != null && config.getAutoLogoutEnabled() && (deviceWasLocked || autoLogout.shouldLogout())) { lockTheApp(WalletApplication.this, activity); if (autoLogout.isTimerActive()) { autoLogout.stopTimer(); } } } @Override protected void onStartedAny(boolean isTheFirstOne) { super.onStartedAny(isTheFirstOne); if (!BuildConfig.DEBUG && myPackageReplaced) { myPackageReplaced = false; ProcessPhoenix.triggerRebirth(WalletApplication.this); } } @Override protected void onStoppedLast() { autoLogout.setAppInBackground(true); } }); walletFile = getFileStreamPath(Constants.Files.WALLET_FILENAME_PROTOBUF); if (walletFileExists()) { fullInitialization(); } registerDeviceInteractiveReceiver(); }</code><technical_language>If var is initialized false declaration, needs set false well</technical_language>

Target:
public void onCreate() { super.onCreate(); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); log.info("WalletApplication.onCreate()"); config = new Configuration(PreferenceManager.getDefaultSharedPreferences(this), getResources()); autoLogout = new AutoLogout(config); registerActivityLifecycleCallbacks(new ActivitiesTracker() { @Override protected void onStartedFirst(Activity activity) { autoLogout.setAppInBackground(false); if (wallet != null && config.getAutoLogoutEnabled() && (deviceWasLocked || autoLogout.shouldLogout())) { lockTheApp(WalletApplication.this, activity); if (autoLogout.isTimerActive()) { autoLogout.stopTimer(); } } } @Override protected void onStartedAny(boolean isTheFirstOne) { super.onStartedAny(isTheFirstOne); if (!BuildConfig.DEBUG && myPackageReplaced) { myPackageReplaced = false; ProcessPhoenix.triggerRebirth(WalletApplication.this); } } @Override protected void onStoppedLast() { autoLogout.setAppInBackground(true); } }); walletFile = getFileStreamPath(Constants.Files.WALLET_FILENAME_PROTOBUF); if (walletFileExists()) { fullInitialization(); } registerDeviceInteractiveReceiver(); }
Source:
<code>public float getProgress() throws IOException { <START> return 1.0f; <END> }</code><technical_language>determine in processing of file</technical_language>

Target:
public float getProgress() throws IOException { float progress = (float) inputStream.getTotalBytes() / availableBytes; return Float.valueOf(df.format(progress)); }
Source:
<code>public static Map<String, Set<String>> parseArgs(String[] args) { Map<String, Set<String>> parsedArgs = new HashMap<>(); for (String arg : args) { int index = arg.indexOf("="); if (arg.startsWith("--") && index > 0) { <START> String key = arg.substring(2, index); <END> Set<String> values = parsedArgs.get(key); if (values == null) { values = new HashSet<>(); parsedArgs.put(key, values); } values.add(arg.substring(index + 1)); } } return parsedArgs; }</code><technical_language>a variant String argName = arg.substring(2, index); parsedArgs.computeIfAbsent(argName, -> new HashSet<>()) .add(arg.substring(index + 1));</technical_language>

Target:
public static Map<String, Set<String>> parseArgs(String[] args) { Map<String, Set<String>> parsedArgs = new HashMap<>(); for (String arg : args) { int index = arg.indexOf("="); if (arg.startsWith("--") && index > 0) { String argName = arg.substring(2, index); parsedArgs.computeIfAbsent(argName, k -> new HashSet<>()) .add(arg.substring(index + 1)); } } return parsedArgs; }
Source:
<code>private void stopNetwork() { logger.debug("stopNetwork()"); try { network.close(); network = null; logger.info("Closed panStamp network"); } catch (ModemException e) { logger.error("Error closing panStamp network: " + e.getMessage(), e); } finally { <START> } <END> }</code><technical_language>remove empty finally block</technical_language>

Target:
private void stopNetwork() { logger.debug("stopNetwork()"); try { network.close(); network = null; logger.info("Closed panStamp network"); } catch (ModemException e) { logger.error("Error closing panStamp network: " + e.getMessage(), e); } }
Source:
<code>public void removeChangeListener() { collection = prepareRealmListInLooperThread(); Realm realm = looperThread.realm; final AtomicInteger listenerCalledCount = new AtomicInteger(0); RealmChangeListener<RealmList<Dog>> listener1 = new RealmChangeListener<RealmList<Dog>>() { @Override public void onChange(RealmList<Dog> element) { fail(); } }; OrderedRealmCollectionChangeListener<RealmList<Dog>> listener2 = new OrderedRealmCollectionChangeListener<RealmList<Dog>>() { @Override public void onChange(RealmList<Dog> collection, OrderedCollectionChangeSet changes) { fail(); } }; collection.addChangeListener(listener1); collection.addChangeListener(listener2); realm.beginTransaction(); collection.get(0).setAge(42); realm.commitTransaction(); collection.removeChangeListener(listener1); <START> collection.removeChangeListener(listener2); <END> realm.beginTransaction(); realm.cancelTransaction(); assertEquals(0, listenerCalledCount.get()); looperThread.testComplete(); }</code><technical_language>I listener in order removeChangeListener remove listeners</technical_language>

Target:
public void removeChangeListener() { collection = prepareRealmListInLooperThread(); Realm realm = looperThread.realm; final AtomicInteger listenerCalledCount = new AtomicInteger(0); RealmChangeListener<RealmList<Dog>> listener1 = new RealmChangeListener<RealmList<Dog>>() { @Override public void onChange(RealmList<Dog> element) { fail(); } }; OrderedRealmCollectionChangeListener<RealmList<Dog>> listener2 = new OrderedRealmCollectionChangeListener<RealmList<Dog>>() { @Override public void onChange(RealmList<Dog> collection, OrderedCollectionChangeSet changes) { assertEquals(0, listenerCalledCount.getAndIncrement()); } }; collection.addChangeListener(listener1); collection.addChangeListener(listener2); realm.beginTransaction(); collection.get(0).setAge(42); realm.commitTransaction(); collection.removeChangeListener(listener1); realm.beginTransaction(); realm.cancelTransaction(); assertEquals(1, listenerCalledCount.get()); looperThread.testComplete(); }
Source:
<code>private void fetchLocationProperties() { hiddenLocationIds = new ArrayList<>(); propertyOwners = new ArrayList<>(); FacilitiesManager.getLocationProperties(this, new Callback<HashMap<String, HashMap<String, String>>>() { @Override public void success(HashMap<String, HashMap<String, String>> stringHashMapHashMap, Response response) { <START> Iterator iterator = stringHashMapHashMap.entrySet().iterator(); <END> while (iterator.hasNext()) { Map.Entry pair = (Map.Entry) iterator.next(); if (pair.getValue().toString().contains(HIDDEN)) { hiddenLocationIds.add(pair.getKey().toString()); } if (pair.getValue().toString().contains(LEASED)) { FacilitiesPropertyOwner propertyOwner = new FacilitiesPropertyOwner(); propertyOwner.setId(pair.getKey().toString()); String value = pair.getValue().toString(); String[] valueSplits = value.split(","); for (int i = 0; i < valueSplits.length; i++) { String[] subvalueSplits = valueSplits[i].split("="); if (subvalueSplits[0].contains(PHONE)) { if (subvalueSplits.length > 1) { propertyOwner.setPhone(removeCharacter(subvalueSplits[1])); } } if (subvalueSplits[0].contains(EMAIL)) { if (subvalueSplits.length > 1) { propertyOwner.setEmail(removeCharacter(subvalueSplits[1])); } } if (subvalueSplits[0].contains(NAME)) { if (subvalueSplits.length > 1) { propertyOwner.setName(removeCharacter(subvalueSplits[1])); } } } propertyOwners.add(propertyOwner); } } if (name.equals(NEARBY_LOCATIONS)) { updatePlacesByLocation(); } else { locationIdsbyCategory = getIntent().getStringArrayListExtra(Constants.FACILITIES_LOCATIONS_KEY); updatePlacesByCategory(); } } @Override public void failure(RetrofitError error) { MitMobileApplication.bus.post(new OttoBusEvent.RetrofitFailureEvent(error)); } }); }</code><technical_language>Instead of pulling json strings in here, a custom deserializer in RetrofitManager parse json output object. a example in bottom of class file</technical_language>

Target:
private void fetchLocationProperties() { propertyOwners = new ArrayList<>(); FacilitiesManager.getLocationProperties(this, new Callback<FacilitiesPropertyOwnerWrapper>() { @Override public void success(FacilitiesPropertyOwnerWrapper facilitiesPropertyOwnerWrapper, Response response) { propertyOwners = facilitiesPropertyOwnerWrapper.getPropertyOwners(); removeHiddenLocations(); if (name.equals(NEARBY_LOCATIONS)) { updatePlacesByLocation(); } else { locationIdsbyCategory = getIntent().getStringArrayListExtra(Constants.FACILITIES_LOCATIONS_KEY); updatePlacesByCategory(); } } @Override public void failure(RetrofitError error) { MitMobileApplication.bus.post(new OttoBusEvent.RetrofitFailureEvent(error)); } }); }
Source:
<code>public FeedDTO fetchFeed(@PathVariable("id") Long feedId, Principal principal) { String username = ""; if (principal != null) { username = principal.getName(); <START> } <END> Optional<Feed> feedOptional = feedFetcherService.getFeed(feedId, username); Feed feed = feedOptional.orElseThrow(() -> new ResourceNotFoundException(feedId)); Optional<PostMonitor> monitorOptional = postMonitorService.getPostMonitor(feedId); PostMonitor postMonitor = monitorOptional.orElse(new PostMonitor(feedId)); return new FeedDTO(feed, postMonitor.getViews()); }</code><technical_language>Optional<PostMonitor> monitorOptional = postMonitorService.getPostMonitor(feedId); PostMonitor postMonitor = monitorOptional.orElse(new PostMonitor(feedId)); if move this code fetchService great</technical_language>

Target:
public FeedDTO fetchFeed(@PathVariable("id") Long feedId, Principal principal) { String username = ""; if (principal != null) { username = principal.getName(); } Optional<Feed> feedOptional = feedFetcherService.getFeed(feedId, username); Feed feed = feedOptional.orElseThrow(() -> new ResourceNotFoundException(feedId)); return new FeedDTO(feed); }