auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void onPositionObserverUpdate() { if (controller == null || txtvPosition == null || txtvLength == null) { return; } TimeSpeedConverter converter = new TimeSpeedConverter(controller.getCurrentPlaybackSpeedMultiplier()); int currentPosition = converter.convert(controller.getPosition()); int duration = converter.convert(controller.getDuration()); int remainingTime = converter.convert( controller.getDuration() - controller.getPosition()); Log.d(TAG, "currentPosition " + Converter.getDurationStringLong(currentPosition)); if (currentPosition == PlaybackService.INVALID_TIME || duration == PlaybackService.INVALID_TIME) { Log.w(TAG, "Could not react to position observer update because of invalid time"); return; } txtvPosition.setText(Converter.getDurationStringLong(currentPosition)); if (showTimeLeft) { txtvLength.setText("-" + Converter.getDurationStringLong(remainingTime)); } else { txtvLength.setText(Converter.getDurationStringLong(duration)); } updateProgressbarPosition(currentPosition, duration); Playable media = controller.getMedia(); <START> if (media instanceof FeedMedia) { <END> FeedMedia feedMedia = (FeedMedia) media; FeedPreferences preferences = feedMedia.getItem().getFeed().getPreferences(); int skipEnd = preferences.getFeedSkipEnding(); if (skipEnd > 0 && remainingTime < skipEnd * 1000) { Log.d(TAG, "Skipping the remaining " + remainingTime / 1000 + " " + skipEnd ); String skipMesg = MediaplayerActivity.this.getString(de.danoeh.antennapod.core.R.string.pref_feed_skip_ending) + " " + skipEnd + " " + MediaplayerActivity.this.getString(de.danoeh.antennapod.core.R.string.time_seconds); Toast toast = Toast.makeText(MediaplayerActivity.this, skipMesg, Toast.LENGTH_LONG); toast.show(); IntentUtils.sendLocalBroadcast(MediaplayerActivity.this, PlaybackService.ACTION_SKIP_CURRENT_EPISODE); } else { Log.d(TAG, "Not Skipping the remaining " + remainingTime / 1000 + " " + skipEnd ); } } }</code><technical_language>This is longer needed, I think</technical_language>

Target:
void onPositionObserverUpdate() { if (controller == null || txtvPosition == null || txtvLength == null) { return; } TimeSpeedConverter converter = new TimeSpeedConverter(controller.getCurrentPlaybackSpeedMultiplier()); int currentPosition = converter.convert(controller.getPosition()); int duration = converter.convert(controller.getDuration()); int remainingTime = converter.convert( controller.getDuration() - controller.getPosition()); Log.d(TAG, "currentPosition " + Converter.getDurationStringLong(currentPosition)); if (currentPosition == PlaybackService.INVALID_TIME || duration == PlaybackService.INVALID_TIME) { Log.w(TAG, "Could not react to position observer update because of invalid time"); return; } txtvPosition.setText(Converter.getDurationStringLong(currentPosition)); if (showTimeLeft) { txtvLength.setText("-" + Converter.getDurationStringLong(remainingTime)); } else { txtvLength.setText(Converter.getDurationStringLong(duration)); } updateProgressbarPosition(currentPosition, duration); }
Source:
<code>List<IRemoteTest> createIndividualTests(Set<TestInfo> testInfos, String configPath) { List<IRemoteTest> tests = new ArrayList<>(); if (configPath == null) { return tests; } File configFie = new File(configPath); if (!configFie.exists()) { return tests; <START> } <END> testInfos = dedupTestInfos(testInfos); for (TestInfo testInfo : testInfos) { super.cleanUpSuiteSetup(); super.clearModuleArgs(); super.clearConfigPaths(); super.addConfigPaths(configFie); parseOptions(testInfo); LinkedHashMap<String, IConfiguration> config = super.loadTests(); for (Map.Entry<String, IConfiguration> entry : config.entrySet()) { tests.addAll(entry.getValue().getTests()); } } return tests; }</code><technical_language>exist configPath null? fail in case</technical_language>

Target:
List<IRemoteTest> createIndividualTests(Set<TestInfo> testInfos, String configPath) { CLog.i("Creating individual tests for configuration: %s", configPath); List<IRemoteTest> tests = new ArrayList<>(); if (configPath == null) { throw new RuntimeException(String.format("Configuration path is null.")); } File configFie = new File(configPath); if (!configFie.exists()) { throw new RuntimeException( String.format("Configuration path: %s doesn't exits.", configPath)); } testInfos = dedupTestInfos(testInfos); for (TestInfo testInfo : testInfos) { super.cleanUpSuiteSetup(); super.clearModuleArgs(); super.clearConfigPaths(); super.addConfigPaths(configFie); parseOptions(testInfo); LinkedHashMap<String, IConfiguration> config = super.loadTests(); for (Map.Entry<String, IConfiguration> entry : config.entrySet()) { tests.addAll(entry.getValue().getTests()); } } return tests; }
Source:
<code>public static <T> PersistentPortability<T> persistent(final Portability<T> normal) { List<Class<?>> proxyInterfaces = new ArrayList<>(); proxyInterfaces.add(PersistentPortability.class); for (Class<?> klazz = normal.getClass(); klazz != null; klazz = klazz.getSuperclass()) { proxyInterfaces.addAll(asList(klazz.getInterfaces())); <START> } <END> return (PersistentPortability<T>) Proxy.newProxyInstance(normal.getClass().getClassLoader(), proxyInterfaces.toArray(new Class[0]), (o, method, os) -> { if (method.getDeclaringClass().equals(Persistent.class)) { return null; } else { return method.invoke(normal, os); } }); }</code><technical_language>This OK in this circumstance, a restriction passed Proxy.newInstance -- "No elements in interfaces array refer identical Class objects". result in IllegalArgumentException. Is chance this restriction violated in this code a surprise</technical_language>

