auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static void assertNoTCCL() { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); if (tccl instanceof ModuleClassLoader) { <START> Assert.assertNull("TCCL is null", tccl); <END> } }</code><technical_language>Assert.fail more here, if if statement passes tccl is null</technical_language>

Target:
private static void assertNoTCCL() { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); Assert.assertFalse("TCCL not ModuleClassLoader: " + tccl, tccl instanceof ModuleClassLoader); }
Source:
<code>public int[] borrowIntArray(int positionCount) { checkState(borrowedIntArrays.size() < maxOutstandingArrays, "Requested too many arrays: %s", borrowedIntArrays.size()); while (!intArrays.isEmpty() && intArrays.peek().length < positionCount) { int[] popped = intArrays.pop(); estimatedSizeInBytes -= sizeOf(popped); } int[] array; if (intArrays.isEmpty()) { array = new int[positionCount]; estimatedSizeInBytes += sizeOf(array); } else { array = intArrays.pop(); } <START> checkState(borrowedIntArrays.add(array), "Attempted to borrow array which was already borrowed"); <END> return array; }</code><technical_language>This is a caller's problem, a bug in implementation of this class. Hence, verify more appropriate</technical_language>

Target:
public int[] borrowIntArray(int positionCount) { checkState(borrowedIntArrays.size() < maxOutstandingArrays, "Requested too many arrays: %s", borrowedIntArrays.size()); int[] array; while (!intArrays.isEmpty() && intArrays.peek().length < positionCount) { array = intArrays.pop(); estimatedSizeInBytes -= sizeOf(array); } if (intArrays.isEmpty()) { array = new int[positionCount]; estimatedSizeInBytes += sizeOf(array); } else { array = intArrays.pop(); } verify(borrowedIntArrays.add(array), "Attempted to borrow array which was already borrowed"); return array; }
Source:
<code>public String getProperty(String key) { <START> return (String) value.get(key); <END> }</code><technical_language>This method "value" map is expected <String, String> <?, ?></technical_language>

Target:
public String getProperty(String key) { return value.get(key); }
Source:
<code>public void run() { Long rescheduleAt = handler.tick(false); scheduledFutureRef.getAndUpdate(value -> { if (value != null) { <START> if (rescheduleAt == null) { <END> return scheduledPool.schedule(scheduleRunnable, 10, TimeUnit.MILLISECONDS); } else if (rescheduleAt != 0) { return scheduledPool.schedule(scheduleRunnable, rescheduleAt - TimeUnit.NANOSECONDS.toMillis(System.nanoTime()), TimeUnit.MILLISECONDS); } } return value; }); }</code><technical_language>this moved function, if rescheduleAt == null, dont need a getAndUpdate method call, a get, function class parent object, instead of creating call</technical_language>

Target:
public void run() { Long rescheduleAt = handler.tick(false); if (rescheduleAt == null) { scheduleOp.setDelay(10); scheduledFutureRef.getAndUpdate(scheduleOp); } else if (rescheduleAt != 0) { scheduleOp.setDelay(rescheduleAt - TimeUnit.NANOSECONDS.toMillis(System.nanoTime())); scheduledFutureRef.getAndUpdate(scheduleOp); } }
Source:
<code>public final LogResult postLog(final Geocache cache, final LogType logType, final Calendar date, final String log, final String logPassword, final List<TrackableLog> trackableLogs) { <START> final LogResult result = ECApi.postLog(cache, logType, date, log); <END> return result; }</code><technical_language>Please do create useless variables, is more readable if use: java return ECApi.postLog(cache, logType, date, log);</technical_language>

Target:
public final LogResult postLog(final Geocache cache, final LogType logType, final Calendar date, final String log, final String logPassword, final List<TrackableLog> trackableLogs) { return ECApi.postLog(cache, logType, date, log); }
Source:
<code>public void testMapInt32ToPrestoInteger() { <START> PrimitiveType intType = new PrimitiveType(OPTIONAL, PrimitiveType.PrimitiveTypeName.INT32, "int_col", OriginalType.INT_32); <END> ColumnDescriptor columnDescriptor = new ColumnDescriptor(new String[]{"int_col"}, PrimitiveType.PrimitiveTypeName.INT32, 0, 1); RichColumnDescriptor intColumn = new RichColumnDescriptor(columnDescriptor, intType); assertEquals(ParquetTypeUtils.getPrestoType(TupleDomain.all(), intColumn), INTEGER); }</code><technical_language>import parquet.schema.PrimitiveType.PrimitiveTypeName; simplify this</technical_language>

Target:
public void testMapInt32ToPrestoInteger() { PrimitiveType intType = new PrimitiveType(OPTIONAL, PrimitiveTypeName.INT32, "int_col", OriginalType.INT_32); ColumnDescriptor columnDescriptor = new ColumnDescriptor(new String[]{"int_col"}, PrimitiveTypeName.INT32, 0, 1); RichColumnDescriptor intColumn = new RichColumnDescriptor(columnDescriptor, intType); assertEquals(getPrestoType(TupleDomain.all(), intColumn), INTEGER); }
Source:
<code>public void configurePipeline(PipelineConfigurer pipelineConfigurer) { Preconditions.checkArgument(!Strings.isNullOrEmpty(config.schema), "Schema must be specified."); try { Schema schema = Schema.parseJson(config.schema); pipelineConfigurer.getStageConfigurer().setOutputSchema(schema); } catch (Exception e) { <START> throw new IllegalArgumentException("Invalid input schema: " + e.getMessage(), e); <END> } }</code><technical_language>Invalid output schema</technical_language>

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { Preconditions.checkArgument(!Strings.isNullOrEmpty(config.schema), "Schema must be specified."); try { Schema schema = Schema.parseJson(config.schema); pipelineConfigurer.getStageConfigurer().setOutputSchema(schema); } catch (Exception e) { throw new IllegalArgumentException("Invalid output schema: " + e.getMessage(), e); } }
Source:
<code>public Principal getUserPrincipal() { if (subject == null || subject.getPrincipals().isEmpty()) return null; <START> return subject.getPrincipals().iterator().next(); <END> }</code><technical_language>Annotate method @Nullable</technical_language>

