auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public void steps_are_not_executed_on_dry_run() throws Throwable { <END> { StepDefinition stepDefinition = mock(StepDefinition.class); Runtime runtime = createRuntime(backend); runtime.getRunner().runPickle(createPickleEventMatchingStepDefinitions(asList(stepDefinition), runtime)); verify(stepDefinition).execute(Matchers.anyString(), Matchers.<Object[]>any()); } { StepDefinition stepDefinition = mock(StepDefinition.class); Runtime dryRuntime = createRuntime(backend, "--dry-run"); dryRuntime.getRunner().runPickle(createPickleEventMatchingStepDefinitions(asList(stepDefinition), dryRuntime)); verify(stepDefinition, never()).execute(Matchers.anyString(), Matchers.<Object[]>any()); } }</code><technical_language>This test verifies things. I tests</technical_language>

Target:
public void steps_are_not_executed_on_dry_run() throws Throwable { final StepDefinition stepDefinition = mock(StepDefinition.class); final Runtime dryRuntime = createRuntime(backend, "--dry-run"); dryRuntime.getRunner().runPickle(createPickleEventMatchingStepDefinitions(asList(stepDefinition), dryRuntime)); verify(stepDefinition, never()).execute(Matchers.anyString(), Matchers.<Object[]>any()); }
Source:
<code>protected boolean nextInner() throws IOException { if (range == null) { return false; } boolean next = range.hasNext(); if (next) { String nextkey = range.next(); <START> key = (K) nextkey; <END> persistent = ((RedisStore<K, T>) getDataStore()).get(key, query.getFields()); } return next; }</code><technical_language>this cast work for a datastore key type Long? String nextkey = "101"; key = (Long) nextkey;</technical_language>

Target:
protected boolean nextInner() throws IOException { if (range == null) { return false; } boolean next = range.hasNext(); if (next) { key = (K) range.next(); persistent = ((RedisStore<K, T>) getDataStore()).get(key, query.getFields()); } return next; }
Source:
<code>public void init() { post( "/list/import", (request, response) -> { MultipartConfigElement multipartConfigElement = new MultipartConfigElement(""); request.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement); String listType = request.headers(LIST_TYPE_HEADER); if (StringUtils.isBlank(listType)) { String exceptionMessage = String.format("The header %s must be set.", LIST_TYPE_HEADER); LOGGER.info(exceptionMessage); createBadRequestResponse(exceptionMessage, response); return null; } List<Part> parts = new ArrayList<>(request.raw().getParts()); <START> Pair<AttachmentInfo, Metacard> attachmentInfo = <END> catalogService.parseAttachments(partsToInfo(parts), null); if (attachmentInfo == null) { String exceptionMessage = "Unable to parse the attachments."; LOGGER.debug(exceptionMessage); createBadRequestResponse(exceptionMessage, response); return null; } try (TemporaryFileBackedOutputStream temporaryFileBackedOutputStream = new TemporaryFileBackedOutputStream()) { IOUtils.copy(attachmentInfo.getLeft().getStream(), temporaryFileBackedOutputStream); for (Splitter splitter : lookupSplitters(attachmentInfo.getLeft().getContentType())) { if (attemptToSplitAndStore( response, listType, attachmentInfo, temporaryFileBackedOutputStream, splitter)) break; } } IOUtils.closeQuietly(attachmentInfo.getLeft().getStream()); return ""; }); }</code><technical_language>Is metacard in pair used? calling getLeft. In case, save pair, AttachmentInfo</technical_language>

Target:
public void init() { post( "/list/import", (request, response) -> { MultipartConfigElement multipartConfigElement = new MultipartConfigElement(""); request.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement); String listType = request.headers(LIST_TYPE_HEADER); if (StringUtils.isBlank(listType)) { String exceptionMessage = String.format("The header %s must be set.", LIST_TYPE_HEADER); LOGGER.info(exceptionMessage); createBadRequestResponse(exceptionMessage, response); return null; } List<Part> parts = new ArrayList<>(request.raw().getParts()); Map.Entry<AttachmentInfo, Metacard> attachmentInfo = catalogService.parseParts(parts, null); if (attachmentInfo == null) { String exceptionMessage = "Unable to parse the attachments."; LOGGER.debug(exceptionMessage); createBadRequestResponse(exceptionMessage, response); return null; } try (TemporaryFileBackedOutputStream temporaryFileBackedOutputStream = new TemporaryFileBackedOutputStream()) { IOUtils.copy(attachmentInfo.getKey().getStream(), temporaryFileBackedOutputStream); for (Splitter splitter : lookupSplitters(attachmentInfo.getKey().getContentType())) { if (attemptToSplitAndStore( response, listType, attachmentInfo, temporaryFileBackedOutputStream, splitter)) break; } } IOUtils.closeQuietly(attachmentInfo.getKey().getStream()); return ""; }); }
Source:
<code>public final void testSelect0() throws Exception { List<String> tables = executeDDL("sample1_ddl.sql", "sample1", "sample1"); <START> List inputList = new ArrayList<>(); <END> inputList.addAll(Arrays.asList("sample1")); assertEquals(inputList, tables); ResultSet res = executeQuery(); assertResultSet(res); cleanupQuery(res); }</code><technical_language>inputLists in this test necessary</technical_language>

Target:
public final void testSelect0() throws Exception { List<String> tables = executeDDL("sample1_ddl.sql", "sample1", "sample1"); assertEquals(Arrays.asList("sample1"), tables); ResultSet res = executeQuery(); assertResultSet(res); cleanupQuery(res); }
Source:
<code>public static String readContent(URL url) throws Exception { if (url == null) throw new Exception("unable to verify a null URL"); <START> return IOUtils.toString(url.openStream(), StandardCharsets.UTF_8); <END> }</code><technical_language>appears previous implementation implicitly Charset.defaultCharset() for processing URL. Some users want (or need) a Charset for processing URL, a small refactoring into: public static String readContent(final URL url) throws Exception { return readContent(url, StandardCharsets.UTF_8); } public static String readContent(final URL url, final Charset encoding) throws Exception { if (url == null) { throw new IllegalArgumentException("Unable verify a null URL"); } if (encoding == null) { throw new IllegalArgumentException("Unable verify URL a null Charset"); } return IOUtils.toString(url.openStream(), encoding); } useful</technical_language>

