auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void openErroDialog(final String title, String pattern, String arg) { final String errorMsg = MessageFormat.format(pattern, new Object[] { arg }); try { MessageDialog.openError(Display.getCurrent().getActiveShell(), title, errorMsg); } catch (NullPointerException e) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { <START> MessageDialog.openError(Display.getCurrent().getActiveShell(), title, errorMsg); <END> } }); } }</code><technical_language>this try/catch is handling case Display.getCurrent returns null (or is getActiveShell?). I this proper if null check</technical_language>

Target:
public void openErroDialog(final String title, String pattern, String arg) { final String errorMsg = MessageFormat.format(pattern, new Object[] { arg }); if (Display.getCurrent() != null) { MessageDialog.openError(Display.getCurrent().getActiveShell(), title, errorMsg); } else { Display.getDefault().syncExec(new Runnable() { @Override public void run() { MessageDialog.openError(Display.getCurrent().getActiveShell(), title, errorMsg); } }); } }
Source:
<code>public void run() { <START> logger.info("Starting MegaHttpServer at " + portnumber + " port"); <END> try { ss = new ServerSocket(portnumber); } catch (IOException e) { logger.debug("ERROR -> " + e.getMessage()); } while (isRunning) { Socket s = null; try { s = ss != null ? ss.accept() : null; } catch (IOException e) { logger.debug("ERROR --> " + e.getMessage()); } if (!ss.isClosed()) { new Thread(new MegaDeviceHttpSocket(s)).start(); } } }</code><technical_language>parameterized logging instead of string concatenation</technical_language>

Target:
public void run() { logger.info("Starting MegaHttpServer at port", portnumber); try { ss = new ServerSocket(portnumber); } catch (IOException e) { logger.error("ERROR -> {}. Can't open socket ", e.getMessage()); } while (isRunning) { Socket s = null; try { s = ss != null ? ss.accept() : null; } catch (IOException e) { logger.error(e.getMessage()); } if (!ss.isClosed()) { try { Thread.sleep(10000); } catch (InterruptedException e) { logger.error(e.getMessage()); } new Thread(new MegaDeviceHttpSocket(s)).start(); } } }
Source:
<code>private ProcessHandler startTestProcess(IJavaProject javaProject, TestExecutionContext context) { File suiteFile = createSuite(context, javaProject); if (suiteFile == null) { throw new RuntimeException("Can't create TestNG suite xml file."); } JavaParameters parameters = new JavaParameters(); parameters.setJavaExecutable("java"); parameters.setMainClassName("org.testng.CheTestNGLauncher"); <START> parameters.setWorkingDirectory("/tmp"); <END> List<String> classPath = new ArrayList<>(); Set<String> projectClassPath = classpathProvider.getProjectClassPath(javaProject); classPath.addAll(projectClassPath); classPath.add(ClasspathUtil.getJarPathForClass(org.testng.CheTestNG.class)); classPath.add(ClasspathUtil.getJarPathForClass(JCommander.class)); parameters.getClassPath().addAll(classPath); parameters.getParametersList().add("-suiteFile", suiteFile.getAbsolutePath()); CommandLine command = parameters.createCommand(); try { return new ProcessHandler(command.createProcess()); } catch (ExecutionException e) { LOG.error("Can't run TestNG JVM", e); } return null; }</code><technical_language>Let;s for TestNG runner is</technical_language>

Target:
private ProcessHandler startTestProcess(IJavaProject javaProject, TestExecutionContext context) { File suiteFile = createSuite(context, javaProject); if (suiteFile == null) { throw new RuntimeException("Can't create TestNG suite xml file."); } JavaParameters parameters = new JavaParameters(); parameters.setJavaExecutable("java"); parameters.setMainClassName("org.testng.CheTestNGLauncher"); String outputDirectory = getOutputDirectory(javaProject); parameters.getParametersList().add("-d", outputDirectory); parameters.setWorkingDirectory(PROJECTS_ROOT_FOLDER + javaProject.getPath()); List<String> classPath = new ArrayList<>(); Set<String> projectClassPath = classpathProvider.getProjectClassPath(javaProject); classPath.addAll(projectClassPath); classPath.add(ClasspathUtil.getJarPathForClass(org.testng.CheTestNG.class)); classPath.add(ClasspathUtil.getJarPathForClass(JCommander.class)); parameters.getClassPath().addAll(classPath); parameters.getParametersList().add("-suiteFile", suiteFile.getAbsolutePath()); if (context.isDebugModeEnable()) { debugPort = generateDebuggerPort(); parameters.getVmParameters().add("-Xdebug"); parameters.getVmParameters().add("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=" + debugPort); } CommandLine command = parameters.createCommand(); try { return new ProcessHandler(command.createProcess()); } catch (ExecutionException e) { LOG.error("Can't run TestNG JVM", e); } return null; }
Source:
<code>public GdbFullCliConsole(ILaunch launch, String label, Process process, PTY pty) { super(label, null, false); fLaunch = launch; fLabel = label; new GdbConsoleLifecycleListener(this); <START> fTerminalConnector = new GdbTerminalConnector(process); <END> resetName(); }</code><technical_language>dispose of this instance stop Jobs. is strictly necessary GDB dead streams close jobs end, cleanup properly future-proof</technical_language>

Target:
public GdbFullCliConsole(ILaunch launch, String label, Process process, PTY pty) { super(label, null, false); fLaunch = launch; fLabel = label; fGdbPty = pty; new GdbConsoleLifecycleListener(this); fTerminalConnector = new GdbTerminalConnector(process); resetName(); }
Source:
<code>public Method getOnStringMessageMethod(Object webSocketEndpoint) { Method[] methods = webSocketEndpoint.getClass().getMethods(); <START> for (Method method : methods) { <END> if (method.isAnnotationPresent(OnMessage.class)) { Class<?>[] paraTypes = method.getParameterTypes(); List<Class<?>> paraList = Arrays.asList(paraTypes); if (paraList.contains(String.class)) { return method; } } } return null; }</code><technical_language>above, for loop throw a NPE if methods variable null</technical_language>