Target:
public Principal getUserPrincipal() { if (subject == null || subject.getPrincipals().isEmpty()) { return null; } return subject.getPrincipals().iterator().next(); }
Source:
<code>public void execute() { Resource umlResource = UmlUtils.getUmlModel(modelSet).getResource(); <START> model = (org.eclipse.uml2.uml.Model) umlResource.getContents().get(0); <END> URI qudvURI = URI.createURI(SysMLResource.QUDV_LIBRARY_PATH).appendFragment("QUDV"); qudv = modelSet.getEObject(qudvURI, true); this.getCommandStack(modelSet).execute(new RecordingCommand(modelSet.getTransactionalEditingDomain()) { @Override protected void doExecute() { PackageImport importPrimitivePack = model.createPackageImport((org.eclipse.uml2.uml.Package) qudv); if (!model.getPackageImports().contains(importPrimitivePack)) { model.getPackageImports().add(importPrimitivePack); } try { model.eResource().save(Collections.EMPTY_MAP); } catch (IOException e) { Activator.getLogHelper().error(e); } } }); }</code><technical_language>root element a Package</technical_language>

Target:
public void execute() { Resource umlResource = UmlUtils.getUmlModel(modelSet).getResource(); root = (org.eclipse.uml2.uml.Package) umlResource.getContents().get(0); URI qudvURI = URI.createURI(SysMLResource.QUDV_LIBRARY_PATH).appendFragment(SysMLResource.QUDV_LIBRARY_ROOT_ID); qudv = (org.eclipse.uml2.uml.Package) modelSet.getEObject(qudvURI, true); this.getCommandStack(modelSet).execute(new RecordingCommand(modelSet.getTransactionalEditingDomain()) { @Override protected void doExecute() { PackageImport importPrimitivePack = root.createPackageImport(qudv); if (!root.getPackageImports().contains(importPrimitivePack)) { root.getPackageImports().add(importPrimitivePack); } try { root.eResource().save(Collections.EMPTY_MAP); } catch (IOException e) { Activator.getLogHelper().error(e); } } }); }
Source:
<code>public byte[] encodeMessage(EhcacheEntityMessage message) { <START> return message.encode(); <END> }</code><technical_language>I do get change. decided messages carry encoding / decoding logic? I understand I gave advice for work @albinsuresh is doing, in mind context is different</technical_language>

Target:
public byte[] encodeMessage(EhcacheEntityMessage message) { if (message.getType() == EhcacheEntityMessage.Type.LIFECYCLE_OP) { return lifeCycleMessageCodec.encode((LifecycleMessage) message); } else { return serverStoreOpCodec.encode((ServerStoreOpMessage) message); } }
Source:
<code>@Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { <START> final PhoenixMultiViewInputSplit pSplit = (PhoenixMultiViewInputSplit)split; <END> final List<ViewInfoWritable> viewInfoTracker = pSplit.getViewInfoTrackerList(); it = viewInfoTracker.iterator(); }</code><technical_language>a good idea check if "split" is assignable "PhoenixMultiViewInputSplit" cast, else return exception</technical_language>

Target:
@Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException { if (split instanceof PhoenixMultiViewInputSplit) { final PhoenixMultiViewInputSplit pSplit = (PhoenixMultiViewInputSplit)split; final List<ViewInfoWritable> viewInfoTracker = pSplit.getViewInfoTrackerList(); it = viewInfoTracker.iterator(); } else { LOGGER.error("InputSplit class cannot cast to PhoenixMultiViewInputSplit."); throw new IOException("InputSplit class cannot cast to PhoenixMultiViewInputSplit"); } }
Source:
<code><START> void enqueuePendingNativeReports() { <END> setChanged(); notifyObservers(new Message( NativeInterface.MessageType.DELIVER_PENDING, null)); }</code><technical_language>visibility of this method private</technical_language>

Target:
private void enqueuePendingNativeReports() { setChanged(); notifyObservers(new Message( NativeInterface.MessageType.DELIVER_PENDING, null)); }
Source:
<code>public Optional<String> getLocalHadoopConfigurationDirectory() { final String hadoopConfDirEnv = System.getenv(Constants.ENV_HADOOP_CONF_DIR); <START> final String hadoopHomeEnv = System.getenv(Constants.ENV_HADOOP_HOME); <END> if (StringUtils.isNotBlank(hadoopConfDirEnv)) { return Optional.of(hadoopConfDirEnv); } if (StringUtils.isNotBlank(hadoopHomeEnv)) { return Optional.of(new Path(hadoopHomeEnv, "/etc/hadoop").toString()); } return Optional.empty(); }</code><technical_language>nit: move variable initialization if block needed beforehand</technical_language>

Target:
public Optional<String> getLocalHadoopConfigurationDirectory() { final String hadoopConfDirEnv = System.getenv(Constants.ENV_HADOOP_CONF_DIR); if (StringUtils.isNotBlank(hadoopConfDirEnv)) { return Optional.of(hadoopConfDirEnv); } final String hadoopHomeEnv = System.getenv(Constants.ENV_HADOOP_HOME); if (StringUtils.isNotBlank(hadoopHomeEnv)) { final File hadoop2ConfDir = new File(hadoopHomeEnv, "/etc/hadoop"); if (hadoop2ConfDir.exists()) { return Optional.of(hadoop2ConfDir.getAbsolutePath()); } final File hadoop1ConfDir = new File(hadoopHomeEnv, "/conf"); if (hadoop1ConfDir.exists()) { return Optional.of(hadoop1ConfDir.getAbsolutePath()); } } return Optional.empty(); }
Source:
<code>public final synchronized void pause() { if (this.lifecycle instanceof Pausable) { <START> ((Pausable)this.lifecycle).pause(); <END> } }</code><technical_language>space ) (checkstyle complain)</technical_language>

