auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String parseToken(final String token) { try { val json = this.cipherExecutor.decode(token); val claims = JwtClaims.parse(json); if (!claims.getIssuer().equals(issuer)) { LOGGER.error("Token issuer does not match CAS"); return null; } if (claims.getAudience().isEmpty() || !claims.getAudience().get(0).equals(issuer)) { LOGGER.error("Token audience does not match CAS"); return null; } if (StringUtils.isBlank(claims.getSubject())) { LOGGER.error("Token has no subject identifier"); return null; } val holder = ClientInfoHolder.getClientInfo(); <START> if (properties.getReset().isCheckServerIpAddress() && !claims.getStringClaimValue("origin").equals(holder.getServerIpAddress())) { LOGGER.error("Token origin server IP address does not match CAS"); return null; } if (properties.getReset().isCheckClientIpAddress() && !claims.getStringClaimValue("client").equals(holder.getClientIpAddress())) { LOGGER.error("Token client IP address does not match CAS"); <END> return null; } val expirationTime = claims.getExpirationTime(); if (expirationTime.isBefore(NumericDate.now())) { LOGGER.error("Token has expired."); return null; } return claims.getSubject(); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }</code><technical_language>Extract properties.getRest() a variable</technical_language>

Target:
public String parseToken(final String token) { try { val json = this.cipherExecutor.decode(token); val claims = JwtClaims.parse(json); val resetProperties = properties.getReset(); if (!claims.getIssuer().equals(issuer)) { LOGGER.error("Token issuer does not match CAS"); return null; } if (claims.getAudience().isEmpty() || !claims.getAudience().get(0).equals(issuer)) { LOGGER.error("Token audience does not match CAS"); return null; } if (StringUtils.isBlank(claims.getSubject())) { LOGGER.error("Token has no subject identifier"); return null; } val holder = ClientInfoHolder.getClientInfo(); if (resetProperties.isIncludeServerIpAddress() && !claims.getStringClaimValue("origin").equals(holder.getServerIpAddress())) { LOGGER.error("Token origin server IP address does not match CAS"); return null; } if (resetProperties.isIncludeClientIpAddress() && !claims.getStringClaimValue("client").equals(holder.getClientIpAddress())) { LOGGER.error("Token client IP address does not match CAS"); return null; } val expirationTime = claims.getExpirationTime(); if (expirationTime.isBefore(NumericDate.now())) { LOGGER.error("Token has expired."); return null; } return claims.getSubject(); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
Source:
<code>public double computeWithResultOption(MetricKey<O> key, T node, MetricOptions options, ResultOption resultOption) { Objects.requireNonNull(key, "The metric key must not be null"); Objects.requireNonNull(resultOption, "The result option must not be null"); <START> MetricOptions safeOptions = options == null ? MetricOptions.emptyOptions() : options; <END> return getLanguageSpecificComputer().computeWithResultOption(key, node, false, safeOptions, resultOption, getLanguageSpecificProjectMemoizer()); }</code><technical_language>Consider making options parameter required</technical_language>

Target:
public double computeWithResultOption(MetricKey<O> key, T node, MetricOptions options, ResultOption resultOption) { Objects.requireNonNull(key, NULL_KEY_MESSAGE); Objects.requireNonNull(options, NULL_OPTIONS_MESSAGE); Objects.requireNonNull(node, NULL_NODE_MESSAGE); Objects.requireNonNull(resultOption, "The result option must not be null"); return getLanguageSpecificComputer().computeWithResultOption(key, node, false, options, resultOption, getLanguageSpecificProjectMemoizer()); }
Source:
<code>public final <M, T> Binding<?, ?> <START> bindValue( <END> IObservableValue<T> targetObservableValue, IObservableValue<M> modelObservableValue, UpdateValueStrategy<T, M> targetToModel, UpdateValueStrategy<M, T> modelToTarget) { UpdateValueStrategy<T, M> targetToModelStrategy = targetToModel != null ? targetToModel : createTargetToModelUpdateValueStrategy(targetObservableValue, modelObservableValue); UpdateValueStrategy<M, T> modelToTargetStrategy = modelToTarget != null ? modelToTarget : createModelToTargetUpdateValueStrategy(modelObservableValue, targetObservableValue); targetToModelStrategy.fillDefaults(targetObservableValue, modelObservableValue); modelToTargetStrategy.fillDefaults(modelObservableValue, targetObservableValue); ValueBinding<M, T> result = new ValueBinding<>( targetObservableValue, modelObservableValue, targetToModelStrategy, modelToTargetStrategy); result.init(this); return result; }</code><technical_language>bindValue this type in patch set 10: Binding<IObservableValue<M>, IObservableValue<T>> leave type parameters Binding, I remove in a future patch set</technical_language>

Target:
public final <M, T> Binding<IObservableValue<M>, IObservableValue<T>> bindValue( IObservableValue<T> targetObservableValue, IObservableValue<M> modelObservableValue, UpdateValueStrategy<T, M> targetToModel, UpdateValueStrategy<M, T> modelToTarget) { UpdateValueStrategy<T, M> targetToModelStrategy = targetToModel != null ? targetToModel : createTargetToModelUpdateValueStrategy(targetObservableValue, modelObservableValue); UpdateValueStrategy<M, T> modelToTargetStrategy = modelToTarget != null ? modelToTarget : createModelToTargetUpdateValueStrategy(modelObservableValue, targetObservableValue); targetToModelStrategy.fillDefaults(targetObservableValue, modelObservableValue); modelToTargetStrategy.fillDefaults(modelObservableValue, targetObservableValue); ValueBinding<M, T> result = new ValueBinding<>( targetObservableValue, modelObservableValue, targetToModelStrategy, modelToTargetStrategy); result.init(this); return result; }
Source:
<code>void addCellToDelMutation(Delete del, byte[] family, byte[] column, long ts, KeyValue.Type type) throws Exception { byte[] rowKey = del.getRow(); <START> Cell cell = new KeyValue(rowKey, family, column, ts, type); <END> del.addDeleteMarker(cell); }</code><technical_language>Ditto KeyValue usage here: Cell / CellUtil APIs</technical_language>

Target:
void addCellToDelMutation(Delete del, byte[] family, byte[] column, long ts, KeyValue.Type type) throws Exception { byte[] rowKey = del.getRow(); Cell cell = CellUtil.createCell(rowKey, family, column, ts, type.getCode(), null); del.addDeleteMarker(cell); }
Source:
<code>public synchronized void stop() { LOG.info("Stopping event hub system consumer..."); List<CompletableFuture<Void>> futures = new ArrayList<>(); streamPartitionReceivers.values().forEach((receiver) -> futures.add(receiver.close())); CompletableFuture<Void> future = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); try { future.get(config.getShutdownWaitTimeMS(), TimeUnit.MILLISECONDS); } catch (ExecutionException | InterruptedException e) { LOG.warn("Failed to close receivers", e); } catch (TimeoutException e) { <START> LOG.warn("Closing the partition sender timed out ", e); <END> } streamEventHubClients.values().forEach(ehClient -> ehClient.close(config.getShutdownWaitTimeMS())); streamEventHubClients.clear(); streamPartitionStartingOffsets.clear(); streamPartitionReceivers.clear(); }</code><technical_language>need separate handling this adding extra information. try/catch ehClient closes</technical_language>

Target:
public void stop() { LOG.debug("Stopping event hub system consumer..."); List<CompletableFuture<Void>> futures = new ArrayList<>(); streamPartitionReceivers.values().forEach((receiver) -> futures.add(receiver.close())); CompletableFuture<Void> future = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); try { future.get(DEFAULT_SHUTDOWN_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (ExecutionException | InterruptedException | TimeoutException e) { LOG.warn("Failed to close receivers", e); } streamEventHubManagers.values().forEach(ehClientManager -> ehClientManager.close(DEFAULT_SHUTDOWN_TIMEOUT_MILLIS)); }
Source:
<code>@Override public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { File yamlFile = new File(Resources.getResource("keywhiz-test.yaml").getFile()); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); ObjectMapper objectMapper = KeywhizService.customizeObjectMapper(Jackson.newObjectMapper()); KeywhizConfig config; try { config = new ConfigurationFactory<>(KeywhizConfig.class, validator, objectMapper, "dw") .build(yamlFile); } catch (IOException | ConfigurationException e) { throw new AssertionError(e); } DataSource dataSource = config.getDataSourceFactory() .build(new MetricRegistry(), "postgres-migrations"); Flyway flyway = new Flyway(); flyway.setDataSource(dataSource); flyway.clean(); flyway.migrate(); DSLContext dslContext = DSL.using(dataSource.getConnection()); PopulateDevDataCommand.doImport(dslContext); <START> dataSource.getConnection().close(); <END> base.evaluate(); } }; }</code><technical_language>Prefer try-with-resources: try (Connection conn = dataSource.getConnection()) { PopulateDevDataCommand.doImport(DSL.using(conn)); }</technical_language>

