auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public synchronized boolean next(LongWritable key, Text value) { while (true) { int bytes = readLine(value); if (bytes > 0) { recordsFromS3++; } else { return false; } if (recordsFromS3 > processedRecords) { pos += bytes; processedRecords++; key.set(processedRecords); return true; } else { <START> value.clear(); <END> } } }</code><technical_language>I checked reader.readLine(value); call clear Text hood, need do explicitly</technical_language>

Target:
public synchronized boolean next(LongWritable key, Text value) throws IOException { while (true) { int bytes = readLine(value); if (bytes <= 0) { if (!selectClient.isRequestComplete()) { throw new RuntimeException("S3 Select request was incomplete as End Event was not received."); } return false; } if (++recordsFromS3 > processedRecords) { position += bytes; processedRecords++; key.set(processedRecords); return true; } } }
Source:
<code>public void botVSPlayer() { int size = tiles.size(); int pairs = size / 2; int mode = (int) Math.sqrt(size); GameState.setPairs(pairs); GameState.setGameState(0); for (int i = 0; i < mode; i++) { for (int j = 0; j < mode; j++) { int n = i; int m = j; massiveTiles[i][j].setOnMouseClicked(event -> { if (GameState.getGameState() == 0) { if (massiveTiles[n][m].isSelected() || event.getClickCount() > 1 || !event.isStillSincePress()) { return; } if (firstselected == null) { firstselected = massiveTiles[n][m]; massiveTiles[n][m].open(() -> { }); } else { massiveTiles[n][m].open(() -> { if (!massiveTiles[n][m].hasSameValue(firstselected)) { firstselected.close(); massiveTiles[n][m].close(); } else { firstselected.setOpen(); massiveTiles[n][m].setOpen(); } <START> GameState.setGameState(1); <END> BotHod(); firstselected = null; secondselected = null; }); } } }); } } }</code><technical_language>setGameState( BOT_VS_PLAYER ). final int</technical_language>

Target:
public void botVSPlayer() { int size = tiles.size(); int pairs = size / 2; int mode = (int) Math.sqrt(size); GameState.setPairs(pairs); GameState.setBotMode(BOT_OFF); for (int i = 0; i < mode; i++) { for (int j = 0; j < mode; j++) { int n = i; int m = j; massiveTiles[i][j].setOnMouseClicked(event -> { if (GameState.getBotMode() == BOT_OFF) { if (massiveTiles[n][m].isSelected() || event.getClickCount() > 1 || !event.isStillSincePress()) { return; } if (firstselected == null) { firstselected = massiveTiles[n][m]; massiveTiles[n][m].open(() -> { }); } else { massiveTiles[n][m].open(() -> { if (!massiveTiles[n][m].hasSameValue(firstselected)) { firstselected.close(); massiveTiles[n][m].close(); } else { firstselected.setOpen(); massiveTiles[n][m].setOpen(); } GameState.setBotMode(BOT_ON); BotTurn(); firstselected = null; secondselected = null; }); } } }); } } }
Source:
<code><START> public Parts createPartialAggregations(SymbolAllocator symbolAllocator, FunctionRegistry functionRegistry) <END> { ImmutableMap.Builder<Symbol, Aggregation> partialAggregation = ImmutableMap.builder(); ImmutableMap.Builder<Symbol, Aggregation> finalAggregation = ImmutableMap.builder(); for (Map.Entry<Symbol, Aggregation> entry : aggregations.entrySet()) { Aggregation originalAggregation = entry.getValue(); Signature signature = originalAggregation.getSignature(); InternalAggregationFunction function = functionRegistry.getAggregateFunctionImplementation(signature); Symbol partialSymbol = symbolAllocator.newSymbol(signature.getName(), function.getIntermediateType()); partialAggregation.put(partialSymbol, new Aggregation(originalAggregation.getCall(), signature, originalAggregation.getMask())); finalAggregation.put(entry.getKey(), new Aggregation( new FunctionCall(QualifiedName.of(signature.getName()), ImmutableList.of(partialSymbol.toSymbolReference())), signature, Optional.empty())); } return new Parts( new StatisticAggregations(partialAggregation.build(), groupingSymbols), new StatisticAggregations(finalAggregation.build(), groupingSymbols)); }</code><technical_language>I divide this method 3 methods. for final aggregation, for partial for mappings. remove Parts. Parts is passed need entity</technical_language>

Target:
public Parts createPartialAggregations(SymbolAllocator symbolAllocator, FunctionRegistry functionRegistry) { ImmutableMap.Builder<Symbol, Aggregation> partialAggregation = ImmutableMap.builder(); ImmutableMap.Builder<Symbol, Aggregation> finalAggregation = ImmutableMap.builder(); ImmutableMap.Builder<Symbol, Symbol> mappings = ImmutableMap.builder(); for (Map.Entry<Symbol, Aggregation> entry : aggregations.entrySet()) { Aggregation originalAggregation = entry.getValue(); Signature signature = originalAggregation.getSignature(); InternalAggregationFunction function = functionRegistry.getAggregateFunctionImplementation(signature); Symbol partialSymbol = symbolAllocator.newSymbol(signature.getName(), function.getIntermediateType()); mappings.put(entry.getKey(), partialSymbol); partialAggregation.put(partialSymbol, new Aggregation(originalAggregation.getCall(), signature, originalAggregation.getMask())); finalAggregation.put(entry.getKey(), new Aggregation( new FunctionCall(QualifiedName.of(signature.getName()), ImmutableList.of(partialSymbol.toSymbolReference())), signature, Optional.empty())); } groupingSymbols.forEach(symbol -> mappings.put(symbol, symbol)); return new Parts( new StatisticAggregations(partialAggregation.build(), groupingSymbols), new StatisticAggregations(finalAggregation.build(), groupingSymbols), mappings.build()); }
Source:
<code><START> void close() throws IOException { <END> client.close(); }</code><technical_language>this implement Closeable, out of interest</technical_language>