Target:
public static <T> PersistentPortability<T> persistent(final Portability<T> normal) { if (normal instanceof PersistentPortability<?>) { return (PersistentPortability<T>) normal; } else { LinkedHashSet<Class<?>> proxyInterfaces = new LinkedHashSet<>(); for (Class<?> klazz = normal.getClass(); klazz != null; klazz = klazz.getSuperclass()) { proxyInterfaces.addAll(asList(klazz.getInterfaces())); } proxyInterfaces.add(PersistentPortability.class); return (PersistentPortability<T>) Proxy.newProxyInstance(normal.getClass().getClassLoader(), proxyInterfaces.toArray(new Class[0]), (o, method, os) -> { if (method.getDeclaringClass().equals(Persistent.class)) { return null; } else { return method.invoke(normal, os); } }); } }
Source:
<code>public void bulkClaim(List<TaskSummary> taskSummaries) { if (taskSummaries == null || taskSummaries.isEmpty()) { return; } <START> taskSummaries.parallelStream().forEach(taskSummary -> { <END> if (getClaimActionCondition().test(taskSummary)) { claimTask(taskSummary); } else { view.displayNotification( constants.ClaimNotAllowedOn(String.valueOf(taskSummary.getId()), taskSummary.getName())); } }); }</code><technical_language>parallelStream more efficient, I suggest a plain _forEach_ behaviour more consistent</technical_language>

Target:
public void bulkClaim(List<TaskSummary> taskSummaries) { if (taskSummaries == null || taskSummaries.isEmpty()) { return; } taskSummaries.forEach(taskSummary -> { if (getClaimActionCondition().test(taskSummary)) { claimTask(taskSummary); } else { view.displayNotification( constants.ClaimNotAllowedOn(String.valueOf(taskSummary.getId()), taskSummary.getName())); } }); }
Source:
<code>public static <T> ArrayList<T> newArrayList(int size) { <START> return new ArrayList<T>( getInitialCapacityFromExpectedSize( size ) ); <END> }</code><technical_language>for a list type</technical_language>

Target:
public static <T> ArrayList<T> newArrayList(int size) { return new ArrayList<T>( size ); }
Source:
<code>private void takeUserRegionLock() throws IOException { try { long waitTime = connectionConfig.getScannerTimeoutPeriod(); <START> if (!userRegionLock.tryLock(waitTime, TimeUnit.MILLISECONDS)) { <END> throw new LockTimeoutException("Failed to get user region lock in" + waitTime + " ms. " + " for accessing meta region server."); } } catch (InterruptedException ie) { LOG.error("Interrupted while waiting for a lock", ie); throw ExceptionUtil.asInterrupt(ie); } }</code><technical_language>@saintstack Rushabh I a quick offline chat this PR. wondering is right timeout for this lock. In client code path a bunch of time out configurations depending path layered top of other. Specifically I wondering if hbase.client.operation.timeout right for this. I understand scanner timeout call wraps a scanner timeout. a client standpoint though, scanner is implementation detail of locateRegion (root caller in this case) root caller wrapped a general operation timeout a timeout is specific scanner. a big deal I curious thoughts. Thanks</technical_language>

Target:
void takeUserRegionLock() throws IOException { try { long waitTime = connectionConfig.getMetaOperationTimeout(); if (!userRegionLock.tryLock(waitTime, TimeUnit.MILLISECONDS)) { throw new LockTimeoutException("Failed to get user region lock in" + waitTime + " ms. " + " for accessing meta region server."); } } catch (InterruptedException ie) { LOG.error("Interrupted while waiting for a lock", ie); throw ExceptionUtil.asInterrupt(ie); } }
Source:
<code>public static void handle(Throwable caught, String name) { if (caught instanceof StatusCodeException) { final StatusCodeException statusCodeException = (StatusCodeException) caught; if (statusCodeException.getStatusCode() == 401) { <START> showErrorMessage("The session is expired", null); <END> Window.Location.reload(); return; } } printMessage(caught, name); }</code><technical_language>Please change error message "The session expired" Is a add a timeout, for now, this error message is briefly showed if user is paying attention, miss happened</technical_language>

Target:
public static void handle(Throwable caught, String name) { if (caught instanceof StatusCodeException) { final StatusCodeException statusCodeException = (StatusCodeException) caught; if (statusCodeException.getStatusCode() == 401) { showErrorMessage("The session has expired", null); Timer timer = new Timer() { @Override public void run() { Window.Location.reload(); } }; timer.schedule(2000); return; } } printMessage(caught, name); }
Source:
<code>static ClassFilter createDefaultInstance() { List<Pattern> patternOverride = loadPatternOverride(); try { if (patternOverride != null) { LOGGER.log(Level.FINE, "Using user specified overrides for class blacklisting"); return new RegExpClassFilter(patternOverride); } else { LOGGER.log(Level.FINE, "Using default in built class blacklisting"); return new RegExpClassFilter(DEFAULT_PATTERNS); } } catch (Error e) { <START> LOGGER.log(Level.SEVERE, "Failed to initialize the default class filter", e); <END> throw e; } }</code><technical_language>a big fan of this construct, hide original OOM if a new Logger listeners. good for other error types</technical_language>

Target:
static ClassFilter createDefaultInstance() { try { List<Pattern> patternOverride = loadPatternOverride(); if (patternOverride != null) { LOGGER.log(Level.FINE, "Using user specified overrides for class blacklisting"); return new RegExpClassFilter(patternOverride); } else { LOGGER.log(Level.FINE, "Using default in built class blacklisting"); return new RegExpClassFilter(DEFAULT_PATTERNS); } } catch (Error e) { LOGGER.log(Level.SEVERE, "Failed to initialize the default class filter", e); throw e; } }
Source:
<code>private boolean retryRelease0(int decrement) { for (;;) { int rawCnt = refCntUpdater.get(this), realCnt = toLiveRealCnt(rawCnt, decrement); if (decrement == realCnt) { if (refCntUpdater.compareAndSet(this, rawCnt, 1)) { <START> maxCapacity(-rawMaxCapacity()); <END> deallocate(); return true; } } else if (decrement < realCnt) { if (refCntUpdater.compareAndSet(this, rawCnt, rawCnt - (decrement << 1))) { return false; } } else { throw new IllegalReferenceCountException(realCnt, -decrement); } Thread.yield(); } }</code><technical_language>assert this positive</technical_language>