Target:
public static String readContent(URL url) throws Exception { return readContent(url, StandardCharsets.UTF_8); }
Source:
<code>private Field[] getFields(Class<?> currentClass) { final List<Field> fields = new ArrayList<>(); <START> if (currentClass != null) { do { <END> fields.addAll(Arrays.asList(currentClass.getDeclaredFields())); currentClass = currentClass.getSuperclass(); } while (currentClass.getSuperclass() != null); } return fields.toArray(new Field[0]); }</code><technical_language>if change while (currentClass != null) avoid outer if clause</technical_language>

Target:
private Field[] getFields(Class<?> currentClass) { final List<Field> fields = new ArrayList<>(); while (currentClass != null) { fields.addAll(Arrays.asList(currentClass.getDeclaredFields())); currentClass = currentClass.getSuperclass(); } return fields.toArray(new Field[0]); }
Source:
<code>public void handleColumnMultiEdit(TreeColumn treeColumn, Collection<TreeItem> treeItems) { try { Set<TeamWorkFlowArtifact> awas = new HashSet<>(); List<Artifact> arts = new ArrayList<>(); for (TreeItem item : treeItems) { Artifact art = AtsClientService.get().getQueryServiceClient().getArtifact(item); if (art.isOfType(AtsArtifactTypes.TeamWorkflow)) { awas.add((TeamWorkFlowArtifact) art); arts.add(art); } } <START> <END> for (AbstractWorkflowArtifact teamArt : awas) { promptChangeVersion(teamArt, AtsClientService.get().getUserService().isAtsAdmin() ? VersionReleaseType.Both : VersionReleaseType.UnReleased, AtsClientService.get().getUserService().isAtsAdmin() ? VersionLockedType.Both : VersionLockedType.UnLocked); ((XViewer) getXViewer()).update(awas.toArray(), null); } return; } catch (OseeCoreException ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } }</code><technical_language>want. If choose 10 workflows, complete 10 dialogs. other work</technical_language>

Target:
public void handleColumnMultiEdit(TreeColumn treeColumn, Collection<TreeItem> treeItems) { try { Set<TeamWorkFlowArtifact> awas = new HashSet<>(); List<Artifact> arts = new ArrayList<>(); for (TreeItem item : treeItems) { Artifact art = AtsClientService.get().getQueryServiceClient().getArtifact(item); if (art.isOfType(AtsArtifactTypes.TeamWorkflow)) { awas.add((TeamWorkFlowArtifact) art); arts.add(art); } } promptChangeVersionMultiSelect(new ArrayList<TeamWorkFlowArtifact>(awas), AtsClientService.get().getUserService().isAtsAdmin() ? VersionReleaseType.Both : VersionReleaseType.UnReleased, AtsClientService.get().getUserService().isAtsAdmin() ? VersionLockedType.Both : VersionLockedType.UnLocked); ((XViewer) getXViewer()).update(awas.toArray(), null); return; } catch (OseeCoreException ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } }
Source:
<code>public void startParsing() { BackgroundTask.wrap(() -> currentCitationfetcher.performSearch(inputTextProperty.getValue())) .onRunning(() -> dialogService.notify(Localization.lang("Your text is being parsed..."))) .onSuccess(parsedEntries -> { <START> dialogService.notify(Localization.lang("GROBID could parse %0 Entries from your query.", String.valueOf(parsedEntries.size()))); <END> importHandler.importEntries(parsedEntries); for (BibEntry bibEntry : parsedEntries) { trackNewEntry(bibEntry); } }).executeWith(taskExecutor); }</code><technical_language>Entries lowercase. I remove "GROBID" (as user this guy is)</technical_language>

Target:
public void startParsing() { BackgroundTask.wrap(() -> currentCitationfetcher.performSearch(inputTextProperty.getValue())) .onRunning(() -> dialogService.notify(Localization.lang("Your text is being parsed..."))) .onSuccess(parsedEntries -> { dialogService.notify(Localization.lang("%0 entries were parsed from your query.", String.valueOf(parsedEntries.size()))); importHandler.importEntries(parsedEntries); for (BibEntry bibEntry : parsedEntries) { trackNewEntry(bibEntry); } }).executeWith(taskExecutor); }
Source:
<code>public Builder() { this.settings = new ESSettings(); this.settings.setClusterName("elasticsearch"); this.settings.setShards(1); this.settings.setReplicas(1); this.settings.setHostToPortMapping(new HashMap<>()); <START> this.settings.setIndexName("test"); <END> }</code><technical_language>default "jena-text"</technical_language>

Target:
public Builder() { this.settings = new ESSettings(); this.settings.setClusterName("elasticsearch"); this.settings.setShards(1); this.settings.setReplicas(1); this.settings.setHostToPortMapping(new HashMap<>()); this.settings.setIndexName("jena-text"); }
Source:
<code>public LocalCluster(String jarFileName, int siteCount, int hostCount, int kfactor, int clusterId, BackendTarget target, FailureState failureState, boolean debug, boolean isRejoinTest, Map<String, String> env) { <START> this(null, null, jarFileName, siteCount, hostCount, kfactor, clusterId, target, failureState, debug, env); <END> }</code><technical_language>remove unused level if remove together</technical_language>

Target:
public LocalCluster(String jarFileName, int siteCount, int hostCount, int kfactor, int clusterId, BackendTarget target, FailureState failureState, boolean debug, boolean isRejoinTest, Map<String, String> env) { this(null, null, jarFileName, siteCount, hostCount, kfactor, clusterId, target, failureState, debug, isRejoinTest, env); }
Source:
<code><START> public <T> void setProperty(PropertyDescriptor<T> propertyDescriptor, T value) { <END> checkValidPropertyDescriptor(propertyDescriptor); propertyValuesByDescriptor.put(propertyDescriptor, value); }</code><technical_language>of Arrays.asList set values is boilerplate-y. I if this additional signature useful: public <T> void setProperty(PropertyDescriptor<List<T>> propertyDescriptor, T... values) Or, maybe, assuming more specific interface is in practice: public <T> void setProperty(MultiValuePropertyDescriptor<T> propertyDescriptor, T... values)</technical_language>

