auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void testExecute_fakeCourse_shouldFail() { InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); loginAsInstructor(instructor1OfCourse1.googleId); ______TS("Get respondents for fake course"); String[] params = new String[] { Const.ParamsNames.COURSE_ID, "fake-course", }; assertNull(logic.getCourse("fake-course")); GetHasResponsesAction getHasResponsesAction = getAction(params); JsonResult jsonResult = getJsonResult(getHasResponsesAction); MessageOutput messageOutput = (MessageOutput) jsonResult.getOutput(); <START> assertEquals(jsonResult.getStatusCode(), HttpStatus.SC_NOT_FOUND); <END> assertEquals(messageOutput.getMessage(), "No course with id: fake-course"); }</code><technical_language>parameter of assertEquals is expected value</technical_language>

Target:
protected void testExecute_fakeCourse_shouldFail() { InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); loginAsInstructor(instructor1OfCourse1.googleId); ______TS("Get respondents for fake course"); String[] params = new String[] { Const.ParamsNames.COURSE_ID, "fake-course", }; assertNull(logic.getCourse("fake-course")); GetHasResponsesAction getHasResponsesAction = getAction(params); JsonResult jsonResult = getJsonResult(getHasResponsesAction); MessageOutput messageOutput = (MessageOutput) jsonResult.getOutput(); assertEquals(HttpStatus.SC_NOT_FOUND, jsonResult.getStatusCode()); assertEquals("No course with id: fake-course", messageOutput.getMessage()); }
Source:
<code>protected void doRemoveSemanticResource(final Resource res, final ResourceSet set) { set.getResources().remove(res); EObject rootObject = tracker.getRootObjectFromResourceURI(res.getURI().toString()); <START> if (rootObject == null) { rootObject = res.getContents() == null ? null : res.getContents().get(0); } <END> for (final DAnalysis analysis : this.allAnalyses()) { analysis.getModels().remove(rootObject); } disableCrossReferencerResolve(res); unregisterResourceInCrossReferencer(res); if (!isFromPackageRegistry(set, res)) { disableCrossReferencerResolve(res); res.unload(); enableCrossReferencerResolve(res); } }</code><technical_language>bug fixed commit <LINK_0> reported</technical_language>

Target:
protected void doRemoveSemanticResource(final Resource res, final ResourceSet set) { set.getResources().remove(res); EObject rootObject = tracker.getRootObjectFromResourceURI(res.getURI().toString()); if (rootObject == null) { rootObject = findSemanticRoot(res); } for (final DAnalysis analysis : this.allAnalyses()) { analysis.getModels().remove(rootObject); } unregisterResourceInCrossReferencer(res); if (!isFromPackageRegistry(set, res)) { disableCrossReferencerResolve(res); res.unload(); enableCrossReferencerResolve(res); } }
Source:
<code>public void testQueueOrderWhenDownloading2Items() { ItemEnqueuePositionCalculator calculator = new ItemEnqueuePositionCalculator(options); DownloadStateProvider stubDownloadStateProvider = mock(DownloadStateProvider.class); stub(stubDownloadStateProvider.isDownloadingFile(any(FeedMedia.class))).toReturn(false); calculator.downloadStateProvider = stubDownloadStateProvider; List<FeedItem> queue = new ArrayList<>(queueInitial); Playable currentlyPlaying = getCurrentlyPlaying(idCurrentlyPlaying); FeedItem tFI101 = setAsDownloading(101, stubDownloadStateProvider); doAddToQueueAndAssertResult(message + " (1st download)", calculator, tFI101, queue, currentlyPlaying, idsExpectedAfter101); <START> <END> FeedItem tFI102 = setAsDownloading(102, stubDownloadStateProvider); doAddToQueueAndAssertResult(message + " (2nd download, it should preserve order of download)", calculator, tFI102, queue, currentlyPlaying, idsExpectedAfter102); }</code><technical_language>empty lines in this test case</technical_language>

