auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static ThreadPool createJettyThreadPool(FileSettings jettySettings) throws Exception { int minThreads = ofNullable(jettySettings.getInteger("minThreads")).orElse(4); int maxThreads = ofNullable(jettySettings.getInteger("maxThreads")).orElse(12); int queueSize = ofNullable(jettySettings.getInteger("queueSize")).orElse(maxThreads); int idleTimeoutMs = ofNullable(jettySettings.getInteger("threadPoolIdleTimeoutMs")) <START> .orElseGet(() -> Long.valueOf(TimeUnit.MINUTES.toMillis(1)).intValue()); <END> QueuedThreadPool threadPool = new QueuedThreadPool(maxThreads, minThreads, idleTimeoutMs, new BlockingArrayQueue<>(queueSize)); threadPool.start(); return threadPool; }</code><technical_language>DEFAULT_IDLE_TIMEOUT = TimeUnit.MINUTES.toMillis(1)</technical_language>

Target:
public static ThreadPool createJettyThreadPool(FileSettings jettySettings) throws Exception { int minThreads = ofNullable(jettySettings.getInteger("minThreads")).orElse(4); int maxThreads = ofNullable(jettySettings.getInteger("maxThreads")).orElse(12); int queueSize = ofNullable(jettySettings.getInteger("queueSize")).orElse(maxThreads); int idleTimeoutMs = ofNullable(jettySettings.getInteger("threadPoolIdleTimeoutMs")).orElse(DEFAULT_IDLE_TIMEOUT_MS); QueuedThreadPool threadPool = new QueuedThreadPool(maxThreads, minThreads, idleTimeoutMs, new BlockingArrayQueue<>(queueSize)); threadPool.start(); return threadPool; }
Source:
<code>public void testEmptyVersionInfoMeansNotAvailable() { <START> BlazeVersionInfo info = new BlazeVersionInfo(ImmutableMap.of()); <END> assertThat(info.isAvailable()).isFalse(); assertThat(info.getSummary()).isNull(); assertThat(info.getReleaseName()).isEqualTo("development version"); }</code><technical_language>typically good practice change unrelated code, a change focused possible. Feel free send a separate clean CL if this adds :-)</technical_language>

Target:
public void testEmptyVersionInfoMeansNotAvailable() { BlazeVersionInfo info = new BlazeVersionInfo(Collections.<String, String>emptyMap()); assertThat(info.isAvailable()).isFalse(); assertThat(info.getSummary()).isNull(); assertThat(info.getReleaseName()).isEqualTo("development version"); }
Source:
<code>public void init() { try { threadMXBean = ManagementFactory.getThreadMXBean(); } catch (Exception e) { throw new IllegalStateException("Problem getting ThreadMXBean:" + e); } log.info("Initializing Thread Monitoring Service"); <START> executor.scheduleWithFixedDelay(this::monitorEngineThreadPools, <END> 0, Config.<Integer>getValue(ConfigValues.ThreadPoolMonitoringIntervalInMinutes), TimeUnit.MINUTES); log.info("Thread Monitoring Service initialized"); }</code><technical_language>propose add option schedule this service if user set a negative zero interval</technical_language>

Target:
public void init() { try { threadMXBean = ManagementFactory.getThreadMXBean(); } catch (Exception e) { throw new IllegalStateException("Problem getting ThreadMXBean:" + e); } log.info("Initializing Thread Monitoring Service"); int threadPoolMonitoringIntervalInMinutes = Config.<Integer>getValue(ConfigValues.ThreadPoolMonitoringIntervalInMinutes); if (threadPoolMonitoringIntervalInMinutes <= 0) { log.info("Thread Monitoring Service is disabled."); } else { executor.scheduleWithFixedDelay(this::monitorEngineThreadPools, 0, threadPoolMonitoringIntervalInMinutes, TimeUnit.MINUTES); log.info("Thread Monitoring Service initialized"); } }
Source:
<code>public static <OUT> Iterator<OUT> collect(DataStream<OUT> stream) { TypeSerializer<OUT> serializer = stream.getType().createSerializer( stream.getExecutionEnvironment().getConfig()); String id = UUID.randomUUID().toString(); String accumulatorName = "dataStreamCollect_" + id; CollectSinkOperatorFactory<OUT> factory = new CollectSinkOperatorFactory<>(serializer, accumulatorName); CollectSinkOperator<OUT> operator = (CollectSinkOperator<OUT>) factory.getOperator(); CollectResultIterator<OUT> iterator = new CollectResultIterator<>( operator.getOperatorIdFuture(), serializer, accumulatorName); CollectStreamSink<OUT> sink = new CollectStreamSink<>(stream, factory); sink.name("Data stream collect sink"); StreamExecutionEnvironment env = stream.getExecutionEnvironment(); env.addOperator(sink.getTransformation()); try { <START> JobClient jobClient = env.executeAsync("DataStreamCollect_" + id); <END> iterator.setJobClient(jobClient); } catch (Exception e) { throw new RuntimeException("Failed to execute data stream", e); } return iterator; }</code><technical_language>id is meaningless here, "data stream collect"</technical_language>

Target:
public static <OUT> Iterator<OUT> collect(DataStream<OUT> stream) { TypeSerializer<OUT> serializer = stream.getType().createSerializer( stream.getExecutionEnvironment().getConfig()); String accumulatorName = "dataStreamCollect_" + UUID.randomUUID().toString(); CollectSinkOperatorFactory<OUT> factory = new CollectSinkOperatorFactory<>(serializer, accumulatorName); CollectSinkOperator<OUT> operator = (CollectSinkOperator<OUT>) factory.getOperator(); CollectResultIterator<OUT> iterator = new CollectResultIterator<>( operator.getOperatorIdFuture(), serializer, accumulatorName); CollectStreamSink<OUT> sink = new CollectStreamSink<>(stream, factory); sink.name("Data stream collect sink"); StreamExecutionEnvironment env = stream.getExecutionEnvironment(); env.addOperator(sink.getTransformation()); try { JobClient jobClient = env.executeAsync("Data Stream Collect"); iterator.setJobClient(jobClient); } catch (Exception e) { throw new RuntimeException("Failed to execute data stream", e); } return iterator; }
Source:
<code><START> public static String getRevision() { <END> return REVISION; }</code><technical_language>this is exposed interface is OK change signature. But, curious other project users depending revision number</technical_language>