Target:
private boolean retryRelease0(int decrement) { for (;;) { int rawCnt = refCntUpdater.get(this), realCnt = toLiveRealCnt(rawCnt, decrement); if (decrement == realCnt) { if (refCntUpdater.compareAndSet(this, rawCnt, 1)) { maxCapacity(-maxCapacity()); deallocate(); return true; } } else if (decrement < realCnt) { if (refCntUpdater.compareAndSet(this, rawCnt, rawCnt - (decrement << 1))) { return false; } } else { throw new IllegalReferenceCountException(realCnt, -decrement); } Thread.yield(); } }
Source:
<code>public void deallocate(ByteBuffer buffer) { synchronized (lock) { availableMemory += buffer.capacity(); <START> if (availableMemory > capacity) { <END> availableMemory = capacity; } lock.notify(); } }</code><technical_language>explain this is reachable</technical_language>

Target:
public void deallocate(ByteBuffer buffer) { synchronized (lock) { availableMemory += buffer.capacity(); if (availableMemory > capacity) { availableMemory = capacity; logger.warn("The total deallocated memory is more than that had been allocated from the buffer pool."); } lock.notify(); } }
Source:
<code>public Token appendCheckpoint(Token snapshotTimestamp, Long streamTail) { long start = System.currentTimeMillis(); if (!Address.isAddress(streamTail)) { snapshotTimestamp = forceHole(); streamTail = snapshotTimestamp.getSequence(); } try { <START> rt.getAddressSpaceView().read(snapshotTimestamp.getSequence()); <END> } catch (TrimmedException te) { log.info("appendCheckpointOnSnapshot: stream tail at has been trimmed. Checkpoint on same state" + "as previous checkpoint.", snapshotTimestamp); } rt.getObjectsView().TXBuild() .type(TransactionType.SNAPSHOT) .snapshot(snapshotTimestamp) .build() .begin(); try (Timer.Context context = MetricsUtils.getConditionalContext(appendCheckpointTimer)) { log.info("appendCheckpoint: Started checkpoint for at snapshot {}", streamId, snapshotTimestamp); ICorfuSMR<T> corfuObject = (ICorfuSMR<T>) this.map; Set<Map.Entry> entries = this.map.entrySet(); startCheckpoint(snapshotTimestamp, streamTail); appendObjectState(entries); finishCheckpoint(); long cpDuration = System.currentTimeMillis() - start; log.info("appendCheckpoint: completed checkpoint for {}, entries({}), tableSize({}) bytes, " + "cpSize({}) bytes at snapshot in ms", streamId, entries.size(), MetricsUtils.sizeOf.deepSizeOf(entries), numBytes, snapshotTimestamp, cpDuration); } finally { rt.getObjectsView().TXEnd(); } return snapshotTimestamp; }</code><technical_language>bad, this related issue #2072. read global tail prevent sequencer regress</technical_language>

Target:
public Token appendCheckpoint(Token snapshotTimestamp, Long streamTail) { long start = System.currentTimeMillis(); if (!Address.isAddress(streamTail)) { snapshotTimestamp = forceHole(); streamTail = snapshotTimestamp.getSequence(); } rt.getAddressSpaceView().read(snapshotTimestamp.getSequence()); long currentEpoch = rt.getSequencerView().query().getEpoch(); if (currentEpoch != snapshotTimestamp.getEpoch()) { throw new WrongEpochException(currentEpoch); } rt.getObjectsView().TXBuild() .type(TransactionType.SNAPSHOT) .snapshot(snapshotTimestamp) .build() .begin(); try (Timer.Context context = MetricsUtils.getConditionalContext(appendCheckpointTimer)) { log.info("appendCheckpoint: Started checkpoint for at snapshot {}", streamId, snapshotTimestamp); Set<Map.Entry> entries = this.map.entrySet(); startCheckpoint(snapshotTimestamp, streamTail); appendObjectState(entries); finishCheckpoint(); long cpDuration = System.currentTimeMillis() - start; log.info("appendCheckpoint: completed checkpoint for {}, entries({}), tableSize({}) bytes, " + "cpSize({}) bytes at snapshot in ms", streamId, entries.size(), MetricsUtils.sizeOf.deepSizeOf(entries), numBytes, snapshotTimestamp, cpDuration); } finally { rt.getObjectsView().TXEnd(); } return snapshotTimestamp; }
Source:
<code>public void agentsConfigFile() throws Exception { j.createSlave("node1", "node1", new EnvVars()); AgentsConfigFile comp = new AgentsConfigFile(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); comp.addContents(new Container() { @Override public void add(@CheckForNull Content content) { try { content.writeTo(baos); } catch (IOException e) { <START> e.printStackTrace(); <END> } } }); String fileContent = baos.toString(); Assert.assertTrue(fileContent.contains("<name>node1</name>")); }</code><technical_language>fail() if wrong here, like</technical_language>

Target:
public void agentsConfigFile() throws Exception { j.createSlave("node1", "node1", new EnvVars()); AgentsConfigFile comp = new AgentsConfigFile(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); comp.addContents(new Container() { @Override public void add(@CheckForNull Content content) { try { content.writeTo(baos); } catch (IOException e) { Assert.fail(e.getMessage()); } } }); String fileContent = baos.toString(); Assert.assertTrue(fileContent.contains("<name>node1</name>")); }
Source:
<code>protected Object encodeCommand(Command command) { switch (command.getType()) { case Command.TYPE_REBOOT_DEVICE: return formatCommand(command, "SA200CMD;{%s};02;Reboot\r", Command.KEY_UNIQUE_ID); case Command.TYPE_POSITION_SINGLE: return formatCommand(command, "SA200GTR;{%s};02;\r", Command.KEY_UNIQUE_ID); case Command.TYPE_OUTPUT_CONTROL: return formatCommand(command, "SA200CMD;{%s};0{%s};Enable{%s}\r", <START> Command.KEY_UNIQUE_ID, Command.KEY_DATA, Command.KEY_DATA); <END> case Command.TYPE_ENGINE_STOP: return formatCommand(command, "SA200CMD;{%s};02;Enable1\r", Command.KEY_UNIQUE_ID); case Command.TYPE_ENGINE_RESUME: return formatCommand(command, "SA200CMD;{%s};02;Disable1\r", Command.KEY_UNIQUE_ID); default: Log.warning(new UnsupportedOperationException(command.getType())); break; } return null; }</code><technical_language>Wait, is in KEY_DATA</technical_language>

