auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void abort(final ServerSideMultipartUpload upload) throws IOException { Validate.notNull(upload, "Upload state object must not be null"); final String postPath = upload.getPartsDirectory() + SEPARATOR + "abort"; final HttpPost post = httpHelper.getRequestFactory().post(postPath); final int expectedStatusCode = HttpStatus.SC_NO_CONTENT; <START> try (CloseableHttpResponse response = httpHelper.getConnectionContext().getHttpClient().execute(post)) { <END> StatusLine statusLine = response.getStatusLine(); validateStatusCode(expectedStatusCode, statusLine.getStatusCode(), "Unable to abort multipart upload", post, response, null, null); LOGGER.info("Aborted multipart upload [id={}]", upload.getId()); } }</code><technical_language>Potentially break context client out a separate variable</technical_language>

Target:
public void abort(final ServerSideMultipartUpload upload) throws IOException { Validate.notNull(upload, "Upload state object must not be null"); final String postPath = upload.getPartsDirectory() + SEPARATOR + "abort"; final HttpPost post = httpHelper.getRequestFactory().post(postPath); final int expectedStatusCode = HttpStatus.SC_NO_CONTENT; final CloseableHttpClient httpClient = httpHelper.getConnectionContext().getHttpClient(); try (CloseableHttpResponse response = httpClient.execute(post)) { StatusLine statusLine = response.getStatusLine(); validateStatusCode(expectedStatusCode, statusLine.getStatusCode(), "Unable to abort multipart upload", post, response, null, null); LOGGER.info("Aborted multipart upload [id={}]", upload.getId()); } }
Source:
<code>public void stopTask(boolean forceFinish) { if (getState() != AsyncTaskState.AttemptingEndAction && getState() != AsyncTaskState.Cleared && getState() != AsyncTaskState.ClearFailed && !getLastTaskStatus().getTaskIsInUnusualState()) { try { log.infoFormat( "SPMAsyncTask::StopTask: Attempting to stop task '{0}' (Parent Command {1}, Parameters Type {2}).", getTaskID(), (getParameters().getDbAsyncTask().getaction_type()), getParameters().getClass().getName()); <START> taskHelper.RunVdsCommand(VDSCommandType.SPMStopTask, <END> new SPMTaskGuidBaseVDSCommandParameters(getStoragePoolID(), getTaskID())); } catch (RuntimeException e) { log.error( String.format("SPMAsyncTask::StopTask: Stopping task '%1$s' threw an exception.", getTaskID()), e); } finally { if (forceFinish) { setState(AsyncTaskState.Ended); setLastTaskStatus(new AsyncTaskStatus(AsyncTaskStatusEnum.finished)); } else { setState(AsyncTaskState.Polling); } } } }</code><technical_language>for stop task. This this get read of RunVdsCommand in taskHelper</technical_language>

Target:
public void stopTask(boolean forceFinish) { if (getState() != AsyncTaskState.AttemptingEndAction && getState() != AsyncTaskState.Cleared && getState() != AsyncTaskState.ClearFailed && !getLastTaskStatus().getTaskIsInUnusualState()) { try { log.infoFormat( "SPMAsyncTask::StopTask: Attempting to stop task '{0}' (Parent Command {1}, Parameters Type {2}).", getTaskID(), (getParameters().getDbAsyncTask().getaction_type()), getParameters().getClass().getName()); taskHelper.stopTask(getStoragePoolID(), getTaskID()); } catch (RuntimeException e) { log.error( String.format("SPMAsyncTask::StopTask: Stopping task '%1$s' threw an exception.", getTaskID()), e); } finally { if (forceFinish) { setState(AsyncTaskState.Ended); setLastTaskStatus(new AsyncTaskStatus(AsyncTaskStatusEnum.finished)); } else { setState(AsyncTaskState.Polling); } } } }
Source:
<code>public InputVDir getInputVDir(@Nonnull VPath path) throws NotFileOrDirectoryException, NoSuchFileException { Iterator<String> iterator = path.split().iterator(); String firstElement = iterator.next(); InputVElement ive = subs.get(firstElement); String pathAsString = path.getPathAsString(IN_ZIP_SEPARATOR); if (ive == null) { throw new <START> NotFileOrDirectoryException(new <END> DirectoryLocation(pathAsString)); } if (iterator.hasNext()) { if (ive instanceof InputVDir) { ive = ((InputVDir) ive).getInputVDir(new VPath( pathAsString.substring(pathAsString.indexOf(IN_ZIP_SEPARATOR) + 1), IN_ZIP_SEPARATOR)); } } if (!(ive instanceof InputVDir)) { throw new NotFileOrDirectoryException(new DirectoryLocation(pathAsString)); } return (InputVDir) ive; }</code><technical_language>NoSuchFileException</technical_language>

Target:
public InputVDir getInputVDir(@Nonnull VPath path) throws NotFileOrDirectoryException, NoSuchFileException { Iterator<String> iterator = path.split().iterator(); String firstElement = iterator.next(); InputVElement ive = subs.get(firstElement); String pathAsString = path.getPathAsString(IN_ZIP_SEPARATOR); if (ive == null) { throw new NoSuchFileException(new DirectoryLocation(pathAsString)); } if (iterator.hasNext()) { if (ive instanceof InputVDir) { ive = ((InputVDir) ive).getInputVDir(new VPath( pathAsString.substring(pathAsString.indexOf(IN_ZIP_SEPARATOR) + 1), IN_ZIP_SEPARATOR)); } } if (!ive.isVDir()) { throw new NotFileOrDirectoryException(new DirectoryLocation(pathAsString)); } return (InputVDir) ive; }
Source:
<code>public HAProxyMessage retain(int increment) { <START> return (HAProxyMessage) super.retain(increment); <END> }</code><technical_language>I want call leak.record in other touch, retain release methods</technical_language>