Target:
public Method getOnStringMessageMethod(Object webSocketEndpoint) { Method[] methods = webSocketEndpoint.getClass().getMethods(); if (methods == null) { return null; } for (Method method : methods) { if (method.isAnnotationPresent(OnMessage.class)) { Class<?>[] paraTypes = method.getParameterTypes(); List<Class<?>> paraList = Arrays.asList(paraTypes); if (paraList.contains(String.class)) { return method; } } } return null; }
Source:
<code>public int ifHit(Vector<Bullet> alienBullets) { <START> Iterator iteralien = ConcreteAggregate.createIterator(alienBullets); <END> while (iteralien.hasNext()) { Bullet bullet = (Bullet) iteralien.next(); if (bullet instanceof MegaBullet) { if (ifHitMega(bullet, iteralien.position()) == true) { return iteralien.position(); } } if (bullet.getY() > ypos - 10 && bullet.getY() < ypos + 16) { if (bullet.getX() > xpos - 6 && bullet.getX() < xpos + 26) { lives -= 1; Game.logfile.writeHit("Spaceship", bullet.getX(), bullet.getY()); if (lives > 0) { Game.logfile.writeString("Spaceship has " + String.valueOf(lives) + " lives left"); } else { Game.logfile.writeString("Spaceship has no lives left"); } return iteralien.position(); } } } return -1; }</code><technical_language>iteralien -> iterAlienBullets</technical_language>

Target:
public int ifHit(Vector<Bullet> alienBullets) { Iterator iterAlienBullets = ConcreteAggregate.createIterator(alienBullets); while (iterAlienBullets.hasNext()) { Bullet bullet = (Bullet) iterAlienBullets.next(); if (bullet instanceof MegaBullet) { if (ifHitMega(bullet, iterAlienBullets.position()) == true) { return iterAlienBullets.position(); } } if (bullet.getY() > ypos - 10 && bullet.getY() < ypos + 16) { if (bullet.getX() > xpos - 6 && bullet.getX() < xpos + 26) { lives -= 1; Game.logfile.writeHit("Spaceship", bullet.getX(), bullet.getY()); if (lives > 0) { Game.logfile.writeString("Spaceship has " + String.valueOf(lives) + " lives left"); } else { Game.logfile.writeString("Spaceship has no lives left"); } return iterAlienBullets.position(); } } } return -1; }
Source:
<code>public Map<Object, Query> getTerms(final Query query) throws IOException { final Map<Object, Query> termMap = new TreeMap<>(); index.withReader(reader -> { LuceneUtil.extractTerms(query, termMap, reader, false); return termMap; }); <START> return termMap; <END> }</code><technical_language>this effectively returns empty TreeMap no</technical_language>

Target:
public Map<Object, Query> getTerms(final Query query) throws IOException { return index.withReader(reader -> { final Map<Object, Query> termMap = new TreeMap<>(); LuceneUtil.extractTerms(query, termMap, reader, false); return termMap; }); }
Source:
<code>private static int convertTalendAvroType(String javaType) { int sqlType = Types.NULL; <START> if (javaType.equals("java.lang.Byte")) { <END> sqlType = Types.SMALLINT; } else if (javaType.equals("java.lang.Short")) { sqlType = Types.SMALLINT; } else if (javaType.equals("java.lang.Character")) { sqlType = Types.CHAR; } else if (javaType.equals("java.util.Date")) { sqlType = Types.DATE; } else if (javaType.equals("java.math.BigDecimal")) { sqlType = Types.DOUBLE; } else { throw new UnsupportedOperationException(javaType + " class can't be converted to SQL type."); } return sqlType; }</code><technical_language>Do enum for **javaType** ? switch case</technical_language>

Target:
private int convertTalendAvroType(String javaType) { Integer sqlType = this.config.CONVERT_JAVATYPE_TO_SQLTYPE.get(javaType); if(sqlType != null){ return sqlType; } switch (javaType) { case "java.lang.Byte": sqlType = Types.SMALLINT; break; case "java.lang.Short": sqlType = Types.SMALLINT; break; case "java.lang.Character": sqlType = Types.CHAR; break; case "java.util.Date": sqlType = Types.DATE; break; case "java.math.BigDecimal": sqlType = Types.DOUBLE; break; default: throw new UnsupportedOperationException(javaType + " class can't be converted to SQL type."); } return sqlType; }
Source:
<code>public Long getDirectUploadExpiration() { <START> return config.get("direct_upload_expiration", Long.class, 10L*60); <END> }</code><technical_language>explain default 10L*60</technical_language>

Target:
public Optional<Long> getDirectUploadExpiration() { return Optional.of(config.get("direct_upload_expiration", Long.class, 10L*60)); }
Source:
<code>public void onMapReady(@NonNull final MapboxMap mapboxMap) { mapboxMap.setStyle(Style.LIGHT, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { ValueAnimatorIconAnimationActivity.this.style = style; mapView.addOnDidFinishRenderingMapListener(ValueAnimatorIconAnimationActivity.this); <START> initLayerIcon(style); <END> initDataSource(style); } }); }</code><technical_language>added StyleBuilder#withIcon</technical_language>

Target:
public void onMapReady(@NonNull final MapboxMap mapboxMap) { mapboxMap.setStyle(new Style.Builder().fromUrl(Style.LIGHT) .withSource(new GeoJsonSource("source-id", FeatureCollection.fromFeatures(new Feature[] { Feature.fromGeometry(Point.fromLngLat( 119.86083984375, -1.834403324493515)), Feature.fromGeometry(Point.fromLngLat( 116.06637239456177, 5.970619502704659)), Feature.fromGeometry(Point.fromLngLat( 114.58740234375, 4.54357027937176)), Feature.fromGeometry(Point.fromLngLat( 118.19091796875, 5.134714634014467)), Feature.fromGeometry(Point.fromLngLat( 110.36865234374999, 1.4500404973608074)), Feature.fromGeometry(Point.fromLngLat( 109.40185546874999, 0.3076157096439005)), Feature.fromGeometry(Point.fromLngLat( 115.79589843749999, 1.5159363834516861)), Feature.fromGeometry(Point.fromLngLat( 113.291015625, -0.9667509997666298)), Feature.fromGeometry(Point.fromLngLat( 116.40083312988281, -0.3392008994314591)) }) )) .withImage(ICON_ID, BitmapUtils.getBitmapFromDrawable( getResources().getDrawable(R.drawable.map_marker_push_pin_pink))), new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { ValueAnimatorIconAnimationActivity.this.style = style; mapView.addOnDidFinishRenderingMapListener(ValueAnimatorIconAnimationActivity.this); } } ); }
Source:
<code>private List<ExceptionInfo> getThrowed(DetailAST methodAst) { final List<ExceptionInfo> returnValue = new ArrayList<>(); final DetailAST blockAst = methodAst.findFirstToken(TokenTypes.SLIST); if (blockAst != null) { final List<DetailAST> throwLiterals = findTokensInAstByType(blockAst, TokenTypes.LITERAL_THROW); for (DetailAST throwAst : throwLiterals) { <START> DetailAST ancestor = throwAst; <END> while (ancestor != blockAst) { if (ancestor.getType() == TokenTypes.LITERAL_TRY || ancestor.getType() == TokenTypes.LAMBDA) { break; } if (ancestor.getType() == TokenTypes.LITERAL_CATCH || ancestor.getType() == TokenTypes.LITERAL_FINALLY) { ancestor = ancestor.getParent(); } ancestor = ancestor.getParent(); } if (ancestor == blockAst) { final DetailAST newAst = throwAst.getFirstChild().getFirstChild(); if (newAst.getType() == TokenTypes.LITERAL_NEW) { final FullIdent ident = FullIdent.createFullIdent(newAst.getFirstChild()); final ExceptionInfo exceptionInfo = new ExceptionInfo( createClassInfo(new Token(ident), currentClassName)); returnValue.add(exceptionInfo); } } } } return returnValue; }</code><technical_language>DetailAST ancestor = throwAst; --> DetailAST ancestor = throwAst.getParent(); do need check throw AST in while I understand</technical_language>

