auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void run() { resetGlobalProgress(); indexingAll = true; for (ObjectType objectType : ObjectType.values()) { startIndexing(objectType); } try { sleep(pause); } catch (InterruptedException e) { <START> Thread.currentThread().interrupt(); <END> logger.error("Thread interrupted: " + e.getMessage()); } currentIndexState = ObjectType.NONE; indexingAll = false; pollingChannel.send(INDEXING_FINISHED_MESSAGE); }</code><technical_language>Move this line logging error, in case error get logged</technical_language>

Target:
public void run() { resetGlobalProgress(); indexingAll = true; for (ObjectType objectType : ObjectType.values()) { startIndexing(objectType); } try { sleep(pause); } catch (InterruptedException e) { logger.error("Thread interrupted: " + e.getMessage()); Thread.currentThread().interrupt(); } currentIndexState = ObjectType.NONE; indexingAll = false; pollingChannel.send(INDEXING_FINISHED_MESSAGE); }
Source:
<code>public RqWithoutHeader(final Request req, final CharSequence name) { super( <START> new RqOf( <END> () -> { final Text prefix = new FormattedText( "%s:", new EnglishLowerCase( name.toString() ).string() ); return new Filtered<>( header -> !new EnglishLowerCase(header).string() .startsWith(prefix.asString()), req.head() ); }, req::body ) ); }</code><technical_language>@fanifieiev above</technical_language>