Target:
protected Object encodeCommand(Command command) { switch (command.getType()) { case Command.TYPE_REBOOT_DEVICE: return formatCommand(command, "SA200CMD;{%s};02;Reboot\r", Command.KEY_UNIQUE_ID); case Command.TYPE_POSITION_SINGLE: return formatCommand(command, "SA200GTR;{%s};02;\r", Command.KEY_UNIQUE_ID); case Command.TYPE_OUTPUT_CONTROL: if (command.getAttributes().containsKey(Command.KEY_DATA)) { if (command.getAttributes().get(Command.KEY_DATA).equals("1")) { return formatCommand(command, "SA200CMD;{%s};02;Enable{%s}\r", Command.KEY_UNIQUE_ID, Command.KEY_INDEX); } else return formatCommand(command, "SA200CMD;{%s};02;Disable{%s}\r", Command.KEY_UNIQUE_ID, Command.KEY_INDEX); } case Command.TYPE_ENGINE_STOP: return formatCommand(command, "SA200CMD;{%s};02;Enable1\r", Command.KEY_UNIQUE_ID); case Command.TYPE_ENGINE_RESUME: return formatCommand(command, "SA200CMD;{%s};02;Disable1\r", Command.KEY_UNIQUE_ID); default: Log.warning(new UnsupportedOperationException(command.getType())); break; } return null; }
Source:
<code>public void testQueueFullEmitsError() { final CountDownLatch latch = new CountDownLatch(1); <START> final int capacity = (int)Math.pow(2, new Random().nextInt(10)); <END> Observable<Integer> observable = Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> o) { for (int i = 0; i < capacity + 10; i++) { o.onNext(i); } latch.countDown(); o.onCompleted(); } }); TestSubscriber<Integer> testSubscriber = new TestSubscriber<Integer>(new Observer<Integer>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer t) { try { latch.await(500, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } }); System.out.println("Using capacity " + capacity); observable.observeOn(Schedulers.newThread(), capacity).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); List<Throwable> errors = testSubscriber.getOnErrorEvents(); assertEquals(1, errors.size()); System.out.println("Errors: " + errors); Throwable t = errors.get(0); if (t instanceof MissingBackpressureException) { } else { if (t.getCause() instanceof MissingBackpressureException) { } else { fail("Expecting MissingBackpressureException"); } } }</code><technical_language>is need for randomized capacity. If want verify multiple sizes, loop a power-of-2 set</technical_language>

Target:
public void testQueueFullEmitsError() { final CountDownLatch latch = new CountDownLatch(1); Observable<Integer> observable = Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> o) { for (int i = 0; i < RxRingBuffer.SIZE + 10; i++) { o.onNext(i); } latch.countDown(); o.onCompleted(); } }); TestSubscriber<Integer> testSubscriber = new TestSubscriber<Integer>(new Observer<Integer>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer t) { try { latch.await(500, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } }); observable.observeOn(Schedulers.newThread()).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); List<Throwable> errors = testSubscriber.getOnErrorEvents(); assertEquals(1, errors.size()); System.out.println("Errors: " + errors); Throwable t = errors.get(0); if (t instanceof MissingBackpressureException) { } else { if (t.getCause() instanceof MissingBackpressureException) { } else { fail("Expecting MissingBackpressureException"); } } }
Source:
<code>public synchronized int submitUnprocessedBuildsForImport(AvailableBuildsList availableBuilds) { List<BuildImportSummary> buildsSortedByDateDescending = BuildByDateSorter .sortBuildsByDateDescending(buildImportSummaries.values()); List<BuildIdentifier> importNeededBuilds = new LinkedList<>(); for (BuildImportSummary buildImportSummary : buildsSortedByDateDescending) { if (buildImportSummary != null && buildImportSummary.getStatus().isImportNeeded()) { importNeededBuilds.add(buildImportSummary.getIdentifier()); submitBuildForImport(availableBuilds, buildImportSummary.getIdentifier()); } } asyncBuildImportExecutor.submit(() -> <START> asyncBuildImportExecutor.submit(() -> comparisonExecutor.scheduleComparisonFinishedLog())); <END> return importNeededBuilds.size(); }</code><technical_language>Also, is this correct submit twice</technical_language>

Target:
public synchronized int submitUnprocessedBuildsForImport(AvailableBuildsList availableBuilds) { List<BuildImportSummary> buildsSortedByDateDescending = BuildByDateSorter .sortBuildsByDateDescending(buildImportSummaries.values()); List<BuildIdentifier> importNeededBuilds = new LinkedList<>(); for (BuildImportSummary buildImportSummary : buildsSortedByDateDescending) { if (buildImportSummary != null && buildImportSummary.getStatus().isImportNeeded()) { importNeededBuilds.add(buildImportSummary.getIdentifier()); submitBuildForImport(availableBuilds, buildImportSummary.getIdentifier()); } } executeAfterAllPendingImportsAndComparisonsDone(() -> LOGGER.info(ALL_BUILD_IMPORTS_AND_COMPARISONS_FINISHED_LOG_ENTRY_FOR_CI_CHECK)); return importNeededBuilds.size(); }
Source:
<code>private void displayYouWontSeeNearbyMessage() { <START> ViewUtil.showLongToast(getActivity(), "You wont see narby place since you didn't gave permission"); <END> }</code><technical_language>Please this a string resource change "Unable display nearest place needs pictures location permissions"</technical_language>