Target:
public void testQueueOrderWhenDownloading2Items() { ItemEnqueuePositionCalculator calculator = new ItemEnqueuePositionCalculator(options); DownloadStateProvider stubDownloadStateProvider = mock(DownloadStateProvider.class); stub(stubDownloadStateProvider.isDownloadingFile(any(FeedMedia.class))).toReturn(false); calculator.downloadStateProvider = stubDownloadStateProvider; List<FeedItem> queue = new ArrayList<>(queueInitial); Playable currentlyPlaying = getCurrentlyPlaying(idCurrentlyPlaying); FeedItem tFI101 = setAsDownloading(101, stubDownloadStateProvider, true); doAddToQueueAndAssertResult(message + " (1st download)", calculator, tFI101, queue, currentlyPlaying, idsExpectedAfter101); FeedItem tFI102 = setAsDownloading(102, stubDownloadStateProvider, true); doAddToQueueAndAssertResult(message + " (2nd download, it should preserve order of download)", calculator, tFI102, queue, currentlyPlaying, idsExpectedAfter102); setAsDownloading(tFI102, stubDownloadStateProvider, false); FeedItem tFI103 = setAsDownloading(103, stubDownloadStateProvider, true); doAddToQueueAndAssertResult(message + " (3rd download, with 2nd download failed; " + "it should be behind 1st download (unless enqueueLocation is BACK)", calculator, tFI103, queue, currentlyPlaying, idsExpectedAfter103); }
Source:
<code>private void installPnpm(List<String> installCommand) { List<String> command = new ArrayList<>(); command.addAll(installCommand); command.add("install"); command.add("pnpm@" + DEFAULT_PNPM_VERSION); FrontendUtils.console(YELLOW, FrontendUtils.commandToString(baseDir, command)); ProcessBuilder builder = FrontendUtils.createProcessBuilder(command); builder.environment().put("ADBLOCK", "1"); builder.directory(new File(baseDir)); builder.redirectInput(ProcessBuilder.Redirect.INHERIT); builder.redirectError(ProcessBuilder.Redirect.INHERIT); Process process = null; try { process = builder.start(); getLogger().debug("Output of `{}`:", <START> command.stream().collect(Collectors.joining(" "))); <END> try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String stdoutLine; while ((stdoutLine = reader.readLine()) != null) { getLogger().debug(stdoutLine); } } int errorCode = process.waitFor(); if (errorCode != 0) { getLogger().error("Couldn't install 'pnpm'"); } else { getLogger().debug("Pnpm is successfully installed"); } } catch (InterruptedException | IOException e) { getLogger().error("Error when running `npm install`", e); } finally { if (process != null) { process.destroyForcibly(); } } }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Invoke method(s) conditionally. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private void installPnpm(List<String> installCommand) { List<String> command = new ArrayList<>(); command.addAll(installCommand); command.add("install"); command.add("pnpm@" + DEFAULT_PNPM_VERSION); FrontendUtils.console(FrontendUtils.YELLOW, FrontendUtils.commandToString(baseDir, command)); ProcessBuilder builder = FrontendUtils.createProcessBuilder(command); builder.environment().put("ADBLOCK", "1"); builder.directory(new File(baseDir)); builder.redirectInput(ProcessBuilder.Redirect.INHERIT); builder.redirectError(ProcessBuilder.Redirect.INHERIT); Process process = null; try { process = builder.start(); getLogger().debug("Output of `{}`:", command.stream().collect(Collectors.joining(" "))); try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String stdoutLine; while ((stdoutLine = reader.readLine()) != null) { getLogger().debug(stdoutLine); } } int errorCode = process.waitFor(); if (errorCode != 0) { getLogger().error("Couldn't install 'pnpm'"); } else { getLogger().debug("Pnpm is successfully installed"); } } catch (InterruptedException | IOException e) { getLogger().error("Error when running `npm install`", e); } finally { if (process != null) { process.destroyForcibly(); } } }
Source:
<code>public HypervisorResource(ConsumerResource consumerResource, ConsumerCurator consumerCurator, ConsumerTypeCurator consumerTypeCurator, I18n i18n, OwnerCurator ownerCurator, Provider<GuestMigration> migrationProvider, ModelTranslator translator, GuestIdResource guestIdResource) { this.consumerResource = consumerResource; this.consumerCurator = consumerCurator; this.consumerTypeCurator = consumerTypeCurator; this.i18n = i18n; this.ownerCurator = ownerCurator; this.migrationProvider = migrationProvider; this.translator = translator; this.guestIdResource = guestIdResource; this.hypervisorType = consumerTypeCurator.lookupByLabel(ConsumerTypeEnum.HYPERVISOR.getLabel()); if (this.hypervisorType == null) { this.hypervisorType = consumerTypeCurator.create(new ConsumerType(ConsumerTypeEnum.HYPERVISOR)); <START> } <END> }</code><technical_language>this lookup create if exist pattern in a couple of places (also in UberCert code path). move curator</technical_language>

Target:
public HypervisorResource(ConsumerResource consumerResource, ConsumerCurator consumerCurator, ConsumerTypeCurator consumerTypeCurator, I18n i18n, OwnerCurator ownerCurator, Provider<GuestMigration> migrationProvider, ModelTranslator translator, GuestIdResource guestIdResource) { this.consumerResource = consumerResource; this.consumerCurator = consumerCurator; this.consumerTypeCurator = consumerTypeCurator; this.i18n = i18n; this.ownerCurator = ownerCurator; this.migrationProvider = migrationProvider; this.translator = translator; this.guestIdResource = guestIdResource; this.hypervisorType = consumerTypeCurator.lookupByLabel(ConsumerTypeEnum.HYPERVISOR.getLabel(), true); }
Source:
<code><START> public QueryRunner<Row> preMergeQueryDecoration(final QueryRunner<Row> runner) <END> { return new SubqueryQueryRunner<>( intervalChunkingQueryRunnerDecorator.decorate( new QueryRunner<Row>() { @Override public Sequence<Row> run(Query<Row> query, Map<String, Object> responseContext) { if (!(query instanceof GroupByQuery)) { return runner.run(query, responseContext); } GroupByQuery groupByQuery = (GroupByQuery) query; ArrayList<DimensionSpec> dimensionSpecs = new ArrayList<>(); Set<String> optimizedDimensions = optimizedExtractionDims(groupByQuery, true); for (DimensionSpec dimensionSpec : groupByQuery.getDimensions()) { if (optimizedDimensions.contains(dimensionSpec.getDimension())) { dimensionSpecs.add( new DefaultDimensionSpec(dimensionSpec.getDimension(), dimensionSpec.getOutputName()) ); } else { dimensionSpecs.add(dimensionSpec); } } return runner.run( new GroupByQuery( groupByQuery.getDataSource(), groupByQuery.getQuerySegmentSpec(), groupByQuery.getDimFilter(), groupByQuery.getGranularity(), dimensionSpecs, groupByQuery.getAggregatorSpecs(), groupByQuery.getPostAggregatorSpecs(), groupByQuery.getHavingSpec(), groupByQuery.getLimitSpec(), groupByQuery.getContext() ), responseContext ); } }, this ) ); }</code><technical_language>Btw, if move this mergeResults for some reason, love reason update docs this method exists</technical_language>

Target:
public QueryRunner<Row> preMergeQueryDecoration(final QueryRunner<Row> runner) { return new SubqueryQueryRunner<>( intervalChunkingQueryRunnerDecorator.decorate( new QueryRunner<Row>() { @Override public Sequence<Row> run(Query<Row> query, Map<String, Object> responseContext) { if (!(query instanceof GroupByQuery)) { return runner.run(query, responseContext); } GroupByQuery groupByQuery = (GroupByQuery) query; ArrayList<DimensionSpec> dimensionSpecs = new ArrayList<>(); Set<String> optimizedDimensions = ImmutableSet.copyOf( Iterables.transform( extractionsToRewrite(groupByQuery), new Function<DimensionSpec, String>() { @Override public String apply(DimensionSpec input) { return input.getDimension(); } } ) ); for (DimensionSpec dimensionSpec : groupByQuery.getDimensions()) { if (optimizedDimensions.contains(dimensionSpec.getDimension())) { dimensionSpecs.add( new DefaultDimensionSpec(dimensionSpec.getDimension(), dimensionSpec.getOutputName()) ); } else { dimensionSpecs.add(dimensionSpec); } } return runner.run( groupByQuery.withDimensionSpecs(dimensionSpecs), responseContext ); } }, this ) ); }
Source:
<code>private void clearAsyncTasksWithOutVdsmId() { for (Guid asyncTaskId : getReturnValue().getAsyncTaskIdList()) { AsyncTasks task = DbFacade.getInstance().getAsyncTaskDao().get(asyncTaskId); <START> if (task.getTaskId().equals(NGuid.Empty)) { <END> AsyncTaskManager.failTaskWithoutVdsmId(task); } } }</code><technical_language>getVdsmTaskId</technical_language>