Target:
private List<ExceptionInfo> getThrowed(DetailAST methodAst) { final List<ExceptionInfo> returnValue = new ArrayList<>(); final DetailAST blockAst = methodAst.findFirstToken(TokenTypes.SLIST); if (blockAst != null) { final List<DetailAST> throwLiterals = findTokensInAstByType(blockAst, TokenTypes.LITERAL_THROW); for (DetailAST throwAst : throwLiterals) { if (!isInIgnoreBlock(blockAst, throwAst)) { final DetailAST newAst = throwAst.getFirstChild().getFirstChild(); if (newAst.getType() == TokenTypes.LITERAL_NEW) { final FullIdent ident = FullIdent.createFullIdent(newAst.getFirstChild()); final ExceptionInfo exceptionInfo = new ExceptionInfo( createClassInfo(new Token(ident), currentClassName)); returnValue.add(exceptionInfo); } } } } return returnValue; }
Source:
<code>private String getThreeWayOverlay(final Diff diff) { final Conflict conflict = diff.getConflict(); final DifferenceKind diffKind = diff.getKind(); final DifferenceSource source = diff.getSource(); ConflictKind conflictKind = null; if (hasDirectOrIndirectConflict(REAL).apply(diff)) { conflictKind = REAL; <START> } else if (or(hasConflict(PSEUDO), allAtomicRefining(hasConflict(PSEUDO))).apply(diff)) { <END> conflictKind = PSEUDO; } String path = ""; if (conflict != null || conflictKind != null) { if ((conflict != null && conflict.getKind() == PSEUDO) || conflictKind == PSEUDO) { path += "p"; } path += "conf"; if (source == DifferenceSource.RIGHT) { path += "r_"; } } else { switch (source) { case LEFT: path += "r_out"; break; case RIGHT: path += "r_in"; break; default: break; } } switch (diffKind) { case ADD: path += ADD_OV; break; case DELETE: path += DEL_OV; break; case CHANGE: case MOVE: path += CHG_OV; break; default: break; } return path; }</code><technical_language>I be: - diff is refined, a pseudo-conflict - is refined, atomic diffs in pseudo-conflict i.e. ignore pseudo-conflict statuc of refined diffs. This aligned done in filters group computation</technical_language>

Target:
private String getThreeWayOverlay(final Diff diff) { final Conflict conflict = diff.getConflict(); final DifferenceKind diffKind = diff.getKind(); final DifferenceSource source = diff.getSource(); ConflictKind conflictKind = null; if (hasDirectOrIndirectConflict(REAL).apply(diff)) { conflictKind = REAL; } else if (canBeConsideredAsPseudoConflicting().apply(diff)) { conflictKind = PSEUDO; } String path = ""; if (conflict != null || conflictKind != null) { if ((conflict != null && conflict.getKind() == PSEUDO) || conflictKind == PSEUDO) { path += "p"; } path += "conf"; if (source == DifferenceSource.RIGHT) { path += "r_"; } } else { switch (source) { case LEFT: path += "r_out"; break; case RIGHT: path += "r_in"; break; default: break; } } switch (diffKind) { case ADD: path += ADD_OV; break; case DELETE: path += DEL_OV; break; case CHANGE: case MOVE: path += CHG_OV; break; default: break; } return path; }
Source:
<code>private void setCurrentLocale(Locale locale) { if (locale.equals(mCurrentLocale)) { return; } mCurrentLocale = locale; mTempDate = getCalendarForLocale(mTempDate, locale); mMinDate = getCalendarForLocale(mMinDate, locale); mMaxDate = getCalendarForLocale(mMaxDate, locale); mCurrentDate = getCalendarForLocale(mCurrentDate, locale); mNumberOfMonths = mTempDate.getActualMaximum(Calendar.MONTH) + 1; mShortMonths = new String[mNumberOfMonths]; <START> <END> String january = DateUtils.getMonthString(Calendar.JANUARY, DateUtils.LENGTH_MEDIUM); if (Character.isDigit(january.charAt(0))) { for (int i = 0; i < mNumberOfMonths; ++i) { mShortMonths[i] = String.format("%d", i + 1); } } else { for (int i = 0; i < mNumberOfMonths; ++i) { mShortMonths[i] = DateUtils.getMonthString(Calendar.JANUARY + i, DateUtils.LENGTH_MEDIUM); } } }</code><technical_language>fix DataUtils if is case, right? DateUtils is strings LocaleDate correct values - not. This a workaround. if some other code needs show a date in kr/ja/zh format - do trick</technical_language>