Target:
public void close() throws IOException { client.close(); }
Source:
<code><START> private synchronized void stopRunningThread(long endTime) { <END> if (!shtThread.isAlive()) { return; } try { Collection<HTInterval> pill = Collections.singletonList(new HTInterval(-1, endTime, -1, TmfStateValue.nullValue())); if (!fCurrentChunk.isEmpty()) { intervalQueue.put(fCurrentChunk); } intervalQueue.put(pill); shtThread.join(); } catch (TimeRangeException e) { Activator.getDefault().logError("Error closing state system", e); } catch (InterruptedException e) { Activator.getDefault().logError("State system interrupted", e); } }</code><technical_language>do this level of private method, in public call this</technical_language>

Target:
private void stopRunningThread(long endTime) { if (!shtThread.isAlive()) { return; } try { Collection<HTInterval> pill = Collections.singletonList(new HTInterval(-1, endTime, -1, TmfStateValue.nullValue())); if (!fCurrentChunk.isEmpty()) { intervalQueue.put(fCurrentChunk); } intervalQueue.put(pill); shtThread.join(); } catch (TimeRangeException e) { Activator.getDefault().logError("Error closing state system", e); } catch (InterruptedException e) { Activator.getDefault().logError("State system interrupted", e); } }
Source:
<code><START> private MoveValidationResultWithDependents chooseSubsetOfUnitsThatCanMove( <END> final List<Unit> units, final Collection<Unit> transportsToLoad, final MoveValidationResultWithDependents initialResult) { if (!transportsToLoad.isEmpty()) { final List<Unit> allUnits = addMustMoveWith(units); final Collection<Unit> loadedUnits = TransportUtils.mapTransports(route, allUnits, transportsToLoad).keySet(); return validateMoveWithDependents(loadedUnits, transportsToLoad); } MoveValidationResultWithDependents lastResult = initialResult; List<Unit> best = units; if (isInvading()) { best = CollectionUtils.getMatches(best, Matches.unitCanInvade()); lastResult = validateMoveWithDependents(best, List.of()); } final boolean hasLandTransports = hasLandTransports(units); final Predicate<Unit> isLandTransportable = Matches.unitIsLandTransportable(); best.sort(getUnitComparator(best).reversed()); while (!best.isEmpty() && !lastResult.getResult().isMoveValid()) { final Unit firstSkipUnit = best.get(0); int startIndex = 1; while (startIndex < best.size() && (!hasLandTransports || !isLandTransportable.test(best.get(startIndex))) && unitsAreEquivalentWithSameMovementLeft(firstSkipUnit, best.get(startIndex))) { startIndex++; } best = best.subList(startIndex, best.size()); lastResult = validateMoveWithDependents(best, transportsToLoad); } return lastResult; }</code><technical_language>Method chooseSubsetOfUnitsThatCanMove a Cognitive Complexity of 8 (exceeds 5 allowed). Consider refactoring</technical_language>

Target:
private MoveValidationResultWithDependents chooseSubsetOfUnitsThatCanMove( final List<Unit> units, final Collection<Unit> transportsToLoad, final MoveValidationResultWithDependents initialResult) { if (!transportsToLoad.isEmpty()) { final List<Unit> allUnits = addMustMoveWith(units); final Collection<Unit> loadedUnits = TransportUtils.mapTransports(route, allUnits, transportsToLoad).keySet(); return validateMoveWithDependents(loadedUnits, transportsToLoad); } MoveValidationResultWithDependents lastResult = initialResult; List<Unit> best = units; if (isInvading()) { best = CollectionUtils.getMatches(best, Matches.unitCanInvade()); lastResult = validateMoveWithDependents(best, List.of()); } final boolean hasLandTransports = hasLandTransports(units); best.sort(getUnitComparator(best).reversed()); while (!best.isEmpty() && !lastResult.getResult().isMoveValid()) { best = nextSublist(best, hasLandTransports); lastResult = validateMoveWithDependents(best, List.of()); } return lastResult; }
Source:
<code>public List<Expression> typeDependencies() { <START> return Arrays.asList(leftOperand, rightOperand); <END> }</code><technical_language>avoid unnecessary calculations, return empty list !is(Kind.AND, Kind.OR)</technical_language>

Target:
public List<Expression> typeDependencies() { if (is(Kind.AND, Kind.OR, Kind.PLUS)) { return Arrays.asList(leftOperand, rightOperand); } return Collections.emptyList(); }
Source:
<code>private void setAccount() throws OrmException, IOException, UnloggedFailure { final Account account = db.accounts().get(id); <START> if (!addEmails.isEmpty()) { <END> for (String email : addEmails) { link(id, email); } } if (!deleteEmails.isEmpty()) { for (String email : deleteEmails) { deleteMail(id, email); } } if (fullName != null) { if (realm.allowsEdit(FieldName.FULL_NAME)) { account.setFullName(fullName); } else { throw new UnloggedFailure(1, "The realm doesn't allow editing names"); } } if (active) { account.setActive(true); } else if (inactive) { account.setActive(false); } addSshKeys = readSshKey(addSshKeys); if (!addSshKeys.isEmpty()) { for (String sshKey : addSshKeys) { addSshKey(sshKey, account); } } deleteSshKeys = readSshKey(deleteSshKeys); if (!deleteSshKeys.isEmpty()) { for (String sshKey : deleteSshKeys) { deleteSshKey(sshKey, account); } } db.accounts().update(Collections.singleton(account)); byIdCache.evict(id); db.close(); }</code><technical_language>Conditions needed (loops simply run)</technical_language>