Target:
public static int getRevision() { return REVISION; }
Source:
<code>public EditorNotificationPanel createNotificationPanel(VirtualFile file, FileEditor fileEditor) { final Module module = ModuleUtilCore.findModuleForFile(file, myProject); if (module == null) { return null; } final AndroidFacet facet = AndroidFacet.getInstance(module); if (facet == null) { return null; } if (!facet.isGradleProject()) { return null; } if (!file.getPath().contains("build")) { return null; } for (VirtualFile baseDir : ModuleRootManager.getInstance(module).getContentRoots()) { <START> VirtualFile build = baseDir.findChild("build"); <END> if (build != null && VfsUtilCore.isAncestor(build, file, true)) { VirtualFile explodedBundled = build.findChild("exploded-bundles"); boolean inAar = explodedBundled != null && VfsUtilCore.isAncestor(explodedBundled, file, true); String text; if (inAar) { text = "Resource files in Android library archive files (.aar) should not be edited"; } else { text = "Files under the build folder are generated and should not be edited."; } EditorNotificationPanel panel = new EditorNotificationPanel(); panel.setText(text); return panel; } } return null; }</code><technical_language>"build" in places (I in some Gradle import code.) Add constant SdkConstants</technical_language>

Target:
public EditorNotificationPanel createNotificationPanel(VirtualFile file, FileEditor fileEditor) { final Module module = ModuleUtilCore.findModuleForFile(file, myProject); if (module == null) { return null; } final AndroidFacet facet = AndroidFacet.getInstance(module); if (facet == null) { return null; } if (!facet.isGradleProject()) { return null; } if (!file.getPath().contains(BUILD_DIR)) { return null; } for (VirtualFile baseDir : ModuleRootManager.getInstance(module).getContentRoots()) { VirtualFile build = baseDir.findChild(BUILD_DIR); if (build != null && VfsUtilCore.isAncestor(build, file, true)) { VirtualFile explodedBundled = build.findChild("exploded-bundles"); boolean inAar = explodedBundled != null && VfsUtilCore.isAncestor(explodedBundled, file, true); String text; if (inAar) { text = "Resource files inside Android library archive files (.aar) should not be edited"; } else { text = "Files under the build folder are generated and should not be edited."; } EditorNotificationPanel panel = new EditorNotificationPanel(); panel.setText(text); return panel; } } return null; }
Source:
<code>public static void convertFileStorages(final FileStorage fileStorageToUpdate) { if (fileStorageToUpdate != null) { try { FileSupport.getInstance().getFileSet().stream() .filter(gf -> fileStorageToUpdate == gf.getFileStorage() && fileStorageToUpdate != gf.getStorage()) <START> .forEach(gf -> gf.updateFileStorage()); <END> logger.debug("FILE Conversion: DONE SUCESSFULLY!"); } catch (final Throwable e) { logger.debug("FILE Conversion: ABORTED!!!"); e.printStackTrace(); } } }</code><technical_language>this changed method reference GenericFile::updateFileStorage</technical_language>

Target:
public static void convertFileStorages(final FileStorage fileStorageToUpdate) { if (fileStorageToUpdate != null) { try { FileSupport.getInstance().getFileSet().stream() .filter(gf -> fileStorageToUpdate == gf.getFileStorage() && fileStorageToUpdate != gf.getStorage()) .forEach(GenericFile::updateFileStorage); logger.debug("FILE Conversion: DONE SUCESSFULLY!"); } catch (final Throwable e) { logger.debug("FILE Conversion: ABORTED!!!"); e.printStackTrace(); } } }
Source:
<code>private List<String> getPrimaryBeanNames(String[] beanNamesForType) { <START> final List<String> list = new ArrayList<>(); <END> if (!(applicationContext instanceof ConfigurableApplicationContext)) { return Collections.emptyList(); } for (String beanName: beanNamesForType) { if (((ConfigurableApplicationContext) applicationContext).getBeanFactory() .getBeanDefinition(beanName).isPrimary()) { list.add(beanName); } } return list; }</code><technical_language>this aligns rest of codebase, remove final keyword here</technical_language>

Target:
private List<String> getPrimaryBeanNames(String[] beanNamesForType) { List<String> list = new ArrayList<>(); if (!(applicationContext instanceof ConfigurableApplicationContext)) { return Collections.emptyList(); } for (String beanName : beanNamesForType) { if (((ConfigurableApplicationContext) applicationContext).getBeanFactory() .getBeanDefinition(beanName).isPrimary()) { list.add(beanName); } } return list; }
Source:
<code>public IStorage getStorage() { try { <START> return fileRevision.getStorage(new NullProgressMonitor()); <END> } catch (CoreException e) { StatusHandler.log(new Status(IStatus.WARNING, ReviewsUiPlugin.PLUGIN_ID, "Cannot retrieve file revision contents from local repository, defaulting to review contents instead")); } return null; }</code><technical_language>NullProgressMonitor is problematic users a cancel retrieval of revision</technical_language>