Target:
private void displayYouWontSeeNearbyMessage() { ViewUtil.showLongToast(getActivity(), getResources().getString(R.string.unable_to_display_nearest_place)); }
Source:
<code>public void testMigration() throws IOException { copyFileFromAssets("database" + File.separator + dbFilename, DATABASE_PATH); FormsDatabaseHelper databaseHelper = new FormsDatabaseHelper(); ensureMigrationAppliesFully(databaseHelper); SQLiteDatabase db = databaseHelper.getReadableDatabase(); assertThat(db.getVersion(), is(FormsDatabaseHelper.DATABASE_VERSION)); List<String> newColumnNames = FormsDatabaseHelper.getFormsColumnNames(db); assertThat(newColumnNames, contains(FormsDatabaseHelper.CURRENT_VERSION_COLUMN_NAMES)); <START> if (description.startsWith("Upgrading")) { <END> assertThatFormsAreKeptAfterUpgrading(); } }</code><technical_language>This is a good check add. adding a boolean parameter instead? Checking description error-prone</technical_language>

Target:
public void testMigration() throws IOException { copyFileFromAssets("database" + File.separator + dbFilename, DATABASE_PATH); FormsDatabaseHelper databaseHelper = new FormsDatabaseHelper(); ensureMigrationAppliesFully(databaseHelper); SQLiteDatabase db = databaseHelper.getReadableDatabase(); assertThat(db.getVersion(), is(FormsDatabaseHelper.DATABASE_VERSION)); List<String> newColumnNames = SQLiteUtils.getColumnNames(db, FORMS_TABLE_NAME); assertThat(newColumnNames, contains(FormsDatabaseHelper.CURRENT_VERSION_COLUMN_NAMES)); if (action.equals(UPGRADE)) { assertThatFormsAreKeptAfterUpgrading(); } }
Source:
<code>public static void requireUShort16(int value) { if (value < 0) { throw new IllegalArgumentException("unsigned 16-bit integers can't be negative"); } <START> if (value > ((1 << 16) - 1)) { <END> throw new IllegalArgumentException("unsigned 16-bit integers can't be greater than 2^16 - 1"); } }</code><technical_language>unrelated fixes - thanks for - in extra commit, unrelated this change</technical_language>

Target:
public static int requireUShort16(int value) { if (value < 0) { throw new IllegalArgumentException("unsigned 16-bit integers can't be negative"); } if (value > ((1 << 16) - 1)) { throw new IllegalArgumentException("unsigned 16-bit integers can't be greater than 2^16 - 1"); } return value; }
Source:
<code>public static String extractSignatureFromAssertion(AssertionType assertion) { <START> return assertion != null && !StringUtils.isBlank(assertion.getSignatureAlgorithm()) ? assertion.getSignatureAlgorithm() : getSignatureAlgorithm(); <END> }</code><technical_language>Optional: Try StringUtils.isNotBlank instead of ! StringUtil.isBlank</technical_language>

Target:
public static String extractSignatureFromAssertion(AssertionType assertion) { return assertion != null && StringUtils.isNotBlank(assertion.getSignatureAlgorithm()) ? assertion.getSignatureAlgorithm() : getSignatureAlgorithm(); }
Source:
<code>public static List<CodeSystemEntry> getAllCodeSystems(ServiceProvider context) { final Repositories repositories = RepositoryRequests.prepareSearch() .all() .build() .execute(context); return repositories.getItems() .stream() <START> .filter( repository -> RepositoryInfo.Health.GREEN == repository.health() ) <END> .flatMap(repository -> { return new RepositoryRequest<>(repository.id(), CodeSystemRequests.prepareSearchCodeSystem() .all() .build()).execute(context).stream(); }) .collect(Collectors.toList()); }</code><technical_language>is general consensus repositories YELLOW health? read</technical_language>

Target:
public static List<CodeSystemEntry> getAllCodeSystems(ServiceProvider context) { final Repositories repositories = RepositoryRequests.prepareSearch() .all() .build() .execute(context); return repositories.getItems() .stream() .flatMap(repository -> { return CodeSystemRequests.prepareSearchCodeSystem() .all() .build(repository.id()) .getRequest() .execute(context) .stream(); }) .collect(Collectors.toList()); }
Source:
<code>public void dispose() { <START> super.dispose(); <END> if (control != null) { control.dispose(); } }</code><technical_language>dispose stuff, call super.dispose() end</technical_language>

Target:
public void dispose() { if (control != null) { control.dispose(); } super.dispose(); }
Source:
<code>public void run() { TransactionImpl txi = null; try { while (true) { String status = "FAILED"; try { txi = new TransactionImpl(env); Transaction tx = txi; if (TracingTransaction.isTracingEnabled()) tx = new TracingTransaction(tx); loader.load(tx); txi.commit(); status = "COMMITTED"; return; } catch (CommitException e) { } catch (Exception e) { log.error("Failed to execute loader " + loader, e); throw new RuntimeException(e); } finally { if (txi != null) TxLogger.logTx(status, loader.getClass().getName(), txi.getStats()); } } } finally { <START> txi.close(); <END> } }</code><technical_language>check if null</technical_language>

Target:
public void run() { TransactionImpl txi = null; try { while (true) { String status = "FAILED"; try { txi = new TransactionImpl(env); Transaction tx = txi; if (TracingTransaction.isTracingEnabled()) tx = new TracingTransaction(tx); loader.load(tx); txi.commit(); status = "COMMITTED"; return; } catch (CommitException e) { } catch (Exception e) { log.error("Failed to execute loader " + loader, e); throw new RuntimeException(e); } finally { if (txi != null) TxLogger.logTx(status, loader.getClass().getName(), txi.getStats()); } } } finally { if (txi != null) { txi.close(); } } }
Source:
<code>private void executeDownload(final DownloadBatch downloadBatch) { InternalDownloadBatchStatus downloadBatchStatus = downloadBatch.status(); if (downloadBatchStatus.status() == DOWNLOADED) { <START> return; <END> } updateStatusToQueuedIfNeeded(downloadBatchStatus); downloadService.download(downloadBatch, downloadBatchCallback()); }</code><technical_language>Mid return worsen readability</technical_language>

