auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static <T extends Locatable> List<T> readSegmentFile(final File segmentsFile, final String[] mandatoryColumns, <START> final Function<DataLine, T> dataLineToSegmentFunction) { <END> try (final TableReader<T> reader = TableUtils.reader(segmentsFile, (columns, formatExceptionFactory) -> { if (!columns.containsAll(mandatoryColumns)) { final Set<String> missingColumns = Sets.difference(new HashSet<>(Arrays.asList(mandatoryColumns)), new HashSet<>(columns.names())); throw formatExceptionFactory.apply("Bad header in file. Not all columns are present. Missing: " + StringUtils.join(missingColumns, ", ")); } return dataLineToSegmentFunction; })) { return reader.stream().collect(Collectors.toList()); } catch (final IOException | UncheckedIOException e) { throw new UserException.CouldNotReadInputFile(segmentsFile, e); } }</code><technical_language>add Utils.nonNull(segmentsFile); Utils.regularReadableUserFile(segmentsFile); here</technical_language>

Target:
public static <T extends Locatable> List<T> readSegmentFile(final File segmentsFile, final String[] mandatoryColumns, final Function<DataLine, T> dataLineToSegmentFunction) { Utils.nonNull(segmentsFile); Utils.regularReadableUserFile(segmentsFile); try (final TableReader<T> reader = TableUtils.reader(segmentsFile, (columns, formatExceptionFactory) -> { if (!columns.containsAll(mandatoryColumns)) { final Set<String> missingColumns = Sets.difference(new HashSet<>(Arrays.asList(mandatoryColumns)), new HashSet<>(columns.names())); throw formatExceptionFactory.apply("Bad header in file. Not all columns are present. Missing: " + StringUtils.join(missingColumns, ", ")); } return dataLineToSegmentFunction; })) { return reader.stream().collect(Collectors.toList()); } catch (final IOException | UncheckedIOException e) { throw new UserException.CouldNotReadInputFile(segmentsFile, e); } }
Source:
<code>public void init(HelixManager helixManager, TableConfig tableConfig) { _helixManager = helixManager; _offlineTableName = tableConfig.getTableName(); _replication = tableConfig.getValidationConfig().getReplicationNumber(); ReplicaGroupStrategyConfig replicaGroupStrategyConfig = tableConfig.getValidationConfig().getReplicaGroupStrategyConfig(); _partitionColumn = replicaGroupStrategyConfig != null ? replicaGroupStrategyConfig.getPartitionColumn() : null; <START> if (InstanceAssignmentConfigUtils.shouldRelocateToTiers(tableConfig)) { <END> _sortedTiers = getSortedTiersForPinotServerStorage(tableConfig.getTierConfigsList()); } if (_partitionColumn == null) { LOGGER.info("Initialized OfflineSegmentAssignment with replication: without partition column for table: ", _replication, _offlineTableName); } else { LOGGER.info("Initialized OfflineSegmentAssignment with replication: and partition column: for table: {}", _replication, _partitionColumn, _offlineTableName); } }</code><technical_language>Move this calculation rebalanceTable() need for assignSegment(). for RealtimeSegmentAssignment</technical_language>

Target:
public void init(HelixManager helixManager, TableConfig tableConfig) { _helixManager = helixManager; _offlineTableName = tableConfig.getTableName(); _replication = tableConfig.getValidationConfig().getReplicationNumber(); ReplicaGroupStrategyConfig replicaGroupStrategyConfig = tableConfig.getValidationConfig().getReplicaGroupStrategyConfig(); _partitionColumn = replicaGroupStrategyConfig != null ? replicaGroupStrategyConfig.getPartitionColumn() : null; if (_partitionColumn == null) { LOGGER.info("Initialized OfflineSegmentAssignment with replication: without partition column for table: ", _replication, _offlineTableName); } else { LOGGER.info("Initialized OfflineSegmentAssignment with replication: and partition column: for table: {}", _replication, _partitionColumn, _offlineTableName); } }
Source:
<code>public String joinPlayerToTeam( @RequestParam(value = "teamPassword", required = true) String enteredPassword, @PathVariable int id, HttpSession session) { Member me = (Member) session.getAttribute("member"); if (me == null) { return "redirect:/denied"; } TeamDao teamDao = new TeamDao(); Team team = teamDao.getTeamById(id, false, true, false); String teamPassword = team.getPassword(); String genPassword = StringUtils.secureString(enteredPassword); if (team == null || !genPassword.equals(teamPassword)) { return "redirect:/tournament/" + team.getTournament().getId() + "/teams"; } if (team.addPlayer(me) == 1) { teamDao.saveTeam(team); Set<Team> invitedTeams = me.getInvitedTeams(); Iterator<Team> teamIterator = invitedTeams.iterator(); while (teamIterator.hasNext()) { Team invitedTeam = teamIterator.next(); if (invitedTeam.getTournament().equals(team.getTournament())) { invitedTeam.removeInvitedPlayer(me); teamDao.saveTeam(invitedTeam); } } <START> new MessageDao().notify(me, "You have succesfully joined " + team.getName()); <END> } return "redirect:/team/" + teamDao.getTeamById(team.getId(), true, true, true).getId() + "/view"; }</code><technical_language>Is this above</technical_language>