Target:
@Override public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { File yamlFile = new File(Resources.getResource("keywhiz-test.yaml").getFile()); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); ObjectMapper objectMapper = KeywhizService.customizeObjectMapper(Jackson.newObjectMapper()); KeywhizConfig config; try { config = new ConfigurationFactory<>(KeywhizConfig.class, validator, objectMapper, "dw") .build(yamlFile); } catch (IOException | ConfigurationException e) { throw new AssertionError(e); } DataSource dataSource = config.getDataSourceFactory() .build(new MetricRegistry(), "postgres-migrations"); Flyway flyway = new Flyway(); flyway.setDataSource(dataSource); flyway.clean(); flyway.migrate(); try (Connection conn = dataSource.getConnection()) { DSLContext dslContext = DSL.using(conn); DbSeedCommand.doImport(dslContext); } base.evaluate(); } }; }
Source:
<code>private void possiblyResetOffsetsOrWait( Map<TopicPartition, Long> outOfRangePartitions, KafkaConsumer<byte[], byte[]> consumer, TaskToolbox taskToolbox ) throws InterruptedException, IOException { final Map<TopicPartition, Long> resetPartitions = new HashMap<>(); boolean doReset = false; if (tuningConfig.isResetOffsetAutomatically()) { for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) { final TopicPartition topicPartition = outOfRangePartition.getKey(); final long nextOffset = outOfRangePartition.getValue(); consumer.seekToBeginning(Collections.singletonList(topicPartition)); final long leastAvailableOffset = consumer.position(topicPartition); consumer.seek(topicPartition, nextOffset); if (leastAvailableOffset > nextOffset) { doReset = true; resetPartitions.put(topicPartition, nextOffset); } } } if (doReset) { <START> sendResetRequestAndAndWait(resetPartitions, taskToolbox); <END> } else { log.warn("Retrying in %dms", task.getPollRetryMs()); pollRetryLock.lockInterruptibly(); try { long nanos = TimeUnit.MILLISECONDS.toNanos(task.getPollRetryMs()); while (nanos > 0L && !pauseRequested && !stopRequested.get()) { nanos = isAwaitingRetry.awaitNanos(nanos); } } finally { pollRetryLock.unlock(); } } }</code><technical_language>Typo: extra 'And' introduced</technical_language>