Target:
public IStorage getStorage() { try { return fileRevision.getStorage(new ProgressMonitorPart(Display.getDefault().getActiveShell(), new FillLayout(), true)); } catch (CoreException e) { StatusHandler.log(new Status(IStatus.WARNING, ReviewsUiPlugin.PLUGIN_ID, "Cannot retrieve file revision contents from local repository, defaulting to review contents instead")); } return null; }
Source:
<code>public CommitUpdate getCommitUpdate(long startTs) { Optional<LockWatchVersion> startVersion = timestampStateStore.getStartVersion(startTs); Optional<CommitInfo> maybeCommitInfo = timestampStateStore.getCommitInfo(startTs); assertTrue(maybeCommitInfo.isPresent() && startVersion.isPresent(), "start or commit info not processed for start timestamp"); CommitInfo commitInfo = maybeCommitInfo.get(); ClientLogEvents update = eventLog.getEventsBetweenVersions(startVersion, commitInfo.commitVersion()); if (update.clearCache()) { return ImmutableInvalidateAll.builder().build(); } assertEventsContainRangeOfVersions( Range.closed(startVersion.get().version(), commitInfo.commitVersion().version()), update, true); <START> return createCommitUpdate(commitInfo, update.events().events()); <END> }</code><technical_language>here: I feel validation done in CommitUpdate</technical_language>

Target:
public CommitUpdate getCommitUpdate(long startTs) { Optional<LockWatchVersion> startVersion = timestampStateStore.getStartVersion(startTs); Optional<CommitInfo> maybeCommitInfo = timestampStateStore.getCommitInfo(startTs); assertTrue(maybeCommitInfo.isPresent() && startVersion.isPresent(), "start or commit info not processed for start timestamp"); CommitInfo commitInfo = maybeCommitInfo.get(); return eventLog.getEventsBetweenVersions(startVersion, commitInfo.commitVersion()) .toCommitUpdate(startVersion.get(), commitInfo); }
Source:
<code>private static String getChildContent(Element element, String tagName) { <START> Optional<String> optionalChildContent = getOptionalChildContent(element, tagName); <END> if (optionalChildContent.isPresent()) { return optionalChildContent.get(); } else { throw new IllegalStateException("Failed to get content of " + tagName); } }</code><technical_language>This replaced a orElseThrow call : <LINK_0> I added of optional instead of a simple null check in this context wrap optional unwrap next call</technical_language>

Target:
private static String getChildContent(Element element, String tagName) { Optional<String> optionalChildContent = getOptionalChildContent(element, tagName); return optionalChildContent. orElseThrow(() -> new IllegalStateException("Failed to get content of " + tagName)); }
Source:
<code>public void emptyLoginTest() throws InterruptedException { find("#repoOwnerField"); <START> selectAll(); <END> push(KeyCode.BACK_SPACE).type("abc").push(KeyCode.TAB); push(KeyCode.BACK_SPACE).type("abc").push(KeyCode.TAB); push(KeyCode.BACK_SPACE).push(KeyCode.TAB).push(KeyCode.BACK_SPACE); click("Sign in"); sleep(1000); assertNodeExists(hasText("Failed to sign in. Please try again.")); click("OK"); }</code><technical_language>If lines together, combined</technical_language>

Target:
public void emptyLoginTest() throws InterruptedException { selectAll(); push(KeyCode.BACK_SPACE).type("abc").push(KeyCode.TAB); push(KeyCode.BACK_SPACE).type("abc").push(KeyCode.TAB); push(KeyCode.BACK_SPACE).push(KeyCode.TAB).push(KeyCode.BACK_SPACE); click("Sign in"); sleep(1000); assertNodeExists(hasText("Failed to sign in. Please try again.")); click("OK"); }
Source:
<code>public boolean isEntity() { <START> return super.isEntity() && isAssociation() || (super.isEntity() && isEntityInRelationshipWithProperties() && !isAnnotationPresent(CompositeProperty.class)); <END> }</code><technical_language>suggestion return super.isEntity() && isAssociation() || (super.isEntity() && isEntityInRelationshipWithProperties() && !isComposite());</technical_language>

Target:
public boolean isEntity() { return super.isEntity() && isAssociation() || (super.isEntity() && isEntityInRelationshipWithProperties() && !isComposite()); }
Source:
<code>public void testGetMyVotedIdeas() { JavaScriptPreviewPage previewPage = executeSnippet(SNIPPET_ID); List jsonList = previewPage.getJsonList(); <START> Assert.assertFalse("GetAllBlogs returned no results", jsonList.isEmpty()); <END> }</code><technical_language>Msg misleading "GetMyVotedIdeas returned results"</technical_language>

Target:
public void testGetMyVotedIdeas() { JavaScriptPreviewPage previewPage = executeSnippet(SNIPPET_ID); List jsonList = previewPage.getJsonList(); Assert.assertFalse("GetMyVotedIdeas returned no results", jsonList.isEmpty()); }
Source:
<code>@Override public SearchRow prepareProxyIndexRow(SearchRow row) { if (row == null) return null; Value[] data = new Value[row.getColumnCount()]; for (int idx = 0; idx < data.length; idx++) data[idx] = row.getValue(idx); if (keyAliasColumnId > 0) { <START> if (row.getValue(keyAliasColumnId) == null && row.getValue(KEY_COL) != null) <END> data[keyAliasColumnId] = row.getValue(KEY_COL); if (row.getValue(KEY_COL) == null && row.getValue(keyAliasColumnId) != null) data[KEY_COL] = row.getValue(keyAliasColumnId); } if (valueAliasColumnId > 0) { if (row.getValue(valueAliasColumnId) == null && row.getValue(VAL_COL) != null) data[valueAliasColumnId] = row.getValue(VAL_COL); if (row.getValue(VAL_COL) == null && row.getValue(valueAliasColumnId) != null) data[VAL_COL] = row.getValue(valueAliasColumnId); } return new SimpleRow(data); }</code><technical_language>code is for key value, please move a separate method</technical_language>