Target:
public final synchronized void pause() { if (this.lifecycle instanceof Pausable) { ( (Pausable) this.lifecycle).pause(); } else { logger.warn("Attempted to pause a component that does not support Pausable " + this.lifecycle); } }
Source:
<code>public void execute() throws MojoExecutionException, MojoFailureException { try { File sourceFatJar = getTargetFile(); thin(sourceFatJar); } catch (Exception e) { <START> throw new MojoExecutionException(e.getMessage()); <END> } }</code><technical_language>Change include original exception: throw new MojoExecutionException(e.getMessage(), e);</technical_language>

Target:
public void execute() throws MojoExecutionException, MojoFailureException { try { File sourceFatJar = getTargetFile(); thin(sourceFatJar); } catch (SpringBootThinException e) { throw new MojoExecutionException( "Plugin execution failed because the application archive is not an executable archive. The repackage goal of the spring-boot-maven-plugin must be configured to run first in order to create the required executable archive.", e); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } }
Source:
<code>public <T extends Comparable<T>> Boolean visit(Operators.Eq<T> eq) { T value = eq.getValue(); if (value == null) { return BLOCK_MIGHT_MATCH; } Operators.Column<T> filterColumn = eq.getColumn(); ColumnChunkMetaData meta = getColumnChunk(filterColumn.getColumnPath()); ColumnDescriptor col = new ColumnDescriptor(meta.getPath().toArray(), meta.getType(), -1, -1); if (meta == null) { return BLOCK_CANNOT_MATCH; } <START> BloomFilterUtility bloomFilterUtility = bloomFilterReader.buildBloomFilterUtility(col); <END> if (bloomFilterUtility != null && !bloomFilterUtility.contains(value)) { return BLOCK_CANNOT_MATCH; } return BLOCK_MIGHT_MATCH; }</code><technical_language>I think, cleaner build a BloomFilterUtility based required objects instead of requiring create a fake ColumnDescriptor</technical_language>

Target:
public <T extends Comparable<T>> Boolean visit(Operators.Eq<T> eq) { T value = eq.getValue(); if (value == null) { return BLOCK_MIGHT_MATCH; } Operators.Column<T> filterColumn = eq.getColumn(); ColumnChunkMetaData meta = getColumnChunk(filterColumn.getColumnPath()); if (meta == null) { return BLOCK_CANNOT_MATCH; } try { BloomFilter bloomFilter = bloomFilterReader.readBloomFilter(meta); if (bloomFilter != null && !bloomFilter.findHash(bloomFilter.hash(value))) { return BLOCK_CANNOT_MATCH; } } catch (RuntimeException e) { LOG.warn(e.getMessage()); return BLOCK_MIGHT_MATCH; } return BLOCK_MIGHT_MATCH; }
Source:
<code>public int hashCode() { <START> return (((startCommit.hashCode() * 31) + numbers.length) * 31) <END> + getNumber(); }</code><technical_language>nit-pick: startCommit.hashCode xored/added in is distributed</technical_language>

Target:
public int hashCode() { return ((startCommit.hashCode() + numbers.length) * 31) + getNumber(); }
Source:
<code>private Locale determineLocale(final HttpServletRequest request) { Locale locale = LocaleUtils.getLocaleFromString(request.getParameter(LOCALE)); if (locale == null) { locale = getLocaleFromCookies(request.getCookies()); } if (locale == null) { locale = request.getLocale(); } if (locale == null) { locale = Locale.US; } locale = lookupSupportedLocale(locale, getLocaleKeys()); <START> log.debug("Filter determined locale to be: " + locale.toLanguageTag()); <END> return locale; }</code><technical_language>suggest changing this a detected locale is (much) browser/cookie locale Locale resolvedLocale = lookupSupportedLocale(locale, getLocaleKeys()); log.debug(String.format("Incoming locale: %s. Filter determined locale be: %s", locale.toLanguageTag(), resolvedLocale.toLanguageTag())); return resolvedLocale;</technical_language>

Target:
private Locale determineLocale(final HttpServletRequest request) { Locale locale = LocaleUtils.getLocaleFromString(request.getParameter(LOCALE)); if (locale == null) { locale = getLocaleFromCookies(request.getCookies()); } if (locale == null) { locale = request.getLocale(); } if (locale == null) { locale = Locale.US; } Locale resolvedLocale = lookupSupportedLocale(locale, getLocaleKeys()); log.debug(String.format("Incoming locale: %s. Filter determined locale to be: %s", locale.toLanguageTag(), resolvedLocale.toLanguageTag())); return resolvedLocale; }
Source:
<code>private void testRecordedVideoPlaybackWithAngle(int angle) throws Exception { int width = RECORDED_VIDEO_WIDTH; int height = RECORDED_VIDEO_HEIGHT; final String file = RECORDED_FILE; final long durationMs = RECORDED_DURATION_MS; if (!hasCamera()) { return; } boolean isSupported = false; mCamera = Camera.open(0); Camera.Parameters parameters = mCamera.getParameters(); List<Camera.Size> <START> previewSizes = <END> parameters.getSupportedVideoSizes(); for (Camera.Size size : previewSizes) { if (size.width == width && size.height == height) { isSupported = true; break; } } mCamera.release(); mCamera = null; if (!isSupported) { width = previewSizes.get(0).width; height = previewSizes.get(0).height; } checkOrientation(angle); recordVideo(width, height, angle, file, durationMs); checkDisplayedVideoSize(width, height, angle, file); checkVideoRotationAngle(angle, file); }</code><technical_language>change this match CL intents? i.e. e.g. recordVideoSizes</technical_language>