Target:
private void possiblyResetOffsetsOrWait( Map<TopicPartition, Long> outOfRangePartitions, KafkaConsumer<byte[], byte[]> consumer, TaskToolbox taskToolbox ) throws InterruptedException, IOException { final Map<TopicPartition, Long> resetPartitions = new HashMap<>(); boolean doReset = false; if (tuningConfig.isResetOffsetAutomatically()) { for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) { final TopicPartition topicPartition = outOfRangePartition.getKey(); final long nextOffset = outOfRangePartition.getValue(); consumer.seekToBeginning(Collections.singletonList(topicPartition)); final long leastAvailableOffset = consumer.position(topicPartition); consumer.seek(topicPartition, nextOffset); if (leastAvailableOffset > nextOffset) { doReset = true; resetPartitions.put(topicPartition, nextOffset); } } } if (doReset) { sendResetRequestAndWaitLegacy(resetPartitions, taskToolbox); } else { log.warn("Retrying in %dms", task.getPollRetryMs()); pollRetryLock.lockInterruptibly(); try { long nanos = TimeUnit.MILLISECONDS.toNanos(task.getPollRetryMs()); while (nanos > 0L && !pauseRequested && !stopRequested.get()) { nanos = isAwaitingRetry.awaitNanos(nanos); } } finally { pollRetryLock.unlock(); } } }
Source:
<code>public void testGetByIdMultiple() throws CacheException { InfinispanCommunicationDetailsCache cdc = createCache(); CommunicationDetails cdMultipleConsumer1 = new CommunicationDetails(); cdMultipleConsumer1.setId("id1"); cdMultipleConsumer1.setTargetFragmentId("fragmentId1"); cdMultipleConsumer1.setMultiConsumer(true); CommunicationDetails cdMultipleConsumer2 = new CommunicationDetails(); cdMultipleConsumer2.setId("id1"); cdMultipleConsumer2.setTargetFragmentId("fragmentId2"); cdMultipleConsumer2.setMultiConsumer(true); CommunicationDetails cd3 = new CommunicationDetails(); cd3.setId("id2"); cdc.store(null, Arrays.asList(cdMultipleConsumer1, cdMultipleConsumer2, cd3)); List<CommunicationDetails> cdFromCache = cdc.getById(null, "id1"); Assert.assertEquals(2, cdFromCache.size()); <START> Assert.assertEquals(new HashSet<>(Arrays.asList(cdMultipleConsumer1, cdMultipleConsumer2)), <END> new HashSet<>(cdFromCache)); }</code><technical_language>this comparison works, so, assuming equals fail if order is different. question is: ordering matter? Is part of contract? If so, expected order</technical_language>

Target:
public void testGetByIdMultiple() throws CacheException { CommunicationDetails cdMultipleConsumer1 = new CommunicationDetails(); cdMultipleConsumer1.setId("id1"); cdMultipleConsumer1.setTargetFragmentId("fragmentId1"); cdMultipleConsumer1.setMultiConsumer(true); CommunicationDetails cdMultipleConsumer2 = new CommunicationDetails(); cdMultipleConsumer2.setId("id1"); cdMultipleConsumer2.setTargetFragmentId("fragmentId2"); cdMultipleConsumer2.setMultiConsumer(true); CommunicationDetails cd3 = new CommunicationDetails(); cd3.setId("id2"); cdc.store(null, Arrays.asList(cdMultipleConsumer1, cdMultipleConsumer2, cd3)); List<CommunicationDetails> cdFromCache = cdc.getById(null, "id1"); Assert.assertEquals(2, cdFromCache.size()); Assert.assertEquals(new HashSet<>(Arrays.asList(cdMultipleConsumer1, cdMultipleConsumer2)), new HashSet<>(cdFromCache)); }
Source:
<code>private void logChangeStatusToConnecting(long timeoutToFence) { String msg; AuditLogType auditLogType; log.warn("Host '{}' is not responding. It will stay in Connecting state for a grace period " + "of seconds and after that an attempt to fence the host will be issued.", cachedVds.getName(), <START> TimeUnit.MILLISECONDS.toSeconds(timeoutToFence)); <END> if (cachedVds.isPmEnabled()) { msg = "Host '{}' is not responding. It will stay in Connecting state for a grace period " + "of seconds and after that an attempt to fence the host will be issued."; auditLogType = AuditLogType.VDS_HOST_NOT_RESPONDING_CONNECTING; log.warn(msg, cachedVds.getName(), TimeUnit.MILLISECONDS.toSeconds(timeoutToFence)); } else { msg = "Host '{}' is not responding."; auditLogType = AuditLogType.VDS_HOST_NOT_RESPONDING; log.warn(msg, cachedVds.getName()); } AuditLogableBase logable = new AuditLogableBase(); logable.setVdsId(cachedVds.getId()); logable.addCustomValue("Seconds", Long.toString(TimeUnit.MILLISECONDS.toSeconds(timeoutToFence))); auditLogDirector.log(logable, AuditLogType.VDS_HOST_NOT_RESPONDING_CONNECTING); }</code><technical_language>Please remove this log, a part of if</technical_language>

Target:
private void logChangeStatusToConnecting(long timeoutToFence) { String msg; AuditLogType auditLogType; if (cachedVds.isPmEnabled()) { msg = "Host '{}' is not responding. It will stay in Connecting state for a grace period " + "of seconds and after that an attempt to fence the host will be issued."; auditLogType = AuditLogType.VDS_HOST_NOT_RESPONDING_CONNECTING; log.warn(msg, cachedVds.getName(), TimeUnit.MILLISECONDS.toSeconds(timeoutToFence)); } else { msg = "Host '{}' is not responding."; auditLogType = AuditLogType.VDS_HOST_NOT_RESPONDING; log.warn(msg, cachedVds.getName()); } AuditLogableBase logable = new AuditLogableBase(); logable.setVdsId(cachedVds.getId()); logable.addCustomValue("Seconds", Long.toString(TimeUnit.MILLISECONDS.toSeconds(timeoutToFence))); auditLogDirector.log(logable, auditLogType); }
Source:
<code>public boolean isSuspended() { if(getSuspendedTo() != null) { <START> return suspendedTo.after(Calendar.getInstance().getTime()); <END> } return false; }</code><technical_language>new Java Date API (LocalDateTime.now()) instead of Calendar</technical_language>

Target:
public boolean isSuspended() { if(getSuspendedTo() != null) { return suspendedTo.after(Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant())); } return false; }
Source:
<code>private IStatus handleRepositoryGroupNodeDrop(RepositoryGroupNode group, DropTargetEvent event) { if (event.data instanceof IStructuredSelection) { IStructuredSelection selection = (IStructuredSelection) event.data; if (onlyRepositoryNodesSelected(selection)) { <START> List<String> reposToAdd <END> = new ArrayList<>(); for (Object treeNode : selection.toList()) { RepositoryNode repo = (RepositoryNode) treeNode; reposToAdd.add( repo.getRepository().getDirectory().toString()); } RepositoryGroups groups = new RepositoryGroups(); groups.addRepositoriesToGroup(group.getGroup().getGroupId(), reposToAdd); refreshRepositoriesView(); return Status.OK_STATUS; } } return Status.CANCEL_STATUS; }</code><technical_language>File</technical_language>