Target:
public RqWithoutHeader(final Request req, final CharSequence name) { super( new RequestOf( () -> { final Text prefix = new FormattedText( "%s:", new Lowered(name.toString()).asString() ); return new Filtered<>( header -> !new Lowered(header).asString() .startsWith(prefix.asString()), req.head() ); }, req::body ) ); }
Source:
<code>public void testTerminationBeforeCacheCreate() throws Exception { CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder() .with(ClusteringServiceConfigurationBuilder.cluster(cluster.getConnectionURI().resolve("/MyCacheManagerName")) .autoCreate() .defaultServerResource("primary-server-resource")); PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false); cacheManager.init(); cluster.getClusterControl().terminateAllServers(); assertExceptionOccurred(IllegalStateException.class, <START> new TimeLimitedTask<Cache<Long, String>>(1000, TimeUnit.SECONDS) { <END> @Override Cache<Long, String> runTask() throws Exception { return cacheManager.createCache("simple-cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .with(ClusteredResourcePoolBuilder.clusteredDedicated(4, MemoryUnit.MB)))); } }) .withRootCauseInstanceOf(TimeoutException.class); }</code><technical_language>want put this sensible</technical_language>

Target:
public void testTerminationBeforeCacheCreate() throws Exception { CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder() .with(ClusteringServiceConfigurationBuilder.cluster(cluster.getConnectionURI().resolve("/MyCacheManagerName")) .autoCreate() .defaultServerResource("primary-server-resource")); PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false); cacheManager.init(); cluster.getClusterControl().terminateAllServers(); assertExceptionOccurred(IllegalStateException.class, new TimeLimitedTask<Cache<Long, String>>(10, TimeUnit.SECONDS) { @Override Cache<Long, String> runTask() throws Exception { return cacheManager.createCache("simple-cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .with(ClusteredResourcePoolBuilder.clusteredDedicated(4, MemoryUnit.MB)))); } }) .withRootCauseInstanceOf(TimeoutException.class); }
Source:
<code>private void validateFormatOptions(ReadableConfig tableOptions) { <START> boolean failOnMissingField = tableOptions.getOptional(FAIL_ON_MISSING_FIELD) .orElse(false); boolean ignoreParseErrors = tableOptions.getOptional(IGNORE_PARSE_ERRORS) .orElse(false); <END> if (ignoreParseErrors && failOnMissingField) { throw new ValidationException(FAIL_ON_MISSING_FIELD.key() + " and " + IGNORE_PARSE_ERRORS.key() + " shouldn't both be true."); } }</code><technical_language>simplified : java boolean failOnMissingField = tableOptions.get(FAIL_ON_MISSING_FIELD); boolean ignoreParseErrors = tableOptions.get(IGNORE_PARSE_ERRORS);</technical_language>

Target:
private void validateFormatOptions(ReadableConfig tableOptions) { boolean failOnMissingField = tableOptions.get(FAIL_ON_MISSING_FIELD); boolean ignoreParseErrors = tableOptions.get(IGNORE_PARSE_ERRORS); if (ignoreParseErrors && failOnMissingField) { throw new ValidationException(FAIL_ON_MISSING_FIELD.key() + " and " + IGNORE_PARSE_ERRORS.key() + " shouldn't both be true."); } }
Source:
<code>public void setSnippetType(SnippetType type) { switch (type) { case CAMELCASE: snippetGenerator = new CamelCaseSnippetGenerator(new JavaSnippet()); break; <START> default: <END> snippetGenerator = new SnippetGenerator(new JavaSnippet()); break; } this.snippetType = type; }</code><technical_language>case UNDERSCORE. default throw CucumberException</technical_language>

Target:
public void setSnippetType(SnippetType type) { switch (type) { case CAMELCASE: snippetGenerator = new SnippetGenerator(new JavaSnippet(), new CamelCaseFunctionNameSanitizer()); break; case UNDERSCORE: snippetGenerator = new SnippetGenerator(new JavaSnippet(), new UnderscoreFunctionNameSanitizer()); break; default: throw new CucumberException(String.format("Unsupported Snippet Type: %s", type.toString())); } }
Source:
<code>protected void doRun() throws IOException { Jenkins instance = Jenkins.get(); if (instance.clouds != null) { for (Cloud cloud : instance.clouds) { if (cloud instanceof EC2Cloud) { EC2Cloud ec2_cloud = (EC2Cloud) cloud; <START> LOGGER.finer("Checking EC2 Connection on: " + ec2_cloud.getDisplayName()); <END> try { if(ec2_cloud.connection != null) { ec2_cloud.connection.describeInstances(); } } catch (AmazonClientException e) { LOGGER.finer("Reconnecting to EC2 on: " + ec2_cloud.getDisplayName()); ec2_cloud.reconnectToEc2(); } } } } }</code><technical_language>suggestion LOGGER.finer(() -> "Checking EC2 Connection on: " + ec2_cloud.getDisplayName()); Lazy logging message construction for log levels</technical_language>

Target:
protected void doRun() throws IOException { Jenkins instance = Jenkins.get(); if (instance.clouds != null) { for (Cloud cloud : instance.clouds) { if (cloud instanceof EC2Cloud) { EC2Cloud ec2_cloud = (EC2Cloud) cloud; LOGGER.finer(() -> "Checking EC2 Connection on: " + ec2_cloud.getDisplayName()); try { if(ec2_cloud.connection != null) { ec2_cloud.connection.describeInstances(); } } catch (AmazonClientException e) { LOGGER.finer(() -> "Reconnecting to EC2 on: " + ec2_cloud.getDisplayName()); ec2_cloud.reconnectToEc2(); } } } } }
Source:
<code>void setState(ParseObject.State newState) { if (isCurrentUser() && getSessionToken() != null && newState.get(KEY_SESSION_TOKEN) == null) { newState = newState.newBuilder().put(KEY_SESSION_TOKEN, getSessionToken()).build(); } if (isCurrentUser() && getAuthData() != null && newState.get(KEY_AUTH_DATA) == null) { <START> newState = newState.newBuilder().put(KEY_AUTH_DATA, getAuthData()).build(); <END> } super.setState(newState); }</code><technical_language>Nit: move isCurrentUser() check out a level do</technical_language>

Target:
void setState(ParseObject.State newState) { if (isCurrentUser()) { State.Builder newStateBuilder = newState.newBuilder(); if (getSessionToken() != null && newState.get(KEY_SESSION_TOKEN) == null) { newStateBuilder.put(KEY_SESSION_TOKEN, getSessionToken()); } if (getAuthData() != null && newState.get(KEY_AUTH_DATA) == null) { newStateBuilder.put(KEY_AUTH_DATA, getAuthData()); } newState = newStateBuilder.build(); } super.setState(newState); }
Source:
<code>protected StudentAttributes getStudentOfCourseFromRequest(String courseId) { if (userInfo == null && StringHelper.isEmpty(getRequestParamValue(Const.ParamsNames.REGKEY))) { <START> throw new UnauthorizedAccessException("Student account is required to access this resource."); <END> } String moderatedPerson = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON); String previewAsPerson = getRequestParamValue(Const.ParamsNames.PREVIEWAS); if (!StringHelper.isEmpty(moderatedPerson)) { return logic.getStudentForEmail(courseId, moderatedPerson); } else if (!StringHelper.isEmpty(previewAsPerson)) { return logic.getStudentForEmail(courseId, previewAsPerson); } else { return getUnregisteredStudent().orElseGet(() -> logic.getStudentForGoogleId(courseId, userInfo.getId())); } }</code><technical_language>error message is correct instructor call method access moderated/preview person. Actually, I is method's responsibility verify login privilege here. long pre-condition for getStudentOfCourseFromRequest is fulfilled, executed. i.e. - login check verified orElseGet - Other login privilege check in checkAccessControlForStudentFeedbackSubmission (e.g., verify is logged in access preview person)</technical_language>

Target:
protected StudentAttributes getStudentOfCourseFromRequest(String courseId) { String moderatedPerson = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON); String previewAsPerson = getRequestParamValue(Const.ParamsNames.PREVIEWAS); if (!StringHelper.isEmpty(moderatedPerson)) { return logic.getStudentForEmail(courseId, moderatedPerson); } else if (!StringHelper.isEmpty(previewAsPerson)) { return logic.getStudentForEmail(courseId, previewAsPerson); } else { return getUnregisteredStudent().orElseGet(() -> { gateKeeper.verifyLoggedInUserPrivileges(); return logic.getStudentForGoogleId(courseId, userInfo.getId()); }); } }
Source:
<code>public <T> void serialize(T event, @Nullable String token, JsonGenerator jsonGenerator) throws IOException { requireNonNull(event, "event is null"); requireNonNull(jsonGenerator, "jsonGenerator is null"); TraceToken traceToken = null; if (token != null) { try (TraceTokenScope scope = registerRequestToken(token)) { <START> traceToken = getCurrentTraceToken(); <END> } } JsonSerializer<T> serializer = getSerializer(event, traceToken); if (serializer == null) { throw new InvalidEventException("Event class [%s] has not been registered as an event", event.getClass().getName()); } serializer.serialize(event, jsonGenerator, null); }</code><technical_language>call serialize(event, getCurrentTraceToken(), jsonGenerator) avoid duplicated code flavors of serialize()</technical_language>

Target:
public <T> void serialize(T event, @Nullable String token, JsonGenerator jsonGenerator) throws IOException { requireNonNull(event, "event is null"); requireNonNull(jsonGenerator, "jsonGenerator is null"); TraceToken traceToken = null; if (token != null) { try (TraceTokenScope scope = registerRequestToken(token)) { traceToken = getCurrentTraceToken(); } } serialize(event, traceToken, jsonGenerator); }
Source:
<code>public void testGetRows_manyColumnRows() { TableReference tableReference = TableReference.createFromFullyQualifiedName("test." + RandomStringUtils.randomAlphanumeric(16)); keyValueService.createTable(tableReference, AtlasDbConstants.GENERIC_TABLE_METADATA); byte[] data = PtBytes.toBytes("data"); <START> ImmutableListMultimap.Builder builder = ImmutableListMultimap.<Cell, Value>builder(); <END> IntStream stream = IntStream.rangeClosed(1, 1000); byte[] row1 = row(1); Map<Cell, Value> tableValues = stream.mapToObj( col -> Cell.create(row1, column(col))) .collect(Collectors.toMap( cell -> cell, cell -> Value.create(data, 1L))); keyValueService.putWithTimestamps(tableReference, KeyedStream.stream(tableValues).collectToSetMultimap()); Map<Cell, Value> result = keyValueService.getRows( tableReference, ImmutableList.of(row1), ColumnSelection.all(), STARTING_ATLAS_TIMESTAMP - 1); assertThat(result).isEqualTo(tableValues); }</code><technical_language>suggestion unused</technical_language>

Target:
public void testGetRows_manyColumnRows() { TableReference tableReference = TableReference.createFromFullyQualifiedName("test." + RandomStringUtils.randomAlphanumeric(16)); keyValueService.createTable(tableReference, AtlasDbConstants.GENERIC_TABLE_METADATA); byte[] data = PtBytes.toBytes("data"); IntStream stream = IntStream.rangeClosed(1, 1000); byte[] row1 = row(1); Map<Cell, Value> tableValues = stream.mapToObj( col -> Cell.create(row1, column(col))) .collect(Collectors.toMap( cell -> cell, cell -> Value.create(data, 1L))); keyValueService.putWithTimestamps(tableReference, KeyedStream.stream(tableValues).collectToSetMultimap()); Map<Cell, Value> result = keyValueService.getRows( tableReference, ImmutableList.of(row1), ColumnSelection.all(), STARTING_ATLAS_TIMESTAMP - 1); assertThat(result).isEqualTo(tableValues); }
Source:
<code>private OrganizationDto insertOrganization(DbSession dbSession, NewOrganization newOrganization, Consumer<OrganizationDto>... extendCreation) { OrganizationDto res = new OrganizationDto() .setUuid(uuidFactory.create()) .setName(newOrganization.getName()) .setKey(newOrganization.getKey()) .setDescription(newOrganization.getDescription()) .setUrl(newOrganization.getUrl()) <START> .setDefaultQualityGateUuid(qualityGateFinder.getBuiltInQualityGate(dbSession).getUuid()) <END> .setAvatarUrl(newOrganization.getAvatar()); Arrays.stream(extendCreation).forEach(c -> c.accept(res)); dbClient.organizationDao().insert(dbSession, res, false); return res; }</code><technical_language>This update done in another commit, "Set built-in QG default of organization, set ORG#DEFAULT_QG column nullable</technical_language>

Target:
private OrganizationDto insertOrganization(DbSession dbSession, NewOrganization newOrganization, Consumer<OrganizationDto>... extendCreation) { OrganizationDto res = new OrganizationDto() .setUuid(uuidFactory.create()) .setName(newOrganization.getName()) .setKey(newOrganization.getKey()) .setDescription(newOrganization.getDescription()) .setUrl(newOrganization.getUrl()) .setAvatarUrl(newOrganization.getAvatar()); Arrays.stream(extendCreation).forEach(c -> c.accept(res)); dbClient.organizationDao().insert(dbSession, res, false); return res; }
Source:
<code>public void testIncrementalOAuth() throws Exception { DbxPKCEWebAuth auth = new DbxPKCEWebAuth(CONFIG, APP); String authUrl = auth.authorize( DbxWebAuth.newRequestBuilder() .withNoRedirect() .withScope("account.info.read") <START> .withIncludeGrantedScopes(IncludeGrantedScopes.USER) <END> .build() ); Map<String, List<String>> params = toParamsMap(new URL(authUrl)); assertEquals(params.get("include_granted_scopes"), Collections.singletonList("user")); }</code><technical_language>this is attempt, this fail if include attempt</technical_language>

Target:
public void testIncrementalOAuth() throws Exception { DbxPKCEWebAuth auth = new DbxPKCEWebAuth(CONFIG, APP); String authUrl = auth.authorize( DbxWebAuth.newRequestBuilder() .withNoRedirect() .withScope("account.info.read") .withIncludeGrantedScopes(IncludeGrantedScopes.USER) .build() ); Map<String, List<String>> params = toParamsMap(new URL(authUrl)); assertEquals(params.get("client_id"), Collections.singletonList(APP.getKey())); assertEquals(params.get("response_type"), Collections.singletonList("code")); assertEquals(params.get("scope"), Collections.singletonList("account.info.read")); assertEquals(params.get("include_granted_scopes"), Collections.singletonList("user")); assertFalse(params.containsKey("redirect_uri")); assertFalse(params.containsKey("state")); assertFalse(params.containsKey("require_role")); assertFalse(params.containsKey("force_reapprove")); assertFalse(params.containsKey("disable_signup")); assertFalse(params.containsKey("token_access_type")); assertNotNull(params.get("code_challenge")); assertEquals(params.get("code_challenge_method"), Collections.singletonList("S256")); }
Source:
<code>public static Class<? extends Datum> getDatumClass(Type type) { switch (type) { case BOOLEAN: return BooleanDatum.class; case INT2: return Int2Datum.class; case INT4: return Int4Datum.class; case INT8: return Int8Datum.class; case FLOAT4: return Float4Datum.class; case FLOAT8: return Float8Datum.class; case CHAR: return CharDatum.class; case TEXT: return TextDatum.class; case TIMESTAMP: return TimestampDatum.class; case INTERVAL: return IntervalDatum.class; case DATE: return DateDatum.class; case TIME: return TimeDatum.class; case BIT: return BitDatum.class; case BLOB: return BlobDatum.class; case INET4: return Inet4Datum.class; case ANY: return AnyDatum.class; case NULL_TYPE: return NullDatum.class; default: <START> throw new TajoRuntimeException(Errors.ResultCode.UNSUPPORTED_DATATYPE, type.name()); <END> } }</code><technical_language>new TajoRuntimeException(new UnsupportedDataType(...)</technical_language>

Target:
public static Class<? extends Datum> getDatumClass(Type type) { switch (type) { case BOOLEAN: return BooleanDatum.class; case INT2: return Int2Datum.class; case INT4: return Int4Datum.class; case INT8: return Int8Datum.class; case FLOAT4: return Float4Datum.class; case FLOAT8: return Float8Datum.class; case CHAR: return CharDatum.class; case TEXT: return TextDatum.class; case TIMESTAMP: return TimestampDatum.class; case INTERVAL: return IntervalDatum.class; case DATE: return DateDatum.class; case TIME: return TimeDatum.class; case BIT: return BitDatum.class; case BLOB: return BlobDatum.class; case INET4: return Inet4Datum.class; case ANY: return AnyDatum.class; case NULL_TYPE: return NullDatum.class; default: throw new TajoRuntimeException(new UnsupportedDataTypeException(type.name())); } }
Source:
<code>public boolean isFileDeletable(FileStatus fStat) { try { <START> lock.readLock().lock(); <END> if (this.fs == null) return false; Path filePath = fStat.getPath(); if (HFileLink.isHFileLink(filePath)) return true; Path parentDir = filePath.getParent(); if (HFileLink.isBackReferencesDir(parentDir)) { Path hfilePath = null; try { hfilePath = HFileLink.getHFileFromBackReference(new Path(CommonFSUtils.getRootDir(getConf()), HConstants.HBASE_TEMP_DIRECTORY), filePath); if (fs.exists(hfilePath)) { return false; } hfilePath = HFileLink.getHFileFromBackReference(MobUtils.getMobHome(getConf()), filePath); if (fs.exists(hfilePath)) { return false; } hfilePath = HFileLink.getHFileFromBackReference(CommonFSUtils.getRootDir(getConf()), filePath); return !fs.exists(hfilePath); } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug("Couldn't verify if the referenced file still exists, keep it just in case: " + hfilePath); } return false; } } Path backRefDir = null; try { backRefDir = HFileLink.getBackReferencesDir(parentDir, filePath.getName()); return CommonFSUtils.listStatus(fs, backRefDir) == null; } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug( "Couldn't get the references, not deleting file, just in case. filePath=" + filePath + ", backRefDir=" + backRefDir); } return false; } } finally { lock.readLock().unlock(); } }</code><technical_language>put this line try block</technical_language>

Target:
public boolean isFileDeletable(FileStatus fStat) { lock.readLock().lock(); try { if (this.fs == null) { return false; } Path filePath = fStat.getPath(); if (HFileLink.isHFileLink(filePath)) { return true; } Path parentDir = filePath.getParent(); if (HFileLink.isBackReferencesDir(parentDir)) { Path hfilePath = null; try { hfilePath = HFileLink.getHFileFromBackReference(new Path( CommonFSUtils.getRootDir(getConf()), HConstants.HBASE_TEMP_DIRECTORY), filePath); if (fs.exists(hfilePath)) { return false; } hfilePath = HFileLink.getHFileFromBackReference(MobUtils.getMobHome(getConf()), filePath); if (fs.exists(hfilePath)) { return false; } hfilePath = HFileLink.getHFileFromBackReference(CommonFSUtils.getRootDir(getConf()), filePath); return !fs.exists(hfilePath); } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug("Couldn't verify if the referenced file still exists, keep it just in case: " + hfilePath); } return false; } } Path backRefDir = null; try { backRefDir = HFileLink.getBackReferencesDir(parentDir, filePath.getName()); return CommonFSUtils.listStatus(fs, backRefDir) == null; } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug( "Couldn't get the references, not deleting file, just in case. filePath=" + filePath + ", backRefDir=" + backRefDir); } return false; } } finally { lock.readLock().unlock(); } }
Source:
<code>public XAStore(Class<K> keyType, Class<V> valueType, Store<K, SoftLock<V>> underlyingStore, TransactionManagerWrapper transactionManagerWrapper, TimeSource timeSource, Journal<K> journal, String uniqueXAResourceId, StatisticsService statisticsService) { super(keyType, valueType, true, statisticsService); this.underlyingStore = underlyingStore; this.transactionManagerWrapper = transactionManagerWrapper; this.timeSource = timeSource; this.journal = journal; this.uniqueXAResourceId = uniqueXAResourceId; this.transactionContextFactory = new XATransactionContextFactory<>(timeSource); this.recoveryXaResource = new EhcacheXAResource<>(underlyingStore, journal, transactionContextFactory); this.eventSourceWrapper = new StoreEventSourceWrapper<>(underlyingStore.getStoreEventSource()); <START> this.statisticsService.registerWithParent(underlyingStore, this); <END> }</code><technical_language>other stores registration done in provider... is this different</technical_language>