Target:
private void clearAsyncTasksWithOutVdsmId() { for (Guid asyncTaskId : getReturnValue().getAsyncTaskIdList()) { AsyncTasks task = DbFacade.getInstance().getAsyncTaskDao().get(asyncTaskId); if (task.getVdsmTaskId().equals(NGuid.Empty)) { AsyncTaskManager.failTaskWithoutVdsmId(task); } } }
Source:
<code>public String removeDotDot(String s) { while (true) { int i = s.indexOf("/../"); if (i < 1) <START> return s; <END> int j = s.lastIndexOf("/", i-1); if (j < 0) j = 0; else j = j + 1; s = s.substring(0, j) + s.substring(i+4); } }</code><technical_language>consider this style of loops dangerous if escape hatch out of loop perfect avenue perform a denial of service threads get stuck in a loop. If changing loop operates simple adding a limit loop is a simple remove 1000 "/../" that</technical_language>

Target:
public String removeDotDot(String s) { int loopCount = 0; while (true) { int i = s.indexOf("/../"); if (i < 1 || ++loopCount > 999) return s; int j = s.lastIndexOf("/", i-1); if (j < 0) j = 0; else j = j + 1; s = s.substring(0, j) + s.substring(i+4); } }
Source:
<code>public static List<Certificate> parseChain(final String chain) throws IOException, CertificateException { final List<Certificate> certs = new ArrayList<Certificate>(); try(final PemReader pemReader = new PemReader(new StringReader(chain));) { final PemObject pemObject = pemReader.readPemObject(); final CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); final ByteArrayInputStream bais = new ByteArrayInputStream(pemObject.getContent()); for (final Certificate cert : certificateFactory.generateCertificates(bais)) { if (cert instanceof X509Certificate) { certs.add(cert); } } if (certs.isEmpty()) { <START> throw new IllegalArgumentException("Unable to decode certificate chain"); <END> } } return certs; }</code><technical_language>Minor Nit: certs is argument this method. Please consider throwing IllegalStateException instead</technical_language>

Target:
public static List<Certificate> parseChain(final String chain) throws IOException, CertificateException { Preconditions.checkNotNull(chain); final List<Certificate> certs = new ArrayList<Certificate>(); try(final PemReader pemReader = new PemReader(new StringReader(chain));) { final PemObject pemObject = pemReader.readPemObject(); final CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); final ByteArrayInputStream bais = new ByteArrayInputStream(pemObject.getContent()); for (final Certificate cert : certificateFactory.generateCertificates(bais)) { if (cert instanceof X509Certificate) { certs.add(cert); } } if (certs.isEmpty()) { throw new IllegalStateException("Unable to decode certificate chain"); } } return certs; }
Source:
<code>private QueryBuilder buildSearchQuery() { BoolQueryBuilder elasticQueryBuilder = new BoolQueryBuilder(); for (ElasticsearchColumnHandle column : columns) { Type type = column.getColumnType(); <START> tupleDomain.getDomains().ifPresent((e) -> { <END> Domain domain = e.get(column); if (domain != null) { elasticQueryBuilder.must(buildPredicate(column.getColumnJsonPath(), domain, type, column.getIsList())); } }); } return elasticQueryBuilder.hasClauses() ? elasticQueryBuilder : new MatchAllQueryBuilder(); }</code><technical_language>e -> domains</technical_language>

Target:
private QueryBuilder buildSearchQuery() { BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); for (ElasticsearchColumnHandle column : columns) { BoolQueryBuilder columnQueryBuilder = new BoolQueryBuilder(); Type type = column.getColumnType(); tupleDomain.getDomains().ifPresent((domains) -> { Domain domain = domains.get(column); if (domain != null) { columnQueryBuilder.should(buildPredicate(column.getColumnJsonPath(), domain, type)); } }); boolQueryBuilder.must(columnQueryBuilder); } return boolQueryBuilder.hasClauses() ? boolQueryBuilder : new MatchAllQueryBuilder(); }
Source:
<code>public DBObject toDBObject(DBObject dbObject, Review model) { TranslatorUtils.fromLocaleToLanguageTag(dbObject, LOCALE_KEY, model.getLocale()); TranslatorUtils.from(dbObject, REVIEW_KEY, model.getReview()); TranslatorUtils.from(dbObject, TYPE_KEY, model.getType()); TranslatorUtils.from(dbObject, PEOPLE_KEY, model.getPeople()); List<DBObject> peopleDbList = model.getPeople().stream() .map(person -> personTranslator.toDBObject(dbObject, person)) .collect(Collectors.toList()); BasicDBList dbPeople = new BasicDBList(); <START> for (DBObject dbObject1 : peopleDbList) { <END> dbPeople.add(dbObject1); } dbObject.put(PEOPLE_KEY, dbPeople); return dbObject; }</code><technical_language>Variable naming: dbPerson is more descriptive</technical_language>