Target:
private IStatus handleRepositoryGroupNodeDrop(RepositoryGroupNode group, DropTargetEvent event) { if (event.data instanceof IStructuredSelection) { IStructuredSelection selection = (IStructuredSelection) event.data; if (onlyRepositoryNodesSelected(selection)) { List<File> reposToAdd = new ArrayList<>(); for (Object treeNode : selection.toList()) { RepositoryNode repo = (RepositoryNode) treeNode; reposToAdd.add(repo.getRepository().getDirectory()); } RepositoryGroups.getInstance().addRepositoriesToGroup( group.getGroup().getGroupId(), reposToAdd); refreshRepositoriesView(); return Status.OK_STATUS; } } return Status.CANCEL_STATUS; }
Source:
<code>private void updateParentProject(final ProjectConfig config) throws UpdateParentsFailedException, NoSuchProjectException { final Project parentProject; if (parentProjectName != null) { final ProjectState parentState = projectCache.get(parentProjectName); if (parentState == null) { throw new NoSuchProjectException(parentProjectName); } parentProject = parentState.getProject(); } else { <START> parentProject = null; <END> } updateParentsFactory.create(Collections.singleton(config.getProject()), parentProject).validateParentUpdate(); config.getProject().setParentName(parentProjectName); }</code><technical_language>This done line 247 avoiding need for else</technical_language>

Target:
private void updateParentProject(final ProjectConfig config) throws UpdateParentsFailedException, NoSuchProjectException { Project parentProject = null; if (parentProjectName != null) { final ProjectState parentState = projectCache.get(parentProjectName); if (parentState == null) { throw new NoSuchProjectException(parentProjectName); } parentProject = parentState.getProject(); } updateParentsFactory.create(Collections.singleton(config.getProject()), parentProject).validateParentUpdate(); config.getProject().setParentName(parentProjectName); }
Source:
<code>private synchronized void tryReleaseWorkers() { if (blockedWorkerIds.size() == numWorkersToSync) { LOG.log(Level.INFO, "{0} workers are blocked. Sending response messages to awake them", numWorkersToSync); transitState(globalStateMachine); <START> final byte[] data = new byte[0]; <END> for (final String workerId : blockedWorkerIds) { sendResponseMessage(workerId, data); } blockedWorkerIds.clear(); } }</code><technical_language>define a static variable instead of creating time</technical_language>

Target:
private synchronized void tryReleaseWorkers() { if (blockedWorkerIds.size() == numWorkersToSync) { LOG.log(Level.INFO, "{0} workers are blocked. Sending response messages to awake them", numWorkersToSync); transitState(globalStateMachine); for (final String workerId : blockedWorkerIds) { sendResponseMessage(workerId, EMPTY_DATA); } blockedWorkerIds.clear(); } }
Source:
<code>private Request readSubscribeCommands() throws IOException, TransportException { Request r = new Request(); r.commands = new HashMap<String, List<SubscribeCommand>>(); <START> r.clientRefState = new HashMap<String, Map<String, ObjectId>>(); <END> String line; ArrayList<SubscribeCommand> cmdList = null; Map<String, ObjectId> stateList = null; String repo = null; while (!(line = in.readString()).startsWith("done")) { if (line == PacketLineIn.END && repo != null) { r.commands.put(repo, cmdList); r.clientRefState.put(repo, stateList); repo = null; cmdList = null; stateList = null; } else if (line.startsWith("repository ")) { repo = line.substring("repository ".length()); cmdList = new ArrayList<SubscribeCommand>(); stateList = new HashMap<String, ObjectId>(); } else { if (repo == null || cmdList == null || stateList == null) throw new TransportException(MessageFormat.format(JGitText .get().invalidSubscribeRequest, line)); if (line.startsWith("want ")) cmdList.add(new SubscribeCommand(SUBSCRIBE, line.substring( "want ".length()))); else if (line.startsWith("stop ")) throw new TransportException("stop command not supported"); else if (line.startsWith("have ")) { String[] parts = line.split(" ", 3); if (parts.length < 3) throw new TransportException(MessageFormat.format( JGitText.get().invalidSubscribeRequest, line)); stateList.put(parts[2], ObjectId.fromString(parts[1])); } } } return r; }</code><technical_language>inline in request</technical_language>

Target:
private Request readSubscribeCommands() throws IOException, TransportException { Request r = new Request(); String line; ArrayList<SubscribeCommand> cmdList = null; Map<String, ObjectId> stateList = null; String repo = null; while (!(line = in.readString()).startsWith("done")) { if (line == PacketLineIn.END && repo != null) { r.commands.put(repo, cmdList); r.clientRefState.put(repo, stateList); repo = null; cmdList = null; stateList = null; } else if (line.startsWith("repository ")) { repo = line.substring("repository ".length()); cmdList = new ArrayList<SubscribeCommand>(); stateList = new HashMap<String, ObjectId>(); } else { if (repo == null || cmdList == null || stateList == null) throw new TransportException(MessageFormat.format(JGitText .get().invalidSubscribeRequest, line)); if (line.startsWith("want ")) cmdList.add(new SubscribeCommand(SUBSCRIBE, line.substring( "want ".length()))); else if (line.startsWith("stop ")) throw new TransportException( JGitText.get().stopCommandNotSupported); else if (line.startsWith("have ")) { String[] parts = line.split(" ", 3); if (parts.length != 3) throw new TransportException(MessageFormat.format( JGitText.get().invalidSubscribeRequest, line)); stateList.put(parts[2], ObjectId.fromString(parts[1])); } } } return r; }
Source:
<code>private boolean updateAnchorFromChildren(RecyclerView.Recycler recycler, RecyclerView.State state, AnchorInfo anchorInfo) { if (getChildCount() == 0) { return false; } final View focused = getFocusedChild(); if (focused != null && anchorInfo.isViewValidAsAnchor(focused, state)) { anchorInfo.assignFromViewAndKeepVisibleRect(focused, getPosition(focused)); return true; } if (mLastStackFromEnd != mStackFromEnd) { return false; } View referenceChild = findReferenceChild( recycler, state, anchorInfo.mLayoutFromEnd, mStackFromEnd); if (referenceChild != null) { anchorInfo.assignFromView(referenceChild, getPosition(referenceChild)); if (!state.isPreLayout() && supportsPredictiveItemAnimations()) { final int childStart = mOrientationHelper.getDecoratedStart(referenceChild); final int childEnd = mOrientationHelper.getDecoratedEnd(referenceChild); final int boundsStart = mOrientationHelper.getStartAfterPadding(); final int boundsEnd = mOrientationHelper.getEndAfterPadding(); final int <START> childSize = <END> childEnd - childStart; boolean outOfBoundsBefore = childEnd <= boundsStart && childStart < boundsStart; boolean outOfBoundsAfter = childStart >= boundsEnd && childEnd > boundsEnd; if (outOfBoundsBefore || outOfBoundsAfter) { anchorInfo.mCoordinate = anchorInfo.mLayoutFromEnd ? boundsEnd : boundsStart; } } return true; } return false; }</code><technical_language>unused</technical_language>