Target:
private void setCurrentLocale(Locale locale) { if (locale.equals(mCurrentLocale)) { return; } mCurrentLocale = locale; mTempDate = getCalendarForLocale(mTempDate, locale); mMinDate = getCalendarForLocale(mMinDate, locale); mMaxDate = getCalendarForLocale(mMaxDate, locale); mCurrentDate = getCalendarForLocale(mCurrentDate, locale); mNumberOfMonths = mTempDate.getActualMaximum(Calendar.MONTH) + 1; if (useNumericMonths()) { mShortMonths = new String[mNumberOfMonths]; for (int i = 0; i < mNumberOfMonths; ++i) { mShortMonths[i] = String.format("%d", i + 1); } } else { mShortMonths = LocaleData.get(Locale.getDefault()).shortMonthNames.clone(); } }
Source:
<code>private CompletableFuture<List<MesosWorkerStore.Worker>> getWorkersAsync() { <START> return CompletableFuture.supplyAsync(() -> { try { final List<MesosWorkerStore.Worker> tasksFromPreviousAttempts = workerStore.recoverWorkers(); for (final MesosWorkerStore.Worker worker : tasksFromPreviousAttempts) { if (worker.state() == MesosWorkerStore.WorkerState.New) { workerStore.removeWorker(worker.taskID()); } } return tasksFromPreviousAttempts; } catch (final Exception e) { throw new CompletionException(new ResourceManagerException(e)); } }); <END> }</code><technical_language>This executed in a global thread pool ForkJoinPool#commonPool(). This is ideal workerStore.recoverWorkers blocking</technical_language>

Target:
private CompletableFuture<List<MesosWorkerStore.Worker>> getWorkersAsync() { return CompletableFuture.supplyAsync(() -> { try { final List<MesosWorkerStore.Worker> tasksFromPreviousAttempts = workerStore.recoverWorkers(); for (final MesosWorkerStore.Worker worker : tasksFromPreviousAttempts) { if (worker.state() == MesosWorkerStore.WorkerState.New) { workerStore.removeWorker(worker.taskID()); } } return tasksFromPreviousAttempts; } catch (final Exception e) { throw new CompletionException(new ResourceManagerException(e)); } }, getIoExecutor()); }
Source:
<code>public void no_effect_when_removing_any_permission_from_group_AnyOne_on_a_private_project() { <START> ComponentDto project = db.components().insertPrivateProject(); <END> userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ProjectPermissions.ALL .forEach(permission -> { newRequest() .setParam(PARAM_GROUP_NAME, "anyone") .setParam(PARAM_PROJECT_ID, project.uuid()) .setParam(PARAM_PERMISSION, permission) .execute(); }); }</code><technical_language>I prefer rename no_effect_... should_not_fail_..., asserts. (or add asserts, of course)</technical_language>

Target:
public void no_effect_when_removing_any_permission_from_group_AnyOne_on_a_private_project() { ComponentDto project = db.components().insertPrivateProject(); ProjectPermissions.ALL .forEach(perm -> unsafeInsertProjectPermissionOnAnyone(perm, project)); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ProjectPermissions.ALL .forEach(permission -> { newRequest() .setParam(PARAM_GROUP_NAME, "anyone") .setParam(PARAM_PROJECT_ID, project.uuid()) .setParam(PARAM_PERMISSION, permission) .execute(); assertThat(db.users().selectAnyonePermissions(db.getDefaultOrganization(), project)).contains(permission); }); }
Source:
<code>public void onEnter() { final String kafkaFlushedBytesMetricName = MetricUtils.metricNameForHiLAStream( this.getContext().getParameters().getConsumingAppId(), this.getContext().getSubscriptionId() ); bytesSentMeter = this.getContext().getMetricRegistry().meter(kafkaFlushedBytesMetricName); this.kafkaConsumer = getKafka().createKafkaConsumer(); this.topologyChangeSubscription = getZk().subscribeForTopologyChanges(() -> addTask(this::topologyChanged)); reactOnTopologyChange(); addTask(this::pollDataFromKafka); scheduleTask(this::checkBatchTimeouts, getParameters().batchTimeoutMillis, TimeUnit.MILLISECONDS); getParameters().streamTimeoutMillis.ifPresent( timeout -> scheduleTask(() -> { final String debugMessage = "Stream timeout reached"; this.sendMetadata(debugMessage); this.shutdownGracefully(debugMessage); }, timeout, TimeUnit.MILLISECONDS)); this.lastCommitMillis = System.currentTimeMillis(); scheduleTask(this::checkCommitTimeout, getParameters().commitTimeoutMillis, TimeUnit.MILLISECONDS); getLog().debug("Register cursor reset listener"); cursorResetSubscription = getZk().subscribeForCursorsReset(() -> { final String message = "Resetting subscription cursors"; sendMetadata(message); shutdownGracefully(message); <START> }); <END> }</code><technical_language>is a task queue, guaranties, actions modify data, is respect this behavior everywhere. is addTask call while subscription reset notification</technical_language>

Target:
public void onEnter() { final String kafkaFlushedBytesMetricName = MetricUtils.metricNameForHiLAStream( this.getContext().getParameters().getConsumingAppId(), this.getContext().getSubscriptionId() ); bytesSentMeter = this.getContext().getMetricRegistry().meter(kafkaFlushedBytesMetricName); this.kafkaConsumer = getKafka().createKafkaConsumer(); this.topologyChangeSubscription = getZk().subscribeForTopologyChanges(() -> addTask(this::topologyChanged)); reactOnTopologyChange(); addTask(this::pollDataFromKafka); scheduleTask(this::checkBatchTimeouts, getParameters().batchTimeoutMillis, TimeUnit.MILLISECONDS); getParameters().streamTimeoutMillis.ifPresent( timeout -> scheduleTask(() -> { final String debugMessage = "Stream timeout reached"; this.sendMetadata(debugMessage); this.shutdownGracefully(debugMessage); }, timeout, TimeUnit.MILLISECONDS)); this.lastCommitMillis = System.currentTimeMillis(); scheduleTask(this::checkCommitTimeout, getParameters().commitTimeoutMillis, TimeUnit.MILLISECONDS); cursorResetSubscription = getZk().subscribeForCursorsReset( () -> addTask(this::resetSubscriptionCursorsCallback)); }
Source:
<code>private boolean isTtlUpdateEntryValid(StoreKey key, Offset indexSegmentStartOffset) throws StoreException { boolean valid = false; FileSpan srcSearchSpan = new FileSpan(srcIndex.getStartOffset(), indexSegmentStartOffset); IndexValue srcValue = srcIndex.findKey(key, srcSearchSpan, EnumSet.of(PersistentIndex.IndexEntryType.PUT)); if (srcValue == null) { logger.trace( "Skipping copying TTL update of in segment with start offset in because the corresponding PUT entry " + "does not exist anymore", key, indexSegmentStartOffset, storeId); } else { IndexValue tgtValue = tgtIndex.findKey(key, null, EnumSet.of(PersistentIndex.IndexEntryType.PUT)); if (tgtValue == null && isOffsetInCurrentCycle(srcValue.getOffset())) { logger.trace( <START> "Skipping copying TTL update of in segment with start offset in because the corresponding PUT entry" <END> + " will be compacted in this cycle ({} are being compacted in this cycle)", key, indexSegmentStartOffset, storeId, srcValue, compactionLog.getCompactionDetails().getLogSegmentsUnderCompaction()); } else { valid = true; } } return valid; }</code><technical_language>statements rephrased, this is skipping anything, "determining" if entry is valid</technical_language>