Target:
public HAProxyMessage retain(int increment) { tryRecord(); return (HAProxyMessage) super.retain(increment); }
Source:
<code>private static void setJobName(JobConf jobConf, List<DataSegment> segments) { if (segments.size() == 1) { final DataSegment segment = segments.get(0); jobConf.setJobName( String.format( "druid-convert-%s-%s-%s", segment.getDataSource(), segment.getInterval(), segment.getVersion() ) ); } else { <START> final Set<String> segmentNames = Sets.newHashSet( <END> Iterables.transform( segments, new Function<DataSegment, String>() { @Override public String apply(DataSegment input) { return input.getDataSource(); } } ) ); final Set<String> versions = Sets.newHashSet( Iterables.transform( segments, new Function<DataSegment, String>() { @Override public String apply(DataSegment input) { return input.getVersion(); } } ) ); jobConf.setJobName( String.format( "druid-convert-%s-%s", Arrays.toString(segmentNames.toArray()), Arrays.toString(versions.toArray()) ) ); } }</code><technical_language>rename variable dataSourceNames dataSources</technical_language>

Target:
private static void setJobName(JobConf jobConf, List<DataSegment> segments) { if (segments.size() == 1) { final DataSegment segment = segments.get(0); jobConf.setJobName( String.format( "druid-convert-%s-%s-%s", segment.getDataSource(), segment.getInterval(), segment.getVersion() ) ); } else { final Set<String> dataSources = Sets.newHashSet( Iterables.transform( segments, new Function<DataSegment, String>() { @Override public String apply(DataSegment input) { return input.getDataSource(); } } ) ); final Set<String> versions = Sets.newHashSet( Iterables.transform( segments, new Function<DataSegment, String>() { @Override public String apply(DataSegment input) { return input.getVersion(); } } ) ); jobConf.setJobName( String.format( "druid-convert-%s-%s", Arrays.toString(dataSources.toArray()), Arrays.toString(versions.toArray()) ) ); } }
Source:
<code>private static Set<Integer> getParametersBoundByParentPlan(Map<PVariable, Integer> variableMappings, SubPlan subPlan) { if (!subPlan.getParentPlans().isEmpty()) { SubPlan parentPlan = subPlan.getParentPlans().get(0); Set<PConstraint> enforcedConstraints = parentPlan.getAllEnforcedConstraints(); Set<PVariable> affectedVariables <START> = getAffectedVariables(enforcedConstraints); <END> return getVariableIndices(variableMappings, affectedVariables); } return Sets.newHashSet(); }</code><technical_language>this differ parentPlan.getAllDeducedVariables()</technical_language>

Target:
private static Set<Integer> getParametersBoundByParentPlan(Map<PVariable, Integer> variableMappings, SubPlan subPlan) { if (!subPlan.getParentPlans().isEmpty()) { SubPlan parentPlan = subPlan.getParentPlans().get(0); Set<PConstraint> enforcedConstraints = parentPlan.getAllEnforcedConstraints(); Set<PVariable> affectedVariables = getAffectedVariables(enforcedConstraints); return getVariableIndices(variableMappings, affectedVariables); } return Collections.emptySet(); }
Source:
<code>public Job recoverReadJob(final UUID jobId) throws SignatureException, IOException, XmlProcessingException, JobRecoveryException { ModifyJobResponse jobResponse = this.client.modifyJob(new ModifyJobRequest(jobId)); if (RequestType.GET != jobResponse.getMasterObjectList().getRequestType()){ <START> throw new JobRecoveryException("GET", jobResponse.getMasterObjectList().getRequestType().toString() ); <END> } return new ReadJobImpl(this.client, jobResponse.getMasterObjectList()); }</code><technical_language>Instead of typing "GET" I do following. RequestType.GET.toString() that</technical_language>

Target:
public Ds3ClientHelpers.Job recoverReadJob(final UUID jobId) throws SignatureException, IOException, XmlProcessingException, JobRecoveryException { final ModifyJobResponse jobResponse = this.client.modifyJob(new ModifyJobRequest(jobId)); if (RequestType.GET != jobResponse.getMasterObjectList().getRequestType()){ throw new JobRecoveryException(RequestType.GET.toString(), jobResponse.getMasterObjectList().getRequestType().toString() ); } return new ReadJobImpl(this.client, jobResponse.getMasterObjectList()); }
Source:
<code>public List<Integer> readIntegers() { <START> return read(Integer.class, this::readInteger); <END> }</code><technical_language>method read integers return List<BigInteger>, is (or be) type store values. List<Integer> is a convenience method</technical_language>