Target:
private void executeDownload(final DownloadBatch downloadBatch) { InternalDownloadBatchStatus downloadBatchStatus = downloadBatch.status(); if (downloadBatchStatus.status() != DOWNLOADED) { updateStatusToQueuedIfNeeded(downloadBatchStatus); downloadService.download(downloadBatch, downloadBatchCallback()); } }
Source:
<code>public void testLoopCreation() { <START> thrown.expect(IllegalArgumentException.class); <END> BusinessService service1 = createService("Business Service #1"); BusinessService service2 = createService("Business Service #2"); BusinessService service3 = createService("Business Service #3"); Long serviceId1 = businessServiceDao.save(service1); Long serviceId2 = businessServiceDao.save(service2); Long serviceId3 = businessServiceDao.save(service3); businessServiceManager.assignChildService(serviceId1, serviceId2); businessServiceManager.assignChildService(serviceId2, serviceId3); businessServiceManager.assignChildService(serviceId3, serviceId1); }</code><technical_language>This is sufficient. IllegalArgumentException thrown in occasians. Please throw a more meaningfull exception "LoopDetectedException" verify IllegalArgumentException is exception expect</technical_language>

Target:
public void testLoopCreation() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Service will form a loop"); BusinessService service1 = createService("Business Service #1"); BusinessService service2 = createService("Business Service #2"); BusinessService service3 = createService("Business Service #3"); Long serviceId1 = businessServiceDao.save(service1); Long serviceId2 = businessServiceDao.save(service2); Long serviceId3 = businessServiceDao.save(service3); businessServiceManager.assignChildService(serviceId1, serviceId2); businessServiceManager.assignChildService(serviceId2, serviceId3); businessServiceManager.assignChildService(serviceId3, serviceId1); }
Source:
<code>public static String injectContextDependentValuesForTest(String content) { Date now = new Date(); return content.replace("<!-- test.url -->", TestProperties.TEAMMATES_URL) .replace("<!-- studentmotd.url -->", Config.STUDENT_MOTD_URL) .replace("<!-- version -->", TestProperties.TEAMMATES_VERSION) .replace("<!-- test.student1 -->", TestProperties.TEST_STUDENT1_ACCOUNT) .replace("<!-- test.student1.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_STUDENT1_ACCOUNT)) .replace("<!-- test.student2 -->", TestProperties.TEST_STUDENT2_ACCOUNT) .replace("<!-- test.student2.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_STUDENT2_ACCOUNT)) .replace("<!-- test.instructor -->", TestProperties.TEST_INSTRUCTOR_ACCOUNT) .replace("<!-- test.instructor.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_INSTRUCTOR_ACCOUNT)) .replace("<!-- test.admin -->", TestProperties.TEST_ADMIN_ACCOUNT) .replace("<!-- test.admin.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_ADMIN_ACCOUNT)) .replace("<!-- nexthour.date -->", TimeHelper.formatDate(TimeHelper.getNextHour())) .replace("<!-- now.datetime -->", TimeHelper.formatTime12H(now)) <START> .replace("<!-- now.datetime.comments -->", TimeHelper.formatDateTimeForComments(now, 8)); <END> }</code><technical_language>This change necessary for this PR. I this line changed</technical_language>

Target:
public static String injectContextDependentValuesForTest(String content) { Date now = new Date(); return content.replace("<!-- test.url -->", TestProperties.TEAMMATES_URL) .replace("<!-- studentmotd.url -->", Config.STUDENT_MOTD_URL) .replace("<!-- version -->", TestProperties.TEAMMATES_VERSION) .replace("<!-- test.student1 -->", TestProperties.TEST_STUDENT1_ACCOUNT) .replace("<!-- test.student1.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_STUDENT1_ACCOUNT)) .replace("<!-- test.student2 -->", TestProperties.TEST_STUDENT2_ACCOUNT) .replace("<!-- test.student2.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_STUDENT2_ACCOUNT)) .replace("<!-- test.instructor -->", TestProperties.TEST_INSTRUCTOR_ACCOUNT) .replace("<!-- test.instructor.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_INSTRUCTOR_ACCOUNT)) .replace("<!-- test.admin -->", TestProperties.TEST_ADMIN_ACCOUNT) .replace("<!-- test.admin.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_ADMIN_ACCOUNT)) .replace("<!-- nexthour.date -->", TimeHelper.formatDate(TimeHelper.getNextHour())) .replace("<!-- now.datetime -->", TimeHelper.formatTime12H(now)) .replace("<!-- now.datetime.comments -->", TimeHelper.formatDateTimeForComments(now, 0)); }
Source:
<code>public void testFindLiveVersionContainer() throws Exception{ Container c = new Container(); c.setFriendlyName("Versionable Container Working"); c.setTitle("Versionable Container Working"); c.setMaxContentlets(2); c.setPreLoop("preloop code"); c.setPostLoop("postloop code"); Structure st=CacheLocator.getContentTypeCache().getStructureByVelocityVarName("host"); List<ContainerStructure> csList = new ArrayList<ContainerStructure>(); ContainerStructure cs = new ContainerStructure(); cs.setStructureId(st.getInode()); cs.setCode("this is the code"); csList.add(cs); <START> c = APILocator.getContainerAPI().save(c, csList, host, user, false); <END> APILocator.getVersionableAPI().setLive(c); Versionable verAPI = APILocator.getVersionableAPI().findLiveVersion(c.getIdentifier(), user, false); assertEquals(verAPI.getTitle(),c.getTitle()); assertEquals(verAPI.getInode(),c.getInode()); APILocator.getContainerAPI().delete(c, user, false); }</code><technical_language>above: Container container = new ContainerDataGen().withStructure(st, "").nextPersisted();</technical_language>