Target:
public XAStore(Class<K> keyType, Class<V> valueType, Store<K, SoftLock<V>> underlyingStore, TransactionManagerWrapper transactionManagerWrapper, TimeSource timeSource, Journal<K> journal, String uniqueXAResourceId, StatisticsService statisticsService) { super(keyType, valueType, true, statisticsService); this.underlyingStore = underlyingStore; this.transactionManagerWrapper = transactionManagerWrapper; this.timeSource = timeSource; this.journal = journal; this.uniqueXAResourceId = uniqueXAResourceId; this.transactionContextFactory = new XATransactionContextFactory<>(timeSource); this.recoveryXaResource = new EhcacheXAResource<>(underlyingStore, journal, transactionContextFactory); this.eventSourceWrapper = new StoreEventSourceWrapper<>(underlyingStore.getStoreEventSource()); }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final String token = tokenExtractor.getToken(httpRequest); if (shouldSkipAuthentication(httpRequest, token)) { filterChain.doFilter(request, response); return; } final HttpSession session = httpRequest.getSession(); Subject subject = (Subject) session.getAttribute("che_subject"); if (subject == null || !subject.getToken().equals(token)) { Jwt jwtToken = (Jwt) httpRequest.getAttribute("token"); if (jwtToken == null) { throw new ServletException("Cannot detect or instantiate user."); } Claims claims = (Claims) jwtToken.getBody(); try { User user = getOrCreateUser( claims.getSubject(), claims.get("email", String.class), claims.get("preferred_username", String.class)); subject = new AuthorizedSubject( new SubjectImpl(user.getName(), user.getId(), token, false), permissionChecker); workspaceSubjectRegistry.updateSubject(subject); session.setAttribute("che_subject", subject); } catch (ServerException | ConflictException e) { throw new ServletException( "Unable to identify user " + claims.getSubject() + " in Che database", e); } } <START> putIdentityIdToMDC(subject); <END> try { EnvironmentContext.getCurrent().setSubject(subject); filterChain.doFilter(addUserInRequest(httpRequest, subject), response); } finally { EnvironmentContext.reset(); } }</code><technical_language>I replace MDC.put(IDENTITY_ID_MDC_KEY, subject.getUserId());</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final String token = tokenExtractor.getToken(httpRequest); if (shouldSkipAuthentication(httpRequest, token)) { filterChain.doFilter(request, response); return; } final HttpSession session = httpRequest.getSession(); Subject subject = (Subject) session.getAttribute("che_subject"); if (subject == null || !subject.getToken().equals(token)) { Jwt jwtToken = (Jwt) httpRequest.getAttribute("token"); if (jwtToken == null) { throw new ServletException("Cannot detect or instantiate user."); } Claims claims = (Claims) jwtToken.getBody(); try { User user = getOrCreateUser( claims.getSubject(), claims.get("email", String.class), claims.get("preferred_username", String.class)); subject = new AuthorizedSubject( new SubjectImpl(user.getName(), user.getId(), token, false), permissionChecker); workspaceSubjectRegistry.updateSubject(subject); session.setAttribute("che_subject", subject); } catch (ServerException | ConflictException e) { throw new ServletException( "Unable to identify user " + claims.getSubject() + " in Che database", e); } } try { EnvironmentContext.getCurrent().setSubject(subject); filterChain.doFilter(addUserInRequest(httpRequest, subject), response); } finally { EnvironmentContext.reset(); } }
Source:
<code>public List<PartitionEndStatistics> loadTopicEndStatistics(final Collection<Timeline> timelines) throws ServiceTemporarilyUnavailableException { try { return Retryer.executeWithRetry(() -> { return loadTopicEndStatisticsInternal(timelines); }, new RetryForSpecifiedCountStrategy(3) .withWaitBetweenEachTry(5000) .withExceptionsThatForceRetry(org.apache.kafka.common.errors.TimeoutException.class)); <START> } catch (final Exception e) { <END> throw new ServiceTemporarilyUnavailableException("Error occurred when fetching partitions offsets", e); } }</code><technical_language>RuntimeException</technical_language>