Target:
public List<BigInteger> readIntegers() { return readStrings().stream() .map(this::parseInteger) .collect(toList()); }
Source:
<code>public String spawnPrefab(@Sender EntityRef sender, @CommandParam("prefabId") String prefabName) { ClientComponent clientComponent = sender.getComponent(ClientComponent.class); LocationComponent characterLocation = clientComponent.character.getComponent(LocationComponent.class); Vector3f spawnPos = characterLocation.getWorldPosition(); Vector3f offset = new Vector3f(characterLocation.getWorldDirection()); offset.scale(2); spawnPos.add(offset); Vector3f dir = new Vector3f(characterLocation.getWorldDirection()); dir.y = 0; if (dir.lengthSquared() > 0.001f) { dir.normalize(); } else { dir.set(Direction.FORWARD.getVector3f()); } Quat4f rotation = Quat4f.shortestArcQuat(Direction.FORWARD.getVector3f(), dir); Optional<Prefab> prefab = Assets.getPrefab(prefabName); <START> if (prefab.isPresent() && prefab.get().getComponent(LocationComponent.class) != null) { <END> entityManager.create(prefab.get(), spawnPos); return "Done"; } else if (!prefab.isPresent()) { return "Unknown prefab"; } else { return "Prefab cannot be spawned (no location component)"; } }</code><technical_language>Do idea Optional in a more idiomatic way? I logic expressed follows, end status strings before... java Assets.getPrefab(prefabName) .filter(prefab -> prefab.getComponent(LocationComponent.class) != null) .ifPresent(prefab -> entityManager.create(prefab.get(), spawnPos);</technical_language>

Target:
public String spawnPrefab(@Sender EntityRef sender, @CommandParam("prefabId") String prefabName) { ClientComponent clientComponent = sender.getComponent(ClientComponent.class); LocationComponent characterLocation = clientComponent.character.getComponent(LocationComponent.class); Vector3f spawnPos = characterLocation.getWorldPosition(); Vector3f offset = new Vector3f(characterLocation.getWorldDirection()); offset.scale(2); spawnPos.add(offset); Vector3f dir = new Vector3f(characterLocation.getWorldDirection()); dir.y = 0; if (dir.lengthSquared() > 0.001f) { dir.normalize(); } else { dir.set(Direction.FORWARD.getVector3f()); } return Assets.getPrefab(prefabName).map(prefab -> { LocationComponent loc = prefab.getComponent(LocationComponent.class); if (loc != null) { entityManager.create(prefab, spawnPos); return "Done"; } else { return "Prefab cannot be spawned (no location component)"; } }).orElse("Unknown prefab"); }
Source:
<code>public PlanItem(String id, String definitionRef) { <START> super(); <END> this.id = id; this.definitionRef = definitionRef; }</code><technical_language>AFAIK this is redundant</technical_language>

Target:
public PlanItem(String id, String definitionRef) { this.id = id; this.definitionRef = definitionRef; }
Source:
<code><START> public void test() throws Exception { <END> Marshaller marshaller = MarshallerFactory.newMarshaller(kbase); try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { marshaller.marshall(baos, ksession); try (final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) { marshaller = MarshallerFactory.newMarshaller(kbase); ksession = marshaller.unmarshall(bais); } } catch (NullPointerException e) { throw new RuntimeException("Consider reopening BZ 1193600!", e); } }</code><technical_language>Test assertions whatsoever</technical_language>

Target:
public void test() throws Exception { Marshaller marshaller = MarshallerFactory.newMarshaller(kbase); try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { marshaller.marshall(baos, ksession); try (final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) { marshaller = MarshallerFactory.newMarshaller(kbase); ksession = marshaller.unmarshall(bais); } } catch (NullPointerException e) { Assertions.fail("Consider reopening BZ 1193600!", e); } }
Source:
<code>public History get(File file, Repository repository, boolean withFiles) throws HistoryException { File cache = getCachedFile(file); if (isUpToDate(file, cache)) { try { return readCache(cache); } catch (Exception e) { LOGGER.log(Level.WARNING, "Error when reading cache file '" + cache, e); } } RuntimeEnvironment env = RuntimeEnvironment.getInstance(); if (isHistoryIndexDone() && repository.hasHistoryForDirectories() && !env.isFetchHistoryWhenNotInCache()) { return null; } final History history; long time; try { time = System.currentTimeMillis(); history = repository.getHistory(file); time = System.currentTimeMillis() - time; } catch (UnsupportedOperationException e) { return null; } if (!file.isDirectory()) { if ((cache != null) && (cache.exists() || (time > env.getHistoryReaderTimeLimit()))) { storeFile(history, file, repository, false); <START> } <END> } return history; }</code><technical_language>here</technical_language>

Target:
public History get(File file, Repository repository, boolean withFiles) throws HistoryException { File cache = getCachedFile(file); if (isUpToDate(file, cache)) { try { return readCache(cache); } catch (Exception e) { LOGGER.log(Level.WARNING, "Error when reading cache file '" + cache, e); } } RuntimeEnvironment env = RuntimeEnvironment.getInstance(); if (isHistoryIndexDone() && repository.hasHistoryForDirectories() && !env.isFetchHistoryWhenNotInCache()) { return null; } final History history; long time; try { time = System.currentTimeMillis(); history = repository.getHistory(file); time = System.currentTimeMillis() - time; } catch (UnsupportedOperationException e) { return null; } if (!file.isDirectory()) { if ((cache != null) && (cache.exists() || (time > env.getHistoryReaderTimeLimit()))) { storeFile(history, file, repository); } } return history; }
Source:
<code><START> Function<String, SnapshotSender> localSnapshotSenderFactory() { <END> return LocalSnapshotSender::new; }</code><technical_language>a notice: localSnapshotSenderFactory getter for locSndrFactory, locSndrFactory LocalSnapshotSender::new default. setLocalSnapshotSenderFactory renamed match Ignite style setters</technical_language>

Target:
Function<String, SnapshotSender> localSnapshotSenderFactory() { return locSndrFactory; }
Source:
<code>public List<Dependency> extract(NpmProject npmProject) { npmProject.getDependencies().forEach(this::populateDependencies); if (!badPackages.isEmpty()) { logger.info((Arrays.toString(badPackages.toArray()))); logger.info("The npm dependencies above could not be found in Artifactory and therefore are not included in the build-info. " + <START> "Make sure the dependencies are available in Artifactory for this build."); <END> } return new ArrayList<>(dependencies.values()); }</code><technical_language>I suggest adding sentence log message, LMK think: "...Deleting local cache force populating Artifactory dependencies.". add this message prompted JFrog CLI</technical_language>

Target:
public Build extract(NpmProject npmProject) throws Exception { String resolutionRepository = npmProject.getResolutionRepository(); List<String> installationArgs = npmProject.getInstallationArgs(); Path workingDir = npmProject.getWorkingDir(); preparePrerequisites(resolutionRepository, workingDir); createTempNpmrc(workingDir, installationArgs); runInstall(workingDir, installationArgs); restoreNpmrc(workingDir); List<Dependency> dependencies = collectDependencies(workingDir); return createBuild(dependencies); }
Source:
<code><START> public void collect(List<String> filePathStrings, String binKey, Map<String, String> extras) throws IOException { <END> DepositBinConfiguration config = getConfiguration(binKey); if (config == null) { log.warn("Invalid bin specified: {}", binKey); return; } List<Path> filePaths; if (filePathStrings != null) { filePaths = new ArrayList<>(filePathStrings.size()); for (String filePathString : filePathStrings) { File file = new File(filePathString); Path filePath = file.toPath(); if (!(file.exists() && applicableFile(file, config) && pathInBins(filePath, config.getBinPaths()))) { throw new IOException("Specified file was not a valid target for bin " + config.getName() + ": " + file.getAbsolutePath()); } filePaths.add(filePath); } } else { List<String> fileList = this.listFiles(binKey); filePaths = new ArrayList<>(fileList.size()); for (String filePathString : fileList) { filePaths.add(Paths.get(filePathString)); } } DepositInfo info = makeDeposit(); moveFiles(filePaths, info, config); registerDeposit(info, config, extras); }</code><technical_language>need some kind of locking here? I assuming BinCollector is a spring instantiated singleton this operation a short while, depending storage data size</technical_language>

Target:
public void collect(List<String> filePathStrings, String binKey, Map<String, String> extras) throws IOException { DepositBinConfiguration config = getConfiguration(binKey); if (config == null) { log.warn("Invalid bin specified: {}", binKey); return; } try { config.getKeyLock().lock(); List<Path> filePaths; if (filePathStrings != null) { filePaths = new ArrayList<>(filePathStrings.size()); for (String filePathString : filePathStrings) { File file = new File(filePathString); Path filePath = file.toPath(); if (!(file.exists() && applicableFile(file, config) && pathInBins(filePath, config.getBinPaths()))) { throw new IOException("Specified file was not a valid target for bin " + config.getName() + ": " + file.getAbsolutePath()); } filePaths.add(filePath); } } else { List<String> fileList = this.listFiles(binKey); filePaths = new ArrayList<>(fileList.size()); for (String filePathString : fileList) { filePaths.add(Paths.get(filePathString)); } } DepositInfo info = makeDeposit(); moveFiles(filePaths, info, config); registerDeposit(info, config, extras); } finally { config.getKeyLock().unlock(); } }
Source:
<code>private void emit(final LogLevel level, final Throwable throwable, final Object... parts) { if (isEnabled(level)) { <START> synchronized (this.out) { <END> this.out.print(level.name()); this.out.print('\t'); this.out.print(getTimestamp()); this.out.print('\t'); this.out.print(this.className); this.out.print('\t'); for (final Object part : parts) { if (part != null && part.getClass().isArray()) { final Class<?> component = part.getClass().getComponentType(); if (component.equals(Boolean.TYPE)) this.out.print(Arrays.toString( (boolean[]) part)); else if (component.equals(Byte.TYPE)) this.out.print(Arrays.toString( (byte[]) part)); else if (component.equals(Character.TYPE)) this.out.print(Arrays.toString( (char[]) part)); else if (component.equals(Double.TYPE)) this.out.print(Arrays.toString( (double[]) part)); else if (component.equals(Float.TYPE)) this.out.print(Arrays.toString( (float[]) part)); else if (component.equals(Integer.TYPE)) this.out.print(Arrays.toString( (int[]) part)); else if (component.equals(Long.TYPE)) this.out.print(Arrays.toString( (long[]) part)); else if (component.equals(Short.TYPE)) this.out.print(Arrays.toString( (short[]) part)); else this.out.print(Arrays.toString( (Object[]) part)); } else { this.out.print(part); } } this.out.println(); if (throwable != null) { throwable.printStackTrace(this.out); } } } }</code><technical_language>Nicklas, Thanks for patch! However, I synchronizing this instance -- globally VM, in cases fully sleuthed -- right approach. create a static lock object in Log synchronize that, please? Thanks</technical_language>

Target:
private void emit(final LogLevel level, final Throwable throwable, final Object... parts) { if (isEnabled(level)) { StringBuffer tmp = new StringBuffer(); tmp.append(level.name()); tmp.append('\t'); tmp.append(getTimestamp()); tmp.append('\t'); tmp.append(this.className); tmp.append('\t'); for (final Object part : parts) { if (part != null && part.getClass().isArray()) { final Class<?> component = part.getClass().getComponentType(); if (component.equals(Boolean.TYPE)) tmp.append(Arrays.toString( (boolean[]) part)); else if (component.equals(Byte.TYPE)) tmp.append(Arrays.toString( (byte[]) part)); else if (component.equals(Character.TYPE)) tmp.append(Arrays.toString( (char[]) part)); else if (component.equals(Double.TYPE)) tmp.append(Arrays.toString( (double[]) part)); else if (component.equals(Float.TYPE)) tmp.append(Arrays.toString( (float[]) part)); else if (component.equals(Integer.TYPE)) tmp.append(Arrays.toString( (int[]) part)); else if (component.equals(Long.TYPE)) tmp.append(Arrays.toString( (long[]) part)); else if (component.equals(Short.TYPE)) tmp.append(Arrays.toString( (short[]) part)); else tmp.append(Arrays.toString( (Object[]) part)); } else { tmp.append(part); } } if (throwable != null) { synchronized (this.out) { this.out.println(tmp.toString()); throwable.printStackTrace(this.out); } } else { this.out.println(tmp.toString()); } } }
Source:
<code>public void validate_shouldFailValidationIfFieldLengthsAreNotCorrect() throws Exception { Role role = new Role(); role.setRole( "too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text"); role.setDescription( "too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text"); Errors errors = new BindException(role, "type"); dao.validate(role, errors); <START> Assert.assertTrue(errors.hasFieldErrors("role")); <END> }</code><technical_language>check message code</technical_language>

Target:
public void validate_shouldFailValidationIfFieldLengthsAreNotCorrect() throws Exception { String errorCode = "error.exceededMaxLengthOfField"; String[] RoleFeilds = new String[] { "role", "description" }; Role role = new Role(); role.setRole( "too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text"); role.setDescription( "too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text"); Errors errors = new BindException(role, "type"); dao.validate(role, errors); for (String feilds : RoleFeilds) { FieldError fielderror = errors.getFieldError(feilds); Assert.assertTrue(errorCode.equals(fielderror.getCode())); } }
Source:
<code>private static List<ExtendedTextEdit> convertToExtendedEdit( List<TextEdit> edits, String filePath) { try { if (!isStartWithProject(filePath)) { filePath = prefixProject(filePath); } CharStreamIterator charStreamIter = <START> new CharStreamIterator(CharStreamEditor.forReader(new FileReader(filePath))); <END> return convertToExtendedEdits(edits, charStreamIter); } catch (IOException e) { LOG.error("Can't read file", e); return Collections.emptyList(); } }</code><technical_language>please forget close stream for new FileReader(filePath)</technical_language>

Target:
private static List<ExtendedTextEdit> convertToExtendedEdit( List<TextEdit> edits, String filePath) { if (!isStartWithProject(filePath)) { filePath = prefixProject(filePath); } try (FileReader reader = new FileReader(filePath)) { CharStreamIterator charStreamIter = new CharStreamIterator(CharStreamEditor.forReader(reader)); return convertToExtendedEdits(edits, charStreamIter); } catch (IOException e) { LOG.error("Can't read file", e); return Collections.emptyList(); } }
Source:
<code>public static LockAwareTransactionManager setupTxManager(KeyValueService kvs, TimestampService tsService, SweepStrategyManager ssm, TransactionService txService) { LockClient lockClient = LockClient.of("sweep client"); LockService lockService = LockServiceImpl.create( LockServerOptions.builder().isStandaloneServer(false).build()); Supplier<AtlasDbConstraintCheckingMode> constraints = () -> AtlasDbConstraintCheckingMode.NO_CONSTRAINT_CHECKING; ConflictDetectionManager cdm = ConflictDetectionManagers.createWithoutWarmingCache(kvs); Cleaner cleaner = new NoOpCleaner(); LockAwareTransactionManager txManager = new SerializableTransactionManager(kvs, tsService, lockClient, <START> lockService, txService, constraints, cdm, ssm, cleaner, false, 16, 4); <END> setupTables(kvs); return txManager; }</code><technical_language>Reuse constants AbstractTransactionTest</technical_language>

Target:
public static LockAwareTransactionManager setupTxManager(KeyValueService kvs, TimestampService tsService, SweepStrategyManager ssm, TransactionService txService) { LockClient lockClient = LockClient.of("sweep client"); LockService lockService = LockServiceImpl.create( LockServerOptions.builder().isStandaloneServer(false).build()); Supplier<AtlasDbConstraintCheckingMode> constraints = () -> AtlasDbConstraintCheckingMode.NO_CONSTRAINT_CHECKING; ConflictDetectionManager cdm = ConflictDetectionManagers.createWithoutWarmingCache(kvs); Cleaner cleaner = new NoOpCleaner(); LockAwareTransactionManager txManager = new SerializableTransactionManager( kvs, tsService, lockClient, lockService, txService, constraints, cdm, ssm, cleaner, false, AbstractTransactionTest.GET_RANGES_THREAD_POOL_SIZE, AbstractTransactionTest.DEFAULT_GET_RANGES_CONCURRENCY); setupTables(kvs); return txManager; }
Source:
<code>public SProcessDefinition getProcessDefinition(final long processId) throws SProcessDefinitionNotFoundException, SProcessDefinitionReadException { try { <START> final SProcessDefinitionDeployInfo processDeploymentInfo = getProcessDeploymentInfo(processId); <END> final Pair<Long, SProcessDefinition> processWithTimestamp = getFromCache(processId); SProcessDefinition sProcessDefinition; if (processWithTimestamp == null || processWithTimestamp.getKey() != processDeploymentInfo.getLastUpdateDate()) { final DesignProcessDefinition objectFromXML = processDefinitionBARContribution.convertXmlToProcess(processDeploymentInfo.getDesignContent() .getContent()); sProcessDefinition = convertDesignProcessDefinition(objectFromXML); setIdOnProcessDefinition(sProcessDefinition, processId); cache(sProcessDefinition, processDeploymentInfo.getLastUpdateDate()); } else { sProcessDefinition = processWithTimestamp.getValue(); } return sProcessDefinition; } catch (XMLParseException | IOException | SReflectException | SCacheException e) { throw new SProcessDefinitionReadException(e); } }</code><technical_language>// Read database (or Hibernate cache):</technical_language>

Target:
public SProcessDefinition getProcessDefinition(final long processId) throws SProcessDefinitionNotFoundException, SProcessDefinitionReadException { try { final SProcessDefinitionDeployInfo processDeploymentInfo = getProcessDeploymentInfo(processId); final Pair<Long, SProcessDefinition> processWithTimestamp = getSProcessDefinitionFromCache(processId); if (isSProcessDefinitionUpToDate(processDeploymentInfo, processWithTimestamp)) { return readSProcessDefinitionFromDatabase(processId, processDeploymentInfo); } else { return processWithTimestamp.getValue(); } } catch (XMLParseException | IOException | SReflectException | SCacheException e) { throw new SProcessDefinitionReadException(e); } }
Source:
<code>protected Warning createWarning(Matcher matcher) { String message = matcher.group(5); String category = classifyIfEmpty(matcher.group(2), message); Priority priority = Priority.LOW; switch (category.charAt(0)){ case 'E': priority = Priority.HIGH; category = "ERROR"; break; case 'W': priority = Priority.NORMAL; category = "WARNING"; break; case 'I': priority = Priority.LOW; category = "IGNORE"; <START> break; <END> } return createWarning(matcher.group(1), getLineNumber(matcher.group(3)), category, message, priority); }</code><technical_language>default: // do change priority category</technical_language>

Target:
protected Warning createWarning(Matcher matcher) { String message = matcher.group(4); String category = classifyIfEmpty(matcher.group(1), message); Priority priority = Priority.LOW; switch (category.charAt(0)){ case 'E': priority = Priority.HIGH; category = "ERROR"; break; case 'W': priority = Priority.NORMAL; category = "WARNING"; break; case 'I': priority = Priority.LOW; category = "IGNORE"; break; default: break; } return createWarning(fileName, getLineNumber(matcher.group(2)), category, message, priority); }
Source:
<code>public AsyncFuture<WriteMetadata> write(final WriteMetadata.Request request) { return doto(c -> { final Series series = request.getSeries(); final String id = series.hash(); final String[] indices; try { indices = c.writeIndices(); } catch (NoIndexSelectedException e) { return async.failed(e); } final List<AsyncFuture<WriteMetadata>> writes = new ArrayList<>(); for (final String index : indices) { if (!writeCache.acquire(Pair.of(index, series.getHashCode()), reporter::reportWriteDroppedByCacheHit, reporter::reportWriteDroppedByRateLimit)) { continue; } final XContentBuilder source = XContentFactory.jsonBuilder(); source.startObject(); buildContext(source, series); source.endObject(); final IndexRequestBuilder builder = c .index(index, TYPE_METADATA) .setId(id) .setSource(source) .setOpType(OpType.CREATE); final RequestTimer<WriteMetadata> timer = WriteMetadata.timer(); final FutureReporter.Context writeContext = reporter.setupBackendWriteReporter(); AsyncFuture<WriteMetadata> result = bind(builder.execute()) .directTransform(response -> timer.end()) .catchFailed(throwable -> { if (throwable instanceof VersionConflictEngineException) { reporter.reportWriteDroppedByDuplicate(); return WriteMetadata.of(); } log.error("Metadata write failed: ", throwable); throw new RuntimeException(throwable); <START> }) <END> .onDone(writeContext); writes.add(result); } return async.collect(writes, WriteMetadata.reduce()); }); }</code><technical_language>helper method</technical_language>

Target:
public AsyncFuture<WriteMetadata> write(final WriteMetadata.Request request) { return doto(c -> { final Series series = request.getSeries(); final String id = series.hash(); final String[] indices; try { indices = c.writeIndices(); } catch (NoIndexSelectedException e) { return async.failed(e); } final List<AsyncFuture<WriteMetadata>> writes = new ArrayList<>(); for (final String index : indices) { if (!writeCache.acquire(Pair.of(index, series.getHashCode()), reporter::reportWriteDroppedByCacheHit, reporter::reportWriteDroppedByRateLimit)) { continue; } final XContentBuilder source = XContentFactory.jsonBuilder(); source.startObject(); buildContext(source, series); source.endObject(); final IndexRequestBuilder builder = c .index(index, TYPE_METADATA) .setId(id) .setSource(source) .setOpType(OpType.CREATE); final RequestTimer<WriteMetadata> timer = WriteMetadata.timer(); final FutureReporter.Context writeContext = reporter.setupBackendWriteReporter(); AsyncFuture<WriteMetadata> result = bind(builder.execute()) .directTransform(response -> timer.end()) .catchFailed(handleVersionConflict(WriteMetadata::of, reporter::reportWriteDroppedByDuplicate)) .onDone(writeContext); writes.add(result); } return async.collect(writes, WriteMetadata.reduce()); }); }
Source:
<code>public void deactivate() { <START> logger.debug("deactivate() is called!"); <END> disconnect(); }</code><technical_language>please remove decrease log level TRACE</technical_language>

Target:
public void deactivate() { logger.trace("deactivate() is called!"); stopWatchdog(); disconnect(); }
Source:
<code>private String getQualifiedName(AstNode node) { Symbol symbol = getContext().symbolTable().getSymbol(node); <START> if (symbol != null) { <END> return symbol.qualifiedName(); } return ""; }</code><technical_language>return symbol != null ? symbol.qualifiedName() : "";</technical_language>

Target:
private String getQualifiedName(AstNode node) { Symbol symbol = getContext().symbolTable().getSymbol(node); return symbol != null ? symbol.qualifiedName() : ""; }
Source:
<code>public Result implement(EnumerableRelImplementor implementor, Prefer pref) { if (getCall().getKind() == SqlKind.TUMBLE) { return tableValuedFunctionWindowingImplement(implementor, pref); } else { <START> BlockBuilder bb = new BlockBuilder(); <END> final JavaRowFormat format; if (getElementType() == null) { format = JavaRowFormat.ARRAY; } else if (rowType.getFieldCount() == 1 && isQueryable()) { format = JavaRowFormat.SCALAR; } else if (getElementType() instanceof Class && Object[].class.isAssignableFrom((Class) getElementType())) { format = JavaRowFormat.ARRAY; } else { format = JavaRowFormat.CUSTOM; } final PhysType physType = PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), format, false); RexToLixTranslator t = RexToLixTranslator.forAggregation( (JavaTypeFactory) getCluster().getTypeFactory(), bb, null, implementor.getConformance()); t = t.setCorrelates(implementor.allCorrelateVariables); bb.add(Expressions.return_(null, t.translate(getCall()))); return implementor.result(physType, bb.toBlock()); } }</code><technical_language>move else branch a single method</technical_language>