Target:
private void testRecordedVideoPlaybackWithAngle(int angle) throws Exception { int width = RECORDED_VIDEO_WIDTH; int height = RECORDED_VIDEO_HEIGHT; final String file = RECORDED_FILE; final long durationMs = RECORDED_DURATION_MS; if (!hasCamera()) { return; } boolean isSupported = false; mCamera = Camera.open(0); Camera.Parameters parameters = mCamera.getParameters(); List<Camera.Size> videoSizes = parameters.getSupportedVideoSizes(); for (Camera.Size size : videoSizes) { if (size.width == width && size.height == height) { isSupported = true; break; } } mCamera.release(); mCamera = null; if (!isSupported) { width = videoSizes.get(0).width; height = videoSizes.get(0).height; } checkOrientation(angle); recordVideo(width, height, angle, file, durationMs); checkDisplayedVideoSize(width, height, angle, file); checkVideoRotationAngle(angle, file); }
Source:
<code>protected void openIntentChooser() throws ActivityNotFoundException { if (this.options.hasKey("forceDialog") && this.options.getBoolean("forceDialog")) { <START> if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) { <END> IntentSender sender = TargetChosenReceiver.getSharingSenderIntent(this.reactContext); Intent chooser = Intent.createChooser(this.getIntent(), this.chooserTitle, sender); chooser.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); this.reactContext.getCurrentActivity().startActivityForResult(chooser, RNShareModule.SHARE_REQUEST_CODE); } else { Intent chooser = Intent.createChooser(this.getIntent(), this.chooserTitle); chooser.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); this.reactContext.getCurrentActivity().startActivityForResult(chooser, RNShareModule.SHARE_REQUEST_CODE); TargetChosenReceiver.sendCallback(true, true, "OK"); } } else { this.getIntent().setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.reactContext.startActivity(this.getIntent()); TargetChosenReceiver.sendCallback(true, true, this.getIntent().getPackage()); } }</code><technical_language>static isSupported() method . TargetChosenReceiver avoid propagating build versions</technical_language>

Target:
protected void openIntentChooser() throws ActivityNotFoundException { if (this.options.hasKey("forceDialog") && this.options.getBoolean("forceDialog")) { Activity activity = this.reactContext.getCurrentActivity(); if (activity == null) { TargetChosenReceiver.sendCallback(false, "Something went wrong"); return; } if (TargetChosenReceiver.isSupported()) { IntentSender sender = TargetChosenReceiver.getSharingSenderIntent(this.reactContext); Intent chooser = Intent.createChooser(this.getIntent(), this.chooserTitle, sender); chooser.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); activity.startActivityForResult(chooser, RNShareModule.SHARE_REQUEST_CODE); } else { Intent chooser = Intent.createChooser(this.getIntent(), this.chooserTitle); chooser.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); activity.startActivityForResult(chooser, RNShareModule.SHARE_REQUEST_CODE); TargetChosenReceiver.sendCallback(true, true, "OK"); } } else { this.getIntent().setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.reactContext.startActivity(this.getIntent()); TargetChosenReceiver.sendCallback(true, true, this.getIntent().getPackage()); } }
Source:
<code>public void afterPropertiesSet() throws Exception { if (this.beanFactory != null) { String[] beanNames = this.beanFactory.getBeanDefinitionNames(); for (String beanName : beanNames) { BeanDefinition def = this.beanFactory.getBeanDefinition(beanName); String className = def.getBeanClassName(); if (className == null && def.getSource() instanceof StandardMethodMetadata) { className = ((StandardMethodMetadata) def.getSource()).getIntrospectedMethod().getReturnType().getName(); } if (StringUtils.hasText(className)){ <START> if (className.startsWith(SI_ROOT_PACKAGE) && !(className.endsWith(IntegrationMBeanExporter.class.getName()))){ <END> siBeanNames.add(beanName); } } } } }</code><technical_language>IntegrationConfigUtils.BASE_PACKAGE remove constants in this class</technical_language>

Target:
public void afterPropertiesSet() throws Exception { if (this.beanFactory != null) { String[] beanNames = this.beanFactory.getBeanDefinitionNames(); for (String beanName : beanNames) { BeanDefinition def = this.beanFactory.getBeanDefinition(beanName); String className = def.getBeanClassName(); if (className == null && def.getSource() instanceof StandardMethodMetadata) { className = ((StandardMethodMetadata) def.getSource()).getIntrospectedMethod().getReturnType().getName(); } if (StringUtils.hasText(className)){ if (className.startsWith(IntegrationConfigUtils.BASE_PACKAGE) && !(className.endsWith(IntegrationMBeanExporter.class.getName()))){ siBeanNames.add(beanName); } } } } }
Source:
<code>public void testCreateRequestMessageBuilderPublishedAtPresent() { String bodyText = "body text"; Payload requestPayload = TestUtils.createPayloadWithTextBody(bodyText); Builder requestMessageBuilder = TestUtils.createMessageBuilder(); Message message = messageFactory.createRequestMessage(requestMessageBuilder, requestPayload); <START> assertNotNull(message.getMeta().getPublishedAt()); <END> }</code><technical_language>This test weaker could. fixed clock check for exact verify nullability</technical_language>

Target:
public void testCreateRequestMessageBuilderPublishedAtPresent() { String bodyText = "body text"; Payload requestPayload = TestUtils.createPayloadWithTextBody(bodyText); Builder requestMessageBuilder = TestUtils.createMessageBuilder(FIXED_CLOCK); Message message = messageFactory.createRequestMessage(requestMessageBuilder, requestPayload); assertNotNull(message.getMeta().getPublishedAt()); assertEquals(message.getMeta().getPublishedAt(), FIXED_CLOCK.instant()); }
Source:
<code>public List<BitstreamFormat> constructBitstreamFormatList(HttpServletRequest request, Context context) { return getStringListFromRequest(request).stream() .map(link -> { if (link.endsWith("/")) { link = link.substring(0, link.length() - 1); } return link.substring(link.lastIndexOf('/') + 1); }) .map(id -> { try { return bitstreamFormatService.find(context, parseInt(id)); } catch (SQLException e) { <START> log.error(e.getMessage(), e); <END> return null; } }) .filter(Objects::nonNull) .collect(toList()); }</code><technical_language>Please log a more descriptive message here. in mind, e.getMessage() null....in case this "Null". want more closely errors occur here. errors...one is id is Integer (and parseInt fails), another is BitstreamFormat found</technical_language>