Target:
private boolean updateAnchorFromChildren(RecyclerView.Recycler recycler, RecyclerView.State state, AnchorInfo anchorInfo) { if (getChildCount() == 0) { return false; } final View focused = getFocusedChild(); if (focused != null && anchorInfo.isViewValidAsAnchor(focused, state)) { anchorInfo.assignFromViewAndKeepVisibleRect(focused, getPosition(focused)); return true; } if (mLastStackFromEnd != mStackFromEnd) { return false; } View referenceChild = findReferenceChild( recycler, state, anchorInfo.mLayoutFromEnd, mStackFromEnd); if (referenceChild != null) { anchorInfo.assignFromView(referenceChild, getPosition(referenceChild)); if (!state.isPreLayout() && supportsPredictiveItemAnimations()) { final int childStart = mOrientationHelper.getDecoratedStart(referenceChild); final int childEnd = mOrientationHelper.getDecoratedEnd(referenceChild); final int boundsStart = mOrientationHelper.getStartAfterPadding(); final int boundsEnd = mOrientationHelper.getEndAfterPadding(); boolean outOfBoundsBefore = childEnd <= boundsStart && childStart < boundsStart; boolean outOfBoundsAfter = childStart >= boundsEnd && childEnd > boundsEnd; if (outOfBoundsBefore || outOfBoundsAfter) { anchorInfo.mCoordinate = anchorInfo.mLayoutFromEnd ? boundsEnd : boundsStart; } } return true; } return false; }
Source:
<code>public static RequiredShuffle unknown() { <START> return new RequiredShuffle(ShuffleType.UNKNOWN, new int[0]); <END> }</code><technical_language>provide another constructor private RequiredShuffle(ShuffleType type)</technical_language>

Target:
public static RequiredShuffle unknown() { return new RequiredShuffle(ShuffleType.UNKNOWN); }
Source:
<code>public Set<EObject> linkExistingInstances(EObject eObject, EReference eReference, LinkCallback... callbacks) { if (!VTableControl.class.isInstance(eObject.eContainer())) { return new LinkedHashSet<EObject>(); } final Set<EObject> candidates = collectLinkCandidates(eObject, eReference); <START> final Set<EObject> selectedInstances = new LinkedHashSet<EObject>( <END> SelectModelElementWizardFactory .showSelectInstanceDialog(candidates, null, eReference.isMany())); org.eclipse.emf.ecp.internal.edit.ECPControlHelper.addModelElementsInReference( eObject, selectedInstances, eReference, AdapterFactoryEditingDomain.getEditingDomainFor(eObject)); return selectedInstances; }</code><technical_language>wrap shoSelectInstanceDialog result in a Set</technical_language>

Target:
public Set<EObject> linkExistingInstances(EObject eObject, EReference eReference, LinkCallback... callbacks) { if (!VTableControl.class.isInstance(eObject.eContainer())) { return new LinkedHashSet<EObject>(); } final Set<EObject> candidates = collectLinkCandidates(eObject, eReference); final Set<EObject> selectedInstances = SelectModelElementWizardFactory .showSelectInstanceDialog(candidates, eReference.isMany()); org.eclipse.emf.ecp.internal.edit.ECPControlHelper.addModelElementsInReference( eObject, selectedInstances, eReference, AdapterFactoryEditingDomain.getEditingDomainFor(eObject)); return selectedInstances; }
Source:
<code>public void testWithSources() throws Exception { try (BndPomRepository bpr = new BndPomRepository()) { Workspace w = Workspace.createStandaloneWorkspace(new Processor(), tmp.toURI()); w.setBase(tmp); bpr.setRegistry(w); Map<String, String> config = new HashMap<>(); config.put("revision", "com.mchange:mchange-commons-java:0.2.10"); config.put("snapshotUrls", "<LINK_0>"); config.put("releaseUrls", "<LINK_0>"); config.put("name", "test"); bpr.setProperties(config); File file = bpr.get("slf4j.api", new Version("1.7.5"), null); assertNotNull(file); <START> assertThat(file.isFile()).isTrue(); <END> File source = bpr.get("slf4j.api.source", new Version("1.7.5"), null); assertNotNull(source); assertThat(source.isFile()).isTrue(); } }</code><technical_language>This written assertThat(file).isFile();</technical_language>

Target:
public void testWithSources() throws Exception { try (BndPomRepository bpr = new BndPomRepository()) { Workspace w = Workspace.createStandaloneWorkspace(new Processor(), tmp.toURI()); w.setBase(tmp); bpr.setRegistry(w); Map<String, String> config = new HashMap<>(); config.put("revision", "com.mchange:mchange-commons-java:0.2.10"); config.put("snapshotUrls", "<LINK_0>"); config.put("releaseUrls", "<LINK_0>"); config.put("name", "test"); bpr.setProperties(config); File file = bpr.get("slf4j.api", new Version("1.7.5"), null); assertNotNull(file); assertThat(file).isFile(); File source = bpr.get("slf4j.api.source", new Version("1.7.5"), null); assertNotNull(source); assertThat(source).isFile(); } }
Source:
<code>protected T getTypedFilter(Filter filter) { if (isFilterAProperSublcass(filter)) { return unchecked(filter); <START> } else { <END> throw new IllegalStateException( String.format( "FilterAdapter %s cannot operate on a filter of type %s", getClass().getCanonicalName(), filter.getClass().getCanonicalName())); } }</code><technical_language>nit: remove else {}, throw exception if block</technical_language>