Target:
public <T> void setProperty(PropertyDescriptor<T> propertyDescriptor, T value) { checkValidPropertyDescriptor(propertyDescriptor); if (value instanceof List) { propertyValuesByDescriptor.put(propertyDescriptor, Collections.unmodifiableList((List) value)); } else { propertyValuesByDescriptor.put(propertyDescriptor, value); } }
Source:
<code>public AmmitEternal(UUID ownerId, CardSetInfo cardSetInfo) { super(ownerId, cardSetInfo, new CardType[]{CardType.CREATURE}, "{2}{B}"); subtype.add("Zombie"); subtype.add("Crocodile"); subtype.add("Demon"); power = new MageInt(5); toughness = new MageInt(5); this.addAbility(new AfflictAbility(3)); this.addAbility(new SpellCastOpponentTriggeredAbility(new AddCountersSourceEffect(CounterType.M1M1.createInstance()), false)); <START> this.addAbility(new DealsDamageToAPlayerTriggeredAbility(new RemoveAllCountersSourceEffect(CounterType.M1M1), false)); <END> }</code><technical_language>This trigger combat damage</technical_language>

Target:
public AmmitEternal(UUID ownerId, CardSetInfo cardSetInfo) { super(ownerId, cardSetInfo, new CardType[]{CardType.CREATURE}, "{2}{B}"); subtype.add("Zombie"); subtype.add("Crocodile"); subtype.add("Demon"); power = new MageInt(5); toughness = new MageInt(5); this.addAbility(new AfflictAbility(3)); this.addAbility(new SpellCastOpponentTriggeredAbility(new AddCountersSourceEffect(CounterType.M1M1.createInstance()), false)); this.addAbility(new DealsCombatDamageToAPlayerTriggeredAbility(new RemoveAllCountersSourceEffect(CounterType.M1M1), false)); }
Source:
<code>public List<InstallationProfile> getInstallationProfiles() { logger.debug("Looking for installation profile features"); List<InstallationProfile> profiles = new ArrayList<InstallationProfile>(); try{ for (Feature feature : featuresService.listFeatures()) { if (feature.getName().contains(InstallationProfile.INSTALLATION_PROFILE_FEATURE_PREFIX)) { InstallationProfile profile = new InstallationProfileImpl(feature); profiles.add(profile); } } } catch(Exception e){ <START> logger.error("Encountered an error whil trying to obtain the installation profile features.", e); <END> } return profiles; }</code><technical_language>Typo 'while' in error message</technical_language>

Target:
public List<Feature> getInstallationProfiles() { logger.debug("Looking for installation profile features"); List<Feature> profiles = new ArrayList<Feature>(); try{ for (Feature feature : featuresService.listFeatures()) { if (feature.getName().contains(INSTALLATION_PROFILE_PREFIX)) { profiles.add(feature); } } } catch(Exception e){ logger.error( "Encountered an error while trying to obtain the installation profile features.", e); } return profiles; }
Source:
<code>protected void serviceInit(Configuration conf) throws Exception { super.serviceInit(conf); threshold = HiveConf.getFloatVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_UTILIZATION); victimsHostName = HiveConf.getTrimmedStringsVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_HOSTNAMES); interval = HiveConf.getTimeVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_INTERVAL, TimeUnit.MILLISECONDS); <START> LOG.info("LlapLoadGeneratorService init with {}", interval, threshold, victimsHostName); <END> }</code><technical_language>add some basic validity/range checks here? I.e. threshold is 0 1? host names valid</technical_language>

Target:
protected void serviceInit(Configuration conf) throws Exception { super.serviceInit(conf); threshold = HiveConf.getFloatVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_UTILIZATION); if (threshold < 0 || threshold > 1.0) { throw new IllegalArgumentException(HiveConf.ConfVars.HIVE_TEST_LOAD_UTILIZATION.varname + " should " + "be between 0.0 and 1.0. The configuration specified [" + threshold + "]"); } victimsHostName = HiveConf.getTrimmedStringsVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_HOSTNAMES); interval = HiveConf.getTimeVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_INTERVAL, TimeUnit.MILLISECONDS); LOG.info("LlapLoadGeneratorService init with {}", interval, threshold, victimsHostName); }
Source:
<code><START> private Comparator<Offer> getComparatorWithSecondarySortOrder(boolean reversePrimarySortOrder) { <END> Comparator<Offer> primary = Comparator.comparing(Offer::getPrice, (o1, o2) -> { long a = o1 != null ? o1.getValue() : 0; long b = o2 != null ? o2.getValue() : 0; if (a != b) { if (o1 != null && CurrencyUtil.isCryptoCurrency(o1.getCurrencyCode())) return a > b ? 1 : -1; else return a < b ? 1 : -1; } else { return 0; } }); if (reversePrimarySortOrder) primary = primary.reversed(); return primary.thenComparing(Offer::getAmount); }</code><technical_language>I this name is preferable: getOfferComparator(...). problem getComparator mention object of comparison</technical_language>

Target:
private Comparator<Offer> getComparatorWithSecondarySortOrder(boolean reversePrimarySortOrder) { Comparator<Offer> primary = Comparator.comparing(Offer::getPrice, (o1, o2) -> { long a = o1 != null ? o1.getValue() : 0; long b = o2 != null ? o2.getValue() : 0; if (a != b) { if (o1 != null && CurrencyUtil.isCryptoCurrency(o1.getCurrencyCode())) return a > b ? 1 : -1; else return a < b ? 1 : -1; } else { return 0; } }); if (reversePrimarySortOrder) primary = primary.reversed(); Comparator<Offer> secondary = Comparator.comparing(Offer::getAmount, Comparator.reverseOrder()); return primary.thenComparing(secondary); }
Source:
<code>public static List<CPListElement> getExistingEntries(IJavaProject project) throws JavaModelException { ArrayList<CPListElement> newClassPath= new ArrayList<>(); for (IClasspathEntry <START> curr : <END> project.getRawClasspath()) { newClassPath.add(CPListElement.createFromExisting(curr, project)); } return newClassPath; }</code><technical_language>rename entry</technical_language>