Target:
public Result implement(EnumerableRelImplementor implementor, Prefer pref) { if (isImplementorDefined((RexCall) getCall())) { return tvfImplementorBasedImplement(implementor, pref); } else { return defaultTableValuedFunctionImplement(implementor, pref); } }
Source:
<code>public Set<Cube> calculate(Cube cube) { ICubicWorld world = cube.getWorld(); ICubeCache cache = world.getCubeCache(); for (int x = -2; x <= 2; ++x) { for (int y = -2; y <= 2; ++y) { for (int z = -2; z <= 2; ++z) { CubeCoords coords = new CubeCoords(cube.getX() + x, cube.getY() + y, cube.getZ() + z); if (!cache.cubeExists(coords) || cache.getCube(coords).getCurrentStage().precedes(generatorStage)) { CubicChunks.LOGGER.error("Missing cube ({})! {}/{}", coords, cache.getCube(coords).getCurrentStage().getName(), generatorStage.getName()); <START> System.exit(1); <END> } } } } setRawSkylight(cube); diffuseSkylight(cube); return Sets.newHashSet(cube); }</code><technical_language>1. System.exit(), Forge show a big warning loading direct reference it, redirect it. FMLCommonHandler.exitJava(). throw new Error(). 2. simply create new FastCubeBlockAccess(cubeCache, centerCube, radius) modify check stage (and check stage, I simply forgot that) - throw exception if required cube loaded dump information cubes loaded (you modify include stage if do now). pass FastCubeBlockAccess some of methods there. leave fix later. I want do in FirstLightProcessor needs fast. Currently close vanilla initial lighting preformance. of time is spent creating FastCubeBlockAccess objects</technical_language>