Target:
@Override public SearchRow prepareProxyIndexRow(SearchRow row) { if (row == null) return null; Value[] data = new Value[row.getColumnCount()]; for (int idx = 0; idx < data.length; idx++) data[idx] = row.getValue(idx); copyAliasColumnData(data, KEY_COL, keyAliasColumnId); copyAliasColumnData(data, VAL_COL, valueAliasColumnId); return new SimpleRow(data); }
Source:
<code>private static ModuleLoader setupModuleLoader(String modulePath, String... systemPackages) { assert modulePath != null : "modulePath not null"; File moduleDir = new File(trimPathToModulesDir(modulePath)); if (!moduleDir.exists() || !moduleDir.isDirectory()) { throw new RuntimeException("The specified module directory " + modulePath + " is invalid or does not exist."); } <START> final String classPath = WildFlySecurityManager.getPropertyPrivileged(SYSPROP_KEY_CLASS_PATH, null); <END> try { WildFlySecurityManager.clearPropertyPrivileged(SYSPROP_KEY_CLASS_PATH); WildFlySecurityManager.setPropertyPrivileged(SYSPROP_KEY_MODULE_PATH, modulePath); StringBuilder packages = new StringBuilder("org.jboss.modules,org.jboss.msc,org.jboss.dmr,org.jboss.threads,org.jboss.as.controller.client"); if (systemPackages != null) { for (String packageName : systemPackages) { packages.append(","); packages.append(packageName); } } WildFlySecurityManager.setPropertyPrivileged("jboss.modules.system.pkgs", packages.toString()); return Module.getBootModuleLoader(); } finally { WildFlySecurityManager.setPropertyPrivileged(SYSPROP_KEY_CLASS_PATH, classPath); } }</code><technical_language>I this need set. In org.jboss.as.server.ServerEnvironment referenced, if present set a deprecated variable. I tested though, thoughts</technical_language>

Target:
private static ModuleLoader setupModuleLoader(String modulePath, String... systemPackages) { assert modulePath != null : "modulePath not null"; File moduleDir = new File(trimPathToModulesDir(modulePath)); if (!moduleDir.exists() || !moduleDir.isDirectory()) { throw new RuntimeException("The first directory of the specified module path " + modulePath + " is invalid or does not exist."); } WildFlySecurityManager.setPropertyPrivileged(SYSPROP_KEY_JBOSS_MODULES_DIR, moduleDir.getPath()); final String classPath = WildFlySecurityManager.getPropertyPrivileged(SYSPROP_KEY_CLASS_PATH, null); try { WildFlySecurityManager.clearPropertyPrivileged(SYSPROP_KEY_CLASS_PATH); WildFlySecurityManager.setPropertyPrivileged(SYSPROP_KEY_MODULE_PATH, modulePath); StringBuilder packages = new StringBuilder("org.jboss.modules,org.jboss.msc,org.jboss.dmr,org.jboss.threads,org.jboss.as.controller.client"); if (systemPackages != null) { for (String packageName : systemPackages) { packages.append(","); packages.append(packageName); } } WildFlySecurityManager.setPropertyPrivileged("jboss.modules.system.pkgs", packages.toString()); return Module.getBootModuleLoader(); } finally { WildFlySecurityManager.setPropertyPrivileged(SYSPROP_KEY_CLASS_PATH, classPath); } }
Source:
<code>private void updateFavPointBox() { final int favCount = cache.getFavoritePoints(); if (favCount >= 0) { favoriteLine.left.setVisibility(View.VISIBLE); <START> favoriteLine.right.setText(favCount + "×"); <END> } else { favoriteLine.left.setVisibility(View.GONE); } final LinearLayout layout = ButterKnife.findById(view, R.id.favpoint_box); final boolean supportsFavoritePoints = cache.supportsFavoritePoints(); layout.setVisibility(supportsFavoritePoints ? View.VISIBLE : View.GONE); if (!supportsFavoritePoints || cache.isOwner() || !Settings.isGCPremiumMember()) { return; } final ImageButton buttonAdd = ButterKnife.findById(view, R.id.add_to_favpoint); final ImageButton buttonRemove = ButterKnife.findById(view, R.id.remove_from_favpoint); final TextView text = ButterKnife.findById(view, R.id.favpoint_text); if (cache.isFavorite()) { buttonAdd.setVisibility(View.GONE); buttonRemove.setVisibility(View.VISIBLE); text.setText(R.string.cache_favpoint_on); } else { buttonAdd.setVisibility(View.VISIBLE); buttonRemove.setVisibility(View.GONE); text.setText(R.string.cache_favpoint_not_on); } if (!cache.isFound()) { buttonAdd.setEnabled(false); buttonAdd.setVisibility(View.GONE); buttonRemove.setEnabled(false); buttonRemove.setVisibility(View.GONE); } }</code><technical_language>introduce (or reuse?) a resource string for text</technical_language>

Target:
private void updateFavPointBox() { final int favCount = cache.getFavoritePoints(); if (favCount >= 0) { favoriteLine.left.setVisibility(View.VISIBLE); favoriteLine.right.setText(res.getString(R.string.favorite_count, favCount)); } else { favoriteLine.left.setVisibility(View.GONE); } final LinearLayout layout = ButterKnife.findById(view, R.id.favpoint_box); final boolean supportsFavoritePoints = cache.supportsFavoritePoints(); layout.setVisibility(supportsFavoritePoints ? View.VISIBLE : View.GONE); if (!supportsFavoritePoints || cache.isOwner() || !Settings.isGCPremiumMember()) { return; } final ImageButton buttonAdd = ButterKnife.findById(view, R.id.add_to_favpoint); final ImageButton buttonRemove = ButterKnife.findById(view, R.id.remove_from_favpoint); final TextView text = ButterKnife.findById(view, R.id.favpoint_text); if (cache.isFavorite()) { buttonAdd.setVisibility(View.GONE); buttonRemove.setVisibility(View.VISIBLE); text.setText(R.string.cache_favpoint_on); } else { buttonAdd.setVisibility(View.VISIBLE); buttonRemove.setVisibility(View.GONE); text.setText(R.string.cache_favpoint_not_on); } if (!cache.isFound()) { buttonAdd.setEnabled(false); buttonAdd.setVisibility(View.GONE); buttonRemove.setEnabled(false); buttonRemove.setVisibility(View.GONE); } }
Source:
<code>public void testQuietOutputIsSorted() throws Exception { when(options.getBoolean("q")).thenReturn(true); <START> int ret = command.run(options, client, out, false, null); <END> assertEquals(0, ret); assertEquals(expectedOrder, readJobIdsFromOutput(false)); }</code><technical_language>final inline call assertEquals</technical_language>