Target:
public static List<CPListElement> getExistingEntries(IJavaProject project) throws JavaModelException { ArrayList<CPListElement> newClassPath= new ArrayList<>(); for (IClasspathEntry entry : project.getRawClasspath()) { newClassPath.add(CPListElement.createFromExisting(entry, project)); } return newClassPath; }
Source:
<code>public void putDownloadRemoteMavenIndexCronJob() throws Exception { <START> Assert.assertTrue(context.containsBean("repositoryIndexManager")); <END> List<CronTaskConfigurationDto> configurationList = getDownloadRemoteMavenIndexOfCarlspringCronJobs(); assertThat(configurationList.size(), CoreMatchers.equalTo(1)); CronTaskConfigurationDto configuration = configurationList.get(0); assertThat(configuration.getProperties().keySet().size(), CoreMatchers.equalTo(4)); assertThat(configuration.getProperties().get("cronExpression"), CoreMatchers.equalTo("0 0 5 * * ?")); configuration.addProperty("cronExpression", "0 0 0 * * ?"); client.put2(getContextBaseUrl() + "/cron", configuration, MediaType.APPLICATION_JSON_VALUE); configurationList = getDownloadRemoteMavenIndexOfCarlspringCronJobs(); assertThat(configurationList.size(), CoreMatchers.equalTo(1)); configuration = configurationList.get(0); assertThat(configuration.getProperties().keySet().size(), CoreMatchers.equalTo(4)); assertThat(configuration.getProperties().get("cronExpression"), CoreMatchers.equalTo("0 0 0 * * ?")); }</code><technical_language>please static imports for asserts*() methods? @ptirador cleaned in #871 for code base. Thanks! :)</technical_language>

Target:
public void putDownloadRemoteMavenIndexCronJob() throws Exception { assertTrue(context.containsBean("repositoryIndexManager")); List<CronTaskConfigurationDto> configurationList = getDownloadRemoteMavenIndexOfCarlspringCronJobs(); assertThat(configurationList.size(), CoreMatchers.equalTo(1)); CronTaskConfigurationDto configuration = configurationList.get(0); assertThat(configuration.getProperties().keySet().size(), CoreMatchers.equalTo(4)); assertThat(configuration.getProperties().get("cronExpression"), CoreMatchers.equalTo("0 0 5 * * ?")); configuration.addProperty("cronExpression", "0 0 0 * * ?"); client.put2(getContextBaseUrl() + "/cron", configuration, MediaType.APPLICATION_JSON_VALUE); configurationList = getDownloadRemoteMavenIndexOfCarlspringCronJobs(); assertThat(configurationList.size(), CoreMatchers.equalTo(1)); configuration = configurationList.get(0); assertThat(configuration.getProperties().keySet().size(), CoreMatchers.equalTo(4)); assertThat(configuration.getProperties().get("cronExpression"), CoreMatchers.equalTo("0 0 0 * * ?")); }
Source:
<code>public long getSerializedSize() { if (valueBuffers.size() != 1) { throw new UnsupportedOperationException("Method not supported for version 2 GenericIndexed."); } <START> return theBuffer.remaining() + 2 + 4 + 4; END> }</code><technical_language>Please Ints.BYTES instead of 4</technical_language>

Target:
public long getSerializedSize() { if (valueBuffers.size() != 1) { throw new UnsupportedOperationException("Method not supported for version 2 GenericIndexed."); } return theBuffer.remaining() + 2 + Ints.BYTES + Ints.BYTES; }
Source:
<code>public boolean add(E object) { switch (additionMode) { <START> case ALL: { <END> int modified = 0; for (Collection<E> parent : parents) { if (parent.add(object)) { modified++; } } return resultBoolean(modified); } case LAST: { return parents.get(parents.size() - 1).add(object); } } throw new IllegalStateException("This SuperCollection has an invalid addition mode!"); }</code><technical_language>braces case statements. Please break/return needed</technical_language>

Target:
public boolean add(E object) { switch (additionMode) { case ALL: int modified = 0; for (Collection<E> parent : parents) { if (parent.add(object)) { modified++; } } return resultBoolean(modified); case LAST: return parents.get(parents.size() - 1).add(object); } throw new IllegalStateException("This SuperCollection has an invalid addition mode!"); }
Source:
<code>public void releaseSerializer(final Serializer<?> serializer) throws IOException { AtomicInteger currentCount = providedVsCount.get(serializer); if(currentCount != null) { if(currentCount.decrementAndGet() < 0) { currentCount.incrementAndGet(); throw new IllegalArgumentException("Given serializer:" + serializer.getClass().getName() + " is not managed by this provider"); } } else { throw new IllegalArgumentException("Given serializer:" + serializer.getClass().getName() + " is not managed by this provider"); } <START> if(instantiated.contains(serializer) && serializer instanceof Closeable) { <END> ((Closeable)serializer).close(); } }</code><technical_language>I this instantiated.remove(serialiser)</technical_language>