Target:
private boolean isTtlUpdateEntryValid(StoreKey key, Offset indexSegmentStartOffset) throws StoreException { boolean valid = false; FileSpan srcSearchSpan = new FileSpan(srcIndex.getStartOffset(), indexSegmentStartOffset); IndexValue srcValue = srcIndex.findKey(key, srcSearchSpan, EnumSet.of(PersistentIndex.IndexEntryType.PUT)); if (srcValue == null) { logger.trace("TTL update of in segment with start offset in is not valid the corresponding PUT entry " + "does not exist anymore", key, indexSegmentStartOffset, storeId); } else { IndexValue tgtValue = tgtIndex.findKey(key, null, EnumSet.of(PersistentIndex.IndexEntryType.PUT)); if (tgtValue == null && isOffsetUnderCompaction(srcValue.getOffset())) { logger.trace( "TTL update of in segment with start offset in is not valid because the corresponding PUT entry" + " will be compacted in this cycle ({} are being compacted in this cycle)", key, indexSegmentStartOffset, storeId, srcValue, compactionLog.getCompactionDetails().getLogSegmentsUnderCompaction()); } else { valid = true; } } return valid; }
Source:
<code>public ConfigurationNode getNode(Locale locale) { ConfigurationNode node = this.nodes.get(locale); if (node == null) { <START> throw new IllegalStateException("Tried to read MultiSourceConfigTranslationDictionary before locale " + locale + " was loaded."); <END> } return node; }</code><technical_language>Preconditions.checkState here</technical_language>

Target:
public ConfigurationNode getNode(Locale locale) { ConfigurationNode node = this.nodes.get(locale); checkState(node != null, "Tried to read MultiSourceConfigTranslationDictionary before locale %s was loaded.", locale); return node; }
Source:
<code>public List<DiffEntry> scan(AbstractTreeIterator a, AbstractTreeIterator b) throws IOException { assertHaveRepository(); <START> TreeWalk walk = new TreeWalk(db, reader); <END> walk.addTree(a); walk.addTree(b); walk.setRecursive(true); TreeFilter filter = getDiffTreeFilterFor(a, b); if (pathFilter instanceof FollowFilter) { walk.setFilter(AndTreeFilter.create( PathFilter.create(((FollowFilter) pathFilter).getPath()), filter)); } else { walk.setFilter(AndTreeFilter.create(pathFilter, filter)); } source = new ContentSource.Pair(source(a), source(b)); List<DiffEntry> files = DiffEntry.scan(walk); if (pathFilter instanceof FollowFilter && isAdd(files)) { a.reset(); b.reset(); walk.reset(); walk.addTree(a); walk.addTree(b); walk.setFilter(filter); if (renameDetector == null) setDetectRenames(true); files = updateFollowFilter(detectRenames(DiffEntry.scan(walk))); } else if (renameDetector != null) files = detectRenames(files); return files; }</code><technical_language>is this change needed</technical_language>

Target:
public List<DiffEntry> scan(AbstractTreeIterator a, AbstractTreeIterator b) throws IOException { assertHaveRepository(); TreeWalk walk = new TreeWalk(reader); walk.addTree(a); walk.addTree(b); walk.setRecursive(true); TreeFilter filter = getDiffTreeFilterFor(a, b); if (pathFilter instanceof FollowFilter) { walk.setFilter(AndTreeFilter.create( PathFilter.create(((FollowFilter) pathFilter).getPath()), filter)); } else { walk.setFilter(AndTreeFilter.create(pathFilter, filter)); } source = new ContentSource.Pair(source(a), source(b)); List<DiffEntry> files = DiffEntry.scan(walk); if (pathFilter instanceof FollowFilter && isAdd(files)) { a.reset(); b.reset(); walk.reset(); walk.addTree(a); walk.addTree(b); walk.setFilter(filter); if (renameDetector == null) setDetectRenames(true); files = updateFollowFilter(detectRenames(DiffEntry.scan(walk))); } else if (renameDetector != null) files = detectRenames(files); return files; }
Source:
<code><START> @Override public boolean clean(ByteBuffer buf) { <END> try { Object cleaner = cleanerMtd.invoke(buf); if (cleaner == null) { return false; } cleanMtd.invoke(cleaner); return true; } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException("Failed to invoke direct buffer cleaner", e); } }</code><technical_language>annotations line method declaration</technical_language>

Target:
public boolean clean(ByteBuffer buf) { try { Object cleaner = cleanerMtd.invoke(buf); if (cleaner == null) { return false; } cleanMtd.invoke(cleaner); return true; } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException("Failed to invoke direct buffer cleaner", e); } }
Source:
<code><START> public static Optional<ArrayByteSource> unzipPathNameInMemory(BeanByteSource source, String relativePathName) { <END> try (ZipInputStream in = new ZipInputStream(source.openStream())) { ZipEntry entry = in.getNextEntry(); while (entry != null) { if (!entry.isDirectory() && entry.getName().equals(relativePathName)) { return Optional.of(ArrayByteSource.copyOf(ByteStreams.toByteArray(in)).withFileName(entry.getName())); } in.closeEntry(); entry = in.getNextEntry(); } } catch (IOException ex) { throw new UncheckedIOException(ex); } return Optional.empty(); }</code><technical_language>A null relative path sense, is currently accepted this method, return Optional.empty</technical_language>

Target:
public static Optional<ArrayByteSource> unzipPathNameInMemory(BeanByteSource source, String relativePathName) { ArgChecker.notNull(relativePathName, "relativePathName"); try (ZipInputStream in = new ZipInputStream(source.openStream())) { ZipEntry entry = in.getNextEntry(); while (entry != null) { if (!entry.isDirectory() && entry.getName().equals(relativePathName)) { return Optional.of(ArrayByteSource.copyOf(ByteStreams.toByteArray(in)).withFileName(entry.getName())); } in.closeEntry(); entry = in.getNextEntry(); } } catch (IOException ex) { throw new UncheckedIOException(ex); } return Optional.empty(); }
Source:
<code><START> public KeyIncrementPair(Random random, int maxKey, int maxInc) { <END> }</code><technical_language>confused. unused params in constructor</technical_language>