Target:
public String joinPlayerToTeam( @RequestParam(value = "teamPassword", required = true) String enteredPassword, @PathVariable int id, HttpSession session) { Member me = (Member) session.getAttribute("member"); if (me == null) { return "redirect:/denied"; } TeamDao teamDao = new TeamDao(); Team team = teamDao.getTeamById(id, false, true, false); String teamPassword = team.getPassword(); String genPassword = StringUtils.secureString(enteredPassword); if (team == null || !genPassword.equals(teamPassword)) { return "redirect:/tournament/" + team.getTournament().getId() + "/teams"; } if (team.addPlayer(me) == 1) { teamDao.saveTeam(team); Set<Team> invitedTeams = me.getInvitedTeams(); Iterator<Team> teamIterator = invitedTeams.iterator(); while (teamIterator.hasNext()) { Team invitedTeam = teamIterator.next(); if (invitedTeam.getTournament().equals(team.getTournament())) { invitedTeam.removeInvitedPlayer(me); teamDao.saveTeam(invitedTeam); } } new MessageDao().notify(me, "You have succesfully joined " + team.getName()); new MessageDao().notify(team.getTeamLeader(), me.getName() + " has joined team " + team.getName()); } return "redirect:/team/" + teamDao.getTeamById(team.getId(), true, true, true).getId() + "/view"; }
Source:
<code>private SymbolStatsEstimate normalizeSymbolStats(Symbol symbol, SymbolStatsEstimate symbolStats, PlanNodeStatsEstimate stats, TypeProvider types) { if (symbolStats.isUnknown()) { return SymbolStatsEstimate.unknown(); } double outputRowCount = stats.getOutputRowCount(); double distinctValuesCount = symbolStats.getDistinctValuesCount(); double nullsFraction = symbolStats.getNullsFraction(); if (!isNaN(distinctValuesCount)) { <START> Type type = requireNonNull(types.get(symbol), () -> "type is missing for symbol: " + symbol); <END> double maxDistinctValuesByLowHigh = maxDistinctValuesByLowHigh(symbolStats, type); if (distinctValuesCount > maxDistinctValuesByLowHigh) { distinctValuesCount = maxDistinctValuesByLowHigh; } if (distinctValuesCount > outputRowCount) { distinctValuesCount = outputRowCount; } double nonNullValues = outputRowCount * (1 - nullsFraction); if (distinctValuesCount > nonNullValues) { double difference = distinctValuesCount - nonNullValues; distinctValuesCount -= difference / 2; nonNullValues += difference / 2; nullsFraction = 1 - nonNullValues / outputRowCount; } } if (distinctValuesCount == 0.0) { return SymbolStatsEstimate.zero(); } return SymbolStatsEstimate.buildFrom(symbolStats) .setDistinctValuesCount(distinctValuesCount) .setNullsFraction(nullsFraction) .build(); }</code><technical_language>nit: other places for symbol %s, :</technical_language>

Target:
private SymbolStatsEstimate normalizeSymbolStats(Symbol symbol, SymbolStatsEstimate symbolStats, PlanNodeStatsEstimate stats, TypeProvider types) { if (symbolStats.isUnknown()) { return SymbolStatsEstimate.unknown(); } double outputRowCount = stats.getOutputRowCount(); checkArgument(outputRowCount > 0, "outputRowCount must be greater than zero: %s", outputRowCount); double distinctValuesCount = symbolStats.getDistinctValuesCount(); double nullsFraction = symbolStats.getNullsFraction(); if (!isNaN(distinctValuesCount)) { Type type = requireNonNull(types.get(symbol), () -> "type is missing for symbol: " + symbol); double maxDistinctValuesByLowHigh = maxDistinctValuesByLowHigh(symbolStats, type); if (distinctValuesCount > maxDistinctValuesByLowHigh) { distinctValuesCount = maxDistinctValuesByLowHigh; } if (distinctValuesCount > outputRowCount) { distinctValuesCount = outputRowCount; } double nonNullValues = outputRowCount * (1 - nullsFraction); if (distinctValuesCount > nonNullValues) { double difference = distinctValuesCount - nonNullValues; distinctValuesCount -= difference / 2; nonNullValues += difference / 2; nullsFraction = 1 - nonNullValues / outputRowCount; } } if (distinctValuesCount == 0.0) { return SymbolStatsEstimate.zero(); } return SymbolStatsEstimate.buildFrom(symbolStats) .setDistinctValuesCount(distinctValuesCount) .setNullsFraction(nullsFraction) .build(); }
Source:
<code>private void testTimeoutHelper(boolean sync) { final int taskTimeout = REPLICATION_TIMEOUT / 4; final int sleepTime = REPLICATION_TIMEOUT / 2; final String sleepOnKey = init(); MapReduceTask<String, String, String, Integer> task = createMapReduceTask(this.<String, String> cache(0)); assertEquals("Wrong task timeout.", REPLICATION_TIMEOUT, task.timeout(MILLISECONDS)); assertEquals("Wrong replication timeout.", REPLICATION_TIMEOUT, cache(0).getCacheConfiguration().clustering() .sync().replTimeout()); task.timeout(taskTimeout, MILLISECONDS); assertEquals("Wrong new task timeout.", taskTimeout, task.timeout(MILLISECONDS)); task.mappedWith(new SleepMapper(sleepTime, sleepOnKey)).reducedWith(new DummyReducer()); long start = System.nanoTime(); if (sync) { try { task.execute(); } catch (CacheException expected) { assertTrue(hasTimeoutException(expected)); } } else { try { Future<Map<String, Integer>> future = task.executeAsynchronously(); future.get(); <START> } catch (CacheException expected) { <END> } catch (InterruptedException e) { } catch (ExecutionException e) { assertTrue(hasTimeoutException(e)); } } long duration = System.nanoTime() - start; assertTrue(NANOSECONDS.toMillis(duration) >= taskTimeout); }</code><technical_language>exceptions propagated</technical_language>