Target:
public List<BitstreamFormat> constructBitstreamFormatList(HttpServletRequest request, Context context) { return getStringListFromRequest(request).stream() .map(link -> { if (link.endsWith("/")) { link = link.substring(0, link.length() - 1); } return link.substring(link.lastIndexOf('/') + 1); }) .map(id -> { try { return bitstreamFormatService.find(context, parseInt(id)); } catch (SQLException | NumberFormatException e) { log.error("Could not find bitstream format for id: " + id, e); return null; } }) .filter(Objects::nonNull) .collect(toList()); }
Source:
<code>private void createShortcut(File executable) { final String executablePath = executable.getAbsolutePath(); final String pathInContainers = executablePath.replace(containersPath, ""); final String[] split = pathInContainers.split("/"); final String engineContainer = split[0]; final String engine = (Character.toUpperCase(engineContainer.charAt(0)) + engineContainer.substring(1)) .replace("prefix", ""); final String container = split[1]; final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); interactiveScriptSession.eval("include([\"Engines\", \"" + engine + "\", \"Shortcuts\", \"" + engine + "\"]);", ignored -> interactiveScriptSession.eval("new " + engine + "Shortcut()", output -> { final ScriptObjectMirror shortcutObject = (ScriptObjectMirror) output; shortcutObject.callMember("name", executable.getName()); shortcutObject.callMember("search", executable.getName()); shortcutObject.callMember("prefix", container); shortcutObject.callMember("create"); <START> }, e -> Platform.runLater(() -> new ErrorMessage(tr("Error while creating shortcut"), e))), <END> e -> Platform.runLater(() -> new ErrorMessage(tr("Error while creating shortcut"), e))); }</code><technical_language>move this (e -> Platform.runLater(() -> new ErrorMessage(tr("Error while creating shortcut"), e))) another method called defaultErrorHandler something</technical_language>

Target:
private void createShortcut(File executable) { final String executablePath = executable.getAbsolutePath(); final String pathInContainers = executablePath.replace(containersPath, ""); final String[] split = pathInContainers.split("/"); final String engineContainer = split[0]; final String engine = (Character.toUpperCase(engineContainer.charAt(0)) + engineContainer.substring(1)) .replace("prefix", ""); final String container = split[1]; final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); interactiveScriptSession.eval("include([\"Engines\", \"" + engine + "\", \"Shortcuts\", \"" + engine + "\"]);", ignored -> interactiveScriptSession.eval("new " + engine + "Shortcut()", output -> { final ScriptObjectMirror shortcutObject = (ScriptObjectMirror) output; shortcutObject.callMember("name", executable.getName()); shortcutObject.callMember("search", executable.getName()); shortcutObject.callMember("prefix", container); shortcutObject.callMember("create"); }, e -> this.showErrorMessage(e, tr("Error while creating shortcut"))), e -> this.showErrorMessage(e, tr("Error while creating shortcut"))); }
Source:
<code>public void test_zeroContextThrowsNullPointException() { try { new NativeRef(0) {}; fail("Should throw NullPointerException when arguments are NULL"); <START> } catch(NullPointerException e) { <END> } }</code><technical_language>NullPointerException expected</technical_language>

Target:
public void test_zeroContextThrowsNullPointException() { try { new NativeRef(0) {}; fail("Should throw NullPointerException when arguments are NULL"); } catch(NullPointerException expected) { } }
Source:
<code>public static String getInternationalizedString(@NonNull String key) { Context ctx = PreferencesState.getInstance().getContext(); String language = getUserLanguage(ctx); String translation = getLocalizedStringFromDB(key, language); if (key == null) { return key; <START> } <END> if (BuildConfig.activeSearchLanguageInDB && wasTranslationFound(translation)) { return translation; } else { return findStringFromAndroidResource(ctx, key, language); } }</code><technical_language>@Amejia481 null previously returning empty string, changed behavior return null. Is special reason for that? check consequences have? I prefer return a null if possible, a good reason for</technical_language>

Target:
public static String getInternationalizedString(@NonNull String key) { Context context = PreferencesState.getInstance().getContext(); String language = getUserLanguage(context); String translation = getLocalizedStringFromDB(key, language); if (key == null) { return ""; } if (BuildConfig.activeSearchLanguageInDB && wasTranslationFound(translation)) { return translation; } else { return findStringFromAndroidResource(context, key, language); } }
Source:
<code>List<List<Integer>> slices(int num) { if (num > this.digitsSize || num == 0) { throw new IllegalArgumentException("Slice size is too big."); <START> } <END> final int limit = this.digitsSize - num + 1; List<List<Integer>> result = new ArrayList<>(limit); List<Integer> tmp; for (int i = 0; i < limit; i++) { tmp = this.digits.subList(i, i + num); result.add(tmp); } return result; }</code><technical_language>I this is correct exception message for num == 0</technical_language>

Target:
List<List<String>> slices(int num) { if (num <= 0) { throw new IllegalArgumentException("Slice size is too small."); } if (num > this.digitsSize) { throw new IllegalArgumentException("Slice size is too big."); } final int limit = this.digitsSize - num + 1; List<List<String>> result = new ArrayList<>(limit); List<String> tmp; for (int i = 0; i < limit; i++) { tmp = this.digits.subList(i, i + num); result.add(tmp); } return result; }
Source:
<code>private int checkForSpecialCharacters(int value) throws IOException { char currChar = (char) value; if (currChar == '&' && available() > 0) { final int readLimit = 10; boolean needsReset = true; super.mark(readLimit); readHelper.saveState(); try { StringBuilder specialCharBuffer = new StringBuilder(); specialCharBuffer.append(currChar); int readCount = 0; while (currChar != ';' && readCount < readLimit && super.available() > 0) { currChar = (char) readHelper.process(super.read()); specialCharBuffer.append(currChar); readCount++; } Character reserved = ReservedCharacters.toCharacter(specialCharBuffer.toString()); if (reserved != null) { needsReset = false; value = reserved; } } finally { if (needsReset) { if (super.markpos > -1) { super.reset(); <START> } <END> readHelper.restoreState(); } } } return value; }</code><technical_language>Suggest logging this well</technical_language>