Target:
public void testFindLiveVersionContainer() throws Exception{ Structure structure = new StructureDataGen().nextPersisted(); Container container = new ContainerDataGen().withStructure(structure, "").nextPersisted(); APILocator.getVersionableAPI().setLive(container); Versionable verAPI = APILocator.getVersionableAPI().findLiveVersion(container.getIdentifier(), user, false); assertEquals(verAPI.getTitle(),container.getTitle()); assertEquals(verAPI.getInode(),container.getInode()); APILocator.getContainerAPI().delete(container, user, false); APILocator.getStructureAPI().delete(structure, user); }
Source:
<code>public ObjectRetentionConfiguration getObjectRetention(String bucketName, String objectName, String versionId) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidResponseException { Map<String, String> queryParamMap = new HashMap<>(); queryParamMap.put("retention", ""); if ( !(versionId == null || versionId.isEmpty())) { queryParamMap.put("versionId",versionId); } <START> HttpResponse response = executeGet(bucketName, objectName, null, queryParamMap); <END> ObjectRetentionConfiguration result = new ObjectRetentionConfiguration(); try { result.parseXml(response.body().charStream()); } finally { response.body().close(); } return result; }</code><technical_language>I missing out of versionId handling. deferring in other places</technical_language>

Target:
public ObjectRetentionConfiguration getObjectRetention(String bucketName, String objectName, String versionId) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidResponseException { Map<String, String> queryParamMap = new HashMap<>(); queryParamMap.put("retention", ""); if (versionId == null) { queryParamMap.put("versionId", ""); } else { queryParamMap.put("versionId", versionId); } HttpResponse response = executeGet(bucketName, objectName, null, queryParamMap); ObjectRetentionConfiguration result = new ObjectRetentionConfiguration(); try { result.parseXml(response.body().charStream()); } finally { response.body().close(); } return result; }
Source:
<code>private IConnectionWrapper createConnection(IServer server) throws MalformedURLException { ConnectorProviderRegistry connectorProviders = OpenShiftCoreActivator.getDefault().getConnectorProviders(); VersionKey version = new VersionDetector(server).guess(); if (version != null) { JMXConnectorProvider provider = connectorProviders.getProvider(version); <START> return new OpenshiftConnectionWrapper(this, server, provider); <END> } return null; }</code><technical_language>if provider == null</technical_language>

Target:
private IConnectionWrapper createConnection(IServer server) throws MalformedURLException { ConnectorProviderRegistry connectorProviders = OpenShiftCoreActivator.getDefault().getConnectorProviders(); VersionKey version = new VersionDetector(server).guess(); if (version != null) { JMXConnectorProvider provider = connectorProviders.getProvider(version); if (provider != null) { return new OpenshiftConnectionWrapper(this, server, provider); } } return null; }
Source:
<code>private static void launchReporter(final URL directory) { LaunchTask launchReporter = new LaunchTask() { @Override public void run() { <START> ApplicationContext context = loadContext(directory, REPORTER_CONFIGURATION, environmentProperties); <END> final ReportingService reportingService = ReportingProvider.getService(context); reportingService.renderReport(true); } }; builder.addMainTask(launchReporter); }</code><technical_language>work in case of configurations reportings defined</technical_language>

Target:
private static void launchReporter(final URL directory) { LaunchTask launchReporter = new LaunchTask() { @Override public void run() { ApplicationContext context = loadContext(directory, REPORTER_CONFIGURATION, environmentProperties); final ReportingService reportingService = (ReportingService) context.getBean("reportingService"); reportingService.renderReport(true); } }; builder.addMainTask(launchReporter); }
Source:
<code>public void setUp() { Project project = new Project(MockUtil.mockContextForProject(), "testProject"); ProjectManager.getInstance().setCurrentProject(project); testSprite = new SingleSprite("sprite"); project.getDefaultScene().addSprite(testSprite); ProjectManager.getInstance().setCurrentSprite(testSprite); <START> ProjectManager.getInstance().setCurrentlyEditedScene(project.getDefaultScene()); <END> testSprite.look.setXInUserInterfaceDimensionUnit(LOOK_X_POSITION); testSprite.look.setYInUserInterfaceDimensionUnit(LOOK_Y_POSITION); testSprite.look.setTransparencyInUserInterfaceDimensionUnit(LOOK_ALPHA); testSprite.look.setBrightnessInUserInterfaceDimensionUnit(LOOK_BRIGHTNESS); testSprite.look.setColorInUserInterfaceDimensionUnit(LOOK_COLOR); testSprite.look.setSizeInUserInterfaceDimensionUnit(LOOK_SCALE); testSprite.look.setDirectionInUserInterfaceDimensionUnit(LOOK_ROTATION); }</code><technical_language>Please remove this line of <LINK_0> currently edited scene is set default scene (auto*magic*ally :wink:). suggestion</technical_language>

Target:
public void setUp() { Project project = new Project(MockUtil.mockContextForProject(), "testProject"); ProjectManager.getInstance().setCurrentProject(project); testSprite = new SingleSprite("sprite"); project.getDefaultScene().addSprite(testSprite); ProjectManager.getInstance().setCurrentSprite(testSprite); testSprite.look.setXInUserInterfaceDimensionUnit(LOOK_X_POSITION); testSprite.look.setYInUserInterfaceDimensionUnit(LOOK_Y_POSITION); testSprite.look.setTransparencyInUserInterfaceDimensionUnit(LOOK_ALPHA); testSprite.look.setBrightnessInUserInterfaceDimensionUnit(LOOK_BRIGHTNESS); testSprite.look.setColorInUserInterfaceDimensionUnit(LOOK_COLOR); testSprite.look.setSizeInUserInterfaceDimensionUnit(LOOK_SCALE); testSprite.look.setDirectionInUserInterfaceDimensionUnit(LOOK_ROTATION); }
Source:
<code>private void setDefaultAssignee(String channel, String sender, String subcomponent, @CheckForNull String owner) { if (!isSenderAuthorized(channel,sender)) { insufficientPermissionError(channel); return; } sendMessage(channel,String.format("Changing default assignee of subcomponent %s to %s",subcomponent,owner)); try { final JiraRestClient client = JiraHelper.createJiraClient(); final Component component = JiraHelper.getComponent(client, IrcBotConfig.JIRA_DEFAULT_PROJECT, subcomponent); Promise<Component> updateComponent = client.getComponentClient().updateComponent(component.getSelf(), <START> new ComponentInput(component.getName(), component.getDescription(), <END> owner != null ? owner : "", AssigneeType.COMPONENT_LEAD)); JiraHelper.wait(updateComponent); sendMessage(channel, owner != null ? "Default assignee set to " + owner : "Default assignee has been removed"); } catch (Exception e) { sendMessage(channel,"Failed to set default assignee: "+e.getMessage()); e.printStackTrace(); } }</code><technical_language>null for parameters changing</technical_language>