Target:
public Set<Cube> calculate(Cube cube) { setRawSkylight(cube); diffuseSkylight(cube); return Sets.newHashSet(cube); }
Source:
<code>private NodeSchemaLoadResult loadSchemaFromYaml(File schemaFile) { <START> LOG.info("Loading network topology layer schema file " + schemaFile); <END> NodeSchemaLoadResult finalSchema; try { FileInputStream fileInputStream = new FileInputStream(schemaFile); Yaml yaml = new Yaml(); NodeSchema nodeTree = yaml.loadAs(fileInputStream, NodeSchema.class); fileInputStream.close(); List<NodeSchema> schemaList = new ArrayList<>(); if (nodeTree.getType() != LayerType.ROOT) { throw new IllegalArgumentException("First layer is not a ROOT node." + " schema file: " + schemaFile.getAbsolutePath()); } schemaList.add(nodeTree); if (nodeTree.getSublayer() != null) { nodeTree = nodeTree.getSublayer().get(0); } while (nodeTree != null) { if (nodeTree.getType() == LayerType.LEAF_NODE && nodeTree.getSublayer() != null) { throw new IllegalArgumentException("Leaf node in the middle of path." + " schema file: " + schemaFile.getAbsolutePath()); } if (nodeTree.getType() == LayerType.ROOT) { throw new IllegalArgumentException("Multiple root nodes are defined." + " schema file: " + schemaFile.getAbsolutePath()); } schemaList.add(nodeTree); if (nodeTree.getSublayer() != null) { nodeTree = nodeTree.getSublayer().get(0); } else { break; } } finalSchema = new NodeSchemaLoadResult(schemaList, true); } catch (Exception e) { throw new IllegalArgumentException("Fail to load network topology node" + " schema file: " + schemaFile.getAbsolutePath() + " , error:" + e.getMessage()); } return finalSchema; }</code><technical_language>NIT: parameterized log4j LOG.info("Loading network topology layer schema file {}", schemaFile);</technical_language>