Target:
public void releaseSerializer(final Serializer<?> serializer) throws IOException { AtomicInteger currentCount = providedVsCount.get(serializer); if(currentCount != null) { if(currentCount.decrementAndGet() < 0) { currentCount.incrementAndGet(); throw new IllegalArgumentException("Given serializer:" + serializer.getClass().getName() + " is not managed by this provider"); } } else { throw new IllegalArgumentException("Given serializer:" + serializer.getClass().getName() + " is not managed by this provider"); } if(instantiated.remove(serializer) && serializer instanceof Closeable) { ((Closeable)serializer).close(); } }
Source:
<code>public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); <START> if (!Utils.isMonkeyRunning()) { <END> updatePreferences(); } }</code><technical_language>is fixing root cause. Please change updatePreferences() call check null field accessing</technical_language>

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); updatePreferences(); }
Source:
<code>public InvitationSentEvent(User user, String mail, String language, Group group, Vo vo) { this.sender = user; this.email = mail; this.language = language; this.group = group; this.vo = vo; this.message = formatMessage("Invitation to VO: %s, group: %s, sent by user: %s, to email: %s, in language: %s", <START> vo, group == null ? "None" : group, sender, email, language); <END> }</code><technical_language>pass string "None", group resolve null in resulting message. parse/check messages, omit VO: group: objects, resolved VO: Vo:[....]. I suggest modify message based passed VO/group: java formatMessage("Invitation %s, %s, email: %s, in language: %s.", (group != null) ? group : vo, sender, email, language);</technical_language>

Target:
public InvitationSentEvent(User user, String mail, String language, Group group, Vo vo) { this.sender = user; this.email = mail; this.language = language; this.group = group; this.vo = vo; this.message = formatMessage("Invitation to %s, sent by %s, to email: %s, in language: %s.", (group != null) ? group : vo, sender, email, language); }
Source:
<code>public String getDosingInstructionsAsString(Locale locale) { StringBuilder dosingInstructions = new StringBuilder(); if (this.dosageAdjustmentPercentage != null) { <START> dosingInstructions.append("Dosage Adjustment Percentage : "); dosingInstructions.append(this.dosageAdjustmentPercentage); dosingInstructions.append("\n"); <END> } if (this.dosageDeliveredTiming != null) { dosingInstructions.append("Dosage Delivered Timing : "); dosingInstructions.append(this.dosageDeliveredTiming); dosingInstructions.append("\n"); } if (this.dosageDilutionInstructions != null) { dosingInstructions.append("Dosage Dilution Instructions : "); dosingInstructions.append(this.dosageDilutionInstructions); dosingInstructions.append("\n"); } return dosingInstructions.toString(); }</code><technical_language>This code moved a single method reuse other if conditions thing. For example formatDosingInformation(String label,String value){ return label + " : " + + "\n"; } call this method if conditions</technical_language>

Target:
public String getDosingInstructionsAsString(Locale locale) { StringBuilder dosingInstructions = new StringBuilder(); if (this.dosageAdjustmentPercentage != null) { dosingInstructions.append(this.formatDosingInformation(ADJUSTMENT_PERCENTAGE, this.dosageAdjustmentPercentage.toString())); } if (this.dosageDeliveredTiming != null) { dosingInstructions.append(this.formatDosingInformation(DELIVERED_TIMING, this.dosageDeliveredTiming)); } if (this.dosageDilutionInstructions != null) { dosingInstructions.append(this.formatDosingInformation(DILUTION_INSTRUCTIONS, this.dosageDilutionInstructions)); } return dosingInstructions.toString(); }
Source:
<code>public void init(IEditorSite site, IEditorInput input) throws PartInitException { super.init(site, input); IEditorInput editorInput = this.getEditorInput(); IFile sessionResourceFile = ((FileEditorInput) editorInput).getFile(); final URI sessionResourceURI = URI.createPlatformResourceURI(sessionResourceFile.getFullPath().toOSString(), true); try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); subMonitor.beginTask(MessageFormat.format(Messages.UI_SessionEditor_session_loading_task_title, new Object[0]), 1); session = SessionManager.INSTANCE.getSession(sessionResourceURI, subMonitor); if (!session.isOpen()) { session.open(monitor); } <START> subMonitor.worked(1); <END> subMonitor.worked(1); subMonitor.done(); } }); } catch (InvocationTargetException | InterruptedException e) { ErrorDialog.openError(getSite().getShell(), MessageFormat.format(Messages.UI_SessionEditor_session_loading_error_message, new Object[0]), e.getMessage(), Status.CANCEL_STATUS); } }</code><technical_language>worked(2) direclty</technical_language>

Target:
public void init(IEditorSite site, IEditorInput input) throws PartInitException { super.init(site, input); IEditorInput editorInput = this.getEditorInput(); IFile sessionResourceFile = ((FileEditorInput) editorInput).getFile(); final URI sessionResourceURI = URI.createPlatformResourceURI(sessionResourceFile.getFullPath().toOSString(), true); try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); subMonitor.beginTask(MessageFormat.format(Messages.UI_SessionEditor_session_loading_task_title, new Object[0]), 1); session = SessionManager.INSTANCE.getSession(sessionResourceURI, subMonitor); if (!session.isOpen()) { session.open(monitor); } subMonitor.worked(1); subMonitor.done(); } }); } catch (InvocationTargetException | InterruptedException e) { ErrorDialog.openError(getSite().getShell(), MessageFormat.format(Messages.UI_SessionEditor_session_loading_error_message, new Object[0]), e.getMessage(), Status.CANCEL_STATUS); } }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append("type: ").append(type); if (incarnationId != null) { sb.append(" incarnationId ").append(incarnationId); } if (!type.equals(Type.Uninitialized)) { if (sessionId != null) { <START> sb.append(" sessionId ").append(sessionId); <END> } if (storeKey != null) { sb.append(" storeKey ").append(storeKey); } sb.append(" offset ").append(offset); sb.append(" bytesRead ").append(bytesRead); } return sb.toString(); }</code><technical_language>inclusiveness in here</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("type: ").append(type); if (incarnationId != null) { sb.append(" incarnationId ").append(incarnationId); } sb.append(" inclusiveness ").append(inclusive == 1 ? true : false); if (!type.equals(Type.Uninitialized)) { if (sessionId != null) { sb.append(" sessionId ").append(sessionId); } if (storeKey != null) { sb.append(" storeKey ").append(storeKey); } sb.append(" offset ").append(offset); sb.append(" bytesRead ").append(bytesRead); } return sb.toString(); }
Source:
<code>public void createX509Credential() throws IOException, CertificateException { val request = new MockHttpServletRequest(); try (val inStream = new FileInputStream(new ClassPathResource("ldap-crl.crt").getFile())) { <START> X509Certificate[] certs = {CertUtils.readCertificate(inStream)}; <END> request.setAttribute(REQUEST_ATTRIBUTE_X509_CERTIFICATE, certs); val cred = factory.fromRequest(request, null).iterator().next(); assertTrue(cred instanceof X509CertificateCredential); } }</code><technical_language>val</technical_language>