Target:
private void setDefaultAssignee(String channel, String sender, String subcomponent, @CheckForNull String owner) { if (!isSenderAuthorized(channel,sender)) { insufficientPermissionError(channel); return; } sendMessage(channel,String.format("Changing default assignee of subcomponent %s to %s",subcomponent,owner)); try { final JiraRestClient client = JiraHelper.createJiraClient(); final Component component = JiraHelper.getComponent(client, IrcBotConfig.JIRA_DEFAULT_PROJECT, subcomponent); Promise<Component> updateComponent = client.getComponentClient().updateComponent(component.getSelf(), new ComponentInput(null, null, owner != null ? owner : "", AssigneeType.COMPONENT_LEAD)); JiraHelper.wait(updateComponent); sendMessage(channel, owner != null ? "Default assignee set to " + owner : "Default assignee has been removed"); } catch (Exception e) { sendMessage(channel,"Failed to set default assignee: "+e.getMessage()); e.printStackTrace(); } }
Source:
<code><START> public CloudBlobMetadata getOldestDeletedBlob(String partitionPath) throws CloudStorageException { <END> List<CloudBlobMetadata> deadBlobs = requestAgent.doWithRetries( () -> cloudDestination.getDeletedBlobs(partitionPath, System.currentTimeMillis(), queryLimit), "GetDeadBlobs", partitionPath); return deadBlobs.isEmpty() ? null : deadBlobs.get(0); }</code><technical_language>please add java docs methods</technical_language>

Target:
public CloudBlobMetadata getOldestDeletedBlob(String partitionPath) throws CloudStorageException { List<CloudBlobMetadata> deadBlobs = requestAgent.doWithRetries( () -> cloudDestination.getDeletedBlobs(partitionPath, 1, System.currentTimeMillis(), 1), "GetDeadBlobs", partitionPath); return deadBlobs.isEmpty() ? null : deadBlobs.get(0); }
Source:
<code>private void addFileToZip(File zipFile, File file, String fileName) throws IOException, URISyntaxException { String entryName = fileName == null ? file.getName() : fileName; Map<String, String> env = new HashMap<>(); env.put("useTempFile", Boolean.toString(this.useTempFile)); try (FileSystem fs = FileSystems.newFileSystem(getZipURI(zipFile), env)) { Path dest = fs.getPath("/", entryName); Files.createDirectories(dest.getParent()); <START> Files.copy(file.toPath(), dest, StandardCopyOption.REPLACE_EXISTING); <END> } }</code><technical_language>this is REPLACE_EXISTING, other is CREATE, if is intention seperate methods, i guess renaming method names option charset is extra piece. wondering if this simplified save a couple of more lines</technical_language>

Target:
private void addFileToZip(File zipFile, File file, String fileName) throws IOException, URISyntaxException { String entryName = fileName == null ? file.getName() : fileName; Map<String, Object> env = new HashMap<>(); env.put("useTempFile", this.useTempFile); try (FileSystem fs = FileSystems.newFileSystem(getZipURI(zipFile), env)) { Path dest = fs.getPath("/", entryName); Files.createDirectories(dest.getParent()); Files.copy(file.toPath(), dest, StandardCopyOption.REPLACE_EXISTING); } }
Source:
<code><START> @Override public ReentrantReadWriteLockWithTracking.ReadLock readLock() { <END> return readLock; }</code><technical_language>Do need ReentrantReadWriteLockWithTracking.ReadLock here? sense change java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock</technical_language>

Target:
@Override public ReentrantReadWriteLock.ReadLock readLock() { return readLock; }
Source:
<code>private static void validateIssuer(Issuer issuer) throws WSSecurityException { if (SamlConstants.URN_OASIS_NAMES.equals(issuer.getFormat())) { if (StringUtils.isNotBlank(issuer.getSPProvidedID())) { throw new WSSecurityException(ErrorCode.FAILED_CHECK, SamlConstants.SECURITY_ASSERTION_ISSUER_FORMAT + " " + SamlConstants.URN_OASIS_NAMES + " " + "and" + SamlConstants.SECURITY_ASSERTION_ISSUER + " " + IS_PRESENT); } if (StringUtils.isNotBlank(issuer.getNameQualifier())) { throw new WSSecurityException(ErrorCode.FAILED_CHECK, SamlConstants.SECURITY_ASSERTION_ISSUER_FORMAT + " " + SamlConstants.URN_OASIS_NAMES + " " + "and" + SamlConstants.SECURITY_ASSERTION_ISSUER + " " + IS_PRESENT); } if (StringUtils.isNotBlank(issuer.getSPNameQualifier())) { throw new WSSecurityException(ErrorCode.FAILED_CHECK, <START> SamlConstants.SECURITY_ASSERTION_ISSUER_FORMAT + " " + SamlConstants.URN_OASIS_NAMES + " " + "and" <END> + SamlConstants.SECURITY_ASSERTION_ISSUER + " " + IS_PRESENT); } } }</code><technical_language>build string in 3 places</technical_language>

Target:
private static void validateIssuer(Issuer issuer) throws WSSecurityException { if (SamlConstants.URN_OASIS_NAMES.equals(issuer.getFormat())) { if (StringUtils.isNotBlank(issuer.getSPProvidedID())) { throw new WSSecurityException(ErrorCode.FAILED_CHECK, getCustomErrorMsg(SamlConstants.SECURITY_ASSERTION_SPPROVIDEDID)); } if (StringUtils.isNotBlank(issuer.getNameQualifier())) { throw new WSSecurityException(ErrorCode.FAILED_CHECK, getCustomErrorMsg(SamlConstants.SECURITY_ASSERTION_NAME_QUALIFIER)); } if (StringUtils.isNotBlank(issuer.getSPNameQualifier())) { throw new WSSecurityException(ErrorCode.FAILED_CHECK, getCustomErrorMsg(SamlConstants.SECURITY_ASSERTION_SPNAME_QUALIFIER)); } } }