Target:
private NodeSchemaLoadResult loadSchemaFromYaml(File schemaFile) { LOG.info("Loading network topology layer schema file {}", schemaFile); NodeSchemaLoadResult finalSchema; try { Yaml yaml = new Yaml(); NodeSchema nodeTree; try (FileInputStream fileInputStream = new FileInputStream(schemaFile)) { nodeTree = yaml.loadAs(fileInputStream, NodeSchema.class); } List<NodeSchema> schemaList = new ArrayList<>(); if (nodeTree.getType() != LayerType.ROOT) { throw new IllegalArgumentException("First layer is not a ROOT node." + " schema file: " + schemaFile.getAbsolutePath()); } schemaList.add(nodeTree); if (nodeTree.getSublayer() != null) { nodeTree = nodeTree.getSublayer().get(0); } while (nodeTree != null) { if (nodeTree.getType() == LayerType.LEAF_NODE && nodeTree.getSublayer() != null) { throw new IllegalArgumentException("Leaf node in the middle of path." + " schema file: " + schemaFile.getAbsolutePath()); } if (nodeTree.getType() == LayerType.ROOT) { throw new IllegalArgumentException("Multiple root nodes are defined." + " schema file: " + schemaFile.getAbsolutePath()); } schemaList.add(nodeTree); if (nodeTree.getSublayer() != null) { nodeTree = nodeTree.getSublayer().get(0); } else { break; } } finalSchema = new NodeSchemaLoadResult(schemaList, true); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalArgumentException("Fail to load network topology node" + " schema file: " + schemaFile.getAbsolutePath() + " , error:" + e.getMessage()); } return finalSchema; }
Source:
<code>protected boolean canAddVm(ArrayList<String> reasons, Collection<StorageDomain> destStorages) { VmStatic vmStaticFromParams = getParameters().getVmStaticData(); boolean returnValue = canAddVm(reasons, vmStaticFromParams.getName(), getStoragePoolId() .getValue(), vmStaticFromParams.getPriority()); if (returnValue) { List<ValidationError> validationErrors = validateCustomProperties(vmStaticFromParams); if (!validationErrors.isEmpty()) { <START> new VmHandler().handleCustomPropertiesError(validationErrors, reasons); <END> returnValue = false; } } if (returnValue && shouldCheckSpaceInStorageDomains()) { if (!getStoragePoolId().equals(getStoragePoolIdFromSourceImageContainer())) { reasons.add(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_MATCH.toString()); returnValue = false; } else { for (StorageDomain domain : destStorages) { StorageDomainValidator storageDomainValidator = new StorageDomainValidator(domain); if (!validate(storageDomainValidator.isDomainWithinThresholds()) || !validate(storageDomainValidator.isDomainHasSpaceForRequest(getNeededDiskSize(domain.getId())))) { return false; } } } } if (returnValue) { returnValue = isDedicatedVdsOnSameCluster(vmStaticFromParams); } return returnValue; }</code><technical_language>I missing handleCustomPropertiesError is static, new VmHandler()</technical_language>