Target:
private void setAccount() throws OrmException, IOException, UnloggedFailure { final Account account = db.accounts().get(id); for (String email : addEmails) { link(id, email); } for (String email : deleteEmails) { deleteMail(id, email); } if (fullName != null) { if (realm.allowsEdit(FieldName.FULL_NAME)) { account.setFullName(fullName); } else { throw new UnloggedFailure(1, "The realm doesn't allow editing names"); } } if (active) { account.setActive(true); } else if (inactive) { account.setActive(false); } addSshKeys = readSshKey(addSshKeys); for (String sshKey : addSshKeys) { addSshKey(sshKey, account); } deleteSshKeys = readSshKey(deleteSshKeys); for (String sshKey : deleteSshKeys) { deleteSshKey(sshKey, account); } db.accounts().update(Collections.singleton(account)); byIdCache.evict(id); db.close(); }
Source:
<code>public Set<Stream> apply(String config, Stream inputStream) throws BadComponentConfigException { try { Map<String, Object> componentConfig = objectMapper.readValue(config, Map.class); Map<String, Object> parserConfig = (Map<String, Object>) componentConfig.get( TopologyLayoutConstants.JSON_KEY_CONFIG); String parsedTuplesStream = (String) parserConfig.get("parsedTuplesStream"); Long parserId; try { <START> parserId = (Long) parserConfig.get("parserId"); <END> } catch (ClassCastException e) { parserId = Long.valueOf((Integer) parserConfig.get("parserId")); } ParserInfo parserInfo = catalogService.getParserInfo(parserId); if (parserInfo == null) { throw new RuntimeException("Parser ID " + parserId + " not found from catalog"); } return Sets.newHashSet(new Stream(parsedTuplesStream, parserInfo.getParserSchema())); } catch (Exception e) { throw new BadComponentConfigException("Exception while simulating evolution of parser schema", e); } }</code><technical_language>instead of try-catch write parserId = ((Number) parserConfig.get("parserId")).longValue();</technical_language>

Target:
public Set<Stream> apply(String config, Stream inputStream) throws BadComponentConfigException { try { Map<String, Object> componentConfig = objectMapper.readValue(config, Map.class); Map<String, Object> parserConfig = (Map<String, Object>) componentConfig.get( TopologyLayoutConstants.JSON_KEY_CONFIG); String parsedTuplesStream = (String) parserConfig.get("parsedTuplesStream"); Long parserId = getParserId(parserConfig); ParserInfo parserInfo = catalogService.getParserInfo(parserId); if (parserInfo == null) { throw new RuntimeException("Parser ID " + parserId + " not found from catalog"); } return Sets.newHashSet(new Stream(parsedTuplesStream, parserInfo.getParserSchema())); } catch (Exception e) { throw new BadComponentConfigException("Exception while simulating evolution of parser schema", e); } }
Source:
<code>private static void addDiskLockedMessage(List<String> lockedDisksAliases, List<String> messages) { int numOfDisks = lockedDisksAliases.size(); if (numOfDisks > 0) { VdcBllMessages message = (numOfDisks == 1 ? VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_LOCKED : VdcBllMessages.ACTION_TYPE_FAILED_DISKS_ARE_LOCKED); ListUtils.nullSafeAdd(messages, message.toString()); <START> <END> String aliases = (numOfDisks == 1 ? "diskAlias" : "diskAliases"); messages.add(String.format("$%1$s %2$s", aliases, StringUtils.join(lockedDisksAliases, ", "))); } }</code><technical_language>prefer this if-else check for of numOfDisks</technical_language>

Target:
private static void addDiskLockedMessage(List<String> lockedDisksAliases, List<String> messages) { int numOfDisks = lockedDisksAliases.size(); if (numOfDisks > 0) { VdcBllMessages message = VdcBllMessages.ACTION_TYPE_FAILED_DISKS_ARE_LOCKED; String aliases = "diskAliases"; if (numOfDisks == 1) { message = VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_LOCKED; aliases = "diskAlias"; } ListUtils.nullSafeAdd(messages, message.toString()); messages.add(String.format("$%1$s %2$s", aliases, StringUtils.join(lockedDisksAliases, ", "))); } }
Source:
<code>public void stop() { if (isRunning()) { LOGGER.info("Kill interpreter process"); try { callRemoteFunction(new RemoteFunction<Void>() { @Override public Void call(RemoteInterpreterService.Client client) throws Exception { client.shutdown(); return null; } }); } catch (Exception e) { <START> LOGGER.warn("ignore the exception when shutting down"); <END> } this.interpreterProcessLauncher.stop(); } interpreterProcessLauncher = null; LOGGER.info("Remote process terminated"); }</code><technical_language>I log error LOGGER.warn("", e)</technical_language>

Target:
public void stop() { if (isRunning()) { LOGGER.info("Kill interpreter process"); try { callRemoteFunction(new RemoteFunction<Void>() { @Override public Void call(RemoteInterpreterService.Client client) throws Exception { client.shutdown(); return null; } }); } catch (Exception e) { LOGGER.warn("ignore the exception when shutting down", e); } this.interpreterProcessLauncher.stop(); } interpreterProcessLauncher = null; LOGGER.info("Remote process terminated"); }
Source:
<code>private void reload(final Repository repository) { if (form.isDisposed()) return; if (repository == null) { asyncExec(new Runnable() { public void run() { clearRepository(); } }); return; } if (!isValidRepo(repository)) return; final boolean repositoryChanged = currentRepository != repository; asyncExec(new Runnable() { public void run() { if (form.isDisposed()) return; <START> final IndexDiffData indexDiff = doReload(repository); <END> final StagingViewUpdate update = new StagingViewUpdate(currentRepository, indexDiff, null); unstagedTableViewer.setInput(update); stagedTableViewer.setInput(update); enableCommitWidgets(true); commitAction.setEnabled(repository.getRepositoryState() .canCommit()); form.setText(StagingView.getRepositoryName(repository)); updateCommitMessageComponent(repositoryChanged); updateSectionText(); } }); }</code><technical_language>check for null</technical_language>

Target:
private void reload(final Repository repository) { if (form.isDisposed()) return; if (repository == null) { asyncExec(new Runnable() { public void run() { clearRepository(); } }); return; } if (!isValidRepo(repository)) return; final boolean repositoryChanged = currentRepository != repository; asyncExec(new Runnable() { public void run() { if (form.isDisposed()) return; final IndexDiffData indexDiff = doReload(repository); if(indexDiff == null) return; final StagingViewUpdate update = new StagingViewUpdate(currentRepository, indexDiff, null); unstagedTableViewer.setInput(update); stagedTableViewer.setInput(update); enableCommitWidgets(true); commitAction.setEnabled(repository.getRepositoryState() .canCommit()); form.setText(StagingView.getRepositoryName(repository)); updateCommitMessageComponent(repositoryChanged); updateSectionText(); } }); }
Source:
<code>public void testTryLockAfterTaskComplete() throws InterruptedException { Task task = NoopTask.create(); <START> exception.expect(IllegalStateException.class); <END> lockbox.add(task); lockbox.remove(task); Assert.assertFalse(lockbox.tryLock(task, new Interval("2015-01-01/2015-01-02")).isPresent()); }</code><technical_language>This ISE. Also, check exception message well. Please refer AppenderatorDriverFailTest example</technical_language>