Target:
public void createX509Credential() throws IOException, CertificateException { val request = new MockHttpServletRequest(); try (val inStream = new FileInputStream(new ClassPathResource("ldap-crl.crt").getFile())) { val certs = new X509Certificate[]{CertUtils.readCertificate(inStream)}; request.setAttribute(REQUEST_ATTRIBUTE_X509_CERTIFICATE, certs); val cred = factory.fromRequest(request, null).iterator().next(); assertTrue(cred instanceof X509CertificateCredential); } }
Source:
<code>public AsyncPrettyPrinter getInstance(final String headerName, final String headerValue) { final MatchResult result = matchAndParseHeader(headerName, headerValue); if (result == null) { return null; } String uri = result.getSchemaUri(); URL schemaURL = parseURL(uri); if (schemaURL == null) { return getErrorAsyncPrettyPrinter(headerName, headerValue); } else { <START> ExecutorService sExecutorService = AsyncPrettyPrinterExecutorHolder.getExecutorService(); <END> final Future<String> response = sExecutorService.submit(new Request(schemaURL)); return new AsyncPrettyPrinter() { public void printTo(PrintWriter output, InputStream payload) throws IOException { try { String schema; try { schema = response.get(); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (IOException.class.isInstance(cause)) { doErrorPrint( output, payload, "Cannot successfully download schema: " + e.getMessage()); return; } else { throw e; } } doPrint(output, payload, schema); } catch (InterruptedException e) { doErrorPrint( output, payload, "Encountered spurious interrupt while downloading schema for pretty printing: " + e.getMessage()); } catch (ExecutionException e) { Throwable cause = e.getCause(); throw ExceptionUtil.propagate(cause); } } public PrettyPrinterDisplayType getPrettifiedType() { return result.getDisplayType(); } }; } }</code><technical_language>executorService</technical_language>

Target:
public AsyncPrettyPrinter getInstance(final String headerName, final String headerValue) { final MatchResult result = matchAndParseHeader(headerName, headerValue); if (result == null) { return null; } String uri = result.getSchemaUri(); URL schemaURL = parseURL(uri); if (schemaURL == null) { return getErrorAsyncPrettyPrinter(headerName, headerValue); } else { ExecutorService executorService = AsyncPrettyPrinterExecutorHolder.getExecutorService(); if (executorService == null) { return null; } final Future<String> response = executorService.submit(new Request(schemaURL)); return new AsyncPrettyPrinter() { public void printTo(PrintWriter output, InputStream payload) throws IOException { try { String schema; try { schema = response.get(); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (IOException.class.isInstance(cause)) { doErrorPrint( output, payload, "Cannot successfully download schema: " + e.getMessage()); return; } else { throw e; } } doPrint(output, payload, schema); } catch (InterruptedException e) { doErrorPrint( output, payload, "Encountered spurious interrupt while downloading schema for pretty printing: " + e.getMessage()); } catch (ExecutionException e) { Throwable cause = e.getCause(); throw ExceptionUtil.propagate(cause); } } public PrettyPrinterDisplayType getPrettifiedType() { return result.getDisplayType(); } }; } }
Source:
<code>static void setTccl(final ClassLoader cl) { if (System.getSecurityManager() == null) { Thread.currentThread().setContextClassLoader(cl); } else { <START> AccessController.doPrivileged(new PrivilegedAction<Object>() { <END> @Override public Object run() { Thread.currentThread().setContextClassLoader(cl); return null; } }); } }</code><technical_language>Is a reason this privileged? I ask if running this a security manager other places set system properties gonna issue well</technical_language>

Target:
static void setTccl(final ClassLoader cl) { Thread.currentThread().setContextClassLoader(cl); }
Source:
<code>protected void writeCommandParameters(ObjectOutput output, ReplicableCommand command) throws IOException { command.writeTo(output); if (command instanceof TopologyAffectedCommand) { output.writeInt(((TopologyAffectedCommand) command).getTopologyId()); } if (command instanceof SegmentSpecificCommand) { <START> UnsignedNumeric.writeUnsignedInt(output, ((SegmentSpecificCommand) command).getSegment()); <END> } }</code><technical_language>1, IMO commands write/read segment</technical_language>

Target:
protected void writeCommandParameters(ObjectOutput output, ReplicableCommand command) throws IOException { command.writeTo(output); if (command instanceof TopologyAffectedCommand) { output.writeInt(((TopologyAffectedCommand) command).getTopologyId()); } }
Source:
<code>public void refreshTimeEstimation() throws NoScriptDefinitionSelectedException { ScriptDefinitionWrapper scriptDefinition = getScriptDefinition() .orElseThrow(() -> new NoScriptDefinitionSelectedException( "Tried to refresh time estimation with no script definition selected")); try { generator.refreshTimeEstimation(scriptGeneratorTable, scriptDefinition); languageSupported = true; threadError = false; } catch (UnsupportedLanguageException e) { <START> firePropertyChange(LANGUAGE_SUPPORT_PROPERTY, languageSupported, false); LOG.error(e); languageSupported = false; <END> } catch (InterruptedException | ExecutionException e) { firePropertyChange(THREAD_ERROR_PROPERTY, threadError, true); LOG.error(e); threadError = true; } }</code><technical_language>suggestion firePropertyChange(LANGUAGE_SUPPORT_PROPERTY, languageSupported, languageSupported=false); LOG.error(e); Similar for thread error below</technical_language>