Target:
protected boolean canAddVm(ArrayList<String> reasons, Collection<StorageDomain> destStorages) { VmStatic vmStaticFromParams = getParameters().getVmStaticData(); boolean returnValue = canAddVm(reasons, vmStaticFromParams.getName(), getStoragePoolId() .getValue(), vmStaticFromParams.getPriority()); if (returnValue) { List<ValidationError> validationErrors = validateCustomProperties(vmStaticFromParams); if (!validationErrors.isEmpty()) { VmHandler.handleCustomPropertiesError(validationErrors, reasons); returnValue = false; } } if (returnValue && shouldCheckSpaceInStorageDomains()) { if (!getStoragePoolId().equals(getStoragePoolIdFromSourceImageContainer())) { reasons.add(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_MATCH.toString()); returnValue = false; } else { for (StorageDomain domain : destStorages) { StorageDomainValidator storageDomainValidator = new StorageDomainValidator(domain); if (!validate(storageDomainValidator.isDomainWithinThresholds()) || !validate(storageDomainValidator.isDomainHasSpaceForRequest(getNeededDiskSize(domain.getId())))) { return false; } } } } if (returnValue) { returnValue = isDedicatedVdsOnSameCluster(vmStaticFromParams); } return returnValue; }
Source:
<code>protected void releaseInstance(T instance) { if(!created.contains(instance)) { throw new IllegalArgumentException("Given instance of " + instance.getClass().getName() + " is not managed by this provider"); } if(instance instanceof Closeable) { try { ((Closeable)instance).close(); <START> created.remove(instance); <END> } catch (IOException e) { throw new RuntimeException("Failed to close the instance of " + instance.getClass().getName(), e); } } }</code><technical_language>I suggest inverting calls, instance longer is in created collection</technical_language>