Target:
private void testTimeoutHelper(boolean sync) throws Exception { final int taskTimeout = REPLICATION_TIMEOUT / 4; final int sleepTime = REPLICATION_TIMEOUT / 2; final String sleepOnKey = init(); MapReduceTask<String, String, String, Integer> task = createMapReduceTask(this.<String, String> cache(0)); assertEquals("Wrong task timeout.", REPLICATION_TIMEOUT, task.timeout(MILLISECONDS)); assertEquals("Wrong replication timeout.", REPLICATION_TIMEOUT, cache(0).getCacheConfiguration().clustering() .sync().replTimeout()); task.timeout(taskTimeout, MILLISECONDS); assertEquals("Wrong new task timeout.", taskTimeout, task.timeout(MILLISECONDS)); task.mappedWith(new SleepMapper(sleepTime, sleepOnKey)).reducedWith(new DummyReducer()); long start = System.nanoTime(); if (sync) { try { task.execute(); fail("Should have gotten an exception for task.execute() call"); } catch (CacheException expected) { assertTrue(hasTimeoutException(expected)); } } else { try { Future<Map<String, Integer>> future = task.executeAsynchronously(); future.get(); fail("Should have gotten an exception for future.get() call"); } catch (ExecutionException e) { assertTrue(hasTimeoutException(e)); } } long duration = System.nanoTime() - start; assertTrue(NANOSECONDS.toMillis(duration) >= taskTimeout); }
Source:
<code>public void idTokenWithAudience_correct() throws IOException { <START> final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; <END> MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; ServiceAccountCredentials credentials = ServiceAccountCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, SCOPES, transportFactory, null); transport.addServiceAccount(SA_CLIENT_EMAIL, accessToken1); TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken1); String targetAudience = "<LINK_0>"; IdTokenCredentials tokenCredential = IdTokenCredentials.create(credentials, targetAudience); tokenCredential.refresh(); assertEquals(defaultIDToken, tokenCredential.getAccessToken().getTokenValue()); assertEquals(defaultIDToken, tokenCredential.getIdToken().getTokenValue()); assertEquals( targetAudience, (String) tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); }</code><technical_language>google style is final local variables required</technical_language>

Target:
public void idTokenWithAudience_correct() throws IOException { String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; ServiceAccountCredentials credentials = ServiceAccountCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, SCOPES, transportFactory, null); transport.addServiceAccount(SA_CLIENT_EMAIL, accessToken1); TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken1); String targetAudience = "<LINK_0>"; IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder() .setIdTokenProvider(credentials) .setTargetAudience(targetAudience) .build(); tokenCredential.refresh(); assertEquals(DEFAULT_ID_TOKEN, tokenCredential.getAccessToken().getTokenValue()); assertEquals(DEFAULT_ID_TOKEN, tokenCredential.getIdToken().getTokenValue()); assertEquals( targetAudience, (String) tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); }
Source:
<code>private static <T> Map<String, T> safeGetMap(Map map, String key, Class<T> valueType) { Map<?, ?> unchecked = safeGet(map, key, Map.class); if (unchecked == null) { return null; } try { return unchecked .entrySet() .stream() .map(e -> new SimpleEntry<>(String.class.cast(e.getKey()), e.getValue())) .map(e -> new SimpleEntry<>(e.getKey(), valueType.cast(e.getValue()))) .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)); } catch (ClassCastException e) { LOGGER.warn( "Form configuration field was malformed, expected a querySettings Map containing type {}", key, <START> valueType.getName()); <END> } return null; }</code><technical_language>feelings for exceptions flow control aside, this log statement is forgot include exception e</technical_language>

Target:
private static <T> Map<String, T> safeGetMap(Map map, String key, Class<T> valueType) { Map<?, ?> unchecked = safeGet(map, key, Map.class); if (unchecked == null) { return null; } try { return unchecked .entrySet() .stream() .map(e -> new SimpleEntry<>(String.class.cast(e.getKey()), e.getValue())) .map(e -> new SimpleEntry<>(e.getKey(), valueType.cast(e.getValue()))) .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)); } catch (ClassCastException e) { LOGGER.debug(EXCEPTION_OCCURRED_PARSING, e); LOGGER.warn( "Form configuration field was malformed, expected a querySettings Map containing type {}", key, valueType.getName()); } return null; }
Source:
<code>public void reset() { m_syncedSinceLastEdit = false; for (SegmentReader reader : m_readCursors.values()) { <START> reader.m_objectReadIndex = 0; <END> reader.m_bytesRead = 0; reader.m_readOffset = SEGMENT_HEADER_BYTES; reader.m_discardCount = 0; } if (m_tmpHeaderBuf != null) { m_tmpHeaderBuf.discard(); m_tmpHeaderBuf = null; } }</code><technical_language>a reset init method reader help</technical_language>

Target:
public void reset() { m_syncedSinceLastEdit = false; for (SegmentReader reader : m_readCursors.values()) { reader.resetReader(); } if (m_tmpHeaderBuf != null) { m_tmpHeaderBuf.discard(); m_tmpHeaderBuf = null; } }
Source:
<code>protected void buttonPressed(int buttonId) { if (buttonId == Window.OK) { try { int result = deleteBranch(selectedRefs, false); if (result == DeleteBranchOperation.REJECTED_UNMERGED) { List<RefNode> nodes = extractSelectedRefNodes(); <START> @SuppressWarnings("unchecked") <END> MessageDialog messageDialog = new UnmergedBranchDialog( getShell(), nodes); if (messageDialog.open() == Window.OK) deleteBranch(selectedRefs, true); else return; } else if (result == DeleteBranchOperation.REJECTED_CURRENT) Activator .handleError( UIText.DeleteBranchCommand_CannotDeleteCheckedOutBranch, null, true); } catch (CoreException e) { Activator.handleError(e.getMessage(), e, true); } } super.buttonPressed(buttonId); }</code><technical_language>required if UnmergedBranchDialog<RefNode></technical_language>

Target:
protected void buttonPressed(int buttonId) { if (buttonId == Window.OK) { try { int result = deleteBranch(selectedRefs, false); if (result == DeleteBranchOperation.REJECTED_UNMERGED) { List<RefNode> nodes = extractSelectedRefNodes(); MessageDialog messageDialog = new UnmergedBranchDialog<RefNode>( getShell(), nodes); if (messageDialog.open() == Window.OK) deleteBranch(selectedRefs, true); else return; } else if (result == DeleteBranchOperation.REJECTED_CURRENT) Activator .handleError( UIText.DeleteBranchCommand_CannotDeleteCheckedOutBranch, null, true); } catch (CoreException e) { Activator.handleError(e.getMessage(), e, true); } } super.buttonPressed(buttonId); }
Source:
<code><START> private static String computeEntryName(Type type, int id) { <END> if (type == Type.SOFT_IRQ) { return type.toString() + ' ' + id + ' ' + SoftIrqLabelProvider.getSoftIrq(id); } return type.toString() + ' ' + id; }</code><technical_language>@NonNull this one</technical_language>