Target:
public DBObject toDBObject(DBObject dbObject, Review model) { TranslatorUtils.fromLocaleToLanguageTag(dbObject, LOCALE_KEY, model.getLocale()); TranslatorUtils.from(dbObject, REVIEW_KEY, model.getReview()); TranslatorUtils.from(dbObject, TYPE_KEY, model.getType()); authorTranslator.toDBObject(dbObject, model.getAuthor()); return dbObject; }
Source:
<code>public byte[] createDigitalSignature(InputStream data, String alias, String password) throws IOException { PrivateKey privateKey = getPrivateKey(alias, password); if (privateKey == null) { throw new CatalogCommandRuntimeException(""); } <START> try (BufferedInputStream bufferedInputStream = new BufferedInputStream(data)) { <END> Signature rsa = Signature.getInstance("SHA256withRSA"); rsa.initSign(getPrivateKey(alias, password)); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = bufferedInputStream.read(buffer)) >= 0) { rsa.update(buffer, OFFSET, len); } return rsa.sign(); } catch (SignatureException | InvalidKeyException | NoSuchAlgorithmException e) { String message = "An error occurred while signing file"; LOGGER.debug(message, e); throw new CatalogCommandRuntimeException(message, e); } }</code><technical_language>Is reason for wrapping data InputStream a BufferedInputStream</technical_language>

Target:
public byte[] createDigitalSignature(InputStream data, String alias, String password) throws IOException { PrivateKey privateKey = getPrivateKey(alias, password); if (privateKey == null) { throw new CatalogCommandRuntimeException("Unable to retrieve private key"); } try { Signature rsa = Signature.getInstance("SHA256withRSA"); rsa.initSign(privateKey); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = data.read(buffer)) >= 0) { rsa.update(buffer, OFFSET, len); } return rsa.sign(); } catch (SignatureException | InvalidKeyException | NoSuchAlgorithmException e) { String message = "An error occurred while signing file"; LOGGER.debug(message, e); throw new CatalogCommandRuntimeException(message, e); } }
Source:
<code>public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) { if (arguments.size() % 2 != 1 || arguments.size() < 3) { throw new IllegalArgumentException("At least 3 odd number of arguments are required for CASE-WHEN-ELSE function"); } _numberWhenStatements = arguments.size() / 2; for (int i = 0; i < _numberWhenStatements; i++) { _whenStatements.add(arguments.get(i)); } _elseThenStatements.add(arguments.get(_numberWhenStatements * 2)); for (int i = _numberWhenStatements; i < _numberWhenStatements * 2; i++) { _elseThenStatements.add(arguments.get(i)); } <START> Preconditions.checkState(_elseThenStatements.size() == _numberWhenStatements + 1, "Missing THEN/ELSE clause in CASE statement"); <END> _resultMetadata = getResultMetadata(_elseThenStatements); }</code><technical_language>this is redundant check check number of arguments is odd</technical_language>

Target:
public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) { if (arguments.size() % 2 != 1 || arguments.size() < 3) { throw new IllegalArgumentException("At least 3 odd number of arguments are required for CASE-WHEN-ELSE function"); } _numberWhenStatements = arguments.size() / 2; for (int i = 0; i < _numberWhenStatements; i++) { _whenStatements.add(arguments.get(i)); } _elseThenStatements.add(arguments.get(_numberWhenStatements * 2)); for (int i = _numberWhenStatements; i < _numberWhenStatements * 2; i++) { _elseThenStatements.add(arguments.get(i)); } getResultMetadata(); }
Source:
<code>public void doubleClick(int x, int y) { log.debug(MessageFormat.format("Double-clicking on {0}", <START> widget)); <END> notify(SWT.MouseEnter, createMouseEvent(x, y, 0, SWT.NONE, 0)); notify(SWT.MouseMove, createMouseEvent(x, y, 0, SWT.NONE, 0)); notify(SWT.MouseHover, createMouseEvent(x, y, 0, SWT.NONE, 0)); notify(SWT.Activate); notify(SWT.FocusIn); notify(SWT.MouseDown, createMouseEvent(x, y, 1, SWT.NONE, 1)); notify(SWT.MouseUp, createMouseEvent(x, y, 1, SWT.BUTTON1, 1)); notify(SWT.MouseDown, createMouseEvent(x, y, 1, SWT.NONE, 1)); notify(SWT.MouseDoubleClick, createMouseEvent(x, y, 1, SWT.BUTTON1, 2)); notify(SWT.MouseUp, createMouseEvent(x, y, 1, SWT.BUTTON1, 2)); log.debug(MessageFormat.format("Double-clicked on {0}", widget)); }</code><technical_language>this, prints Canvas {*Wrong Thread*}</technical_language>

Target:
public void doubleClick(int x, int y) { log.debug(MessageFormat.format("Double-clicking on {0}", this)); notify(SWT.MouseEnter, createMouseEvent(x, y, 0, SWT.NONE, 0)); notify(SWT.MouseMove, createMouseEvent(x, y, 0, SWT.NONE, 0)); notify(SWT.Activate); notify(SWT.FocusIn); notify(SWT.MouseDown, createMouseEvent(x, y, 1, SWT.NONE, 1)); notify(SWT.MouseUp, createMouseEvent(x, y, 1, SWT.BUTTON1, 1)); notify(SWT.MouseDown, createMouseEvent(x, y, 1, SWT.NONE, 2)); notify(SWT.MouseDoubleClick, createMouseEvent(x, y, 1, SWT.NONE, 2)); notify(SWT.MouseUp, createMouseEvent(x, y, 1, SWT.BUTTON1, 2)); log.debug(MessageFormat.format("Double-clicked on {0}", this)); }
Source:
<code><START> public static PCA createPCA(final List<String> variables, final List<String> samples, final RealMatrix dataMatrix, final Function<RealMatrix, SVD> svdFactory) { <END> Utils.nonNull(variables, "variable names"); Utils.nonNull(samples, "sample names"); Utils.nonNull(dataMatrix, "the input matrix cannot be null"); Utils.nonNull(svdFactory, "the SVD factory cannot be null"); final List<String> variableNames = checkNonNullUniqueNames(variables, "variable"); final List<String> sampleNames = checkNonNullUniqueNames(samples, "sample"); final int rowCount = dataMatrix.getRowDimension(); final int columnCount = dataMatrix.getColumnDimension(); final double[] centers = new double[rowCount]; final RealMatrix centered = new Array2DRowRealMatrix(rowCount, columnCount); for (int i = 0; i < rowCount; i++) { final double[] row = dataMatrix.getRow(i); final double center = MathUtils.mean(row, 0, row.length); for (int j = 0; j < columnCount; j++) { row[j] -= center; } centered.setRow(i, row); centers[i] = center; } final SVD svd = svdFactory.apply(centered); final RealMatrix eigenVectors = svd.getU(); final double inverseDenominator = 1.0 / (columnCount - 1.0); final double[] variances = DoubleStream.of(svd.getSingularValues()).map(d -> d * d * inverseDenominator).toArray(); return new PCA(variableNames, sampleNames, centers, eigenVectors, variances); }</code><technical_language>forward, do want require variable sample names PCA? give option createPCA variable/sample names, check for names writing HDF5</technical_language>