Target:
public void refreshTimeEstimation() throws NoScriptDefinitionSelectedException { ScriptDefinitionWrapper scriptDefinition = getScriptDefinition() .orElseThrow(() -> new NoScriptDefinitionSelectedException( "Tried to refresh time estimation with no script definition selected")); try { generator.refreshTimeEstimation(scriptGeneratorTable, scriptDefinition); languageSupported = true; threadError = false; } catch (UnsupportedLanguageException e) { firePropertyChange(LANGUAGE_SUPPORT_PROPERTY, languageSupported, languageSupported = false); LOG.error(e); } catch (InterruptedException | ExecutionException e) { registerThreadError(e); } }
Source:
<code>private void setProperties() { <START> configProperties.setProperty("store.default-rocksdb.opts.gwNamespace", "default"); <END> configProperties.setProperty("store.default-rocksdb.type", "rocksdb"); }</code><technical_language>rocksdb references in of properties</technical_language>

Target:
private void setProperties() { configProperties.setProperty("store.default-filesystem.opts.gwNamespace", ""); configProperties.setProperty("store.default-filesystem.type", "filesystem"); }
Source:
<code>public void testReusedArrayWithString() throws Exception { <START> List<String> input = Arrays.asList("second"); <END> h.registerArrayType(String.class, "text"); h.inTransaction(t -> { t.createUpdate("create table test_reused_array(id int, a text[], unique (id))").execute(); t.createUpdate("insert into test_reused_array(id, a) values(1, '{\"first\"}')").execute(); t.createUpdate("insert into test_reused_array(id, a) values(1, :array) " + "on conflict(id) do update set a=:array") .bindArray("array", String.class, input) .execute(); Array result = t.createQuery("select a from test_reused_array where id=1") .map((rs, ctx) -> rs.getArray("a")).first(); t.createUpdate("drop table test_reused_array"); assertThat((String[]) result.getArray()).hasSameElementsAs(input); return 1; }); }</code><technical_language>this a multi-value array drive home point exclude mental concept of array/list flattened a regular single</technical_language>

Target:
public void testReusedArrayWithString() throws Exception { h.registerArrayType(String.class, "text"); assertThat(h.createQuery("select :array = :array") .bindArray("array", String.class, Collections.singletonList("element")) .mapTo(boolean.class) .one()).isTrue(); }
Source:
<code>synchronized private Config getResourceDescription(ConfigResource resource) { switch (resource.type()) { case BROKER: { int brokerId = Integer.parseInt(resource.name()); if (brokerId >= brokerConfigs.size()) { throw new InvalidRequestException("Broker " + resource.name() + " not found."); } return toConfigObject(brokerConfigs.get(brokerId)); } case TOPIC: { TopicMetadata topicMetadata = allTopics.get(resource.name()); if (topicMetadata != null && !topicMetadata.markedForDeletion) { <START> if (topicMetadata.fetchesRemainingUntilVisible > 0) topicMetadata.fetchesRemainingUntilVisible--; <END> else return new Config(topicMetadata.configs.entrySet().stream() .map(entry -> new ConfigEntry(entry.getKey(), entry.getValue())) .collect(Collectors.toList())); } throw new UnknownTopicOrPartitionException("Resource " + resource + " not found."); } default: throw new UnsupportedOperationException("Not implemented yet"); } }</code><technical_language>nit: topicMetadata.fetchesRemainingUntilVisible = Math.max(0, topicMetadata.fetchesRemainingUntilVisible -1);</technical_language>

Target:
synchronized private Config getResourceDescription(ConfigResource resource) { switch (resource.type()) { case BROKER: { int brokerId = Integer.parseInt(resource.name()); if (brokerId >= brokerConfigs.size()) { throw new InvalidRequestException("Broker " + resource.name() + " not found."); } return toConfigObject(brokerConfigs.get(brokerId)); } case TOPIC: { TopicMetadata topicMetadata = allTopics.get(resource.name()); if (topicMetadata != null && !topicMetadata.markedForDeletion) { if (topicMetadata.fetchesRemainingUntilVisible > 0) topicMetadata.fetchesRemainingUntilVisible = Math.max(0, topicMetadata.fetchesRemainingUntilVisible - 1); else return new Config(topicMetadata.configs.entrySet().stream() .map(entry -> new ConfigEntry(entry.getKey(), entry.getValue())) .collect(Collectors.toList())); } throw new UnknownTopicOrPartitionException("Resource " + resource + " not found."); } default: throw new UnsupportedOperationException("Not implemented yet"); } }
Source:
<code>List getNetworkInterfaces(VM vm){ <START> List net <END> = new ArrayList(); Map resultMap = new HashMap(); List Inet6List = new ArrayList(); List Inet4List = new ArrayList(); resultMap.put("name", "eth0"); Inet6List.add("fe80::21a:4aff:fe16:2016"); Inet6List.add("2620:52:0:2380:21a:4aff:fe16:2016"); resultMap.put("inet6", Inet6List); Inet4List.add(vm.getIp()); resultMap.put("inet", Inet4List); resultMap.put("hw", vm.getMacAddress()); net.add(resultMap); log.debug("network list is {}", net.toString()); return net; }</code><technical_language>update generics well</technical_language>

Target:
List getNetworkInterfaces(VM vm){ List<Map> net = new ArrayList(); Map<String, Object> resultMap = new HashMap(); List Inet6List = new ArrayList(); List Inet4List = new ArrayList(); resultMap.put("name", "eth0"); Inet6List.add("fe80::21a:4aff:fe16:2016"); Inet6List.add("2620:52:0:2380:21a:4aff:fe16:2016"); resultMap.put("inet6", Inet6List); Inet4List.add(vm.getIp()); resultMap.put("inet", Inet4List); resultMap.put("hw", vm.getMacAddress()); net.add(resultMap); log.debug("network list is {}", net.toString()); return net; }
Source:
<code>private void moveObject(PID objPid) { aclService.assertHasAccess("Agent " + agent.getUsername() + " does not have permission to move object " + objPid, objPid, agent.getPrincipals(), Permission.move); RepositoryObject moveObj = repositoryObjectLoader.getRepositoryObject(objPid); <START> ContentObject moveContent = (ContentObject) moveObj; <END> destroyProxy(objPid); destContainer.addMember(moveContent); }</code><technical_language>lines 149-150 combined</technical_language>