Target:
protected void releaseInstance(T instance) throws IOException { if(!created.remove(instance)) { throw new IllegalArgumentException("Given instance of " + instance.getClass().getName() + " is not managed by this provider"); } if(instance instanceof Closeable) { ((Closeable)instance).close(); } }
Source:
<code>public void removed(Provider<E> provider, E element) { final E existingElement; elementWriteLock.lock(); try { final K uid = element.getUID(); existingElement = identifierToElement.get(uid); if (existingElement == null) { logger.debug("{} with key '{}' could not be removed from provider because it does not exist!", element.getClass().getSimpleName(), uid, provider.getClass().getSimpleName()); return; } try { onRemoveElement(existingElement); } catch (final RuntimeException ex) { <START> logger.warn("Could not remove element: {}", ex.getMessage(), ex); <END> return; } identifierToElement.remove(uid); elementToProvider.remove(existingElement); providerToElements.get(provider).remove(existingElement); elements.remove(existingElement); } finally { elementWriteLock.unlock(); } notifyListenersAboutRemovedElement(existingElement); }</code><technical_language>suggestion logger.warn("Could remove key '{}': {}", element.getClass().getSimpleName(), uid, ex.getMessage(), ex);</technical_language>

Target:
public void removed(Provider<E> provider, E element) { final E existingElement; elementWriteLock.lock(); try { final K uid = element.getUID(); existingElement = identifierToElement.get(uid); if (existingElement == null) { logger.debug("Cannot remove \"{}\" with key \"{}\" from provider \"{}\" because it does not exist!", element.getClass().getSimpleName(), uid, provider.getClass().getSimpleName()); return; } try { onRemoveElement(existingElement); } catch (final RuntimeException ex) { logger.warn("Cannot remove \"{}\" with key \"{}\": {}", element.getClass().getSimpleName(), uid, ex.getMessage(), ex); return; } identifierToElement.remove(uid); elementToProvider.remove(existingElement); providerToElements.get(provider).remove(existingElement); elements.remove(existingElement); } finally { elementWriteLock.unlock(); } notifyListenersAboutRemovedElement(existingElement); }
Source:
<code>public ConfigDescription getConfigDescription(URI uri, Locale locale) { if ("thing".equals(uri.getScheme()) == false) { return null; } <START> if (thingRegistry == null || thingTypeRegistry == null) { <END> return null; } ThingUID thingUID = new ThingUID(uri.getSchemeSpecificPart()); Thing thing = thingRegistry.get(thingUID); if (thing == null) { return null; } ThingType thingType = thingTypeRegistry.getThingType(thing.getThingTypeUID()); if (thingType == null) { return null; } URI configURI = thingType.getConfigDescriptionURI(); if (configURI == null) { return null; } ConfigDescription config = configDescriptionRegistry.getConfigDescription(configURI, locale); if (config == null) { return null; } return config; }</code><technical_language>chose a policy=static for reference, null</technical_language>

Target:
public ConfigDescription getConfigDescription(URI uri, Locale locale) { if ("thing".equals(uri.getScheme()) == false) { return null; } ThingUID thingUID = new ThingUID(uri.getSchemeSpecificPart()); Thing thing = thingRegistry.get(thingUID); if (thing == null) { return null; } ThingType thingType = thingTypeRegistry.getThingType(thing.getThingTypeUID()); if (thingType == null) { return null; } URI configURI = thingType.getConfigDescriptionURI(); if (configURI == null) { return null; } ConfigDescription config = configDescriptionRegistry.getConfigDescription(configURI, locale); if (config == null) { return null; } return config; }
Source:
<code>DefaultOperatorContext( Path projectPath, TaskRequest taskRequest, SecretProvider secretProvider, PrivilegedVariables privilegedVariables) { <START> this.projectPath = projectPath; <END> this.taskRequest = taskRequest; this.secretProvider = secretProvider; this.privilegedVariables = privilegedVariables; }</code><technical_language>null checks</technical_language>

Target:
DefaultOperatorContext( Path projectPath, TaskRequest taskRequest, SecretProvider secretProvider, PrivilegedVariables privilegedVariables) { this.projectPath = requireNonNull(projectPath, "projectPath"); this.taskRequest = requireNonNull(taskRequest, "taskRequest"); this.secretProvider = requireNonNull(secretProvider, "secretProvider"); this.privilegedVariables = requireNonNull(privilegedVariables, "privilegedVariables"); }
Source:
<code>public void startReset(final String email) { if (mCachedPasswordReset == null || !TextUtils.equals(email, mCachedPasswordReset.first)) { mCachedPasswordReset = Pair.create(email, mAuth.sendPasswordResetEmail(email)); } <START> mFlowHolder.getProgressListener().setValue(false); <END> mCachedPasswordReset.second.addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { mFlowHolder.getProgressListener().setValue(true); mPasswordResetListener.setValue(task.isSuccessful() ? Tasks.forResult(email) : Tasks.<String>forException(task.getException())); } }); }</code><technical_language>expose mFlowHolder a getter? Accessing superclass variables I definition kinda freaks out</technical_language>

Target:
public void startReset(final String email) { mProgressLiveData.setValue(new Resource<String>()); getAuth().sendPasswordResetEmail(email) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Resource<String> state = task.isSuccessful() ? new Resource<>(email) : new Resource<String>(task.getException()); mProgressLiveData.setValue(state); } }); }