Target:
protected T getTypedFilter(Filter filter) { if (isFilterAProperSublcass(filter)) { return unchecked(filter); } throw new IllegalStateException( String.format( "FilterAdapter %s cannot operate on a filter of type %s", getClass().getCanonicalName(), filter.getClass().getCanonicalName())); }
Source:
<code>public static void createSymlink(@Nonnull File baseDir, @Nonnull String targetPath, @Nonnull String symlinkPath, @Nonnull TaskListener listener) throws InterruptedException { try { Path path = new File(baseDir, symlinkPath).toPath(); Path target = Paths.get(targetPath, new String[0]); final int maxNumberOfTries = 4; final int timeInMillis = 100; for (int tryNumber = 1; tryNumber <= maxNumberOfTries; tryNumber++) { Files.deleteIfExists(path); try { Files.createSymbolicLink(path, target); break; } catch (FileAlreadyExistsException fileAlreadyExistsException) { if (tryNumber < maxNumberOfTries) { TimeUnit.MILLISECONDS.sleep(timeInMillis); continue; } LOGGER.warning("symlink FileAlreadyExistsException thrown " + maxNumberOfTries + " times => cannot createSymbolicLink"); throw fileAlreadyExistsException; } } } catch (UnsupportedOperationException e) { PrintStream log = listener.getLogger(); log.print("Symbolic links are not supported on this platform"); Functions.printStackTrace(e, log); } catch (IOException e) { if (Functions.isWindows() && e instanceof FileSystemException) { <START> warnWindowsSymlink(); <END> } PrintStream log = listener.getLogger(); log.printf("ln %s %s failed%n",targetPath, new File(baseDir, symlinkPath)); Util.displayIOException(e,listener); Functions.printStackTrace(e, log); } }</code><technical_language>sure. Try follow logging/throwing behavior of original method possible, I guess. design weird; prefer TaskListener method throw exception if fails create symlink for reason (let caller decide do next). Anyway, if get rid of build number symlinks, common callers of this method</technical_language>

Target:
public static void createSymlink(@Nonnull File baseDir, @Nonnull String targetPath, @Nonnull String symlinkPath, @Nonnull TaskListener listener) throws InterruptedException { try { Path path = new File(baseDir, symlinkPath).toPath(); Path target = Paths.get(targetPath, new String[0]); final int maxNumberOfTries = 4; final int timeInMillis = 100; for (int tryNumber = 1; tryNumber <= maxNumberOfTries; tryNumber++) { Files.deleteIfExists(path); try { Files.createSymbolicLink(path, target); break; } catch (FileAlreadyExistsException fileAlreadyExistsException) { if (tryNumber < maxNumberOfTries) { TimeUnit.MILLISECONDS.sleep(timeInMillis); continue; } LOGGER.warning("symlink FileAlreadyExistsException thrown " + maxNumberOfTries + " times => cannot createSymbolicLink"); throw fileAlreadyExistsException; } } } catch (UnsupportedOperationException e) { PrintStream log = listener.getLogger(); log.print("Symbolic links are not supported on this platform"); Functions.printStackTrace(e, log); } catch (InvalidPathException | IOException e) { if (Functions.isWindows() && e instanceof FileSystemException) { warnWindowsSymlink(); return; } PrintStream log = listener.getLogger(); log.printf("ln %s %s failed%n",targetPath, new File(baseDir, symlinkPath)); Functions.printStackTrace(e, log); } }
Source:
<code>public List<String> getStrongDependencies() { <START> List<String> StrongDependencies = new ArrayList<String>(); <END> StrongDependencies.add(AttributesManager.NS_USER_FACILITY_ATTR_DEF + ":shell"); StrongDependencies.add(AttributesManager.NS_FACILITY_ATTR_DEF + ":shells"); StrongDependencies.add(AttributesManager.NS_USER_FACILITY_ATTR_DEF + ":prefferedShells"); StrongDependencies.add(AttributesManager.NS_RESOURCE_ATTR_DEF + ":shells"); return StrongDependencies; }</code><technical_language>Fist character of variable name in lowercase</technical_language>

Target:
public List<String> getStrongDependencies() { List<String> strongDependencies = new ArrayList<String>(); strongDependencies.add(AttributesManager.NS_USER_FACILITY_ATTR_DEF + ":shell"); strongDependencies.add(AttributesManager.NS_FACILITY_ATTR_DEF + ":shells"); strongDependencies.add(AttributesManager.NS_USER_FACILITY_ATTR_DEF + ":prefferedShells"); strongDependencies.add(AttributesManager.NS_RESOURCE_ATTR_DEF + ":shells"); return strongDependencies; }
Source:
<code>public long getTotalTasksCount() { return executeReadOnlyTransaction(session -> { Query query = session.getNamedQuery("getTotalTasksCount"); <START> Long count = (Long) query.uniqueResult(); <END> return count; }); }</code><technical_language>return Long count</technical_language>

Target:
public long getTotalTasksCount() { return executeReadOnlyTransaction(session -> { return (Long) session.getNamedQuery("getTotalTasksCount").uniqueResult(); }); }
Source:
<code>public void updateStatusReplicaAtStartupTest(){ spy.updateStatus(State.REPLICA); verify(spy).updateStatus(State.REPLICA); <START> verify(spy, never()).updateOnRunningConsumer(State.REPLICA); <END> verify(spy, times(1)).askAndProcessSnapshotOnDemand(any(SnapshotInfos.class)); verify(spy, times(1)).enableConsumeAndStartLoop(State.REPLICA); verify(spy, times(1)).setLastProcessedKey(); verify(spy, times(1)).assignAndStartConsume(); }</code><technical_language>Please any(State.class) never() more reliable</technical_language>