Target:
public static PCA createPCA(final List<String> variables, final List<String> samples, final RealMatrix dataMatrix, final Function<RealMatrix, SVD> svdFactory) { Utils.nonNull(dataMatrix, "the input matrix cannot be null"); Utils.nonNull(svdFactory, "the SVD factory cannot be null"); final List<String> variableNames = checkNonNullUniqueNames(variables, "variable"); final List<String> sampleNames = checkNonNullUniqueNames(samples, "sample"); final int rowCount = dataMatrix.getRowDimension(); final int columnCount = dataMatrix.getColumnDimension(); final double[] centers = new double[rowCount]; final RealMatrix centered = new Array2DRowRealMatrix(rowCount, columnCount); for (int i = 0; i < rowCount; i++) { final double[] row = dataMatrix.getRow(i); final double center = MathUtils.mean(row, 0, row.length); for (int j = 0; j < columnCount; j++) { row[j] -= center; } centered.setRow(i, row); centers[i] = center; } final SVD svd = svdFactory.apply(centered); final RealMatrix eigenVectors = svd.getU(); final double inverseDenominator = 1.0 / (columnCount - 1.0); final double[] variances = DoubleStream.of(svd.getSingularValues()).map(d -> d * d * inverseDenominator).toArray(); return new PCA(variableNames, sampleNames, centers, eigenVectors, variances); }
Source:
<code><START> private void initiateActiveContainerFailover(String containerID, String resourceID, <END> AbstractContainerAllocator containerAllocator) { Optional<Entry<String, SamzaResource>> standbyContainer = this.selectStandby(containerID, resourceID); if (standbyContainer.isPresent()) { String standbyContainerId = standbyContainer.get().getKey(); SamzaResource standbyResource = standbyContainer.get().getValue(); String standbyResourceID = standbyResource.getResourceID(); String standbyHost = standbyResource.getHost(); this.registerFailover(containerID, resourceID, standbyResourceID, standbyHost); log.info("Initiating failover and stopping standby container, found standbyContainer = resource {}, " + "for active container {}", standbyContainerId, standbyResourceID, containerID); samzaApplicationState.failoversToStandby.incrementAndGet(); this.clusterResourceManager.stopStreamProcessor(standbyResource); return; } else { log.info("No standby container found for active container {}, making a request for {}", containerID, ResourceRequestState.ANY_HOST); samzaApplicationState.failoversToAnyHost.incrementAndGet(); containerAllocator.requestResource(containerID, ResourceRequestState.ANY_HOST); return; } }</code><technical_language>this function appears multiple things.. rethink follows? For "active" case: split functionality in this method defined roles: - stopStandbyContainerForActiveContainer(containerId) For "standby" case: ANY_HOST request inlined call-site/ a separate helper</technical_language>

Target:
private void initiateActiveContainerFailover(String containerID, String resourceID, AbstractContainerAllocator containerAllocator) { Optional<Entry<String, SamzaResource>> standbyContainer = this.selectStandby(containerID, resourceID); if (standbyContainer.isPresent()) { String standbyContainerId = standbyContainer.get().getKey(); SamzaResource standbyResource = standbyContainer.get().getValue(); String standbyResourceID = standbyResource.getResourceID(); String standbyHost = standbyResource.getHost(); FailoverMetadata failoverMetadata = this.registerActiveContainerFailure(containerID, resourceID); failoverMetadata.updateStandbyContainer(standbyResourceID, standbyHost); log.info("Initiating failover and stopping standby container, found standbyContainer = resource {}, " + "for active container {}", standbyContainerId, standbyResourceID, containerID); samzaApplicationState.failoversToStandby.incrementAndGet(); this.clusterResourceManager.stopStreamProcessor(standbyResource); } else { log.info("No standby container found for active container {}, making a request for {}", containerID, ResourceRequestState.ANY_HOST); samzaApplicationState.failoversToAnyHost.incrementAndGet(); containerAllocator.requestResource(containerID, ResourceRequestState.ANY_HOST); } }
Source:
<code>public Props getProperties(final Project project, final Flow flow, final String jobName, final String source) throws ProjectManagerException { <START> if (Double.compare(flow.getAzkabanFlowVersion(), Constants.AZKABAN_FLOW_VERSION_2_0) == 0) { <END> return getPropertiesFromFlowFile(flow, jobName, source, 1); } else { return this.projectLoader.fetchProjectProperty(project, source); } }</code><technical_language>consider put check in util class FlowUtils? i guess in multiple cases? remember Double.compare compare doubles. for occasionally "==" :)</technical_language>

Target:
public Props getProperties(final Project project, final Flow flow, final String jobName, final String source) throws ProjectManagerException { if (FlowLoaderUtils.isAzkabanFlowVersion20(flow.getAzkabanFlowVersion())) { return getPropertiesFromFlowFile(flow, jobName, source, 1); } else { return this.projectLoader.fetchProjectProperty(project, source); } }
Source:
<code>public void testContinousIntegrationCommentsAreRemoved() throws Exception { ChangeDetailXAsResult result = parseFile("testdata/ChangeDetailX_hudson.json"); ChangeDetailX changeDetailX = result.result; <START> assertEquals(1, changeDetailX.getMessages().size()); <END> }</code><technical_language>assert message contents right through</technical_language>