Target:
public void testTryLockAfterTaskComplete() { Task task = NoopTask.create(); exception.expect(ISE.class); exception.expectMessage("Unable to grant lock to inactive Task"); lockbox.add(task); lockbox.remove(task); Assert.assertFalse(lockbox.tryLock(task, new Interval("2015-01-01/2015-01-02")).isPresent()); }
Source:
<code><START> private long updateCardCurrentDid(Card card) { <END> if(card == null) { return -1; } card.setDid(mCurrentDid); return mCurrentDid; }</code><technical_language>need return here, unused</technical_language>

Target:
private long updateCardCurrentDid(Card card) { if(card == null) { return -1; } mLastDid = card.getDid(); card.setDid(mCurrentDid); return mCurrentDid; }
Source:
<code>public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Log.d(TAG, "onUpdate() called with: " + "context = [" + context + "], appWidgetManager = [" + appWidgetManager + "], appWidgetIds = [" + Arrays.toString(appWidgetIds) + "]"); for (int appWidgetId : appWidgetIds) { SharedPreferences prefs = context.getSharedPreferences(WIDGET_PREFS, Context.MODE_PRIVATE); <START> String backgroundColor = prefs.getString(WIDGET_COLOR + appWidgetId, "#7F262C31"); <END> RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.player_widget); views.setInt(R.id.widgetLayout,"setBackgroundColor", Color.parseColor(backgroundColor)); appWidgetManager.updateAppWidget(appWidgetId, views); } PlayerWidgetJobService.updateWidget(context); }</code><technical_language>This default color is a change current value. I prefer color stay updating AntennaPod</technical_language>

Target:
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Log.d(TAG, "onUpdate() called with: " + "context = [" + context + "], appWidgetManager = [" + appWidgetManager + "], appWidgetIds = [" + Arrays.toString(appWidgetIds) + "]"); PlayerWidgetJobService.updateWidget(context); }
Source:
<code>private void sleepForAWhile() { try { Thread.sleep(1000); } catch (InterruptedException e) { <START> assertThat(e).isNull(); <END> } }</code><technical_language>astonished:</technical_language>

Target:
private void sleepForAWhile() { SystemClock.sleep(1000); }
Source:
<code>public void testGroupByFloatColumn() { <START> if (config.getDefaultStrategy().equals(GroupByStrategySelector.STRATEGY_V1)) { <END> return; } GroupByQuery query = GroupByQuery .builder() .setDataSource(QueryRunnerTestHelper.dataSource) .setQuerySegmentSpec(QueryRunnerTestHelper.firstToThird) .setDimensions(Lists.<DimensionSpec>newArrayList(new DefaultDimensionSpec("index", "index_alias", ValueType.FLOAT))) .setDimFilter(new SelectorDimFilter("quality", "entertainment", null)) .setAggregatorSpecs( Arrays.asList( QueryRunnerTestHelper.rowsCount, new LongSumAggregatorFactory("idx", "index") ) ) .setGranularity(QueryRunnerTestHelper.dayGran) .build(); List<Row> expectedResults; if (config.getDefaultStrategy().equals(GroupByStrategySelector.STRATEGY_V1)) { expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "index_alias", "158.74722", "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "index_alias", "166.01605", "rows", 1L, "idx", 166L ) ); } else { expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "index_alias", 158.747224f, "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "index_alias", 166.016049f, "rows", 1L, "idx", 166L ) ); } Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query); TestHelper.assertExpectedObjects(expectedResults, results, ""); }</code><technical_language>Please expectedException skipping test</technical_language>