Target:
private int checkForSpecialCharacters(int value) throws IOException { char currChar = (char) value; if (currChar == '&' && available() > 0) { final int readLimit = 10; boolean needsReset = true; super.mark(readLimit); readHelper.saveState(); try { StringBuilder specialCharBuffer = new StringBuilder(); specialCharBuffer.append(currChar); int readCount = 0; while (currChar != ';' && readCount < readLimit && super.available() > 0) { currChar = (char) readHelper.process(super.read()); specialCharBuffer.append(currChar); readCount++; } Character reserved = ReservedCharacters.toCharacter(specialCharBuffer.toString()); if (reserved != null) { needsReset = false; value = reserved; } } finally { if (needsReset) { super.reset(); readHelper.restoreState(); } } } return value; }
Source:
<code>public Token appendCheckpoints(CorfuRuntime rt, String author) { log.info("appendCheckpoints: appending checkpoints for maps", maps.size()); Token minSnapshot = Token.UNINITIALIZED; final long cpStart = System.currentTimeMillis(); try { for (ICorfuSMR<T> map : maps) { UUID streamId = map.getCorfuStreamID(); final long mapCpStart = System.currentTimeMillis(); int mapSize = ((T) map).size(); CheckpointWriter<T> cpw = new CheckpointWriter(rt, streamId, author, (T) map); ISerializer serializer = ((CorfuCompileProxy<Map>) map.getCorfuSMRProxy()) .getSerializer(); cpw.setSerializer(serializer); log.trace("appendCheckpoints: checkpoint map begin", Utils.toReadableId(map.getCorfuStreamID())); Token minCPSnapshot = cpw.appendCheckpoint(); if (minSnapshot == Token.UNINITIALIZED) { minSnapshot = minCPSnapshot; } else if (minSnapshot.getEpoch() != minCPSnapshot.getEpoch()) { throw new IllegalStateException("Epoch changed during GC cycle aborting"); } else if (Token.min(minCPSnapshot, minSnapshot) == minCPSnapshot) { minSnapshot = minCPSnapshot; } log.trace("appendCheckpoints: checkpoint map end", Utils.toReadableId(map.getCorfuStreamID())); <START> final long mapCpEnd = System.currentTimeMillis(); <END> log.info("appendCheckpoints: took ms to checkpoint entries for {}", mapCpEnd - mapCpStart, mapSize, streamId); } } finally { log.trace("appendCheckpoints: finished, author '{}' at min globalAddress {}", author, minSnapshot); rt.getObjectsView().TXEnd(); } final long cpStop = System.currentTimeMillis(); log.info("appendCheckpoints: took ms to append checkpoints", cpStop - cpStart, maps.size()); return minSnapshot; }</code><technical_language>this transaction started</technical_language>

Target:
public Token appendCheckpoints(CorfuRuntime rt, String author) { log.info("appendCheckpoints: appending checkpoints for maps", maps.size()); Token minSnapshot = Token.UNINITIALIZED; final long cpStart = System.currentTimeMillis(); try { for (ICorfuSMR<T> map : maps) { UUID streamId = map.getCorfuStreamID(); CheckpointWriter<T> cpw = new CheckpointWriter(rt, streamId, author, (T) map); ISerializer serializer = ((CorfuCompileProxy<Map>) map.getCorfuSMRProxy()) .getSerializer(); cpw.setSerializer(serializer); Token minCPSnapshot = cpw.appendCheckpoint(); if (minSnapshot == Token.UNINITIALIZED) { minSnapshot = minCPSnapshot; } else if (minSnapshot.getEpoch() != minCPSnapshot.getEpoch()) { String msg = String.format("Epoch changed during GC cycle from %s to %s", minSnapshot, minCPSnapshot); throw new IllegalStateException(msg); } else if (Token.min(minCPSnapshot, minSnapshot) == minCPSnapshot) { minSnapshot = minCPSnapshot; } } } finally { log.trace("appendCheckpoints: finished, author '{}' at min globalAddress {}", author, minSnapshot); rt.getObjectsView().TXEnd(); } final long cpStop = System.currentTimeMillis(); log.info("appendCheckpoints: took ms to append checkpoints", cpStop - cpStart, maps.size()); return minSnapshot; }
Source:
<code>public static String startAppiumServer() throws UnknownHostException { service = new AppiumServiceBuilder().usingPort(port).build(); service.start(); <START> InetAddress inetAddress =InetAddress.getLocalHost(); <END> return inetAddress.getHostAddress(); }</code><technical_language>missing space</technical_language>

Target:
public static String startAppiumServer() throws UnknownHostException { service = new AppiumServiceBuilder().usingPort(PORT).build(); service.start(); InetAddress inetAddress = InetAddress.getLocalHost(); return inetAddress.getHostAddress(); }
Source:
<code>private Set<String> filterUntrackedFolders(Set<String> untracked, Set<String> untrackedFolders) { Set<String> filtered = new TreeSet<String>(); fileLoop: for (String file : untracked) { for (String folder : untrackedFolders) { if (file.startsWith(folder)) { <START> continue fileLoop; <END> } } filtered.add(file); } return filtered; }</code><technical_language>a huge fan of continuing a label. populating filters untracked entries remove entries match untracked folder prefix</technical_language>

Target:
private Set<String> filterUntrackedFolders(Set<String> untracked, Set<String> untrackedFolders) { Set<String> filtered = new TreeSet<String>(untracked); for (String file : untracked) for (String folder : untrackedFolders) if (file.startsWith(folder)) { filtered.remove(file); break; } return filtered; }
Source:
<code>public EmbeddedForeignKeyDescriptor( EmbeddedIdentifierMappingImpl mappingType, String keyColumnContainingTable, List<String> keyColumnExpressions, String targetColumnContainingTable, List<String> targetColumnExpressions, MappingModelCreationProcess creationProcess) { this.keyColumnContainingTable = keyColumnContainingTable; this.keyColumnExpressions = keyColumnExpressions; this.targetColumnContainingTable = targetColumnContainingTable; this.targetColumnExpressions = targetColumnExpressions; this.mappingType = mappingType; jdbcMappings = new ArrayList<>(); mappingType.getAttributes().forEach( attribute -> { final TypeConfiguration typeConfiguration = creationProcess.getCreationContext() .getTypeConfiguration(); if ( attribute instanceof SingularAssociationAttributeMapping ) { SingularAssociationAttributeMapping associationAttributeMapping = (SingularAssociationAttributeMapping) attribute; associationAttributeMapping.getAssociatedEntityMappingType() .getEntityPersister() .getIdentifierMapping() .visitJdbcTypes( jdbcMapping -> jdbcMappings.add( jdbcMapping ) , null, typeConfiguration ); } else { attribute.visitJdbcTypes( jdbcMapping -> { jdbcMappings.add( jdbcMapping ); <START> }, <END> null, typeConfiguration ); } } ); }</code><technical_language>a good candidate of method reference usage attribute.visitJdbcTypes( jdbcMappings::add, ... );</technical_language>