Target:
public List<PartitionEndStatistics> loadTopicEndStatistics(final Collection<Timeline> timelines) throws ServiceTemporarilyUnavailableException { try { return Retryer.executeWithRetry(() -> { return loadTopicEndStatisticsInternal(timelines); }, new RetryForSpecifiedCountStrategy(3) .withWaitBetweenEachTry(5000) .withExceptionsThatForceRetry(org.apache.kafka.common.errors.TimeoutException.class)); } catch (final RuntimeException e) { throw new ServiceTemporarilyUnavailableException("Error occurred when fetching partitions offsets", e); } }
Source:
<code>public AccelerationCap(PDP pdp, double hardStopVoltage, int... channels) { this.pdp = pdp; this.hardStopVoltage = hardStopVoltage; this.channels = channels; <START> disableCurrent = pdp.getTotalCurrent() > AccelerationCap.REASONABLE_RESTING_CURRENT; <END> currentSpeed = 0; voltageDrop = 0; lastUpdate = System.currentTimeMillis(); }</code><technical_language>print a warning if disable current</technical_language>

Target:
public AccelerationCap(PDP pdp, double hardStopVoltage, int... channels) { this.pdp = pdp; this.hardStopVoltage = hardStopVoltage; this.channels = channels; disableCurrent = pdp.getTotalCurrent() > AccelerationCap.REASONABLE_RESTING_CURRENT; if (disableCurrent) { LogKitten.w("Disabling current for AccelerationCap, PDP seems unreliable"); } currentSpeed = 0; voltageDrop = 0; lastVoltageDrop = 0; lastUpdate = System.currentTimeMillis(); }
Source:
<code>public boolean canFlipToNextPage() { if (getNextPage() == null) return false; try { if (!fragment.isComplete()) return false; <START> } catch (Exception e) { <END> return false; } return true; }</code><technical_language>catching Exception is a good idea. a user get report back? log</technical_language>