Target:
public void testGroupByFloatColumn() { if (config.getDefaultStrategy().equals(GroupByStrategySelector.STRATEGY_V1)) { expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("GroupBy v1 only supports dimensions with an outputType of STRING."); } GroupByQuery query = GroupByQuery .builder() .setDataSource(QueryRunnerTestHelper.dataSource) .setQuerySegmentSpec(QueryRunnerTestHelper.firstToThird) .setDimensions(Lists.<DimensionSpec>newArrayList(new DefaultDimensionSpec("index", "index_alias", ValueType.FLOAT))) .setDimFilter(new SelectorDimFilter("quality", "entertainment", null)) .setAggregatorSpecs( Arrays.asList( QueryRunnerTestHelper.rowsCount, new LongSumAggregatorFactory("idx", "index") ) ) .addOrderByColumn(new OrderByColumnSpec( "index_alias", OrderByColumnSpec.Direction.ASCENDING, StringComparators.NUMERIC )) .setGranularity(QueryRunnerTestHelper.dayGran) .build(); Assert.assertEquals( Functions.<Sequence<Row>>identity(), query.getLimitSpec().build( query.getDimensions(), query.getAggregatorSpecs(), query.getPostAggregatorSpecs() ) ); List<Row> expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "index_alias", 158.747224f, "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "index_alias", 166.016049f, "rows", 1L, "idx", 166L ) ); Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query); TestHelper.assertExpectedObjects(expectedResults, results, ""); }
Source:
<code>static Optional<ACLHandle> getEffectiveAcl(final FedoraResource resource) { try { final IdentifierConverter<Resource, FedoraResource> translator = new DefaultIdentifierTranslator(resource.getNode().getSession()); final List<String> acls = resource.getTriples(translator, PROPERTIES) .filter(triple -> triple.getPredicate().equals(createURI(WEBAC_ACCESS_CONTROL_VALUE))) .map(triple -> { if (triple.getObject().isURI()) { return triple.getObject().getURI(); <START> } else { <END> final String error = String.format("The value %s of the %s on this resource must be a URI", triple.getObject(), WEBAC_ACCESS_CONTROL_VALUE); LOGGER.error(error); throw new MalformedRdfException(error); } }).collect(toList()); if (!acls.isEmpty()) { if (acls.size() > 1) { LOGGER.warn("Found multiple ACLs defined for this node. Using: {}", acls.get(0)); } return Optional.of(new ACLHandle(URI.create(acls.get(0)), resource)); } else if (resource.getNode().getDepth() == 0) { LOGGER.debug("No ACLs defined on this node or in parent hierarchy"); return Optional.empty(); } else { LOGGER.trace("Checking parent resource for ACL. No ACL found at {}", resource.getPath()); return getEffectiveAcl(resource.getContainer()); } } catch (final RepositoryException ex) { LOGGER.debug("Exception finding effective ACL: {}", ex.getMessage()); return Optional.empty(); } }</code><technical_language>I this else braces necessary, they</technical_language>

Target:
static Optional<ACLHandle> getEffectiveAcl(final FedoraResource resource) { try { final IdentifierConverter<Resource, FedoraResource> translator = new DefaultIdentifierTranslator(resource.getNode().getSession()); final List<String> acls = resource.getTriples(translator, PROPERTIES) .filter(triple -> triple.getPredicate().equals(createURI(WEBAC_ACCESS_CONTROL_VALUE))) .map(triple -> { if (triple.getObject().isURI()) { return triple.getObject().getURI(); } final String error = String.format("The value %s of the %s on this resource must be a URI", triple.getObject(), WEBAC_ACCESS_CONTROL_VALUE); LOGGER.error(error); throw new MalformedRdfException(error); }).collect(toList()); if (!acls.isEmpty()) { if (acls.size() > 1) { LOGGER.warn("Found multiple ACLs defined for this node. Using: {}", acls.get(0)); } return Optional.of(new ACLHandle(URI.create(acls.get(0)), resource)); } else if (resource.getNode().getDepth() == 0) { LOGGER.debug("No ACLs defined on this node or in parent hierarchy"); return Optional.empty(); } else { LOGGER.trace("Checking parent resource for ACL. No ACL found at {}", resource.getPath()); return getEffectiveAcl(resource.getContainer()); } } catch (final RepositoryException ex) { LOGGER.debug("Exception finding effective ACL: {}", ex.getMessage()); return Optional.empty(); } }
Source:
<code>HiveSplitSource( String connectorId, String databaseName, String tableName, TupleDomain<? extends ColumnHandle> compactEffectivePredicate, int maxOutstandingSplits, DataSize maxOutstandingSplitsSize, HiveSplitLoader splitLoader, Executor executor) { this.connectorId = requireNonNull(connectorId, "connectorId is null"); this.databaseName = requireNonNull(databaseName, "databaseName is null"); this.tableName = requireNonNull(tableName, "tableName is null"); this.compactEffectivePredicate = requireNonNull(compactEffectivePredicate, "compactEffectivePredicate is null"); this.queue = new AsyncQueue<>(maxOutstandingSplits, executor); <START> this.maxOutstandingSplitsBytes = Ints.checkedCast(maxOutstandingSplitsSize.toBytes()); <END> this.splitLoader = splitLoader; }</code><technical_language>toIntExact</technical_language>

Target:
HiveSplitSource( String connectorId, String databaseName, String tableName, TupleDomain<? extends ColumnHandle> compactEffectivePredicate, int maxOutstandingSplits, DataSize maxOutstandingSplitsSize, HiveSplitLoader splitLoader, Executor executor) { this.connectorId = requireNonNull(connectorId, "connectorId is null"); this.databaseName = requireNonNull(databaseName, "databaseName is null"); this.tableName = requireNonNull(tableName, "tableName is null"); this.compactEffectivePredicate = requireNonNull(compactEffectivePredicate, "compactEffectivePredicate is null"); this.queue = new AsyncQueue<>(maxOutstandingSplits, executor); this.maxOutstandingSplitsBytes = toIntExact(maxOutstandingSplitsSize.toBytes()); this.splitLoader = splitLoader; }
Source:
<code>public VariableInstance<?> assignVariableInstance(String variableName, ValueReference reference) { VariableScope variableScope = getVariableScope(); Variable variable = variableScope.findVariable(variableName); if (variable == null) { variable = new Variable(variableName); <START> variable.setMetaData("on-the-fly", true); <END> } variableScope.validateVariable( getProcessInstance().getProcessName(), variableName, reference.get()); VariableInstance<?> instance = addVariableInstance(variableName); instance.setReference(reference); return instance; }</code><technical_language>is this on-the-fly for</technical_language>

Target:
public VariableInstance<?> assignVariableInstance(String variableName, ValueReference reference) { VariableScope variableScope = getVariableScope(); Variable variable = variableScope.findVariable(variableName); if (variable == null) { variable = new Variable(variableName); variable.setMetaData("on-the-fly", true); } variableScope.validateVariable( getProcessInstance().getProcessName(), variableName, reference.get()); VariableInstance<?> instance = getVariableInstance(variableName); instance.setReference(reference); return instance; }
Source:
<code>Set<EMOperation> markOperationComplete(final EMOperation op) { <START> final OpExecutionStatus prevStatus = emOperationsRequested.replace(op, OpExecutionStatus.Complete); <END> if (prevStatus == null) { throw new RuntimeException("The operation " + op + " was never in the request queue"); } planExecutionLatch.countDown(); return plan.onComplete(op); }</code><technical_language>replace(key, oldValue, newValue) API? give more explicit semantics status transition of operation. emOperationsRequested.replace(op, OpExecutionStatus.In_Progress, OpExecutionStatus.Complete)</technical_language>

Target:
Set<EMOperation> markOperationComplete(final EMOperation op) { planExecutionLatch.countDown(); final boolean wasInProgress = emOperationsRequested.replace(op, OpExecutionStatus.IN_PROGRESS, OpExecutionStatus.COMPLETE); if (!wasInProgress) { throw new RuntimeException("The operation " + op + " was never in the request queue"); } return plan.onComplete(op); }
Source:
<code>private void testQosAppendedToResultSet(List<VdsNetworkInterface> result) { result.forEach(r-> { if (r.getQos() == null) { HostNetworkQos hostNetworkQos = new HostNetworkQos(); hostNetworkQos.setId(r.getId()); hostNetworkQos.setOutAverageLinkshare(31); <START> hostNetworkQos.setOutAverageUpperlimit(31); <END> hostNetworkQos.setOutAverageRealtime(31); hostNetworkQosDao.save(hostNetworkQos); } else { r.getQos().setOutAverageLinkshare(31); r.getQos().setOutAverageUpperlimit(31); r.getQos().setOutAverageRealtime(31); hostNetworkQosDao.update(r.getQos()); } }); result = dao.getAllInterfacesForVds(VDS_ID); assertNotNull(result); assertEquals(2, result.size()); result.forEach(r -> { assertNotNull(r.getQos()); assertEquals(r.getId(), r.getQos().getId()); assertEquals(QosType.HOSTNETWORK, r.getQos().getQosType()); assertEquals(31, r.getQos().getOutAverageLinkshare().intValue()); assertEquals(31, r.getQos().getOutAverageRealtime().intValue()); assertEquals(31, r.getQos().getOutAverageUpperlimit().intValue()); }); }</code><technical_language>32</technical_language>

Target:
private void testQosAppendedToResultSet(List<VdsNetworkInterface> result) { result.forEach(r-> { if (r.getQos() == null) { HostNetworkQos hostNetworkQos = new HostNetworkQos(); hostNetworkQos.setId(r.getId()); hostNetworkQos.setOutAverageLinkshare(31); hostNetworkQos.setOutAverageUpperlimit(32); hostNetworkQos.setOutAverageRealtime(33); hostNetworkQosDao.save(hostNetworkQos); } else { r.getQos().setOutAverageLinkshare(31); r.getQos().setOutAverageUpperlimit(32); r.getQos().setOutAverageRealtime(33 ); hostNetworkQosDao.update(r.getQos()); } }); result = dao.getAllInterfacesForVds(VDS_ID); assertNotNull(result); assertEquals(2, result.size()); result.forEach(r -> { assertNotNull(r.getQos()); assertEquals(r.getId(), r.getQos().getId()); assertEquals(QosType.HOSTNETWORK, r.getQos().getQosType()); assertEquals(31, r.getQos().getOutAverageLinkshare().intValue()); assertEquals(32, r.getQos().getOutAverageUpperlimit().intValue()); assertEquals(33, r.getQos().getOutAverageRealtime().intValue()); }); }
Source:
<code>private void addToSpec(Map<String, Object> inputs, T output) { T reference = consistentInputs().get(inputs); if (consistentInputs().size() == 0) { consistentInputs().put(inputs, output); this.keys = inputs.keySet(); return; } if (reference == null && this.keys.equals(inputs.keySet())) { consistentInputs().put(inputs, output); return; } if (output.equals(reference) && this.keys.equals(inputs.keySet())) { <START> this.logger.warn("You may have some redundant test: same input and same outcome, only one will be used: discarded."); END> return; } this.inconsistentInputs.add(inputs); if (!this.keys.equals(inputs.keySet())) { this.logger.debug("Malformed problems: the same input value has different outcome: discarded."); consistentInputs().remove(inputs); } else { this.logger.debug("Inconsistent specification: same input with same outcome, the condition can be flipped with no impact: discarded."); } }</code><technical_language>in log line add specification well</technical_language>

Target:
private void addToSpec(Map<String, Object> inputs, T output) { T reference = consistentInputs().get(inputs); if (consistentInputs().size() == 0) { consistentInputs().put(inputs, output); this.keys = inputs.keySet(); return; } if (reference == null && this.keys.equals(inputs.keySet())) { consistentInputs().put(inputs, output); return; } if (output.equals(reference) && this.keys.equals(inputs.keySet())) { this.logger.warn("You have redundant tests: same input and same outcome, only one will be used to speed-up synthesis: discarded inputs={} : output={}.", inputs, output); return; } if (!this.keys.equals(inputs.keySet())) { this.logger.debug("Ill-formed problem: not the input variables in input={} reference={}", inputs, this.keys); this.inconsistentInputs.add(inputs); consistentInputs().remove(inputs); } else { this.logger.debug("Same input with different outcome, logical contradiction, discarding the second one discarded={}, current output={}, reference output={}", inputs, output, consistentInputs.get(inputs)); this.inconsistentInputs.add(inputs); } }
Source:
<code><START> public Mono<AreaCodes> getAllAreaCodes( <END> String locationType, String countryCode, String phonePlanId, List<LocationOptionsQuery> locationOptions) { LocationOptionsQueries locationOptionsQueries = new LocationOptionsQueries(); locationOptionsQueries.setLocationOptions(locationOptions); return phoneNumberAdminClient.getPhoneNumberAdministrations().getAllAreaCodesAsync( locationType, countryCode, phonePlanId, locationOptionsQueries); }</code><technical_language>Please ensure of methods throw exception. Exception returned Mono.error Flux.error</technical_language>

Target:
public Mono<AreaCodes> getAllAreaCodes( String locationType, String countryCode, String phonePlanId, List<LocationOptionsQuery> locationOptions) { LocationOptionsQueries locationOptionsQueries = new LocationOptionsQueries(); locationOptionsQueries.setLocationOptions(locationOptions); return phoneNumberAdministrations.getAllAreaCodesAsync( locationType, countryCode, phonePlanId, locationOptionsQueries); }
Source:
<code>private String setBuildEnvironmentText(Object[] environments){ <START> String result = ""; <END> String actualEnvironment = ""; buildEnvironments = new ArrayList<String>(); for(int i = 0; i < environments.length; ++i){ actualEnvironment = environments[i].toString(); buildEnvironments.add(actualEnvironment); if(i == 0) { result += actualEnvironment; continue; } result += "; " + actualEnvironment; } return result; }</code><technical_language>Please, stringbuilder</technical_language>

Target:
private String setBuildEnvironmentText(Object[] environments){ StringBuilder result = new StringBuilder(); String actualEnvironment = ""; buildEnvironments = new ArrayList<String>(); for(int i = 0; i < environments.length; ++i){ actualEnvironment = environments[i].toString(); buildEnvironments.add(actualEnvironment); if(i == 0) { result.append(actualEnvironment); continue; } result.append("; "); result.append(actualEnvironment); } return result.toString(); }
Source:
<code>public void testGetCourses() throws InvalidParametersException { CourseAttributes c = createNewCourse(); List<String> courseIds = new ArrayList<>(); <START> ______TS("Success: get existent courses"); <END> courseIds.add(c.getId()); List<CourseAttributes> retrieved = coursesDb.getCourses(courseIds); assertEquals(1, retrieved.size()); ______TS("Failure: get a non-existent course"); courseIds.remove(c.getId()); courseIds.add("non-existent-course"); retrieved = coursesDb.getCourses(courseIds); assertEquals(0, retrieved.size()); ______TS("Failure: get null parameters"); try { coursesDb.getCourse(null); signalFailureToDetectException(); } catch (AssertionError e) { assertEquals(Const.StatusCodes.DBLEVEL_NULL_INPUT, e.getMessage()); } }</code><technical_language>Technically a single is "Success: get existent course"</technical_language>

Target:
public void testGetCourses() throws InvalidParametersException { CourseAttributes c = createNewCourse(); List<String> courseIds = new ArrayList<>(); ______TS("Success: get an existent course"); courseIds.add(c.getId()); List<CourseAttributes> retrieved = coursesDb.getCourses(courseIds); assertEquals(1, retrieved.size()); ______TS("Failure: get a non-existent course"); courseIds.remove(c.getId()); courseIds.add("non-existent-course"); retrieved = coursesDb.getCourses(courseIds); assertEquals(0, retrieved.size()); ______TS("Failure: get null parameters"); try { coursesDb.getCourse(null); signalFailureToDetectException(); } catch (AssertionError e) { assertEquals(Const.StatusCodes.DBLEVEL_NULL_INPUT, e.getMessage()); } }
Source:
<code>static Challenge parseChallenge(final String challenge) throws ResourceAuthenticationChallengeException { <START> final String scheme = parseScheme(challenge); <END> Logger.d(TAG, "Parsing scheme: " + scheme); final String challengeSansScheme = challenge.substring(scheme.length() + 1); final Map<String, String> params = parseParams(challengeSansScheme); return new Challenge(scheme, params); }</code><technical_language>do need null checks for scheme, challengeSansScheme challenge</technical_language>

Target:
static Challenge parseChallenge(final String challenge) throws ResourceAuthenticationChallengeException { final String methodName = ":parseChallenge"; if (StringExtensions.isNullOrBlank(challenge)) { Logger.w(TAG + methodName, "Cannot parse null/empty challenge."); throw new ResourceAuthenticationChallengeException(AUTH_HEADER_MISSING); } final String scheme = parseScheme(challenge); Logger.i(TAG + methodName, "Parsing scheme", "Scheme value [" + scheme + "]"); Logger.i(TAG + methodName, "Removing scheme from source challenge", "[" + challenge + "]"); Logger.v(TAG + methodName, "Parsing challenge substr. Total length: " + challenge.length() + " Scheme index: " + scheme.length() + 1); final String challengeSansScheme = challenge.substring(scheme.length() + 1); final Map<String, String> params = parseParams(challengeSansScheme); return new Challenge(scheme, params); }
Source:
<code>public void removeDestination(String... destination) { this.destinationLock.lock(); try { for (String d : destination) { if (this.destinations.remove(d)) { if (this.logger.isDebugEnabled()) { logger.debug("Removed '" + d + "' from subscriptions."); } StompSession.Subscription subscription = this.subscriptions.get(d); if (subscription != null) { subscription.unsubscribe(); } <START> } <END> } } finally { this.destinationLock.unlock(); } }</code><technical_language>debug log? (tried remove non-existent subs)</technical_language>

Target:
public void removeDestination(String... destination) { Assert.notNull(destination, "'destination' cannot be null"); this.destinationLock.lock(); try { for (String d : destination) { if (this.destinations.remove(d)) { if (this.logger.isDebugEnabled()) { logger.debug("Removed '" + d + "' from subscriptions."); } StompSession.Subscription subscription = this.subscriptions.get(d); if (subscription != null) { subscription.unsubscribe(); } else { if (this.logger.isDebugEnabled()) { logger.debug("No subscription for destination '" + d + "'."); } } } } } finally { this.destinationLock.unlock(); } }
Source:
<code>private void commitUpToCheckpoint(long checkpointId) throws Exception { helper.commitUpToCheckpoint(checkpointId); <START> NavigableMap<Long, Set<String>> newPartitions = this.newPartitions.headMap(checkpointId, true); <END> Set<String> partitions = new HashSet<>(committablePartitions); committablePartitions.clear(); newPartitions.values().forEach(partitions::addAll); newPartitions.clear(); CommitMessage message = new CommitMessage( checkpointId, getRuntimeContext().getIndexOfThisSubtask(), getRuntimeContext().getNumberOfParallelSubtasks(), new ArrayList<>(partitions)); output.collect(new StreamRecord<>(message)); }</code><technical_language>Change another name avoid override variable names</technical_language>

Target:
private void commitUpToCheckpoint(long checkpointId) throws Exception { helper.commitUpToCheckpoint(checkpointId); NavigableMap<Long, Set<String>> headPartitions = this.newPartitions.headMap(checkpointId, true); Set<String> partitions = new HashSet<>(committablePartitions); committablePartitions.clear(); headPartitions.values().forEach(partitions::addAll); headPartitions.clear(); CommitMessage message = new CommitMessage( checkpointId, getRuntimeContext().getIndexOfThisSubtask(), getRuntimeContext().getNumberOfParallelSubtasks(), new ArrayList<>(partitions)); output.collect(new StreamRecord<>(message)); }
Source:
<code>public GlowEntity spawn(Location location, Class<? extends GlowEntity> clazz, SpawnReason reason) throws IllegalArgumentException { GlowEntity entity = null; if (TNTPrimed.class.isAssignableFrom(clazz)) { entity = new GlowTNTPrimed(location, null); } if (entity == null) { try { Constructor<? extends GlowEntity> constructor = clazz.getConstructor(Location.class); entity = constructor.newInstance(location); if (entity instanceof LivingEntity) { CreatureSpawnEvent spawnEvent = new CreatureSpawnEvent((LivingEntity) entity, reason); if (!spawnEvent.isCancelled()) { <START> entity.createSpawnMessage(); <END> } else { entity.remove(); } } else { entity.createSpawnMessage(); } } catch (NoSuchMethodException e) { GlowServer.logger.log(Level.WARNING, "Invalid entity spawn: ", e); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { GlowServer.logger.log(Level.SEVERE, "Unable to spawn entity: ", e); } } if (entity != null) { return entity; } throw new UnsupportedOperationException("Not supported yet."); }</code><technical_language>I this before, pretty spawn message needs players chunk entity is in</technical_language>

Target:
public GlowEntity spawn(Location location, Class<? extends GlowEntity> clazz, SpawnReason reason) throws IllegalArgumentException { GlowEntity entity = null; if (TNTPrimed.class.isAssignableFrom(clazz)) { entity = new GlowTNTPrimed(location, null); } if (entity == null) { try { Constructor<? extends GlowEntity> constructor = clazz.getConstructor(Location.class); entity = constructor.newInstance(location); GlowEntity impl = entity; EntitySpawnEvent spawnEvent; if (entity instanceof LivingEntity) { spawnEvent = EventFactory.callEvent(new CreatureSpawnEvent((LivingEntity) entity, reason)); } else { spawnEvent = EventFactory.callEvent(new EntitySpawnEvent(entity)); } if (!spawnEvent.isCancelled()) { List<Message> spawnMessage = entity.createSpawnMessage(); getRawPlayers().stream().filter(player -> player.canSeeEntity(impl)).forEach(player -> player.getSession().sendAll(spawnMessage.toArray(new Message[spawnMessage.size()]))); } else { entity.remove(); } } catch (NoSuchMethodException e) { GlowServer.logger.log(Level.WARNING, "Invalid entity spawn: ", e); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { GlowServer.logger.log(Level.SEVERE, "Unable to spawn entity: ", e); } } if (entity != null) { return entity; } throw new UnsupportedOperationException("Not supported yet."); }
Source:
<code>private void checkOutput() throws IOException { String validationOutput; File folder = new File(directory); FilenameFilter filenameFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.split("_")[0].equals("validation.txt")) { return true; } return false; } }; File validationFile = folder.listFiles(filenameFilter)[0]; <START> FileInputStream inputStream = new FileInputStream(validationFile); <END> try { validationOutput = IOUtils.toString(inputStream); System.out.println("Validation output: " + validationOutput); } finally { inputStream.close(); } Assert.assertTrue(validationOutput.contains("exactly-once: 0")); Assert.assertEquals("Duplicates: exactly-once: 0, at-least-once: " + tuplesUntilKill, validationOutput); }</code><technical_language>try-with-resources</technical_language>