Target:
public void testQuietOutputIsSorted() throws Exception { when(options.getBoolean("q")).thenReturn(true); final int ret = command.run(options, client, out, false, null); assertEquals(0, ret); assertEquals(expectedOrder, readJobIdsFromOutput(false)); }
Source:
<code>private static void logCodeMiningProviderException(Throwable e) { <START> if (e.getCause() instanceof CancellationException) { <END> return; } try { String PLUGIN_ID= "org.eclipse.jface.text"; ILog log= Platform.getLog(Platform.getBundle(PLUGIN_ID)); log.log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, e.getMessage(), e)); } catch (Exception ex) { } }</code><technical_language>check if (e != null && (e instanceof CancellationException || (e.getCause() != && e.getCause() instanceof CancellationException))</technical_language>

Target:
private static void logCodeMiningProviderException(Throwable e) { if (e != null && (e instanceof CancellationException || (e.getCause() != null && e.getCause() instanceof CancellationException))) { return; } try { String PLUGIN_ID= "org.eclipse.jface.text"; ILog log= Platform.getLog(Platform.getBundle(PLUGIN_ID)); log.log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, e.getMessage(), e)); } catch (Exception ex) { } }
Source:
<code>public void execute() throws MojoExecutionException, MojoFailureException { <START> long start = System.currentTimeMillis(); <END> getLog().debug("Validating Mule application..."); if (!skipValidation) { validateMandatoryFolders(); validateMandatoryDescriptors(); validateMulePluginDependencies(); validateSharedLibraries(); } getLog().debug(MessageFormat.format("Validation for Mule application done ({0}ms)", System.currentTimeMillis() - start)); }</code><technical_language>please move log snippet if clause? If validation is skipped is reason log this user</technical_language>

Target:
public void execute() throws MojoExecutionException, MojoFailureException { if (!skipValidation) { long start = System.currentTimeMillis(); getLog().debug("Validating Mule application..."); validateMandatoryFolders(); validateMandatoryDescriptors(); validateMulePluginDependencies(); validateSharedLibraries(); getLog().debug(MessageFormat.format("Validation for Mule application done ({0}ms)", System.currentTimeMillis() - start)); } else { getLog().debug("Skipping Validation for Mule application"); } }
Source:
<code>private static Element getEndpointConfigurationVersionByLatest(NodeList configurationList, Logger log) { Element latestVersion = null; Float valueVersion = 0.0F; for (int confIndex = 0; confIndex < configurationList.getLength(); confIndex++) { Element epConfiguration = (Element) configurationList.item(confIndex); String currentVersionString = getTextContentOf(epConfiguration, "version"); <START> if (currentVersionString.contains("LEVEL")) { <END> if (latestVersion != null) { if (currentVersionString.equals("LEVEL_a1")) { latestVersion = epConfiguration; } } else { latestVersion = epConfiguration; } } else { float currentVersionFloat = toFloat(currentVersionString, log); if (currentVersionFloat > valueVersion) { valueVersion = currentVersionFloat; latestVersion = epConfiguration; } } } return latestVersion; }</code><technical_language>Needs equalIgnoreCase comparison</technical_language>

Target:
private static Element getEndpointConfigurationVersionByLatest(NodeList configurationList, Logger log) { Element latestVersion = null; Float valueVersion = 0.0F; for (int confIndex = 0; confIndex < configurationList.getLength(); confIndex++) { Element epConfiguration = (Element) configurationList.item(confIndex); String currentVersionString = getTextContentOf(epConfiguration, "version"); if (currentVersionString.toUpperCase().contains("LEVEL")) { if (latestVersion != null) { if (currentVersionString.equalsIgnoreCase("LEVEL_a1")) { latestVersion = epConfiguration; } } else { latestVersion = epConfiguration; } } else { float currentVersionFloat = toFloat(currentVersionString, log); if (currentVersionFloat > valueVersion) { valueVersion = currentVersionFloat; latestVersion = epConfiguration; } } } return latestVersion; }
Source:
<code>@Override public void onDisconnected(IgniteFuture<?> reconnectFut) { synchronized (opsMux) { assert !disconnected; disconnected = true; <START> pendingMasterKey = null; <END> lastChangedMasterKeyDigest = null; cancelFutures("Client node was disconnected from topology (operation result is unknown)."); } }</code><technical_language>nullify variables here? happen if process in progress? finished</technical_language>