Target:
public void testContinousIntegrationCommentsAreRemoved() throws Exception { ChangeDetailXAsResult result = parseFile("testdata/ChangeDetailX_hudson.json"); ChangeDetailX changeDetailX = result.result; assertEquals(1, changeDetailX.getMessages().size()); ChangeMessage lastMessageLeft = changeDetailX.getMessages().get(0); boolean doesNotContainHudsonMessage = !lastMessageLeft.getMessage().contains("hudson.eclipse.org"); assertEquals(true, doesNotContainHudsonMessage); }
Source:
<code>private Map<String, Object> createAmendment(Site site, Map<String, ?> relatedArticle) { Map<String, Object> amendment = new HashMap<>(relatedArticle); String relationshipType = (String) relatedArticle.get("type"); AmendmentType amendmentType = AmendmentType.BY_RELATIONSHIP_TYPE.get(relationshipType); if (amendmentType == null) return null; if (amendmentType != AmendmentType.CORRECTION) { RenderContext renderContext = new RenderContext(site); renderContext.setArticleId((String) amendment.get("doi")); String body; try { body = getAmendmentBody(renderContext); } catch (IOException e) { <START> throw new RuntimeException(e); <END> } amendment.put("body", body); } amendment.put("type", amendmentType.getLabel()); return amendment; }</code><technical_language>A log statement good here, lines of "could get amendment body for amendment DOI: <doi>"</technical_language>

Target:
private Map<String, Object> createAmendment(Site site, Map<String, ?> relatedArticle) { Map<String, Object> amendment = new HashMap<>(relatedArticle); String relationshipType = (String) relatedArticle.get("type"); AmendmentType amendmentType = AmendmentType.BY_RELATIONSHIP_TYPE.get(relationshipType); if (amendmentType == null) return null; if (amendmentType != AmendmentType.CORRECTION) { RenderContext renderContext = new RenderContext(site); String doi = (String) amendment.get("doi"); renderContext.setArticleId(doi); String body; try { body = getAmendmentBody(renderContext); } catch (IOException e) { throw new RuntimeException("Could not get body for amendment: " + doi, e); } amendment.put("body", body); } amendment.put("type", amendmentType.getLabel()); return amendment; }
Source:
<code>public void testSaveChanges() { DataModel dataModel = homepage.menu().selectDataExplorer().selectEntity("TypeTest").selectDataTab(); final FormsModalModel model = dataModel.clickOnEditFirstRowButton(); dataModel = model.clickOnSaveChangesButton(); assertTrue(dataModel.existAlertMessage("", "")); assertFalse(model.isModalFormOpen()); <START> LOG.info("Tested save changes button"); <END> }</code><technical_language>show 'saved' message is unnecessary. update testplan</technical_language>

Target:
public void testSaveChanges() { DataModel dataModel = homepage.menu().selectDataExplorer().selectEntity("TypeTest").selectDataTab(); final FormsModalModel model = dataModel.clickOnEditFirstRowButton(); dataModel = model.clickOnSaveChangesButton(); assertTrue(model.isModalFormClosed()); LOG.info("Tested save changes button"); }
Source:
<code>public void close() throws IOException { closeJSONStream(); <START> super.close(); <END> }</code><technical_language>InputStream.close() implementation drop call (but matter). I pretty base class close get implementation some time break previously working subclasses</technical_language>

Target:
public void close() throws IOException { jsonElementStream.close(); }
Source:
<code><START> public void init(SamzaContainerContext containerContext, TaskContext taskContext) { <END> super.init(containerContext, taskContext); writeFn.init(containerContext, taskContext); }</code><technical_language>Minor: move init beginning constructor</technical_language>

Target:
public void init(SamzaContainerContext containerContext, TaskContext taskContext) { super.init(containerContext, taskContext); putNs = taskContext.getMetricsRegistry().newTimer(groupName, tableId + "-put-ns"); putThrottleNs = taskContext.getMetricsRegistry().newTimer(groupName, tableId + "-put-throttle-ns"); deleteNs = taskContext.getMetricsRegistry().newTimer(groupName, tableId + "-delete-ns"); flushNs = taskContext.getMetricsRegistry().newTimer(groupName, tableId + "-flush-ns"); numPuts = taskContext.getMetricsRegistry().newCounter(groupName, tableId + "-num-puts"); numDeletes = taskContext.getMetricsRegistry().newCounter(groupName, tableId + "-num-deletes"); numFlushes = taskContext.getMetricsRegistry().newCounter(groupName, tableId + "-num-flushes"); }
Source:
<code><START> @VisibleForTesting protected Iterator<LlapCacheableBuffer> getIterator() { <END> final LlapCacheableBuffer currentHead = clockHand; if (currentHead == null) { return new Iterator<LlapCacheableBuffer>() { @Override public boolean hasNext() { return false; } @Override public LlapCacheableBuffer next() { return null; } }; } final LlapCacheableBuffer tail = clockHand.prev; return new Iterator<LlapCacheableBuffer>() { LlapCacheableBuffer current = currentHead; private boolean isLast = false; @Override public boolean hasNext() { return !isLast; } @Override public LlapCacheableBuffer next() { if (isLast) { throw new NoSuchElementException("Iterator done"); } if (current == tail) { isLast = true; } LlapCacheableBuffer r = current; current = current.next; return r; } }; }</code><technical_language>If this is required for testing. protected access? package private</technical_language>

Target:
@VisibleForTesting protected Iterator<LlapCacheableBuffer> getIterator() { final LlapCacheableBuffer currentHead = clockHand; if (currentHead == null) { return new Iterator<LlapCacheableBuffer>() { @Override public boolean hasNext() { return false; } @Override public LlapCacheableBuffer next() { throw new NoSuchElementException("empty iterator"); } }; } final LlapCacheableBuffer tail = clockHand.prev; return new Iterator<LlapCacheableBuffer>() { LlapCacheableBuffer current = currentHead; private boolean isLast = false; @Override public boolean hasNext() { return !isLast; } @Override public LlapCacheableBuffer next() { if (isLast) { throw new NoSuchElementException("Iterator done"); } if (current == tail) { isLast = true; } LlapCacheableBuffer r = current; current = current.next; return r; } }; }
Source:
<code><START> private boolean networkExists() { <END> List<NetworkCluster> networks = getNetworkClusterDAO().getAllForCluster(getVdsGroupId()); for (NetworkCluster networkCluster : networks) { if (networkCluster.getNetworkId().equals( getNetworkCluster().getNetworkId())) { return true; } } return false; }</code><technical_language>get method accepts NetworkClusterId</technical_language>