Target:
private static @NonNull String computeEntryName(Type type, int id) { if (type == Type.SOFT_IRQ) { return type.toString() + ' ' + id + ' ' + SoftIrqLabelProvider.getSoftIrq(id); } return type.toString() + ' ' + id; }
Source:
<code>private static boolean isSubdirectory(String path) { final int slashIndex = <START> path.indexOf("/"); <END> return slashIndex >= 0 && slashIndex < path.length() - 1; }</code><technical_language>please change '/'? This is faster</technical_language>

Target:
private static boolean isSubdirectory(String path) { final int slashIndex = path.indexOf('/'); return slashIndex >= 0 && slashIndex < path.length() - 1; }
Source:
<code>public int getTextLength() { final StackElement stackElement = tokenStack.peek(); try { setXmlText(stackElement, jsonParser); return stackElement.value.length; } catch (IOException e) { <START> throw new IllegalStateException(e); <END> } }</code><technical_language>is rethrow this UncheckedIOException</technical_language>

Target:
public int getTextLength() { final StackElement stackElement = tokenStack.peek(); try { assert stackElement != null; setXmlText(stackElement, jsonParser); return stackElement.value.length; } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
<code>private void testSearch() throws Exception { ______TS("content: default help page"); helpPage.verifyHtmlMainContent("/instructorHelpPageDefault.html"); ______TS("search for empty keyword"); helpPage.clearSearchBox(); helpPage.clickSearchButton(); helpPage.verifyHtmlMainContent("/instructorHelpPageDefault.html"); ______TS("search for single keyword"); String searchContent = "course"; helpPage.inputSearchQuery(searchContent); helpPage.clickSearchButton(); helpPage.verifyHtmlMainContent("/instructorHelpPageSearchSingleKeyword.html"); ______TS("search for multiple keywords"); searchContent = "enroll students"; helpPage.clearSearchBox(); helpPage.inputSearchQuery(searchContent); helpPage.clickSearchButton(); String searchResultsMultipleKeywords = helpPage.getSearchResults(); <START> helpPage.verifyHtmlMainContent("/instructorHelpPageSearchMultipleKeywords.html"); <END> ______TS("check case insensitivity of query"); searchContent = "eNroLL STUDENTs"; helpPage.clearSearchBox(); helpPage.inputSearchQuery(searchContent); helpPage.clickSearchButton(); assertEquals(searchResultsMultipleKeywords, helpPage.getSearchResults()); ______TS("reset search"); helpPage.clickResetButton(); helpPage.verifyHtmlMainContent("/instructorHelpPageDefault.html"); ______TS("search for non existing keyword"); searchContent = "non existing keyword"; helpPage.clearSearchBox(); helpPage.inputSearchQuery(searchContent); helpPage.clickSearchButton(); assertEquals("", helpPage.getSearchResults()); }</code><technical_language>If verifyHtmlPart save a file</technical_language>

Target:
private void testSearch() throws Exception { ______TS("content: default help page"); helpPage.verifyHtmlMainContent("/instructorHelpPageDefault.html"); ______TS("search for empty keyword"); helpPage.clearSearchBox(); helpPage.clickSearchButton(); helpPage.verifyHtmlMainContent("/instructorHelpPageDefault.html"); ______TS("search for single keyword"); String searchContent = "course"; helpPage.inputSearchQuery(searchContent); helpPage.clickSearchButton(); helpPage.verifyHtmlPart(SEARCH_RESULTS, "/instructorHelpPageSearchSingleKeyword.html"); ______TS("search for multiple keywords"); searchContent = "enroll students"; helpPage.clearSearchBox(); helpPage.inputSearchQuery(searchContent); helpPage.clickSearchButton(); helpPage.verifyHtmlPart(SEARCH_RESULTS, "/instructorHelpPageSearchMultipleKeywords.html"); ______TS("check case insensitivity of query"); searchContent = "eNroLL STUDENTs"; helpPage.clearSearchBox(); helpPage.inputSearchQuery(searchContent); helpPage.clickSearchButton(); helpPage.verifyHtmlPart(SEARCH_RESULTS, "/instructorHelpPageSearchMultipleKeywords.html"); ______TS("reset search"); helpPage.clickResetButton(); helpPage.verifyHtmlMainContent("/instructorHelpPageDefault.html"); ______TS("search for non existing keyword"); searchContent = "non existing keyword"; helpPage.clearSearchBox(); helpPage.inputSearchQuery(searchContent); helpPage.clickSearchButton(); assertEquals("", helpPage.getSearchResults()); }
Source:
<code>public void setAccelerator (int accelerator) { checkWidget(); if (this.accelerator == accelerator) return; long accelGroup = getAccelGroup (); if (accelGroup != 0) removeAccelerator (accelGroup); this.accelerator = accelerator; <START> if (accelGroup != 0) { addAccelerator (accelGroup); } } <END></code><technical_language>I this re-factoring. changes in this function other this refactoring. I recommend submit a separate re-factoring patch. This patch is long. Also, if here, ideally do this if-separation widget in a 2nd refactoring patch (or of menu-item ideally). Also, touch this line, change identical line if statement (L 900) this function a bit inconsistent</technical_language>

Target:
public void setAccelerator (int accelerator) { checkWidget(); if (this.accelerator == accelerator) return; long accelGroup = getAccelGroup (); if (accelGroup != 0) removeAccelerator (accelGroup); this.accelerator = accelerator; if (accelGroup != 0) addAccelerator (accelGroup); }
Source:
<code>public void testEncryptionGcm() throws Exception { Configuration conf = new Configuration(); <START> conf.set(SchemaCryptoPropertiesFactory.CONF_ENCRYPTION_ALGORITHM, "AES_GCM_CTR_V1"); <END> runTest(conf); }</code><technical_language>I suggest related constant instead</technical_language>

Target:
public void testEncryptionGcm() throws Exception { Configuration conf = new Configuration(); conf.set(SchemaCryptoPropertiesFactory.CONF_ENCRYPTION_ALGORITHM, ParquetCipher.AES_GCM_V1.toString()); runTest(conf); }
Source:
<code>protected void ExecuteVdsBrokerCommand() { status = getBroker().glusterValidateSshConnection(getParameters().getRemoteServer(), getParameters().getFingerprint(), getParameters().getUserName()); ProceedProxyReturnValue(); <START> setReturnValue(getReturnValue()); <END> }</code><technical_language>is purpose of this statement</technical_language>

Target:
protected void ExecuteVdsBrokerCommand() { status = getBroker().glusterValidateSshConnection(getParameters().getRemoteServer(), getParameters().getFingerprint(), getParameters().getUserName()); ProceedProxyReturnValue(); setReturnValue(true); }
Source:
<code>public Response listWorkflows(Long pageSize, String pageToken, String keyValueSearch, ConsonanceUser user) throws NotFoundException { Long optionalPageSize = pageSize; String optionalPageToken = pageToken; String optionalKeyFilter = keyValueSearch; Ga4ghWesWorkflowListResponse list = new Ga4ghWesWorkflowListResponse(); List<Job> allJobs = orderResource.listWorkflowRuns(user); <START> Map <Integer, JobState> serialize = new TreeMap<Integer, JobState>(); <END> allJobs.stream().forEach((Job j) -> serialize.put(j.getJobId(), j.getState())); for (Integer key: serialize.keySet()){ Ga4ghWesWorkflowDesc descriptor = new Ga4ghWesWorkflowDesc(); descriptor.setWorkflowId(String.valueOf(key)); descriptor.setState(mapState(serialize.get(key))); list.addWorkflowsItem(descriptor); } return Response.ok().entity(list).build(); }</code><technical_language>serialize is a verb is reserved for method names. a noun, serialized describe do here. treemap? listWorkflows in order use? this simplified a single map allJobs</technical_language>

Target:
public Response listWorkflows(Long pageSize, String pageToken, String keyValueSearch, ConsonanceUser user) throws NotFoundException { Long optionalPageSize = pageSize; String optionalPageToken = pageToken; String optionalKeyFilter = keyValueSearch; Ga4ghWesWorkflowListResponse list = new Ga4ghWesWorkflowListResponse(); List<Job> allJobs = orderResource.listWorkflowRuns(user); Map <Integer, JobState> serialized = new TreeMap<Integer, JobState>(); allJobs.stream().forEach((Job j) -> serialized.put(j.getJobId(), j.getState())); for (Integer key: serialized.keySet()){ Ga4ghWesWorkflowDesc descriptor = new Ga4ghWesWorkflowDesc(); descriptor.setWorkflowId(String.valueOf(key)); descriptor.setState(mapState(serialized.get(key))); list.addWorkflowsItem(descriptor); } return Response.ok().entity(list).build(); }
Source:
<code>private void removeManagedBlockStorageDisk() { Future<ActionReturnValue> future = commandCoordinatorUtil.executeAsyncCommand( ActionType.RemoveManagedBlockStorageDisk, getParameters(), cloneContextAndDetachFromParent()); try { setReturnValue(future.get()); setSucceeded(getReturnValue().getSucceeded()); } catch (InterruptedException | ExecutionException e) { log.error("Error removing <START> Cinder disk <END> '{}': {}", getDiskImage().getDiskAlias(), e.getMessage()); log.debug("Exception", e); } }</code><technical_language>This is "Managed Block Storage"</technical_language>

Target:
private void removeManagedBlockStorageDisk() { Future<ActionReturnValue> future = commandCoordinatorUtil.executeAsyncCommand( ActionType.RemoveManagedBlockStorageDisk, getParameters(), cloneContextAndDetachFromParent()); try { setReturnValue(future.get()); setSucceeded(getReturnValue().getSucceeded()); } catch (InterruptedException | ExecutionException e) { log.error("Error removing managed block storage disk '{}': {}", getDiskImage().getDiskAlias(), e.getMessage()); log.debug("Exception", e); } }
Source:
<code>public final Session session( AccessMode mode ) { assertOpen(); Session session = newSessionWithMode( mode ); if( closed.get() ) { closeResources(); <START> throw new IllegalStateException( "This driver instance has already been closed" ); <END> } return session; }</code><technical_language>pull creation of this exception in a method is duplicated in assertOpen</technical_language>

Target:
public final Session session( AccessMode mode ) { assertOpen(); Session session = newSessionWithMode( mode ); if( closed.get() ) { closeResources(); throw driverCloseException(); } return session; }
Source:
<code>public void should_insert_json_using_prepare_statement() { try (CqlSession session = sessionWithCustomCodec()) { User user = new User(2, "bob", 35); PreparedStatement pst = session.prepare(insertInto("json_jackson_row").json(bindMarker("user")).build()); session.execute(pst.bind().set("user", user, User.class)); List<Row> rows = session.execute(selectFrom("json_jackson_row").json().all().build()).all(); <START> Assertions.assertThat(rows.get(0).get(0, User.class)).isEqualTo(user); <END> } }</code><technical_language>Nit: remove Assertions., method is statically imported. (this in a other places)</technical_language>

Target:
public void should_insert_json_using_prepare_statement() { try (CqlSession session = sessionWithCustomCodec()) { User user = new User(2, "bob", 35); PreparedStatement pst = session.prepare(insertInto("json_jackson_row").json(bindMarker("user")).build()); session.execute(pst.bind().set("user", user, User.class)); List<Row> rows = session.execute(selectFrom("json_jackson_row").json().all().build()).all(); assertThat(rows.get(0).get(0, User.class)).isEqualTo(user); } }
Source:
<code>public CTFStream getStream(Long id) { <START> if( id == null){ <END> return fStreams.get(Long.valueOf(0)); } return fStreams.get(id); }</code><technical_language>spacing *sigh*</technical_language>

Target:
public CTFStream getStream(Long id) { if (id == null) { return fStreams.get(0L); } return fStreams.get(id); }
Source:
<code>public boolean isModified(DirCacheEntry entry, boolean forceContentCheck) { <START> return isModified(entry, false, null); <END> }</code><technical_language>No</technical_language>

Target:
public boolean isModified(DirCacheEntry entry, boolean forceContentCheck) { return isModified(entry, forceContentCheck, null); }
Source:
<code>protected boolean checkAltitudeName(String name) { <START> if (AltitudeSweCoordinateName.isAltitudeSweCoordinateName(name)) { <END> return true; } return CoordinateHelper.getInstance().hasAltitudeName(name); }</code><technical_language>java @VisibleForTesting protected boolean checkAltitudeName(String name) { return AltitudeSweCoordinateName.isAltitudeSweCoordinateName(name) || CoordinateHelper.getInstance().hasAltitudeName(name) }</technical_language>

Target:
protected boolean checkAltitudeName(String name) { return AltitudeSweCoordinateName.isAltitudeSweCoordinateName(name) || CoordinateHelper.getInstance().hasAltitudeName(name); }
Source:
<code>public boolean handleExceptionsForConfiguration(FileformatInterface newFile, Process process) { String rules = ConfigCore.getParameter("copyData.onExport"); if (rules != null && !rules.equals("- keine Konfiguration gefunden -")) { try { new DataCopier(rules).process(new CopierData(newFile, process)); } catch (ConfigurationException e) { <START> logger.error(e.getMessage(), e); <END> Helper.setFehlerMeldung("dataCopier.syntaxError", e.getMessage()); return false; } catch (RuntimeException e) { logger.error(e.getMessage(), e); Helper.setFehlerMeldung("dataCopier.runtimeException", e.getMessage()); return false; } } return true; }</code><technical_language>setErrorMessage</technical_language>

Target:
public boolean handleExceptionsForConfiguration(FileformatInterface newFile, Process process) { String rules = ConfigCore.getParameter("copyData.onExport"); if (rules != null && !rules.equals("- keine Konfiguration gefunden -")) { try { new DataCopier(rules).process(new CopierData(newFile, process)); } catch (ConfigurationException e) { Helper.setErrorMessage("dataCopier.syntaxError", logger, e); return false; } catch (RuntimeException e) { Helper.setErrorMessage("dataCopier.runtimeException", logger, e); return false; } } return true; }
Source:
<code>public void shouldSetRecordMetadata() { testDriver = new TopologyTestDriver(setupSingleProcessorTopology(), config); testDriver.pipeInput(consumerRecord1); final List<String> processedRecords = supplier.theCapturedProcessor().processed; assertEquals(1, processedRecords.size()); final String record = processedRecords.get(0); <START> final String expectedResult = MockProcessor.makeRecord(consumerRecord1.key(), consumerRecord1.value(), consumerRecord1.timestamp()); <END> assertThat(record, equalTo(expectedResult)); }</code><technical_language>nit: import makeRecord</technical_language>

Target:
public void shouldSetRecordMetadata() { testDriver = new TopologyTestDriver(setupSingleProcessorTopology(), config); testDriver.pipeInput(consumerRecord1); final List<Record> processedRecords = mockProcessors.get(0).processedRecords; assertEquals(1, processedRecords.size()); final Record record = processedRecords.get(0); final Record expectedResult = new Record(consumerRecord1, 0L); assertThat(record, equalTo(expectedResult)); }
Source:
<code>protected long getParentDid() { long deckID; <START> deckID = getCol().getDecks().selected(); <END> return deckID; }</code><technical_language>this declaration - line suggestion long deckID = getCol().getDecks().selected();</technical_language>

Target:
protected long getParentDid() { long deckID = getCol().getDecks().selected(); return deckID; }
Source:
<code>public JPAPlaceholderResolverStrategy(String persistenceUnit, ClassLoader cl) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(cl); this.emf = Persistence.createEntityManagerFactory(persistenceUnit); initializeManagedClasses(); this.closeEmf = true; } finally { Thread.currentThread().setContextClassLoader(tccl); } this.classLoader = cl; <START> this.name += ":" + persistenceUnit; <END> }</code><technical_language>I this is breaking compatibility register name persisted this change I additional cunstructor break existing sessions</technical_language>