Target:
public void updateStatusReplicaAtStartupTest(){ spy.updateStatus(State.REPLICA); verify(spy).updateStatus(State.REPLICA); verify(spy, never()).updateOnRunningConsumer(any(State.class)); verify(spy, times(1)).askAndProcessSnapshotOnDemand(any(SnapshotInfos.class)); verify(spy, times(1)).enableConsumeAndStartLoop(eq(State.REPLICA)); verify(spy, times(1)).setLastProcessedKey(); verify(spy, times(1)).assignAndStartConsume(); }
Source:
<code>public void validateCopartition() { final List<Set<String>> copartitionGroups = copartitionSourceGroups .stream() .map(sourceGroup -> sourceGroup .stream() <START> .flatMap(node -> nodeToSourceTopics.get(node).stream()) <END> .collect(Collectors.toSet()) ).collect(Collectors.toList()); for (final Set<String> copartition : copartitionGroups) { final Map<String, Integer> topicPartNum = new HashMap<>(); copartition.forEach(topic -> { final InternalTopicProperties prop = internalTopicNamesWithProperties.get(topic); if (prop != null && prop.getNumberOfPartitions().isPresent()) { topicPartNum.put(topic, prop.getNumberOfPartitions().get()); } }); internalTopicNamesWithProperties.forEach((topic, prop) -> { if (copartition.contains(topic) && prop.getNumberOfPartitions().isPresent()) { topicPartNum.put(topic, prop.getNumberOfPartitions().get()); } }); if (copartition.equals(topicPartNum.keySet())) { final Collection<Integer> partNums = topicPartNum.values(); final Integer first = partNums.iterator().next(); for (final Integer partNum : partNums) { if (partNum.equals(first)) { final String msg = String.format("Following topics do not have the same number of " + "partitions: [%s]", new TreeMap<>(topicPartNum)); throw new TopologyException(msg); } } } } }</code><technical_language>rename node -> sourceNodeName</technical_language>

Target:
public void validateCopartition() { final List<Set<String>> allCopartitionedSourceTopics = copartitionSourceGroups .stream() .map(sourceGroup -> sourceGroup .stream() .flatMap(sourceNodeName -> nodeToSourceTopics.getOrDefault(sourceNodeName, Collections.emptyList()).stream()) .collect(Collectors.toSet()) ).collect(Collectors.toList()); for (final Set<String> copartition : allCopartitionedSourceTopics) { final Map<String, Integer> numberOfPartitionsPerTopic = new HashMap<>(); copartition.forEach(topic -> { final InternalTopicProperties prop = internalTopicNamesWithProperties.get(topic); if (prop != null && prop.getNumberOfPartitions().isPresent()) { numberOfPartitionsPerTopic.put(topic, prop.getNumberOfPartitions().get()); } }); if (!numberOfPartitionsPerTopic.isEmpty() && copartition.equals(numberOfPartitionsPerTopic.keySet())) { final Collection<Integer> partitionNumbers = numberOfPartitionsPerTopic.values(); final Integer first = partitionNumbers.iterator().next(); for (final Integer partitionNumber : partitionNumbers) { if (!partitionNumber.equals(first)) { final String msg = String.format("Following topics do not have the same number of " + "partitions: [%s]", new TreeMap<>(numberOfPartitionsPerTopic)); throw new TopologyException(msg); } } } } }
Source:
<code>void authorizeUserInTree(String userName, String resourceId, String action, boolean updateCache) throws UserStoreException { write.lock(); try { SearchResult sr = getNode(root, PermissionTreeUtil.toComponenets(resourceId)); if (sr.getUnprocessedPaths() != null) { List<String> paths = sr.getUnprocessedPaths(); TreeNode tn = sr.getLastNode().create(paths); tn.authorizeUser(userName, PermissionTreeUtil.actionToPermission(action)); } else { sr.getLastNode().authorizeUser(userName, PermissionTreeUtil.actionToPermission(action)); } if (updateCache) { invalidateCache(root); } <START> } catch (Exception e) { <END> throw new UserStoreException("Error while authorizing user: " + userName + "in permission tree for resource id: " + resourceId + "for action: " + action, e); } finally { write.unlock(); } }</code><technical_language>Catch relevant exceptions</technical_language>

Target:
void authorizeUserInTree(String userName, String resourceId, String action, boolean updateCache) throws UserStoreException { write.lock(); try { SearchResult sr = getNode(root, PermissionTreeUtil.toComponenets(resourceId)); if (sr.getUnprocessedPaths() != null) { List<String> paths = sr.getUnprocessedPaths(); TreeNode tn = sr.getLastNode().create(paths); tn.authorizeUser(userName, PermissionTreeUtil.actionToPermission(action)); } else { sr.getLastNode().authorizeUser(userName, PermissionTreeUtil.actionToPermission(action)); } if (updateCache) { invalidateCache(root); } } catch (IllegalArgumentException e) { throw new UserStoreException("Error while authorizing user: " + userName + "in permission tree for resource id: " + resourceId + "for action: " + action, e); } finally { write.unlock(); } }
Source:
<code>protected String toSqlType(Type type) { if (type instanceof VarcharType) { if (((VarcharType) type).isUnbounded()) { return "varchar(max)"; } return "varchar(" + ((VarcharType) type).getLengthSafe() + ')'; } if (type instanceof CharType) { if (((CharType) type).getLength() == CharType.MAX_LENGTH) { <START> return "char(max)"; <END> } return "char(" + ((CharType) type).getLength() + ')'; } String sqlType = SQL_TYPES.get(type); if (sqlType != null) { return sqlType; } throw new PrestoException(NOT_SUPPORTED, "Unsupported column type: " + type.getTypeSignature()); }</code><technical_language>cases "-quoting work speak []-slang</technical_language>