Target:
public boolean canFlipToNextPage() { if (getNextPage() == null) return false; try { if (!fragment.isComplete()) return false; } catch (Exception e) { Trace.trace(Trace.STRING_WARNING, "Exception caught checking if page is complete", e); return false; } return true; }
Source:
<code>public void testAUserCannotCreateMeetingWithStartTimeLessOfEndTime() { HomeTabletPage home = new HomeTabletPage(); home.clickScheduleBtn() <START> .setOrganizerTxtBox(organizer) <END> .setSubjectTxtBox(subject) .setStartTimeDate(startTime) .setEndTimeDate(endTime) .setAttendeeTxtBoxPressingEnter(attendee) .setBodyTxtBox(body) .clickCreateBtn(); Assert.assertTrue(schedule.isMessageOfTimeErrorDisplayed()); }</code><technical_language>method set values of scheduled page</technical_language>

Target:
public void testAUserCannotCreateMeetingWithStartTimeLessOfEndTime() { ExcelReader excelReader = new ExcelReader(EXCEL_INPUT_DATA); List<Map<String, String>> meetingData = excelReader.getMapValues("MeetingData"); String organizer = meetingData.get(8).get("Organizer"); String subject = meetingData.get(8).get("Subject"); String startTime = meetingData.get(8).get("Start time"); String endTime = meetingData.get(8).get("End time"); String attendee = meetingData.get(8).get("Attendee"); String body = meetingData.get(8).get("Body"); HomeTabletPage homePage = new HomeTabletPage(); SchedulePage schedulePage = homePage.clickScheduleBtn() .setOrganizerTxtBox(organizer) .setSubjectTxtBox(subject) .setStartTimeDate(startTime) .setEndTimeDate(endTime) .setAttendeeTxtBoxPressingEnter(attendee) .setBodyTxtBox(body) .clickCreateBtn(); Assert.assertTrue(schedulePage.isMessageOfTimeErrorDisplayed()); }
Source:
<code>public String getRule() { <START> return "Whenever a source you control other than {this} deals damage to another player, " + super.getRule(); <END> }</code><technical_language>This "to opponent"</technical_language>