Target:
public KeyIncrementPair(Random random, int maxKey, int maxInc) { key = random.nextInt(maxKey); inc = random.nextInt(maxInc-1)+1; }
Source:
<code><START> static Optional<ChargeStatus> newChargeStateForChargeNotification(String notificationStatus, ChargeStatus chargeStatus) { <END> final EpdqNotification.StatusCode statusCode = EpdqNotification.StatusCode.byCode(notificationStatus); switch (statusCode) { case EPDQ_AUTHORISATION_REFUSED: return Optional.of(AUTHORISATION_REJECTED); case EPDQ_AUTHORISED: return Optional.of(AUTHORISATION_SUCCESS); case EPDQ_AUTHORISED_CANCELLED: switch (chargeStatus) { case USER_CANCEL_SUBMITTED: return Optional.of(USER_CANCELLATION_FLOW.getSuccessTerminalState()); case EXPIRE_CANCEL_SUBMITTED: return Optional.of(EXPIRE_FLOW.getSuccessTerminalState()); case SYSTEM_CANCEL_SUBMITTED: case CREATED: case ENTERING_CARD_DETAILS: return Optional.of(SYSTEM_CANCELLATION_FLOW.getSuccessTerminalState()); default: return Optional.empty(); } case EPDQ_PAYMENT_REQUESTED: return Optional.of(CAPTURED); default: return Optional.empty(); } }</code><technical_language>is this method private? of this class</technical_language>

Target:
private static Optional<ChargeStatus> newChargeStateForChargeNotification(String notificationStatus, ChargeStatus chargeStatus) { final EpdqNotification.StatusCode statusCode = EpdqNotification.StatusCode.byCode(notificationStatus); switch (statusCode) { case EPDQ_AUTHORISATION_REFUSED: return Optional.of(AUTHORISATION_REJECTED); case EPDQ_AUTHORISED: return Optional.of(AUTHORISATION_SUCCESS); case EPDQ_AUTHORISED_CANCELLED: switch (chargeStatus) { case USER_CANCEL_SUBMITTED: return Optional.of(USER_CANCELLATION_FLOW.getSuccessTerminalState()); case EXPIRE_CANCEL_SUBMITTED: return Optional.of(EXPIRE_FLOW.getSuccessTerminalState()); case SYSTEM_CANCEL_SUBMITTED: case CREATED: case ENTERING_CARD_DETAILS: return Optional.of(SYSTEM_CANCELLATION_FLOW.getSuccessTerminalState()); default: return Optional.empty(); } case EPDQ_PAYMENT_REQUESTED: return Optional.of(CAPTURED); default: return Optional.empty(); } }
Source:
<code>protected CompletableFuture<Integer> getValue() { <START> if (getter.isPresent()) { <END> return getter.map(integerGetter -> integerGetter.get()).get(); } else { return null; } }</code><technical_language>good point null, replacing get orElse do trick return getter.map(integerGetter -> integerGetter.get()).orElse(null);</technical_language>

Target:
protected CompletableFuture<Integer> getValue() { return getter.map(integerGetter -> integerGetter.get()).orElse(null); }
Source:
<code>public void shouldReturnTheCorrectStateForNonXPostalCode() { Optional<CanadaProvinceOrTerritory> canadaProvinceTerritory = CanadaPostalcodeToProvinceOrTerritoryMapper.getProvinceOrTerritory("A1A1A1"); assertThat(canadaProvinceTerritory.isPresent(), is (true)); <START> assertThat(canadaProvinceTerritory.get().getAbbreviation(), is ("NL")); assertThat(canadaProvinceTerritory.get().getFullName(), is ("Newfoundland and Labrador")); <END> }</code><technical_language>assert equal enum value, checking abbreviation full name separately</technical_language>

Target:
public void shouldReturnTheCorrectStateForNonXPostalCode() { Optional<CanadaProvinceOrTerritory> canadaProvinceTerritory = CanadaPostalcodeToProvinceOrTerritoryMapper.getProvinceOrTerritory("A1A1A1"); assertThat(canadaProvinceTerritory.isPresent(), is (true)); assertThat(canadaProvinceTerritory.get(), is (CanadaProvinceOrTerritory.NEWFOUNDLAND_AND_LABRADOR)); }
Source:
<code><START> public static ColumnValueSelector makeColumnValueSelectorWithFloatDefault( <END> final ColumnSelectorFactory metricFactory, final ExprMacroTable macroTable, final String fieldName, final String fieldExpression, final float nullValue ) { if (fieldName != null && fieldExpression == null) { return metricFactory.makeColumnValueSelector(fieldName); } if (fieldName == null && fieldExpression != null) { final Expr expr = Parser.parse(fieldExpression, macroTable); final ColumnValueSelector<ExprEval> baseSelector = ExpressionSelectors.makeExprEvalSelector(metricFactory, expr); class ExpressionFloatColumnSelector implements FloatColumnSelector { @Override public float getFloat() { final ExprEval exprEval = baseSelector.getObject(); return exprEval.isNumericNull() ? nullValue : (float) exprEval.asDouble(); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("baseSelector", baseSelector); } @Override public boolean isNull() { final ExprEval exprEval = baseSelector.getObject(); return exprEval == null || exprEval.isNumericNull(); } } return new ExpressionFloatColumnSelector(); } throw new IllegalArgumentException("Must have a valid, non-null fieldName or expression"); }</code><technical_language>This change is needed if NullableAggregatorFactory is parameterized</technical_language>