Target:
public EmbeddedForeignKeyDescriptor( EmbeddedIdentifierMappingImpl mappingType, String keyColumnContainingTable, List<String> keyColumnExpressions, String targetColumnContainingTable, List<String> targetColumnExpressions, MappingModelCreationProcess creationProcess) { this.keyColumnContainingTable = keyColumnContainingTable; this.keyColumnExpressions = keyColumnExpressions; this.targetColumnContainingTable = targetColumnContainingTable; this.targetColumnExpressions = targetColumnExpressions; this.mappingType = mappingType; jdbcMappings = new ArrayList<>(); mappingType.getAttributes().forEach( attribute -> { final TypeConfiguration typeConfiguration = creationProcess.getCreationContext() .getTypeConfiguration(); if ( attribute instanceof SingularAssociationAttributeMapping ) { SingularAssociationAttributeMapping associationAttributeMapping = (SingularAssociationAttributeMapping) attribute; associationAttributeMapping.getAssociatedEntityMappingType() .getEntityPersister() .getIdentifierMapping() .visitJdbcTypes( jdbcMapping -> jdbcMappings.add( jdbcMapping ) , null, typeConfiguration ); } else { attribute.visitJdbcTypes( jdbcMappings::add, null, typeConfiguration ); } } ); }
Source:
<code>private void initCommandExecutor() { for (CommandEntity cmdEntity : commandsRepository.getCommands(true)) { if (!cmdEntity.isExecuted() && cmdEntity.getCommandStatus() != CommandStatus.FAILED && cmdEntity.getCommandStatus() != CommandStatus.EXECUTION_FAILED) { CommandBase<?> failedCommand = commandsRepository.retrieveCommand(cmdEntity.getId()); failedCommand.setCommandStatus(CommandStatus.EXECUTION_FAILED); } <START> if (!cmdEntity.isCallbackNotified() && !cmdEntity.isWaitingForEvent()) { <END> commandsRepository.addToCallbackMap(cmdEntity); } } }</code><technical_language>if commands pending for events engine rebooted left waiting for a long time frustrating users. if a good chance events missed wait. if do decide poll commands, do add subscriptions for engine start</technical_language>

Target:
private void initCommandExecutor() { for (CommandEntity cmdEntity : commandsRepository.getCommands(true)) { if (!cmdEntity.isExecuted() && cmdEntity.getCommandStatus() != CommandStatus.FAILED && cmdEntity.getCommandStatus() != CommandStatus.EXECUTION_FAILED) { CommandBase<?> failedCommand = commandsRepository.retrieveCommand(cmdEntity.getId()); failedCommand.setCommandStatus(CommandStatus.EXECUTION_FAILED); } if (!cmdEntity.isCallbackNotified()) { commandsRepository.addToCallbackMap(cmdEntity); } } }
Source:
<code>protected static Encrypt0Message decompression(byte[] cipherText, Message message) throws OSException { Encrypt0Message enc = new Encrypt0Message(false, true); try { decodeObjectSecurity(message, enc); } catch (OSException e) { LOGGER.error(e.getMessage()); <START> throw new OSException(e.getMessage()); <END> } catch (Exception e) { LOGGER.error("Failed to decode object security option."); throw new OSException("Failed to decode object security option."); } if (cipherText != null) enc.setEncryptedContent(cipherText); return enc; }</code><technical_language>is OSException simply thrown again? throw e original stacktrace</technical_language>

Target:
protected static Encrypt0Message decompression(byte[] cipherText, Message message) throws OSException { Encrypt0Message enc = new Encrypt0Message(false, true); try { decodeObjectSecurity(message, enc); } catch (OSException e) { LOGGER.error(e.getMessage()); throw e; } catch (Exception e) { LOGGER.error("Failed to decode object security option."); throw new OSException("Failed to decode object security option."); } if (cipherText != null) enc.setEncryptedContent(cipherText); return enc; }
Source:
<code>public SQLServerQueryRewriter(JdbcDataContext dataContext) { <START> super(dataContext, 11); <END> }</code><technical_language>magic number</technical_language>

Target:
public SQLServerQueryRewriter(JdbcDataContext dataContext) { super(dataContext, FIRST_FETCH_SUPPORTING_VERSION); }
Source:
<code>private EventResult runConnectHostToPoolEvent(final Guid storagePoolId, final VDS vds) { EventResult result = new EventResult(true, EventType.VDSCONNECTTOPOOL); storage_pool storagePool = getStoragePoolDAO().get(storagePoolId); StorageDomain masterDomain = getStorageDomainDAO().getStorageDomainByTypeAndPool(storagePoolId, StorageDomainType.Master); boolean shouldProceedVdsStats = true; try { runVdsCommand(VDSCommandType.ConnectStoragePool, new ConnectStoragePoolVDSCommandParameters(vds.getId(), storagePoolId, vds.getVdsSpmId(), masterDomain.getId(), <START> storagePool.getmaster_domain_version())).getSucceeded(); <END> } catch (VdcBLLException e) { if (e.getErrorCode() != VdcBllErrors.VDS_NETWORK_ERROR && e.getErrorCode() != VdcBllErrors.PROTOCOL_ERROR && (masterDomain.getStatus() == StorageDomainStatus.InActive || masterDomain.getStatus() == StorageDomainStatus.Unknown)) { shouldProceedVdsStats = false; } else { log.errorFormat("Could not connect host {0} to pool {1}", vds.getName(), storagePool .getname()); result.setSuccess(false); } } catch (RuntimeException exp) { log.errorFormat("Could not connect host {0} to pool {1}", vds.getName(), storagePool .getname()); result.setSuccess(false); } if (result.isSuccess() && shouldProceedVdsStats) { result.setSuccess(proceedVdsStats()); if (!result.isSuccess()) { AuditLogDirector.log(new AuditLogableBase(getVdsId()), AuditLogType.VDS_STORAGE_VDS_STATS_FAILED); } } return result; }</code><technical_language>remove .getSucceeded();</technical_language>