Target:
public JPAPlaceholderResolverStrategy(String persistenceUnit, ClassLoader cl) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(cl); this.emf = Persistence.createEntityManagerFactory(persistenceUnit); initializeManagedClasses(); this.closeEmf = true; } finally { Thread.currentThread().setContextClassLoader(tccl); } this.classLoader = cl; }
Source:
<code>private static void ensureNoneIsMarkedAsDefault(QualityProfileDto profile, List<QualityProfileDto> descendants) { if (profile.isDefault()) { <START> throw new IllegalArgumentException("Profile is marked as 'default' and cannot be deleted"); <END> } descendants.stream() .filter(QualityProfileDto::isDefault) .findFirst() .ifPresent(p -> { throw new IllegalArgumentException("Profile cannot be deleted because its descendant named [" + p.getName() + "] is marked as 'default'"); }); }</code><technical_language>replace checkArgument</technical_language>

Target:
private static void ensureNoneIsMarkedAsDefault(QualityProfileDto profile, List<QualityProfileDto> descendants) { checkArgument(!profile.isDefault(), "Profile '%s' cannot be deleted because it is marked as default", profile.getName()); descendants.stream() .filter(QualityProfileDto::isDefault) .findFirst() .ifPresent(p -> { throw new IllegalArgumentException(String.format("Profile '%s' cannot be deleted because its descendant named '%s' is marked as default", profile.getName(), p.getName())); }); }
Source:
<code>@Override protected MetadataMarshalled run(@Nullable MetadataTypeArgs arg) throws IgniteException { try { if (future == null) { ignite.context().security().authorize(null, SecurityPermission.ADMIN_METADATA_OPS); assert Objects.nonNull(arg); int typeId = arg.typeId(ignite.context()); BinaryMetadata meta = ((CacheObjectBinaryProcessorImpl)ignite.context().cacheObjects()) .binaryMetadata(typeId); byte[] marshalled = U.marshal(ignite.context(), meta); res = new MetadataMarshalled(marshalled, meta); ignite.context().cacheObjects().removeType(typeId); future = ignite.compute().broadcastAsync(new DropAllThinSessionsJob());; jobCtx.holdcc(); future.listen(new IgniteInClosure<IgniteFuture<Void>>() { <START> @Override public void apply(IgniteFuture<Void> f) { <END> if (f.isDone()) jobCtx.callcc(); } }); return null; } return res; } catch (IgniteCheckedException e) { throw new IgniteException(e); } }</code><technical_language>Is lamda IgniteInClosure is non-functional interface</technical_language>