Target:
private boolean networkExists() { return getNetworkClusterDAO().get(getNetworkCluster().getId()) != null; }
Source:
<code>public Collection<ObjQualifier> getObjQualifiers() { return this.dateAttributes.stream() <START> .map(attribute -> attribute.getAttribute()) <END> .collect(Collectors.toSet()); }</code><technical_language>consider method reference</technical_language>

Target:
public Collection<ObjQualifier> getObjQualifiers() { return this.dateAttributes.stream() .map(OverPeriodDateAttribute::getAttribute) .collect(Collectors.toSet()); }
Source:
<code>void start() throws IOException { if (portFile.exists()) { throw new FileAlreadyExistsException(portFile.toString(), null, "Port file already exists. If the emulator crashed, please delete it"); } port = getFreePort(); try { <START> process = Runtime.getRuntime().exec(emulatorPath.toString() + " --host=localhost --port=" + port); <END> } catch (FileNotFoundException e) { throw new RuntimeException("cbtemulator could not be found"); } writeProps(); isStarted = true; }</code><technical_language>print out emulator logs somewhere</technical_language>

Target:
void start() throws IOException { if (portFile.exists()) { throw new FileAlreadyExistsException(portFile.toString(), null, "Port file already exists. If the emulator crashed, please delete it"); } port = getFreePort(); try { process = new ProcessBuilder(emulatorPath.toString(), "--host=localhost", "--port=" + port) .redirectErrorStream(true) .redirectOutput(logFile) .start(); } catch (FileNotFoundException e) { throw new RuntimeException("cbtemulator could not be found"); } writeProps(); isStarted = true; }
Source:
<code>Statement compileAlterTableDropColumn(Table table, String colName, boolean cascade) { HsqlName writeName = null; int colindex = table.getColumnIndex(colName); if (table.getColumnCount() == 1) { throw Error.error(ErrorCode.X_42591); } if (table.timeToLive != null) { final String ttlColumn = table.timeToLive.ttlColumn.getNameString(); if (colName.equalsIgnoreCase(ttlColumn)) { <START> throw Error.error("This column used by TTL cannot be dropped."); <END> } } Object[] args = new Object[] { table.getColumn(colindex).getName(), Integer.valueOf(SchemaObject.CONSTRAINT), Boolean.valueOf(cascade), Boolean.valueOf(false) }; if (!table.isTemp()) { writeName = table.getName(); } return new StatementSchema(null, StatementTypes.DROP_COLUMN, args, null, writeName); }</code><technical_language>I remove worth This error message Columns TTL dropped</technical_language>

Target:
Statement compileAlterTableDropColumn(Table table, String colName, boolean cascade) { HsqlName writeName = null; int colindex = table.getColumnIndex(colName); if (table.getColumnCount() == 1) { throw Error.error(ErrorCode.X_42591); } if (table.timeToLive != null) { final String ttlColumn = table.timeToLive.ttlColumn.getNameString(); if (colName.equalsIgnoreCase(ttlColumn)) { throw Error.error("Columns used by TTL cannot be dropped."); } } Object[] args = new Object[] { table.getColumn(colindex).getName(), Integer.valueOf(SchemaObject.CONSTRAINT), Boolean.valueOf(cascade), Boolean.valueOf(false) }; if (!table.isTemp()) { writeName = table.getName(); } return new StatementSchema(null, StatementTypes.DROP_COLUMN, args, null, writeName); }
Source:
<code>public YearsMonthsValue fromDMNString(final String dmnString) { <START> String dmnStringWithoutWhiteSpaces = dmnString.replaceAll("\\s",""); <END> final YearsMonthsValue yearsMonthsValue = new YearsMonthsValue(); final String value = removePrefixAndSuffix(dmnStringWithoutWhiteSpaces); final String[] yearsSplit = value.split(YEARS); String months = ""; if (yearsSplit.length > 0 && !yearsSplit[0].equals(value)) { yearsMonthsValue.setYears(yearsSplit[0]); if (yearsSplit.length == 2) { months = getMonths(yearsSplit[1]); } } else { months = getMonths(value); } yearsMonthsValue.setMonths(months); return yearsMonthsValue; }</code><technical_language>discussed todays meeting. Please remove this line</technical_language>

Target:
public YearsMonthsValue fromDMNString(final String dmnString) { final YearsMonthsValue yearsMonthsValue = new YearsMonthsValue(); final String value = removePrefixAndSuffix(dmnString); final String[] yearsSplit = value.split(YEARS); String months = ""; if (yearsSplit.length > 0 && !yearsSplit[0].equals(value)) { yearsMonthsValue.setYears(yearsSplit[0]); if (yearsSplit.length == 2) { months = getMonths(yearsSplit[1]); } } else { months = getMonths(value); } yearsMonthsValue.setMonths(months); return yearsMonthsValue; }
Source:
<code>private T doGetItem() { T item = this.available.poll(); if (item != null && logger.isDebugEnabled()) { logger.debug("Obtained " + item + " from pool."); } if (item == null) { item = this.callback.createForPool(); if (logger.isDebugEnabled()) { logger.debug("Obtained new " + item + "."); } allocated.add(item); } else if (this.callback.isStale(item)) { if (logger.isDebugEnabled()) { logger.debug("Received a stale item, will attempt to get a new one."); } <START> doRemoveItem(item); <END> item = doGetItem(); } return item; }</code><technical_language>So, issue... :+1:</technical_language>