Target:
@Override public void onDisconnected(IgniteFuture<?> reconnectFut) { synchronized (opsMux) { assert !disconnected; disconnected = true; masterKeyChangeRequest = null; masterKeyDigest = null; cancelFutures("Client node was disconnected from topology (operation result is unknown)."); } }
Source:
<code>private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { <START> Adaptor adaptor = new Adaptor() { <END> @Override public void deserialize(GetField getField, Serializable serializable) throws Exception { final boolean caseSensitive = getField.get("_caseSensitive", true); { final Field caseSensitiveField = SimpleDictionary.class.getDeclaredField("_caseSensitive"); caseSensitiveField.setAccessible(true); caseSensitiveField.set(serializable, caseSensitive); } try { final Object oldValues = getField.get("_values", null); if (oldValues != null) { @SuppressWarnings("deprecation") SimpleReferenceValues srv = (SimpleReferenceValues) oldValues; @SuppressWarnings("deprecation") final Object[] values = srv.getValues(); final Set<String> valueSet = createValueSet(values, caseSensitive); final Field valuesField = SimpleDictionary.class.getDeclaredField("_valueSet"); valuesField.setAccessible(true); valuesField.set(serializable, valueSet); } } catch (IllegalArgumentException e) { } } }; ReadObjectBuilder.create(this, SimpleDictionary.class).readObject(stream, adaptor); }</code><technical_language>final (and variable pretty useless, wont agree :))</technical_language>

Target:
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { final Adaptor adaptor = new Adaptor() { @Override public void deserialize(GetField getField, Serializable serializable) throws Exception { final boolean caseSensitive = getField.get("_caseSensitive", true); { final Field caseSensitiveField = SimpleDictionary.class.getDeclaredField("_caseSensitive"); caseSensitiveField.setAccessible(true); caseSensitiveField.set(serializable, caseSensitive); } try { final Object oldValues = getField.get("_values", null); if (oldValues != null) { @SuppressWarnings("deprecation") SimpleReferenceValues srv = (SimpleReferenceValues) oldValues; @SuppressWarnings("deprecation") final Object[] values = srv.getValues(); final Set<String> valueSet = createValueSet(values, caseSensitive); final Field valuesField = SimpleDictionary.class.getDeclaredField("_valueSet"); valuesField.setAccessible(true); valuesField.set(serializable, valueSet); } } catch (IllegalArgumentException e) { } } }; ReadObjectBuilder.create(this, SimpleDictionary.class).readObject(stream, adaptor); }
Source:
<code>private int getMappingQualityImpl() { try { if (isAligned) { return getCurrentAlignment().getMappingQuality(); } } catch (ErrorMsg e) { throw new RuntimeException(e); } <START> return SAMRecord.NO_ALIGNMENT_START; <END> }</code><technical_language>SAMRecord.NO_MAPPING_QUALITY</technical_language>

Target:
private int getMappingQualityImpl() { try { if (isAligned) { return getCurrentAlignment().getMappingQuality(); } } catch (ErrorMsg e) { throw new RuntimeException(e); } return SAMRecord.NO_MAPPING_QUALITY; }
Source:
<code>public ShortUiColumn( final List<HeaderMetaData> headerMetaData, final double width, final boolean isResizable, final boolean isVisible, final GuidedDecisionTablePresenter.Access access, final TextBoxShortSingletonDOMElementFactory factory ) { super( headerMetaData, new CellRenderer<Short, NumericShortTextBox, TextBoxDOMElement<Short, NumericShortTextBox>>( factory ) { @Override protected void doRenderCellContent( final Text t, final Short value, final GridBodyCellRenderContext context ) { <START> t.setText( value.toString() ); <END> } }, width, isResizable, isVisible, access, factory ); }</code><technical_language>value.toString() vs. factory.convert(..) a bit lower, line 63</technical_language>

Target:
public ShortUiColumn( final List<HeaderMetaData> headerMetaData, final double width, final boolean isResizable, final boolean isVisible, final GuidedDecisionTablePresenter.Access access, final TextBoxShortSingletonDOMElementFactory factory ) { super( headerMetaData, new CellRenderer<Short, NumericShortTextBox, TextBoxDOMElement<Short, NumericShortTextBox>>( factory ) { @Override protected void doRenderCellContent( final Text t, final Short value, final GridBodyCellRenderContext context ) { t.setText( ( (TextBoxShortSingletonDOMElementFactory) factory ).convert( value ) ); } }, width, isResizable, isVisible, access, factory ); }
Source:
<code>public static void decreaseClientNum() throws InterruptedException { if (ACTIVE_CLIENT_COUNT.decrementAndGet() == 0) { VoltLogger.shutdownAsynchronousLogging(); EstTimeUpdater.stop(); ReverseDNSCache.stop(); } <START> } <END></code><technical_language>java count = ACTIVE_CLIENT_COUNT.get(); if (count < 0) { ACTIVE_CLIENT_COUNT.compareAndSet(count,0); }</technical_language>

Target:
public static void decreaseClientNum() throws InterruptedException { int count = ACTIVE_CLIENT_COUNT.get(); if (count <= 0) { return; } if (ACTIVE_CLIENT_COUNT.decrementAndGet() == 0) { VoltLogger.shutdownAsynchronousLogging(); EstTimeUpdater.stop(); ReverseDNSCache.stop(); } count = ACTIVE_CLIENT_COUNT.get(); if (count < 0) { ACTIVE_CLIENT_COUNT.compareAndSet(count,0); } }
Source:
<code>private Scenario createScenario(final Description testMethodDescription) { Scenario scenario = new Scenario(); String description = ""; <START> String name = ScenarioConfiguration.getScenarioName(testMethodDescription, MultipleBuildsRule.getCurrentBuildRun()); <END> scenario.setName(name); DocuDescription docuDescription = testMethodDescription.getAnnotation(DocuDescription.class); if (docuDescription != null) { description = docuDescription.description(); scenario.addDetail("User Role", docuDescription.userRole()); } scenario.setDescription(description); Labels labels = testMethodDescription.getAnnotation(Labels.class); if (labels != null) { Set<String> labelsSet = new HashSet<String>(); labelsSet.addAll(Arrays.asList(labels.value())); scenario.getLabels().setLabels(labelsSet); } UserStories userStories = testMethodDescription.getAnnotation(UserStories.class); if (userStories != null && userStories.value().length > 0) { long[] storyIds = userStories.value(); ObjectList<ObjectTreeNode<ObjectDescription>> featureEpicUserStoriesTrees = IssuesTrackingAccessHelper .loadFeatureTreesForWorkItemIds(storyIds); scenario.addDetail("Requirements", featureEpicUserStoriesTrees); } scenario.addDetail("Very Long Metadata Lines", createLongLine()); return scenario; }</code><technical_language>i changed now. ok is now</technical_language>