Target:
@Override protected MetadataMarshalled run(@Nullable MetadataTypeArgs arg) throws IgniteException { try { if (future == null) { ignite.context().security().authorize(null, SecurityPermission.ADMIN_METADATA_OPS); assert Objects.nonNull(arg); int typeId = arg.typeId(ignite.context()); BinaryMetadata meta = ((CacheObjectBinaryProcessorImpl)ignite.context().cacheObjects()) .binaryMetadata(typeId); byte[] marshalled = U.marshal(ignite.context(), meta); res = new MetadataMarshalled(marshalled, meta); ignite.context().cacheObjects().removeType(typeId); future = ignite.compute().broadcastAsync(new DropAllThinSessionsJob()); jobCtx.holdcc(); future.listen((IgniteInClosure<IgniteFuture<Void>>)f -> { if (f.isDone()) jobCtx.callcc(); }); return null; } return res; } catch (IgniteCheckedException e) { throw new IgniteException(e); } }
Source:
<code>Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range, ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions downloadRetryOptions, BlobRequestConditions requestConditions, boolean rangeGetContentMd5, Context context) { BlobRange rangeReal = range == null ? new BlobRange(0) : range; final ParallelTransferOptions finalParallelTransferOptions = ModelHelper.populateAndApplyDefaults(parallelTransferOptions); <START> BlobRequestConditions conditionsReal = requestConditions == null <END> ? new BlobRequestConditions() : requestConditions; AsynchronousFileChannel channel = downloadToFileResourceSupplier(filePath); return Mono.just(channel) .flatMap(c -> this.downloadToFileImpl(c, rangeReal, finalParallelTransferOptions, downloadRetryOptions, conditionsReal, rangeGetContentMd5, context)) .doFinally(signalType -> this.downloadToFileCleanup(channel, filePath, signalType)); }</code><technical_language>name finalRequestConditions something? conditionsReal sounds a odd</technical_language>