Target:
private EventResult runConnectHostToPoolEvent(final Guid storagePoolId, final VDS vds) { EventResult result = new EventResult(true, EventType.VDSCONNECTTOPOOL); StoragePool storagePool = getStoragePoolDAO().get(storagePoolId); StorageDomain masterDomain = getStorageDomainDAO().getStorageDomainByTypeAndPool(storagePoolId, StorageDomainType.Master); boolean shouldProceedVdsStats = true; try { runVdsCommand(VDSCommandType.ConnectStoragePool, new ConnectStoragePoolVDSCommandParameters(vds.getId(), storagePoolId, vds.getVdsSpmId(), masterDomain.getId(), storagePool.getmaster_domain_version())); } catch (VdcBLLException e) { if (e.getErrorCode() != VdcBllErrors.VDS_NETWORK_ERROR && (masterDomain.getStatus() == StorageDomainStatus.InActive || masterDomain.getStatus() == StorageDomainStatus.Unknown)) { shouldProceedVdsStats = false; log.infoFormat("Could not connect host {0} to pool {1}, as the master domain is in inactive/unknown status - not failing the operation", vds.getName(), storagePool .getname()); } else { log.errorFormat("Could not connect host {0} to pool {1}", vds.getName(), storagePool .getname()); result.setSuccess(false); } } if (result.isSuccess() && shouldProceedVdsStats) { result.setSuccess(proceedVdsStats()); if (!result.isSuccess()) { AuditLogDirector.log(new AuditLogableBase(getVdsId()), AuditLogType.VDS_STORAGE_VDS_STATS_FAILED); } } return result; }
Source:
<code>public FormValidation doCheckTargetTraceCollectionPort(@QueryParameter("targetTraceCollectionPort") final String targetTraceCollectionPort) { <START> if (!validatePort(targetTraceCollectionPort) && collectBuildLogs) { <END> return FormValidation.error("Invalid Trace Collection Port"); } return FormValidation.ok("Valid Trace Collection Port"); }</code><technical_language>suggestion if (!validatePort(targetTraceCollectionPort) && collectBuildTraces) {</technical_language>

Target:
public FormValidation doCheckTargetTraceCollectionPort(@QueryParameter("targetTraceCollectionPort") final String targetTraceCollectionPort) { if (!validatePort(targetTraceCollectionPort) && collectBuildTraces) { return FormValidation.error("Invalid Trace Collection Port"); } return FormValidation.ok("Valid Trace Collection Port"); }
Source:
<code>public Transformation<RowData> createInputFormatTransformation( StreamExecutionEnvironment env, InputFormat<RowData, ?> inputFormat, InternalTypeInfo<RowData> outputTypeInfo, String name) { InputFormatSourceFunction<RowData> func = new InputFormatSourceFunction<>(inputFormat, outputTypeInfo); Transformation<RowData> transformation = env.addSource(func, name, outputTypeInfo).getTransformation(); <START> ExecNodeUtil.setManagedMemoryWeight(transformation, 0L); <END> return transformation; }</code><technical_language>Is necessary set 0 managed memory weight, default 0</technical_language>

Target:
public Transformation<RowData> createInputFormatTransformation( StreamExecutionEnvironment env, InputFormat<RowData, ?> inputFormat, InternalTypeInfo<RowData> outputTypeInfo, String name) { InputFormatSourceFunction<RowData> func = new InputFormatSourceFunction<>(inputFormat, outputTypeInfo); return env.addSource(func, name, outputTypeInfo).getTransformation(); }
Source:
<code>OSInAppMessageAction(@NonNull JSONObject json) throws JSONException { clickId = json.optString(ID, null); clickName = json.optString(NAME, null); clickUrl = json.optString(URL, null); urlTarget = OSInAppMessageActionUrlType.fromString(json.optString(URL_TARGET, null)); if (urlTarget == null) urlTarget = OSInAppMessageActionUrlType.IN_APP_WEBVIEW; closesMessage = json.optBoolean(CLOSE, true); if (json.has(OUTCOMES)) { JSONArray outcomesJsonArray = json.getJSONArray(OUTCOMES); for (int i = 0; i < outcomesJsonArray.length(); i++) { outcomes.add(new OSInAppMessageOutcome((JSONObject) outcomesJsonArray.get(i))); } } if (json.has(TAGS)) tags = new OSInAppMessageTag(json.getJSONObject(TAGS)); if (json.has(PROMPTS)) { <START> JSONArray promptsJsonArray = json.getJSONArray(PROMPTS); <END> for (int i = 0; i < promptsJsonArray.length(); i++) { if (promptsJsonArray.get(i).equals(LOCATION_PROMPT_KEY) ) { prompts.add(new OSInAppMessageLocationPrompt()); } } } }</code><technical_language>Create a class handles this constructor for replace this a liner</technical_language>

Target:
OSInAppMessageAction(@NonNull JSONObject json) throws JSONException { clickId = json.optString(ID, null); clickName = json.optString(NAME, null); clickUrl = json.optString(URL, null); urlTarget = OSInAppMessageActionUrlType.fromString(json.optString(URL_TARGET, null)); if (urlTarget == null) urlTarget = OSInAppMessageActionUrlType.IN_APP_WEBVIEW; closesMessage = json.optBoolean(CLOSE, true); if (json.has(OUTCOMES)) parseOutcomes(json); if (json.has(TAGS)) tags = new OSInAppMessageTag(json.getJSONObject(TAGS)); if (json.has(PROMPTS)) parsePrompts(json); }