Target:
public static BaseFloatColumnValueSelector makeColumnValueSelectorWithFloatDefault( final ColumnSelectorFactory metricFactory, final ExprMacroTable macroTable, final String fieldName, final String fieldExpression, final float nullValue ) { if (fieldName != null && fieldExpression == null) { return metricFactory.makeColumnValueSelector(fieldName); } if (fieldName == null && fieldExpression != null) { final Expr expr = Parser.parse(fieldExpression, macroTable); final ColumnValueSelector<ExprEval> baseSelector = ExpressionSelectors.makeExprEvalSelector(metricFactory, expr); class ExpressionFloatColumnSelector implements FloatColumnSelector { @Override public float getFloat() { final ExprEval exprEval = baseSelector.getObject(); return exprEval.isNumericNull() ? nullValue : (float) exprEval.asDouble(); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("baseSelector", baseSelector); } @Override public boolean isNull() { final ExprEval exprEval = baseSelector.getObject(); return exprEval == null || exprEval.isNumericNull(); } } return new ExpressionFloatColumnSelector(); } throw new IllegalArgumentException("Must have a valid, non-null fieldName or expression"); }
Source:
<code>protected void logSearchRequest(SearchRequest request, NxQueryBuilder query, SearchType searchType) { if (log.isDebugEnabled()) { String scroll = ""; if (request.scroll() != null) { scroll = "&scroll=" + request.scroll().toString(); <START> } <END> log.debug(String.format( "Search query: curl -XGET 'http://localhost:9200/%s/%s/_search?pretty&search_type=%s%s' -d '%s'", getSearchIndexesAsString(query), DOC_TYPE, searchType.toString().toLowerCase(), scroll, request.source().toString())); } }</code><technical_language>Double assignment scroll is bad style, toString is implicit concatenating a String. use: IDontKnowTheType requestScroll = request.scroll(); String scroll = requestScroll == null ? null : "&scroll=" + requestScroll;</technical_language>

Target:
protected void logSearchRequest(SearchRequest request, NxQueryBuilder query, SearchType searchType) { if (log.isDebugEnabled()) { String scroll = request.scroll() != null ? "&scroll=" + request.scroll() : ""; log.debug(String.format( "Search query: curl -XGET 'http://localhost:9200/%s/%s/_search?pretty&search_type=%s%s' -d '%s'", getSearchIndexesAsString(query), DOC_TYPE, searchType.toString().toLowerCase(), scroll, request.source().toString())); } }
Source:
<code>SlackService getSlackService(final String baseUrl, final String teamDomain, final String authTokenCredentialId, final boolean botUser, final String room) { <START> return new StandardSlackService(baseUrl, teamDomain, null, authTokenCredentialId, botUser, room); <END> }</code><technical_language>please, no! ship a null object! :cry:</technical_language>

Target:
SlackService getSlackService(final String baseUrl, final String teamDomain, final String authTokenCredentialId, final boolean botUser, final String room) { return new StandardSlackService(baseUrl, teamDomain, authTokenCredentialId, botUser, room); }
Source:
<code>public void reinitializeCharts() { <START> if (getGlobalPC() != null) { <END> getGlobalPC().dispose(); } fGlobalPC = new PieChart(this, SWT.NONE); getGlobalPC().getTitle().setText(fGlobalPCname); getGlobalPC().getAxisSet().getXAxis(0).getTitle().setText(""); if (getTimeRangePC() != null) { getTimeRangePC().dispose(); fTimeRangePC = null; } layout(); setCurrentState(new PieChartViewerStateNoContentSelected(this)); }</code><technical_language>need check isDisposed() in method</technical_language>

Target:
public void reinitializeCharts() { if (getGlobalPC() != null && !getGlobalPC().isDisposed()) { getGlobalPC().dispose(); } fGlobalPC = new PieChart(this, SWT.NONE); getGlobalPC().getTitle().setText(fGlobalPCname); getGlobalPC().getAxisSet().getXAxis(0).getTitle().setText(""); if (getTimeRangePC() != null && !getTimeRangePC().isDisposed()) { getTimeRangePC().dispose(); fTimeRangePC = null; } layout(); setCurrentState(new PieChartViewerStateNoContentSelected(this)); }
Source:
<code>public TaskExecutor(int runnerThreads, int minDrivers, int guaranteedNumberOfDriversPerTask, int maximumNumberOfDriversPerTask, Ticker ticker) { this( <START> new Duration(1, SECONDS), <END> runnerThreads, minDrivers, guaranteedNumberOfDriversPerTask, maximumNumberOfDriversPerTask, new EmbedVersion(new ServerConfig()), new MultilevelSplitQueue(2), ticker); }</code><technical_language>used? duration a parameter too</technical_language>

Target:
public TaskExecutor(int runnerThreads, int minDrivers, int guaranteedNumberOfDriversPerTask, int maximumNumberOfDriversPerTask, Ticker ticker) { this( new TaskManagerConfig().getSplitRunDuration(), runnerThreads, minDrivers, guaranteedNumberOfDriversPerTask, maximumNumberOfDriversPerTask, new EmbedVersion(new ServerConfig()), new MultilevelSplitQueue(2), ticker); }
Source:
<code><T> Mono<DigitalTwinsResponse<T>> createDigitalTwinWithResponse(String digitalTwinId, T digitalTwin, Class<T> clazz, Context context) { return protocolLayer .getDigitalTwins() .addWithResponseAsync(digitalTwinId, digitalTwin, context) .flatMap(response -> { T genericResponse = null; try { genericResponse = DeserializationHelpers.castObject(mapper, response.getValue(), clazz); } catch (JsonProcessingException e) { <START> logger.error("JsonProcessingException occurred while creating digital twin: ", e); <END> return Mono.error(e); } DigitalTwinsResponseHeaders twinHeaders = mapper.convertValue(response.getDeserializedHeaders(), DigitalTwinsResponseHeaders.class); return Mono.just(new DigitalTwinsResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), genericResponse, twinHeaders)); }); }</code><technical_language>nit: exception occurred while deserializing response -> technically twin created successfully, CL deserialization failed</technical_language>

Target:
<T> Mono<DigitalTwinsResponse<T>> createDigitalTwinWithResponse(String digitalTwinId, T digitalTwin, Class<T> clazz, Context context) { return protocolLayer .getDigitalTwins() .addWithResponseAsync(digitalTwinId, digitalTwin, context) .flatMap(response -> { T genericResponse = null; try { genericResponse = DeserializationHelpers.castObject(mapper, response.getValue(), clazz); } catch (JsonProcessingException e) { logger.error("JsonProcessingException occurred while deserializing the response: ", e); return Mono.error(e); } DigitalTwinsResponseHeaders twinHeaders = mapper.convertValue(response.getDeserializedHeaders(), DigitalTwinsResponseHeaders.class); return Mono.just(new DigitalTwinsResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), genericResponse, twinHeaders)); }); }
Source:
<code>public <T extends Plugin> List<T> loadEnabled(@NonNull CoreConfiguration config, @NonNull Class<T> clazz) { List<T> list = load(clazz); for (Iterator<T> iterator = list.iterator(); iterator.hasNext(); ) { T plugin = iterator.next(); if (!plugin.enabled(config)) { <START> if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "Removing non-enabled plugin : " + plugin); <END> iterator.remove(); } } return list; }</code><technical_language>non-enabled = disabled</technical_language>