Target:
Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range, ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions downloadRetryOptions, BlobRequestConditions requestConditions, boolean rangeGetContentMd5, Context context) { BlobRange finalRange = range == null ? new BlobRange(0) : range; final ParallelTransferOptions finalParallelTransferOptions = ModelHelper.populateAndApplyDefaults(parallelTransferOptions); BlobRequestConditions finalConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; AsynchronousFileChannel channel = downloadToFileResourceSupplier(filePath); return Mono.just(channel) .flatMap(c -> this.downloadToFileImpl(c, finalRange, finalParallelTransferOptions, downloadRetryOptions, finalConditions, rangeGetContentMd5, context)) .doFinally(signalType -> this.downloadToFileCleanup(channel, filePath, signalType)); }
Source:
<code>boolean useNonce(final String nonce, byte[] salt) throws AuthenticationMechanismException { try { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); ByteIterator byteIterator = CodePointIterator.ofChars(nonce.toCharArray()).base64Decode(); byte[] nonceBytes = byteIterator.drain(); if (nonceBytes.length != PREFIX_LENGTH + messageDigest.getDigestLength()) { throw log.invalidNonceLength(HttpConstants.DIGEST_NAME); } <START> long age = System.currentTimeMillis() - ByteBuffer.wrap(nonceBytes, Integer.BYTES, Long.BYTES).getLong(); <END> if (age < 0 || age > validityPeriod) { log.tracef("Nonce %s rejected due to age %d being less than 0 or greater than the validity period %d", nonce, age, validityPeriod); return false; } if (Arrays2.equals(nonceBytes, PREFIX_LENGTH, digest(nonceBytes, 0, PREFIX_LENGTH, salt, messageDigest)) == false) { if (log.isTraceEnabled()) { log.tracef("Nonce %s rejected due to failed comparison using secret key with seed %s.", nonce, new String(salt, StandardCharsets.UTF_8)); } return false; } if (singleUse) { synchronized(usedNonces) { boolean used = usedNonces.add(nonce); if (used) { executor.schedule(() -> { synchronized(usedNonces) { usedNonces.remove(nonce); } }, validityPeriod - age, TimeUnit.MILLISECONDS); } else { log.tracef("Nonce %s rejected as previously used.", nonce); } return used; } } return true; } catch (GeneralSecurityException e) { throw new IllegalStateException(e); } }</code><technical_language>For age based expiry important System.nanoTime()</technical_language>