Target:
public String getRule() { return "Whenever a source you control other than {this} deals damage to an opponent, " + super.getRule(); }
Source:
<code>void setRevisionSupported(NotebookRepo repo) { <START> if (repo instanceof NotebookRepoWithVersionControl) { <END> getConfig().put("isRevisionSupported", true); } else { getConfig().put("isRevisionSupported", false); } }</code><technical_language>IIUC, repo NotebookRepoSync, NotebookRepoWithVersionControl</technical_language>

Target:
void setRevisionSupported(NotebookRepo repo) { if (repo instanceof NotebookRepoSync) { getConfig() .put("isRevisionSupported", ((NotebookRepoSync) repo).isRevisionSupportedInDefaultRepo()); } else if (repo instanceof NotebookRepoWithVersionControl) { getConfig().put("isRevisionSupported", true); } else { getConfig().put("isRevisionSupported", false); } }
Source:
<code>public Void call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); ac.getGroupsManager().moveGroup(ac.getSession(), <START> ac.getGroupById(parms.readInt("destinationGroup")), <END> ac.getGroupById(parms.readInt("movingGroup"))); return null; }</code><technical_language>in perun-core, is possibility provide null for destinationGroup, retrieve group provided ID. Please destinationGroup param optional (check presence) allow moving groups top-level</technical_language>

Target:
public Group call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); if (parms.contains("parentGroup")) { return ac.getGroupsManager().createGroup(ac.getSession(), ac.getGroupById(parms.readInt("parentGroup")), parms.read("group", Group.class)); } else if (parms.contains("vo")) { Group group = parms.read("group", Group.class); if (group.getParentGroupId() == null) { return ac.getGroupsManager().createGroup(ac.getSession(), ac.getVoById(parms.readInt("vo")), group); } else { throw new RpcException(RpcException.Type.WRONG_PARAMETER, "Top-level groups can't have parentGroupId set!"); } } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "vo or parentGroup"); } }
Source:
<code>public HttpHandler createHttpHandler(Predicate predicate, final HttpHandler next) { final HttpHandler mcmp = managementAccessPredicate != null ? Handlers.predicate(managementAccessPredicate, config.create(modCluster, next), next) : config.create(modCluster, next); final HttpHandler proxyHandler = modCluster.getProxyHandler(); HttpHandler theHandler = new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { proxyHandler.handleRequest(exchange); if(!exchange.isDispatched() && !exchange.isComplete()) { exchange.setResponseCode(200); mcmp.handleRequest(exchange); } } }; <START> UndertowLogger.ROOT_LOGGER.modClusterMCMPHttpHandlerCreated(); <END> if (predicate != null) { return new PredicateHandler(predicate, theHandler, next); } else { return theHandler; } }</code><technical_language>UndertowLogger.ROOT_LOGGER.debug("....");</technical_language>

Target:
public HttpHandler createHttpHandler(Predicate predicate, final HttpHandler next) { final HttpHandler mcmp = managementAccessPredicate != null ? Handlers.predicate(managementAccessPredicate, config.create(modCluster, next), next) : config.create(modCluster, next); final HttpHandler proxyHandler = modCluster.getProxyHandler(); HttpHandler theHandler = new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { proxyHandler.handleRequest(exchange); if(!exchange.isDispatched() && !exchange.isComplete()) { exchange.setResponseCode(200); mcmp.handleRequest(exchange); } } }; UndertowLogger.ROOT_LOGGER.debug("HttpHandler for mod_cluster MCMP created."); if (predicate != null) { return new PredicateHandler(predicate, theHandler, next); } else { return theHandler; } }
Source:
<code>public String getExecutable(final Launcher launcher) throws IOException, InterruptedException { final File exe = launcher.getChannel().call(new MasterToSlaveCallable<File, IOException>() { <START> private static final long serialVersionUID = 5572701806697595613L; <END> @Override public File call() throws IOException { return getExeFile(); } }); final boolean existis = launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() { private static final long serialVersionUID = 5572701806697595613L; @Override public Boolean call() throws IOException { return exe.exists(); } }); if (!existis) { launcher.getListener().error("Gradle executable does not exist: " + exe.getPath()); return null; } else { return exe.getPath(); } }</code><technical_language>is serialVersionUID for? IIUC, Jenkins XStream serialize/deserialize data, Java serialization. is this required</technical_language>

Target:
public String getExecutable(final Launcher launcher) throws IOException, InterruptedException { final File exe = launcher.getChannel().call(new MasterToSlaveCallable<File, IOException>() { @Override public File call() throws IOException { return getExeFile(); } }); final boolean existis = launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() { @Override public Boolean call() throws IOException { return exe.exists(); } }); if (!existis) { launcher.getListener().error("Gradle executable does not exist: " + exe.getPath()); return null; } else { return exe.getPath(); } }
Source:
<code>public List<BibEntry> performSearch(String query) { return fetchers.stream().flatMap(searchBasedFetcher -> { try { return searchBasedFetcher.performSearch(query).stream(); } catch (FetcherException e) { LOGGER.warn(String.format("%s API request failed", searchBasedFetcher.getName()), e); return Stream.empty(); } <START> }).parallel().collect(Collectors.toList()); <END> }</code><technical_language>I add a limit(...) of 30 items here, paged fetcher implemented</technical_language>

Target:
public List<BibEntry> performSearch(String query) { return fetchers.stream().flatMap(searchBasedFetcher -> { try { return searchBasedFetcher.performSearch(query).stream(); } catch (FetcherException e) { LOGGER.warn(String.format("%s API request failed", searchBasedFetcher.getName()), e); return Stream.empty(); } }).parallel() .limit(maximumNumberOfReturnedResults) .collect(Collectors.toList()); }
Source:
<code>public static boolean isExcludedColumn(VerifyTreeData tree, int ind) { List<Integer> excludedColumns = tree.getExcludedColumns(); <START> for (Integer excludedColumn : excludedColumns) { <END> if (excludedColumn.equals(ind)) { return true; } } return false; }</code><technical_language>excludedColumns.contains(Integer.valueOf(ind))</technical_language>