Target:
private void moveObject(PID objPid) { aclService.assertHasAccess("Agent " + agent.getUsername() + " does not have permission to move object " + objPid, objPid, agent.getPrincipals(), Permission.move); ContentObject moveContent = (ContentObject) repositoryObjectLoader.getRepositoryObject(objPid); destroyProxy(objPid); destContainer.addMember(moveContent); }
Source:
<code>public void testPublishAndReadMessages() throws Exception { eventBus = new SimpleEventBus(); ProducerFactory<String, byte[]> producerFactory = ProducerConfigUtil.ackProducerFactory(kafka, ByteArraySerializer.class); KafkaPublisher<String, byte[]> publisher = KafkaPublisher.<String, byte[]>builder() .messageSource(eventBus) .producerFactory(producerFactory) .topic("integration") .build(); publisher.start(); <START> ConsumerFactory<String, byte[]> cf = <END> new DefaultConsumerFactory<>(minimal(kafka, "consumer1", ByteArrayDeserializer.class)); Fetcher fetcher = AsyncFetcher.<String, byte[]>builder() .consumerFactory(cf) .topic("integration") .pollTimeout(300, TimeUnit.MILLISECONDS) .build(); KafkaMessageSource messageSource = new KafkaMessageSource(fetcher); BlockingStream<TrackedEventMessage<?>> stream1 = messageSource.openStream(null); stream1.close(); BlockingStream<TrackedEventMessage<?>> stream2 = messageSource.openStream(null); eventBus.publish(asEventMessage("test")); assertTrue(stream2.hasNextAvailable(20, TimeUnit.SECONDS)); TrackedEventMessage<?> actual = stream2.nextAvailable(); assertNotNull(actual); stream2.close(); producerFactory.shutDown(); fetcher.shutdown(); publisher.shutDown(); }</code><technical_language>cf -> consumerFactory</technical_language>

Target:
public void testPublishAndReadMessages() throws Exception { eventBus = new SimpleEventBus(); ProducerFactory<String, byte[]> producerFactory = ProducerConfigUtil.ackProducerFactory(kafka, ByteArraySerializer.class); KafkaPublisher<String, byte[]> publisher = KafkaPublisher.<String, byte[]>builder() .messageSource(eventBus) .producerFactory(producerFactory) .topic("integration") .build(); publisher.start(); ConsumerFactory<String, byte[]> consumerFactory = new DefaultConsumerFactory<>(minimal(kafka, "consumer1", ByteArrayDeserializer.class)); Fetcher fetcher = AsyncFetcher.<String, byte[]>builder() .consumerFactory(consumerFactory) .topic("integration") .pollTimeout(300, TimeUnit.MILLISECONDS) .build(); KafkaMessageSource messageSource = new KafkaMessageSource(fetcher); BlockingStream<TrackedEventMessage<?>> stream1 = messageSource.openStream(null); stream1.close(); BlockingStream<TrackedEventMessage<?>> stream2 = messageSource.openStream(null); eventBus.publish(asEventMessage("test")); assertTrue(stream2.hasNextAvailable(20, TimeUnit.SECONDS)); TrackedEventMessage<?> actual = stream2.nextAvailable(); assertNotNull(actual); stream2.close(); producerFactory.shutDown(); fetcher.shutdown(); publisher.shutDown(); }
Source:
<code>public void decorate(Object element, IDecoration decoration) { <START> if (element instanceof IProject) { <END> IProject prj = (IProject) element; String prjName = prj.getName(); Object suffix; try { suffix = prj.getSessionProperty(DECO_PROP); } catch (CoreException e) { e.printStackTrace(); suffix = null; } if (suffix != null) { decoration.addSuffix((String) suffix); } if (prjName.equals(TestWorkspace.P1_PROJECT_NAME)) { try { semaphoreDecoratorP1Ran.release(); semaphoreBlockDecoration.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } else if (prjName.equals(TestWorkspace.P2_PROJECT_NAME)) { try { semaphoreDecoratorP2Ran.release(); semaphoreBlockDecoration.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } } }</code><technical_language>I prefer guard fast return avoid long indented if blocks, i.e. if (!(element instanceof IProject)) { return; } WDYT</technical_language>

Target:
public void decorate(Object element, IDecoration decoration) { if (!(element instanceof IProject)) { return; } IProject prj = (IProject) element; String prjName = prj.getName(); Object suffix; try { suffix = prj.getSessionProperty(DECO_PROP); } catch (CoreException e) { e.printStackTrace(); suffix = null; } if (suffix != null) { decoration.addSuffix((String) suffix); } if (prjName.equals(TestWorkspace.P1_PROJECT_NAME)) { try { semaphoreDecoratorP1Ran.release(); semaphoreBlockDecoration.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } else if (prjName.equals(TestWorkspace.P2_PROJECT_NAME)) { try { semaphoreDecoratorP2Ran.release(); semaphoreBlockDecoration.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } }
Source:
<code><START> public DictionaryLemmatizer(final InputStream dictionary) { <END> this.dictMap = new HashMap<>(); final BufferedReader breader = new BufferedReader( new InputStreamReader(dictionary)); String line; try { while ((line = breader.readLine()) != null) { final String[] elems = line.split("\t"); this.dictMap.put(Arrays.asList(elems[0], elems[1]), Arrays.asList(elems[2])); } } catch (final IOException e) { e.printStackTrace(); } }</code><technical_language>constructor throw IOException. caller deal IOException thrown reading stream</technical_language>

Target:
public DictionaryLemmatizer(final InputStream dictionary) throws IOException { this.dictMap = new HashMap<>(); final BufferedReader breader = new BufferedReader( new InputStreamReader(dictionary)); String line; while ((line = breader.readLine()) != null) { final String[] elems = line.split("\t"); this.dictMap.put(Arrays.asList(elems[0], elems[1]), Arrays.asList(elems[2])); } }