Target:
private Scenario createScenario(final Description testMethodDescription) { Scenario scenario = new Scenario(); String description = ""; String name = getNameFromMethod(testMethodDescription); scenario.setName(name); DocuDescription docuDescription = testMethodDescription.getAnnotation(DocuDescription.class); if (docuDescription != null) { description = docuDescription.description(); scenario.addDetail("User Role", docuDescription.userRole()); } scenario.setDescription(description); Labels labels = testMethodDescription.getAnnotation(Labels.class); if (labels != null) { Set<String> labelsSet = new HashSet<String>(); labelsSet.addAll(Arrays.asList(labels.value())); scenario.getLabels().setLabels(labelsSet); } UserStories userStories = testMethodDescription.getAnnotation(UserStories.class); if (userStories != null && userStories.value().length > 0) { long[] storyIds = userStories.value(); ObjectList<ObjectTreeNode<ObjectDescription>> featureEpicUserStoriesTrees = IssuesTrackingAccessHelper .loadFeatureTreesForWorkItemIds(storyIds); scenario.addDetail("Requirements", featureEpicUserStoriesTrees); } scenario.addDetail("Very Long Metadata Lines", createLongLine()); return scenario; }
Source:
<code>private void onStopRemoveBricks() { if (getConfirmWindow() == null) { return; } ConfirmationModel model = (ConfirmationModel) getConfirmWindow(); if (model.getProgress() != null) { return; <START> } <END> if (getSelectedItems() == null || getSelectedItems().isEmpty()) { return; } GlusterVolumeEntity volumeEntity = (GlusterVolumeEntity) getEntity(); ArrayList<GlusterBrickEntity> list = new ArrayList<GlusterBrickEntity>(); for (GlusterBrickEntity brick : volumeEntity.getBricks()) { if (brick.getAsyncTask() != null && brick.getAsyncTask().getStatus() == JobExecutionStatus.STARTED) { list.add(brick); } } GlusterVolumeRemoveBricksParameters parameter = new GlusterVolumeRemoveBricksParameters(volumeEntity.getId(), list); model.startProgress(null); Frontend.RunAction(VdcActionType.StopRemoveGlusterVolumeBricks, parameter, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); setConfirmWindow(null); } }, model); }</code><technical_language>curious, checking progress here</technical_language>

Target:
private void onStopRemoveBricks() { if (getConfirmWindow() == null) { return; } ConfirmationModel model = (ConfirmationModel) getConfirmWindow(); if (getSelectedItems() == null || getSelectedItems().isEmpty()) { return; } GlusterVolumeEntity volumeEntity = (GlusterVolumeEntity) getEntity(); ArrayList<GlusterBrickEntity> list = new ArrayList<GlusterBrickEntity>(); GlusterAsyncTask volumeTask = volumeEntity.getAsyncTask(); for (GlusterBrickEntity brick : volumeEntity.getBricks()) { if (brick.getAsyncTask() != null && brick.getAsyncTask().getTaskId() != null && volumeTask != null && volumeTask.getStatus() == JobExecutionStatus.STARTED) { list.add(brick); } } GlusterVolumeRemoveBricksParameters parameter = new GlusterVolumeRemoveBricksParameters(volumeEntity.getId(), list); model.startProgress(null); Frontend.RunAction(VdcActionType.StopRemoveGlusterVolumeBricks, parameter, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); setConfirmWindow(null); } }, model); }
Source:
<code>public void testIncludeTag() throws Exception { Repository localDb = createWorkRepository(); Repository tempDb = createWorkRepository(); StringBuilder xmlContent = new StringBuilder(); xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<include name=\"_include.xml\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("</manifest>"); JGitTestUtil.writeTrashFile( tempDb, "manifest.xml", xmlContent.toString()); xmlContent = new StringBuilder(); xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<remote name=\"remote1\" fetch=\".\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("<project path=\"foo\" name=\"") .append(defaultUri) .append("\" />") .append("</manifest>"); JGitTestUtil.writeTrashFile( tempDb, <START> "manifest.xml", xmlContent.toString()); <END> RepoCommand command = new RepoCommand(localDb); command .setPath(tempDb.getWorkTree().getAbsolutePath() + "/manifest.xml") .setURI(rootUri) .call(); File hello = new File(localDb.getWorkTree(), "foo/hello.txt"); assertTrue("submodule should be checked out", hello.exists()); BufferedReader reader = new BufferedReader(new FileReader(hello)); String content = reader.readLine(); reader.close(); assertEquals("submodule content should be as expected", "master world", content); }</code><technical_language>_include.xml here</technical_language>