Target:
private void checkOutput() throws IOException { String validationOutput; File folder = new File(directory); FilenameFilter filenameFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.split("_")[0].equals("validation.txt")) { return true; } return false; } }; File validationFile = folder.listFiles(filenameFilter)[0]; try (FileInputStream inputStream = new FileInputStream(validationFile)) { validationOutput = IOUtils.toString(inputStream); logger.info("Validation output: {}", validationOutput); } Assert.assertTrue(validationOutput.contains("exactly-once: 0")); Assert.assertEquals("Duplicates: exactly-once: 0, at-least-once: " + tuplesUntilKill, validationOutput); }
Source:
<code>public AbstractLunRemoveColumn(SanStorageModelBase model) { super(new AbstractToggleButtonCell<LunModel>() { @Override public void onClickEvent(LunModel lunModel) { if (lunModel != null) { lunModel.setRemoveLunSelected(!lunModel.isRemoveLunSelected()); } } <START> @Override <END> public void render(Context context, LunModel value, SafeHtmlBuilder sb, String id) { String inputId = id + "_input"; SafeHtml input; boolean lastLunAvailable = model.getNumOfLUNsToRemove() == model.getItems().size() - 1; model.getRequireTableRefresh().setEntity(lastLunAvailable); if (value.isRemoveLunSelected()) { input = templates.toggledDown(inputId, "Remove"); } else if (model.getMetadataDevices().contains(value.getLunId()) || model.getSelectedLuns().size() == 1 || lastLunAvailable) { input = templates.disabled(inputId, constants.notAvailableLabel()); } else { input = templates.toggledUp(inputId, "Remove"); } sb.append(templates.span(id, input)); } }); }</code><technical_language>a blank line methods</technical_language>

Target:
public AbstractLunRemoveColumn(SanStorageModelBase model) { super(new AbstractToggleButtonCell<LunModel>() { @Override public void onClickEvent(LunModel lunModel) { if (lunModel != null && !model.getMetadataDevices().contains(lunModel.getLunId())) { lunModel.setRemoveLunSelected(!lunModel.isRemoveLunSelected()); } } @Override public void render(Context context, LunModel value, SafeHtmlBuilder sb, String id) { String inputId = id + "_input"; SafeHtml input; boolean lastLunAvailable = false; if (model.getMetadataDevices().size() == 0) { lastLunAvailable = model.getNumOfLUNsToRemove() == model.getItems().size() - 1; } model.getRequireTableRefresh().setEntity(lastLunAvailable); if (model.getMetadataDevices().contains(value.getLunId()) || model.getSelectedLuns().size() == 1 || lastLunAvailable) { input = templates.disabled(inputId, constants.notAvailableLabel()); } else if (value.isRemoveLunSelected()) { input = templates.toggledDown(inputId, "Remove"); } else { input = templates.toggledUp(inputId, "Remove"); } sb.append(templates.span(id, input)); } }); }