Target:
protected String toSqlType(Type type) { if (type instanceof VarcharType) { VarcharType varcharType = (VarcharType) type; if (varcharType.isUnbounded() || varcharType.getLengthSafe() > MSSQL_VARCHAR_MAX) { return "varchar(max)"; } return "varchar(" + ((VarcharType) type).getLengthSafe() + ')'; } if (type instanceof CharType) { CharType charType = (CharType) type; if (charType.getLength() > MSSQL_CHAR_MAX) { return "char(max)"; } return "char(" + charType.getLength() + ')'; } String sqlType = MSSQL_SQL_TYPES.get(type); if (sqlType != null) { return sqlType; } throw new PrestoException(NOT_SUPPORTED, "Unsupported column type: " + type.getTypeSignature()); }
Source:
<code>private static <F> Optional<Binding<F>> getPropertyBinding(Binding<?> binding, Field field) { Method setter = ReflectionUtil.findSetter(field); if (setter == null) { return Optional.empty(); } Method getter = ReflectionUtil.findGetter(field); if (getter == null) { LOGGER.error("Cannot bind field with setter but no getter", field, setter); return Optional.empty(); } Binding<F> fieldBinding = new Binding<F>() { @Override public F get() { try { return (F) getter.invoke(binding.get()); } catch (IllegalAccessException e) { <START> throw new RuntimeException("Unreachable"); <END> } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } } @Override public void set(F value) { try { setter.invoke(binding.get(), value); } catch (IllegalAccessException e) { throw new RuntimeException("Unreachable"); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } } }; return Optional.of(binding.makeChildBinding(fieldBinding)); }</code><technical_language>Pretty ambiguous message, propagate e in this class</technical_language>

Target:
private static <F> Optional<Binding<F>> getPropertyBinding(Binding<?> binding, Field field) { Method setter = ReflectionUtil.findSetter(field); if (setter == null) { return Optional.empty(); } Method getter = ReflectionUtil.findGetter(field); if (getter == null) { LOGGER.error("Cannot bind field with setter but no getter", field, setter); return Optional.empty(); } Binding<F> fieldBinding = new Binding<F>() { @Override public F get() { try { return (F) getter.invoke(binding.get()); } catch (IllegalAccessException e) { throw new RuntimeException("Unreachable", e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } } @Override public void set(F value) { try { setter.invoke(binding.get(), value); } catch (IllegalAccessException e) { throw new RuntimeException("Unreachable", e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } } }; return Optional.of(binding.makeChildBinding(fieldBinding)); }
Source:
<code>public String executeRequest(String urlString, ParamsMap params, Method method, ContentType contentTypeFormat) throws MambuApiException { String applicationKey = MambuAPIFactory.getApplicationKey(); if (applicationKey != null) { if (params == null) params = new ParamsMap(); params.addParam(APPLICATION_KEY, applicationKey); <START> LOGGER.info("Added Application key=" + applicationKey); <END> } String response = ""; try { switch (method) { case GET: response = executeGetRequest(urlString, params, contentTypeFormat); break; case POST: response = executePostRequest(urlString, params, contentTypeFormat); break; } } catch (MalformedURLException e) { LOGGER.severe("MalformedURLException: " + e.getMessage()); throw new MambuApiException(e); } catch (IOException e) { LOGGER.warning("IOException: message= " + e.getMessage()); throw new MambuApiException(e); } return response; }</code><technical_language>application key is private, log characters "..." in between</technical_language>

Target:
public String executeRequest(String urlString, ParamsMap params, Method method, ContentType contentTypeFormat) throws MambuApiException { String applicationKey = MambuAPIFactory.getApplicationKey(); if (applicationKey != null) { if (params == null) params = new ParamsMap(); params.addParam(APPLICATION_KEY, applicationKey); final int keyLength = applicationKey.length(); final int printLength = 3; if (keyLength >= printLength) LOGGER.info("Added Application key=" + applicationKey.substring(0, printLength) + "..." + applicationKey.substring(keyLength - printLength, keyLength)); } String response = ""; try { switch (method) { case GET: response = executeGetRequest(urlString, params, contentTypeFormat); break; case POST: response = executePostRequest(urlString, params, contentTypeFormat); break; } } catch (MalformedURLException e) { LOGGER.severe("MalformedURLException: " + e.getMessage()); throw new MambuApiException(e); } catch (IOException e) { LOGGER.warning("IOException: message= " + e.getMessage()); throw new MambuApiException(e); } return response; }
Source:
<code>static synchronized DatabaseHelper getDatabaseHelper(Context context, String instance) { if (TextUtils.isEmpty(instance)) { instance = Constants.DEFAULT_INSTANCE; } <START> instance = instance.toLowerCase(); <END> DatabaseHelper dbHelper = instances.get(instance); if (dbHelper == null) { if (instance.equalsIgnoreCase(Constants.DEFAULT_INSTANCE)) { dbHelper = new DatabaseHelper(context.getApplicationContext()); } else { dbHelper = new DatabaseHelper(context.getApplicationContext(), instance); } instances.put(instance, dbHelper); } return dbHelper; }</code><technical_language>lines of logic refactored a normalizeInstanceName method</technical_language>

Target:
static synchronized DatabaseHelper getDatabaseHelper(Context context, String instance) { instance = Utils.normalizeInstanceName(instance); DatabaseHelper dbHelper = instances.get(instance); if (dbHelper == null) { dbHelper = new DatabaseHelper(context.getApplicationContext(), instance); instances.put(instance, dbHelper); } return dbHelper; }
Source:
<code>public void doDoRename( StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { <START> super.doDoRename2(req, rsp); <END> }</code><technical_language>super. unnecessary overridden</technical_language>

Target:
public void doDoRename( StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String newName = req.getParameter("newName"); doConfirmRename(newName).generateResponse(req, rsp, null); }
Source:
<code>public void run(IProgressMonitor monitor) throws CoreException { ArrayList<TextFileChange> list = new ArrayList<>(); if (fDesc != null) { <START> SubMonitor subMonitor = SubMonitor.convert(monitor, "", 3); END> findRequireBundleReferences(list, subMonitor.newChild(1)); findFragmentReferences(list, subMonitor.newChild(1)); findXFriendReferences(list, subMonitor.newChild(1)); } fChanges = list.toArray(new Change[list.size()]); }</code><technical_language>two-argument constructor</technical_language>

Target:
public void run(IProgressMonitor monitor) throws CoreException { ArrayList<TextFileChange> list = new ArrayList<>(); if (fDesc != null) { SubMonitor subMonitor = SubMonitor.convert(monitor, 3); findRequireBundleReferences(list, subMonitor.newChild(1)); findFragmentReferences(list, subMonitor.newChild(1)); findXFriendReferences(list, subMonitor.newChild(1)); } fChanges = list.toArray(new Change[list.size()]); }