Target:
public static boolean isExcludedColumn(VerifyTreeData tree, int ind) { List<Integer> excludedColumns = tree.getExcludedColumns(); return excludedColumns.contains(ind); }
Source:
<code><START> public void execInitClipboardForm(ClipboardForm form) { <END> }</code><technical_language>This method protected instead of public</technical_language>

Target:
protected void execInitClipboardForm(ClipboardForm form) { }
Source:
<code>public void setUp() throws Exception { <START> DefaultClockModel.updateClockTimerTask.setPaused(true); <END> xsb = Mockito.mock(XmlScoreBoard.class); sbm = new DefaultScoreBoardModel(xsb); sm = sbm.getStatsModel(); sbepm = ScoreBoardEventProviderManager.getSingleton(); }</code><technical_language>fix indentation in this file</technical_language>

Target:
public void setUp() throws Exception { DefaultClockModel.updateClockTimerTask.setPaused(true); ScoreBoardManager.setPropertyOverride(JettyServletScoreBoardController.class.getName() + ".html.dir", "html"); sbm = new DefaultScoreBoardModel(); sm = sbm.getStatsModel(); sbepm = ScoreBoardEventProviderManager.getSingleton(); for(String tid : Arrays.asList(Team.ID_1, Team.ID_2)) { TeamModel tm = sbm.getTeamModel(tid); for (int i = 0; i <= 15; i++) { String number = String.format("%s%02d", tid, i); tm.addSkaterModel(ID_PREFIX + number, "name-" + number, number, ""); } } team1 = sbm.getTeamModel(Team.ID_1); }
Source:
<code>private Inventory getInventory(YamlConfiguration playerFile, int size, int number, String title) { String data = playerFile.getString(String.format(VAULTKEY, number)); if (Base64Serialization.fromBase64(data) == null) { return null; } Inventory inventory = Bukkit.createInventory(null, size, title); <START> for (ItemStack itemStack : Base64Serialization.fromBase64(data).getContents()) { <END> if (itemStack != null) { inventory.addItem(itemStack); } } return inventory; }</code><technical_language>Deserializing data twice</technical_language>

Target:
private Inventory getInventory(YamlConfiguration playerFile, int size, int number, String title) { String data = playerFile.getString(String.format(VAULTKEY, number)); Inventory deserializedData = Base64Serialization.fromBase64(data); if (deserializedData == null) { return null; } Inventory inventory = Bukkit.createInventory(null, size, title); for (ItemStack itemStack : deserializedData.getContents()) { if (itemStack != null) { inventory.addItem(itemStack); } } return inventory; }
Source:
<code>public void testCreateDBAuditObj() { AuditRepositoryOrchImpl auditRepo = new AuditRepositoryOrchImpl(); AssertionType assertion = createAssertion(); LogEventSecureRequestType auditObj = createLogEventSecureObj(assertion); AuditRepositoryRecord dbRec = auditRepo.createDBAuditObj(auditObj, assertion); assertEquals("AuditRepositoryRecord.Direction mismatch", dbRec.getDirection(), auditObj.getDirection()); assertEquals("AuditRepositoryRecord.EventType mismatch", dbRec.getEventType(), EVENT_TYPE); assertEquals("AuditRepositoryRecord.EventId mismatch", dbRec.getEventId(), EVENT_ID_CODE_DISP_NAME); assertEquals("AuditRepositoryRecord.RelatesTo", dbRec.getRelatesTo(), RELATES_TO_1); <START> } <END></code><technical_language>set message Id in assertion verify message Id exists</technical_language>

Target:
public void testCreateDBAuditObj() { AuditRepositoryOrchImpl auditRepo = new AuditRepositoryOrchImpl(); AssertionType assertion = createAssertion(); LogEventSecureRequestType auditObj = createLogEventSecureObj(assertion); AuditRepositoryRecord dbRec = auditRepo.createDBAuditObj(auditObj, assertion); assertEquals("AuditRepositoryRecord.Direction mismatch", dbRec.getDirection(), auditObj.getDirection()); assertEquals("AuditRepositoryRecord.EventType mismatch", dbRec.getEventType(), EVENT_TYPE); assertEquals("AuditRepositoryRecord.EventId mismatch", dbRec.getEventId(), EVENT_ID_CODE_DISP_NAME); assertEquals("AuditRepositoryRecord.RelatesTo", dbRec.getRelatesTo(), RELATES_TO_1); assertNotNull("AuditRepositoryRecord.MessageId", dbRec.getMessageId()); }
Source:
<code>private static void assertDataSketchesAvailable() { try { new StringSketch(); } <START> catch (Throwable t) { <END> throw new ISE(t, "DataSketches is unvailable. Try adding the druid-datasketches extension to the classpath."); } }</code><technical_language>I this catch type of error. I guess ClassNotFoundException caught</technical_language>

Target:
private static void assertDataSketchesAvailable() { try { new StringSketch(); } catch (NoClassDefFoundError e) { throw new ISE( e, "DataSketches is unvailable." + " Try loading the druid-datasketches extension from the classpath for the overlord and middleManagers/indexers." ); } }
Source:
<code>public Permission getRequiredPermission() { <START> return Jenkins.CONFIGURE; <END> }</code><technical_language>I hope sensitive environment variables system properties</technical_language>