Target:
private T doGetItem() { T item = this.available.poll(); if (item != null && logger.isDebugEnabled()) { logger.debug("Obtained " + item + " from pool."); } if (item == null) { item = this.callback.createForPool(); if (logger.isDebugEnabled()) { logger.debug("Obtained new " + item + "."); } allocated.add(item); } else if (this.callback.isStale(item)) { if (logger.isDebugEnabled()) { logger.debug("Received a stale item, will attempt to get a new one."); } doRemoveItem(item); item = doGetItem(); } this.inUse.add(item); return item; }
Source:
<code>private List<LatLon> getLatLonList(List<Double> numbers) { List<LatLon> latLons = new ArrayList<>(); for (int index = 0; index < numbers.size(); index++) { double latitude = numbers.get(index); <START> if (isValidLatitude(latitude)) { <END> if (index + 1 < numbers.size()) { double longitude = numbers.get(index + 1); if (isValidLongitude(longitude)) { latLons.add(LatLon.from(latitude, longitude)); ++index; } } } } return latLons; }</code><technical_language>move validation of coordinates LatLon object reusable</technical_language>

Target:
private List<LatLon> getLatLonList(List<Double> numbers) { List<LatLon> latLons = new ArrayList<>(); for (int index = 0; index < numbers.size(); index++) { double latitude = numbers.get(index); if (LatLon.isValidLatitude(latitude) && index + 1 < numbers.size()) { double longitude = numbers.get(index + 1); if (LatLon.isValidLongitude(longitude)) { latLons.add(LatLon.from(latitude, longitude)); ++index; } } } return latLons; }
Source:
<code>public LineRecordWriter(DataOutputStream out) { this.out = out; jsonMapper.getFactory() .configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true); jsonWriter = jsonMapper.writer(new JsonIndenter()); try { <START> out.writeBytes("["); <END> } catch (IOException e) { } }</code><technical_language>JSON lines opening [ necessary anymore</technical_language>

Target:
public LineRecordWriter(DataOutputStream out) { this.out = out; jsonMapper.getFactory() .configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true); jsonWriter = jsonMapper.writer(new JsonIndenter()); }
Source:
<code>public Status(@JsonProperty(value = "expectedValue", required = true) String expectedValue) { if (isNumeric(expectedValue)) { matcher = CoreMatchers.is(expectedValue); } else if (isFamily(expectedValue)) { matcher = CoreMatchers.startsWith(expectedValue.substring(0, 1)); <START> } <END> }</code><technical_language>do like: expectedValue.replace("X", ".") match a regular expression. 4XX (converted "4..") match 404,410,400, etc. If want match size of String, do a validation constructor</technical_language>

Target:
public Status(@JsonProperty(value = "expectedValue", required = true) String expectedValue) { if (!PATTERN.matcher(expectedValue).matches()) { throw new StatusCodeDefinitionException(expectedValue); } matcher = CoreMatchers.startsWith(expectedValue.toLowerCase().replace("x", "")); }
Source:
<code>protected void shutDown() throws Exception { log.info("Shutting Down"); if (server != null) { <START> if (!server.isStopping()) { <END> server.stop(); } } final List<AbstractIdleService> shutdownServices = ImmutableList.of(hostInfoReporter, agentInfoReporter, environmentVariableReporter, agent, zkRegistrar, model); for (AbstractIdleService subService : shutdownServices) { log.info("shutting down " + subService); subService.stopAsync(); } for (AbstractIdleService subService : shutdownServices) { log.info("awaiting termination " + subService); subService.awaitTerminated(); } if (serviceRegistrar != null) { log.info("closing service registrar"); serviceRegistrar.close(); } log.info("stopping metrics"); metrics.stop(); log.info("stopping zk client"); zooKeeperClient.close(); try { log.info("releasing persistent state lock"); stateLock.release(); } catch (IOException e) { log.error("Failed to release state lock", e); } try { stateLockFile.close(); } catch (IOException e) { log.error("Failed to close state lock file", e); } }</code><technical_language>reason for ifs instead of this? if (server != null && !server.isStopping())</technical_language>

Target:
protected void shutDown() throws Exception { if (server != null) { server.stop(); } hostInfoReporter.stopAsync().awaitTerminated(); agentInfoReporter.stopAsync().awaitTerminated(); environmentVariableReporter.stopAsync().awaitTerminated(); agent.stopAsync().awaitTerminated(); if (serviceRegistrar != null) { serviceRegistrar.close(); } zkRegistrar.stopAsync().awaitTerminated(); model.stopAsync().awaitTerminated(); metrics.stop(); zooKeeperClient.close(); try { stateLock.release(); } catch (IOException e) { log.error("Failed to release state lock", e); } try { stateLockFile.close(); } catch (IOException e) { log.error("Failed to close state lock file", e); } }
Source:
<code>private static String getSubmissionUri() { try { SharedPreferences settings = CommCareApplication._().getCurrentApp().getAppPreferences(); return settings.getString(CommCarePreferences.PREFS_SUBMISSION_URL_KEY, CommCareApplication._().getString(R.string.PostURL)); } catch (Exception e) { <START> return CommCareApplication._().getString(R.string.PostURL); <END> } }</code><technical_language>catch NPEs app seated? I prefer explicit null checks catching NullPointerException general Exception</technical_language>

Target:
private static String getSubmissionUri() { CommCareApp currentApp = CommCareApplication._().getCurrentApp(); if (currentApp != null) { return currentApp.getAppPreferences().getString( CommCarePreferences.PREFS_SUBMISSION_URL_KEY, CommCareApplication._().getString(R.string.PostURL)); } else { return CommCareApplication._().getString(R.string.PostURL); } }
Source:
<code>protected void doAccept(IModelDeltaVisitor visitor, int depth) { if (visitor.visit(this, depth)) { for (IModelDelta <START> childDelta : <END> getChildDeltas()) { ((ModelDelta)childDelta).doAccept(visitor, depth+1); } } }</code><technical_language>rename delta</technical_language>

Target:
protected void doAccept(IModelDeltaVisitor visitor, int depth) { if (visitor.visit(this, depth)) { for (IModelDelta delta : getChildDeltas()) { ((ModelDelta)delta).doAccept(visitor, depth+1); } } }