Target:
boolean useNonce(final String nonce, byte[] salt) throws AuthenticationMechanismException { try { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); ByteIterator byteIterator = CodePointIterator.ofChars(nonce.toCharArray()).base64Decode(); byte[] nonceBytes = byteIterator.drain(); if (nonceBytes.length != PREFIX_LENGTH + messageDigest.getDigestLength()) { throw log.invalidNonceLength(HttpConstants.DIGEST_NAME); } long age = System.nanoTime() - ByteBuffer.wrap(nonceBytes, Integer.BYTES, Long.BYTES).getLong(); if (age < 0 || age > validityPeriodNano) { log.tracef("Nonce %s rejected due to age %d (ns) being less than 0 or greater than the validity period %d (ns)", nonce, age, validityPeriodNano); return false; } if (Arrays2.equals(nonceBytes, PREFIX_LENGTH, digest(nonceBytes, 0, PREFIX_LENGTH, salt, messageDigest)) == false) { if (log.isTraceEnabled()) { log.tracef("Nonce %s rejected due to failed comparison using secret key with seed %s.", nonce, new String(salt, StandardCharsets.UTF_8)); } return false; } if (singleUse) { synchronized(usedNonces) { boolean used = usedNonces.add(nonce); if (used) { executor.schedule(() -> { synchronized(usedNonces) { usedNonces.remove(nonce); } }, validityPeriodNano - age, TimeUnit.MILLISECONDS); } else { log.tracef("Nonce %s rejected as previously used.", nonce); } return used; } } return true; } catch (GeneralSecurityException e) { throw new IllegalStateException(e); } }
Source:
<code><START> protected abstract OutputStream getOutputStreamInternal(RepositoryPath repositoryPath) <END> throws IOException; protected final RepositoryOutputStream decorate(RepositoryPath repositoryPath, OutputStream os) throws IOException { if (os == null || os instanceof RepositoryOutputStream) { return (RepositoryOutputStream) os; } String path = RepositoryFiles.stringValue(repositoryPath); return RepositoryOutputStream.of(repositoryPath.getRepository(), path, os).with(this); }</code><technical_language>is necessary rename methods</technical_language>

Target:
protected abstract OutputStream getOutputStreamInternal(RepositoryPath repositoryPath) throws IOException; protected final RepositoryOutputStream decorate(RepositoryPath repositoryPath, OutputStream os) throws IOException { if (os == null || os instanceof RepositoryOutputStream) { return (RepositoryOutputStream) os; } return RepositoryOutputStream.of(repositoryPath, os).with(this); }
Source:
<code>public void run() { try { <START> Pattern pattern = Pattern.compile(".*rpc-response.*"); <END> consumer.subscribe(pattern); while (!closed.get()) { ConsumerRecords<String, byte[]> records = consumer.poll(Long.MAX_VALUE); for (ConsumerRecord<String, byte[]> record : records) { RpcMessageProtos.RpcMessage rpcMessage = RpcMessageProtos.RpcMessage.parseFrom(record.value()); ResponseCallback responseCb = rpcResponseMap.get(rpcMessage.getRpcId()); if (responseCb != null) { responseCb.sendResponse(rpcMessage.getRpcContent().toStringUtf8()); } } } } catch (WakeupException e) { if (!closed.get()) { throw e; } } catch (InvalidProtocolBufferException e) { LOG.error("Error while parsing response", e); } finally { LOG.info("closing kafka consumer"); consumer.close(); } }</code><technical_language>this match topics 'rpc-response' *anywhere* in name</technical_language>

Target:
public void run() { Logging.putPrefix(RpcClientFactory.LOG_PREFIX); if (topics.isEmpty()) { while (!topicAdded.get()) { try { firstTopicAdded.await(1, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.info("Interrupted before first topic was added. Terminating Kafka RPC consumer thread."); return; } } LOG.info("First topic is added, consumer will be started."); } while (!closed.get()) { if (topicAdded.get()) { synchronized (topics) { LOG.info("Subscribing Kafka RPC consumer to topics named: {}", topics); consumer.subscribe(topics); topicAdded.set(false); } } try { ConsumerRecords<String, byte[]> records = consumer.poll(Long.MAX_VALUE); for (ConsumerRecord<String, byte[]> record : records) { ResponseCallback responseCb = rpcResponseMap.get(record.key()); if (responseCb != null) { RpcMessageProtos.RpcMessage rpcMessage = RpcMessageProtos.RpcMessage .parseFrom(record.value()); responseCb.sendResponse(rpcMessage.getRpcContent().toStringUtf8()); } else { LOG.warn("Received a response for request with ID:{}, but no outstanding request was found with this id, The request may have timed out.", record.key()); } } } catch (InvalidProtocolBufferException e) { LOG.error("error while parsing response", e); } catch (WakeupException e) { LOG.info(" consumer got wakeup exception, closed = ", closed.get(), e); } } consumer.close(); }
Source:
<code>private static RowExpressionVisitor<BytecodeNode, Scope> fieldReferenceCompiler( final CallSiteBinder callSiteBinder, final Variable leftPosition, final Variable leftPage, final Variable rightPosition, final Variable rightPage, final int leftBlocksSize) { return new InputReferenceCompiler( (scope, field) -> { if (field < leftBlocksSize) { return leftPage.invoke("getBlock", Block.class, constantInt(field)); } <START> else { <END> return rightPage.invoke("getBlock", Block.class, constantInt(field - leftBlocksSize)); } }, (scope, field) -> field < leftBlocksSize ? leftPosition : rightPosition, callSiteBinder); }</code><technical_language>Redundant else</technical_language>

Target:
private static RowExpressionVisitor<BytecodeNode, Scope> fieldReferenceCompiler( final CallSiteBinder callSiteBinder, final Variable leftPosition, final Variable leftPage, final Variable rightPosition, final Variable rightPage, final int leftBlocksSize) { return new InputReferenceCompiler( (scope, field) -> { if (field < leftBlocksSize) { return leftPage.invoke("getBlock", Block.class, constantInt(field)); } return rightPage.invoke("getBlock", Block.class, constantInt(field - leftBlocksSize)); }, (scope, field) -> field < leftBlocksSize ? leftPosition : rightPosition, callSiteBinder); }