Target:
public Permission getRequiredPermission() { return Jenkins.MANAGE; }
Source:
<code>private RollingHistogram getOrAddBucket(String name) { lock.writeLock().lock(); try { <START> RollingHistogram hist = statBuckets.get(name); if (hist == null) { hist = new RollingHistogram(NUM_ROLLING_HISTOGRAMS); statBuckets.put(name, hist); } return hist; <END> } finally { lock.writeLock().unlock(); } }</code><technical_language>I a ConcurrentMap for statBuckets (and putIfAbsent() here) allow get rid of explicit locking (and performance locking more fine grained. require add some locking RollingHistogram (making method synchronized sufficient)</technical_language>

Target:
private RollingHistogram getOrAddBucket(String name) { return statBuckets.computeIfAbsent(name, (n) -> new RollingHistogram(NUM_ROLLING_HISTOGRAMS)); }
Source:
<code>public void testUnApplyStereotypeApplication() { editor = fixture.getEditor(MODEL_DI); fixture.openDiagram("ClassDiagram"); NamedElement stereotypedClass = fixture.getModel().getOwnedMember(STEREOTYPEDCLASS); EditPart stereotypedClassEditPart = fixture.findEditPart(stereotypedClass); for(Object o : stereotypedClassEditPart.getChildren()){ if(o instanceof AppliedStereotypeEmptyEditPart){ assertTrue(STEREOTYPEDCLASS+" do not refer to any AppliedStereotypeEmptyEditPart comment", true); } } <START> assertEquals(STEREOTYPEDCLASS + " has not the right number of children", 5, stereotypedClassEditPart.getChildren().size()); END> NamedElement stereotypedLink = fixture.getModel().getOwnedMember(STEREOTYPEDLINK); EditPart stereotypedLinkEditPart = fixture.findEditPart(stereotypedLink); for(Object o : stereotypedLinkEditPart.getChildren()){ if(o instanceof AppliedStereotypeEmptyEditPart){ assertTrue(STEREOTYPEDLINK+" do not refer to any AppliedStereotypeEmptyEditPart comment", true); } } assertEquals(STEREOTYPEDLINK + " has not the right number of children", 2, stereotypedLinkEditPart.getChildren().size()); }</code><technical_language>explain 5</technical_language>

Target:
public void testUnApplyStereotypeApplication() { fixture.openDiagram("ClassDiagram"); NamedElement stereotypedClass = fixture.getModel().getOwnedMember(STEREOTYPEDCLASS); EditPart stereotypedClassEditPart = fixture.findEditPart(stereotypedClass); for(Object o : stereotypedClassEditPart.getChildren()){ if(o instanceof AppliedStereotypeEmptyEditPart){ assertTrue(STEREOTYPEDCLASS+" do not refer to any AppliedStereotypeEmptyEditPart comment", true); } } assertEquals(STEREOTYPEDCLASS + " has not the right number of children", 5, stereotypedClassEditPart.getChildren().size()); NamedElement stereotypedLink = fixture.getModel().getOwnedMember(STEREOTYPEDLINK); EditPart stereotypedLinkEditPart = fixture.findEditPart(stereotypedLink); for(Object o : stereotypedLinkEditPart.getChildren()){ if(o instanceof AppliedStereotypeEmptyEditPart){ assertTrue(STEREOTYPEDLINK+" do not refer to any AppliedStereotypeEmptyEditPart comment", true); } } assertEquals(STEREOTYPEDLINK + " has not the right number of children", 2, stereotypedLinkEditPart.getChildren().size()); }
Source:
<code>public void trackValuePropLearnMoreTapped(@NonNull String courseId, @Nullable String assignmentId, @NonNull String screenName) { final FirebaseEvent event = new FirebaseEvent(Events.VALUE_PROP_LEARN_MORE_CLICKED, Values.VALUE_PROP_LEARN_MORE_CLICKED); event.putCourseId(courseId); <START> if (assignmentId != null) { <END> event.putString(Keys.ASSIGNMENT_ID, assignmentId); } event.putString(Keys.SCREEN_NAME, screenName); logFirebaseEvent(event.getName(), event.getBundle()); }</code><technical_language>condition replaced !TextUtils.isEmpty(assignmentId)</technical_language>

Target:
public void trackValuePropLearnMoreTapped(@NonNull String courseId, @Nullable String assignmentId, @NonNull String screenName) { final FirebaseEvent event = new FirebaseEvent(Events.VALUE_PROP_LEARN_MORE_CLICKED, Values.VALUE_PROP_LEARN_MORE_CLICKED); event.putCourseId(courseId); if (TextUtils.isEmpty(assignmentId)) { event.putString(Keys.ASSIGNMENT_ID, assignmentId); } event.putString(Keys.SCREEN_NAME, screenName); logFirebaseEvent(event.getName(), event.getBundle()); }
Source:
<code>public void writeInterval(ByteBuffer buffer) { final byte byteFromType = getByteFromType(sv.getType()); buffer.putLong(start); buffer.putLong(end); buffer.putInt(attribute); buffer.put(byteFromType); switch (byteFromType) { case TYPE_NULL: break; case TYPE_INTEGER: buffer.putInt(sv.unboxInt()); break; case TYPE_STRING: String string = sv.unboxStr(); byte[] strArray = string.getBytes(); if (strArray.length > Byte.MAX_VALUE) { <START> throw new IllegalArgumentException("State value string is too long: " + string); END> } buffer.put((byte) strArray.length); buffer.put(strArray); buffer.put((byte) 0); break; case TYPE_LONG: buffer.putLong(sv.unboxLong()); break; case TYPE_DOUBLE: buffer.putDouble(sv.unboxDouble()); break; default: break; } }</code><technical_language>need this check (it arguably before...) casting (byte) below, writing full strArray truncating. check moved constructor though. Illegal*Argument*Exception more sense</technical_language>

Target:
public void writeInterval(ByteBuffer buffer) { final byte byteFromType = getByteFromType(sv.getType()); buffer.putLong(start); buffer.putLong(end); buffer.putInt(attribute); buffer.put(byteFromType); switch (byteFromType) { case TYPE_NULL: break; case TYPE_INTEGER: buffer.putInt(sv.unboxInt()); break; case TYPE_STRING: String string = sv.unboxStr(); byte[] strArray = string.getBytes(); buffer.put((byte) strArray.length); buffer.put(strArray); buffer.put((byte) 0); break; case TYPE_LONG: buffer.putLong(sv.unboxLong()); break; case TYPE_DOUBLE: buffer.putDouble(sv.unboxDouble()); break; default: break; } }