Target:
public <T extends Plugin> List<T> loadEnabled(@NonNull CoreConfiguration config, @NonNull Class<T> clazz) { List<T> list = load(clazz); for (Iterator<T> iterator = list.iterator(); iterator.hasNext(); ) { T plugin = iterator.next(); if (!plugin.enabled(config)) { if (ACRA.DEV_LOGGING) ACRA.log.d(LOG_TAG, "Removing disabled plugin : " + plugin); iterator.remove(); } } return list; }
Source:
<code>public void testHistoryTrackerConfigurer() throws Exception { final CountDownLatch latch = new CountDownLatch(1); testSink.input().subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { Assert.isTrue(message.getHeaders().containsKey("SPRING_CLOUD_STREAM_HISTORY"), "Message header should have tracking history info"); BindingProperties inputBindingProps = (BindingProperties) ((Map)((List) message.getHeaders() .get("SPRING_CLOUD_STREAM_HISTORY")).get(0)).get("input"); Assert.isTrue(inputBindingProps.getDestination().equals("configure")); Assert.isTrue(inputBindingProps.getTrackHistory()); BindingProperties outputBindingProps = (BindingProperties) ((Map)((List) message.getHeaders() .get("SPRING_CLOUD_STREAM_HISTORY")).get(0)).get("output");; Assert.isTrue(outputBindingProps.getDestination().equals("configure")); Assert.isTrue(!outputBindingProps.getTrackHistory()); latch.countDown(); } }); testSource.output().send(MessageBuilder.withPayload("{\"test\":\"value\"}").build()); <START> latch.await(10, TimeUnit.SECONDS); <END> }</code><technical_language>ditto - fix merge if I find other issues</technical_language>

Target:
public void testHistoryTrackerConfigurer() throws Exception { final CountDownLatch latch1 = new CountDownLatch(1); MessageHandler messageHandler1 = new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { assertTrue("Message header should have tracking history info", message.getHeaders().containsKey("SPRING_CLOUD_STREAM_HISTORY")); Map<String, String> headerValue = ((Map) ((List) message.getHeaders() .get("SPRING_CLOUD_STREAM_HISTORY")).get(0)); String inputBindingProps = (String) headerValue.get("input"); assertTrue(inputBindingProps.contains("destination=configure")); assertTrue(inputBindingProps.contains("trackHistory=true")); assertTrue(headerValue.get("instanceIndex").equals("0")); assertTrue(headerValue.get("instanceCount").equals("1")); assertTrue(headerValue.get("producer.nextModuleCount").equals("1")); assertTrue(headerValue.get("consumer.concurrency").equals("1")); String outputBindingProps = (String) ((Map) ((List) message.getHeaders() .get("SPRING_CLOUD_STREAM_HISTORY")).get(0)).get("output"); ; assertTrue(outputBindingProps.contains("destination=configure")); assertTrue(outputBindingProps.contains("trackHistory=true")); latch1.countDown(); } }; testSink.input().subscribe(messageHandler1); testSource.output().send(MessageBuilder.withPayload("{\"test\":\"value\"}").build()); latch1.await(10, TimeUnit.SECONDS); testSink.input().unsubscribe(messageHandler1); }
Source:
<code>public void setSnapshotTransferDoneAndStartApply(LogReplicationEntry message) { setSnapshotTransferDone(message); long seqNum = logReplicationMetadataManager.query(null, LogReplicationMetadataManager.LogReplicationMetadataType.LAST_SNAPSHOT_SEQ_NUM); if (seqNum != Address.NON_ADDRESS) { phase = Phase.ApplyPhase; long snapshot = rt.getAddressSpaceView().getLogTail(); clearTables(); for (UUID uuid : streamViewMap.keySet()) { appliedSeq = applyShadowStream(uuid, appliedSeq, snapshot); } } <START> logReplicationMetadataManager.setSnapshotApplied(message); <END> }</code><technical_language>Apply phase is Done, do need mark Transfer phase</technical_language>

Target:
public void setSnapshotTransferDoneAndStartApply(LogReplicationEntry message) { setSnapshotTransferDone(message); long seqNum = logReplicationMetadataManager.query(null, LogReplicationMetadataManager.LogReplicationMetadataType.LAST_SNAPSHOT_SEQ_NUM); if (seqNum != Address.NON_ADDRESS) { phase = Phase.ApplyPhase; long snapshot = rt.getAddressSpaceView().getLogTail(); clearTables(); for (UUID uuid : streamViewMap.keySet()) { appliedSeq = applyShadowStream(uuid, appliedSeq, snapshot); } } logReplicationMetadataManager.setSnapshotApplied(message); phase = Phase.TransferPhase; }
Source:
<code>public String replace( String self, String oldString, String newString, Object maxSplitO) throws EvalException { int maxSplit = Integer.MAX_VALUE; if (maxSplitO != Runtime.NONE) { maxSplit = Math.max(0, (Integer) maxSplitO); } if (oldString.equals("")) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < self.length(); i++) { if (maxSplit > 0) { sb.append(newString); maxSplit--; } sb.append(self.charAt(i)); } if (maxSplit > 0) { sb.append(newString); } return sb.toString(); } <START> return StringUtils.replace(self, oldString, newString, maxSplit); <END> }</code><technical_language>replace function needed is pretty easy write; I warrants another dependency: int start = 0; for (int i = 0; i < maxSplit; i++) { int end = self.indexOf(old, start); if (end < 0) break; sb.append(self, start, end).append(newString); start = end + old.length(); } sb.append(self, start, self.length());</technical_language>

Target:
public String replace( String self, String oldString, String newString, Object maxSplitO) throws EvalException { int maxSplit = Integer.MAX_VALUE; if (maxSplitO != Runtime.NONE) { maxSplit = Math.max(0, (Integer) maxSplitO); } StringBuilder sb = new StringBuilder(); int start = 0; for (int i = 0; i < maxSplit; i++) { if (oldString.isEmpty()) { sb.append(newString); if (start < self.length()) { sb.append(self.charAt(start++)); } else { break; } } else { int end = self.indexOf(oldString, start); if (end < 0) break; sb.append(self, start, end).append(newString); start = end + oldString.length(); } } sb.append(self, start, self.length()); return sb.toString(); }