Target:
public void testIncludeTag() throws Exception { Repository localDb = createWorkRepository(); Repository tempDb = createWorkRepository(); StringBuilder xmlContent = new StringBuilder(); xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<include name=\"_include.xml\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("</manifest>"); JGitTestUtil.writeTrashFile( tempDb, "manifest.xml", xmlContent.toString()); xmlContent = new StringBuilder(); xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<remote name=\"remote1\" fetch=\".\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("<project path=\"foo\" name=\"") .append(defaultUri) .append("\" />") .append("</manifest>"); JGitTestUtil.writeTrashFile( tempDb, "_include.xml", xmlContent.toString()); RepoCommand command = new RepoCommand(localDb); command .setPath(tempDb.getWorkTree().getAbsolutePath() + "/manifest.xml") .setURI(rootUri) .call(); File hello = new File(localDb.getWorkTree(), "foo/hello.txt"); assertTrue("submodule should be checked out", hello.exists()); BufferedReader reader = new BufferedReader(new FileReader(hello)); String content = reader.readLine(); reader.close(); assertEquals("submodule content should be as expected", "master world", content); }
Source:
<code>public void testExternalZookeeperWithExternalNetwork() throws Exception { try ( Network network = Network.newNetwork(); KafkaContainer kafka = new KafkaContainer(KAFKA_TEST_IMAGE) .withNetwork(network) .withExternalZookeeper("zookeeper:2181"); GenericContainer<?> zookeeper = new GenericContainer<>(ZOOKEEPER_TEST_IMAGE) .withNetwork(network) .withNetworkAliases("zookeeper") .withEnv("ZOOKEEPER_CLIENT_PORT", "2181"); GenericContainer application = new GenericContainer("alpine") <START> .withNetwork(kafka.getNetwork()) <END> .withNetworkAliases("dummy") .withCommand("sleep 10000") ) { zookeeper.start(); kafka.start(); application.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } }</code><technical_language>#3128 suggestion .withNetwork(network)</technical_language>

Target:
public void testExternalZookeeperWithExternalNetwork() throws Exception { try ( Network network = Network.newNetwork(); KafkaContainer kafka = new KafkaContainer(KAFKA_TEST_IMAGE) .withNetwork(network) .withExternalZookeeper("zookeeper:2181"); GenericContainer<?> zookeeper = new GenericContainer<>(ZOOKEEPER_TEST_IMAGE) .withNetwork(network) .withNetworkAliases("zookeeper") .withEnv("ZOOKEEPER_CLIENT_PORT", "2181"); GenericContainer<?> application = new GenericContainer<>(DockerImageName.parse("alpine")) .withNetwork(network) .withNetworkAliases("dummy") .withCommand("sleep 10000") ) { zookeeper.start(); kafka.start(); application.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } }
Source:
<code>protected void onStop() { if (themeChooser != null && themeChooser.isShowing()) { themeChooser.dismiss(); } app.getSessionFunnel().persistSession(); <START> if (textToSpeech.isSpeaking()) { <END> getCurPageFragment().stopSpeakArticle(textToSpeech); } super.onStop(); unregisterBus(); }</code><technical_language>I this needs a null check or, if possible, initialize textToSpeech in onCreate</technical_language>

Target:
protected void onStop() { if (themeChooser != null && themeChooser.isShowing()) { themeChooser.dismiss(); } app.getSessionFunnel().persistSession(); if (textToSpeech.isSpeaking()) { getCurPageFragment().stopSpeakArticle(textToSpeech); textToSpeech.shutdown(); } super.onStop(); unregisterBus(); }
Source:
<code>public void handleSetClockConfigurationResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleSetClockConfigurationResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Set Clock Configuration Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } <START> this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() <END> .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
public void handleSetClockConfigurationResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleSetClockConfigurationResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Set Clock Configuration Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send(responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>public Number apply(List<Expr> args, Map<String, Number> bindings) { if (args.size() < 3) { throw new RuntimeException("function 'caseWhen' needs at least 3 arguments"); } for (int i = 0; i < args.size(); i += 2) { Number x = args.get(i).eval(bindings); if (x instanceof Long && x.longValue() > 0 || x.doubleValue() > 0) { return args.get(i + 1).eval(bindings); } } if (args.size() % 2 != 0) { return args.get(args.size() - 1).eval(bindings); } <START> return 0; <END> }</code><technical_language>this is implicit ELSE 0, right</technical_language>

Target:
public Number apply(List<Expr> args, Map<String, Number> bindings) { if (args.size() < 3) { throw new RuntimeException("function 'case' needs at least 3 arguments"); } final Number leftVal = args.get(0).eval(bindings); for (int i = 1; i < args.size() - 1; i += 2) { Number x = Evals.eq(leftVal, args.get(i).eval(bindings)); if (x instanceof Long && x.longValue() > 0 || x.doubleValue() > 0) { return args.get(i + 1).eval(bindings); } } if (args.size() % 2 != 1) { return args.get(args.size() - 1).eval(bindings); } return leftVal instanceof Long ? 0L : 0.0d; }
Source:
<code><START> public void publishLiveProcessorList(List<String> processors, String leaseId) { <END> try { byte[] data = SamzaObjectMapper.getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsBytes(processors); byte[] pageData = Arrays.copyOf(data, (int) BARRIER_STATE_BLOCK_SIZE); InputStream is = new ByteArrayInputStream(pageData); blob.uploadPages(is, JOB_MODEL_BLOCK_SIZE + BARRIER_STATE_BLOCK_SIZE, PROCESSOR_LIST_BLOCK_SIZE, AccessCondition.generateLeaseCondition(leaseId), null, null); LOG.info("Uploaded list of live processors to blob."); } catch (StorageException | IOException e) { LOG.error("Processor list: " + processors + "publish failed", e); throw new AzureException(e); } }</code><technical_language>useful do if leaseId is null ? Alternatively, method return a boolean indicating a successful operation not. If is for usage, update it</technical_language>

Target:
public boolean publishLiveProcessorList(List<String> processors, String leaseId) { try { if (leaseId == null) { return false; } byte[] data = SamzaObjectMapper.getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsBytes(processors); byte[] pageData = Arrays.copyOf(data, (int) BARRIER_STATE_BLOCK_SIZE); InputStream is = new ByteArrayInputStream(pageData); blob.uploadPages(is, JOB_MODEL_BLOCK_SIZE + BARRIER_STATE_BLOCK_SIZE, PROCESSOR_LIST_BLOCK_SIZE, AccessCondition.generateLeaseCondition(leaseId), null, null); LOG.info("Uploaded list of live processors to blob."); return true; } catch (StorageException | IOException e) { LOG.error("Processor list: " + processors + "publish failed", e); return false; } }