auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void createProject() throws ProjectCreationFailedException { final StringBuilder err = validateParameters(); if (err.length() == 0) { try { nameKey = new Project.NameKey(createProjectArgs.getProjectName()); final String head = createProjectArgs.isPermissionsOnly() ? GitRepositoryManager.REF_CONFIG : createProjectArgs .getBranch(); final Repository repo = repoManager.createRepository(nameKey); try { rq.replicateNewProject(nameKey, head); final RefUpdate u = repo.updateRef(Constants.HEAD); u.disableRefLog(); u.link(head); createProjectConfig(); if (!createProjectArgs.isPermissionsOnly() && createProjectArgs.isCreateEmptyCommit()) { createEmptyCommit(repo, nameKey, createProjectArgs.getBranch()); } } finally { repo.close(); } } catch (RepositoryCaseMismatchException ee) { throw new ProjectCreationFailedException("Cannot create \"" + nameKey + "\" because the name is already occupied by another project. " + "The other project has the same name, only spelled in " + "a different case.", ee); } catch (RepositoryNotFoundException e) { throw new ProjectCreationFailedException("Repository not exists", e); } catch (IOException e) { throw new ProjectCreationFailedException("IO error", e); } catch (ConfigInvalidException e) { throw new ProjectCreationFailedException("Configuration error", e); } catch (IllegalStateException e) { try { Repository repo = repoManager.openRepository(nameKey); try { if (repo.getObjectDatabase().exists()) { throw new ProjectCreationFailedException("Project \"" + nameKey + "\" exists", e); } } finally { repo.close(); } } catch (RepositoryNotFoundException er) { throw new ProjectCreationFailedException("Cannot create \"" + nameKey + "\"", er); } } } else { throw new ProjectCreationFailedException("validation error:" + err); } }

Target:
public void createProject() throws ProjectCreationFailedException { validateParameters(); try { nameKey = createProjectArgs.getProject(); final String head = createProjectArgs.permissionsOnly ? GitRepositoryManager.REF_CONFIG : createProjectArgs.branch; final Repository repo = repoManager.createRepository(nameKey); try { rq.replicateNewProject(nameKey, head); final RefUpdate u = repo.updateRef(Constants.HEAD); u.disableRefLog(); u.link(head); createProjectConfig(); if (!createProjectArgs.permissionsOnly && createProjectArgs.createEmptyCommit) { createEmptyCommit(repo, nameKey, createProjectArgs.branch); } } finally { repo.close(); } } catch (IllegalStateException e) { handleRepositoryExistsException(nameKey, e); } catch (RepositoryCaseMismatchException ee) { handleRepositoryExistsException(ee.getNameOfExistingProject(), ee); } catch (RepositoryNotFoundException e) { throw new ProjectCreationFailedException("Repository not exists", e); } catch (IOException e) { throw new ProjectCreationFailedException("IO error", e); } catch (ConfigInvalidException e) { throw new ProjectCreationFailedException("Configuration error", e); } }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { List<TmfEventTableColumn> columns = getColumns(event.getApplicationContext()); long start = getStart(event.getApplicationContext()); long end = getEnd(event.getApplicationContext()); ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); ITmfFilter filter = TmfTraceManager.getInstance().getCurrentTraceContext().getFilter(); if (trace != null) { Job job = new CopyToClipboardJob(trace, filter, columns, start, end); job.schedule(); } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { List<TmfEventTableColumn> columns = getColumns(event.getApplicationContext()); Long start = getStart(event.getApplicationContext()); Long end = getEnd(event.getApplicationContext()); ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); ITmfFilter filter = TmfTraceManager.getInstance().getCurrentTraceContext().getFilter(); if (trace != null && columns != null && start != null && end != null) { Job job = new CopyToClipboardJob(trace, filter, columns, start, end); job.schedule(); } return null; }
Source:
public void testDefaultProperties() { Map<String, String> defaultProperties = ap.getDefaultProperties(); Assert.assertEquals(7, defaultProperties.size()); Map<String, String> defaultPropertiesValidationMap = new HashMap<String, String>(); defaultPropertiesValidationMap.put("dt.test.1", "package-default"); defaultPropertiesValidationMap.put("dt.test.2", "package-default"); defaultPropertiesValidationMap.put("dt.test.3", "package-default"); defaultPropertiesValidationMap.put("dt.test.4", "package-default"); defaultPropertiesValidationMap.put("dt.test.5", "package-default"); defaultPropertiesValidationMap.put("dt.test.6", "package-default"); defaultPropertiesValidationMap.put("dt.operator.testModule.prop.testInput", "default-value-1"); for (String key : ap.getDefaultProperties().keySet()) { Assert.assertEquals(defaultPropertiesValidationMap.get(key), defaultProperties.get(key)); } }

Target:
public void testDefaultProperties() { Map<String, AppPackage.PropertyInfo> defaultProperties = ap.getDefaultProperties(); Assert.assertEquals(8, defaultProperties.size()); Assert.assertEquals("package-default", defaultProperties.get("dt.test.1").getValue()); Assert.assertEquals("package-default", defaultProperties.get("dt.test.2").getValue()); Assert.assertEquals("package-default", defaultProperties.get("dt.test.3").getValue()); Assert.assertEquals("package-default", defaultProperties.get("dt.test.4").getValue()); Assert.assertEquals("package-default", defaultProperties.get("dt.test.5").getValue()); Assert.assertEquals("package-default", defaultProperties.get("dt.test.6").getValue()); Assert.assertEquals("default-value-1", defaultProperties.get("dt.operator.testModule.prop.testInput").getValue()); Assert.assertEquals("default-value-1", defaultProperties.get("dt.operator.stdout.prop.testInput").getValue()); }
Source:
public void extractAgent() throws Exception { agentJar = new File(tmpDir.getRoot(), "old-agent.jar"); FileUtils.copyURLToFile(getClass().getResource("/old-remoting/remoting-minimal-supported.jar"), agentJar); }

Target:
public void extractAgent() throws Exception { agentJar = new File(tmpDir.getRoot(), "old-agent.jar"); FileUtils.copyURLToFile(OldRemotingAgentTest.class.getResource("/old-remoting/remoting-minimal-supported.jar"), agentJar); }
Source:
public void testNonEmptyInputs(boolean... inputSequence) { List<Object> booleanList = new ArrayList<>(); for (boolean b : inputSequence) { booleanList.add(b); } assertCount(booleanList, 0, distinctCount(booleanList)); }

Target:
public void testNonEmptyInputs(boolean... inputSequence) { List<Boolean> values = Booleans.asList(inputSequence); assertCount(values, 0, distinctCount(values)); }
Source:
private PeekingIterator<JsonNode> configureSplitObj(Iterator<JsonNode> nodeItr){ if (!nodeItr.hasNext()) { throw new MarkLogicIOException("No header found."); } PeekingIterator<JsonNode> peekingIterator = new PeekingIterator<JsonNode>(nodeItr); csvHeaderNode = peekingIterator.getFirst(); Iterator<String> headerValue = csvHeaderNode.fieldNames(); this.headers = new ObjectMapper().createArrayNode(); while (headerValue.hasNext()) { headers.add(headerValue.next()); } return peekingIterator; }

Target:
private PeekingIterator<JsonNode> configureSplitObj(Iterator<JsonNode> nodeItr){ if (nodeItr == null || !nodeItr.hasNext()) { throw new MarkLogicIOException("No header found."); } PeekingIterator<JsonNode> peekingIterator = new PeekingIterator<JsonNode>(nodeItr); Iterator<String> headerValue = peekingIterator.getFirst().fieldNames(); this.headers = new ObjectMapper().createArrayNode(); while (headerValue.hasNext()) { headers.add(headerValue.next()); } return peekingIterator; }
Source:
public void apply(Project project) { project.getTasks().withType(Test.class).configureEach(task -> { task.jvmArgs("-XX:+HeapDumpOnOutOfMemoryError", "-XX:+CrashOnOutOfMemoryError"); if (!Objects.equals("true", project.findProperty("com.palantir.baseline.restore-test-cache"))) { task.getOutputs().cacheIf(t -> false); } String shouldRecreate = System.getProperty("recreate", "false"); task.systemProperty("recreate", shouldRecreate); task.getInputs().property("recreate", shouldRecreate); }); project.getPlugins().withType(JavaPlugin.class, unusedPlugin -> { project.afterEvaluate(proj -> { proj.getConvention() .getPlugin(JavaPluginConvention.class) .getSourceSets() .matching(ss -> hasCompileDependenciesMatching(proj, ss, BaselineTesting::isJunitJupiter)) .forEach(ss -> { Optional<Test> maybeTestTask = getTestTaskForSourceSet(proj, ss); if (!maybeTestTask.isPresent()) { log.warn("Detected 'org:junit.jupiter:junit-jupiter', but unable to find test task"); return; } log.info( "Detected 'org:junit.jupiter:junit-jupiter', enabling useJUnitPlatform() on {}", maybeTestTask.get().getName()); enableJunit5ForTestTask(maybeTestTask.get()); }); }); TaskProvider<CheckJUnitDependencies> task = project.getTasks().register("checkJUnitDependencies", CheckJUnitDependencies.class); project.getTasks().findByName(JavaPlugin.TEST_TASK_NAME).dependsOn(task); }); }

Target:
public void apply(Project project) { project.getTasks().withType(Test.class).configureEach(task -> { task.jvmArgs("-XX:+HeapDumpOnOutOfMemoryError", "-XX:+CrashOnOutOfMemoryError"); if (!Objects.equals("true", project.findProperty("com.palantir.baseline.restore-test-cache"))) { task.getOutputs().cacheIf(t -> false); } boolean shouldRecreate = Boolean.getBoolean("recreate"); task.systemProperty("recreate", Boolean.toString(shouldRecreate)); if (shouldRecreate) { task.getOutputs().upToDateWhen(t -> false); } }); project.getPlugins().withType(JavaPlugin.class, unusedPlugin -> { project.afterEvaluate(proj -> { proj.getConvention() .getPlugin(JavaPluginConvention.class) .getSourceSets() .matching(ss -> hasCompileDependenciesMatching(proj, ss, BaselineTesting::isJunitJupiter)) .forEach(ss -> { Optional<Test> maybeTestTask = getTestTaskForSourceSet(proj, ss); if (!maybeTestTask.isPresent()) { log.warn("Detected 'org:junit.jupiter:junit-jupiter', but unable to find test task"); return; } log.info( "Detected 'org:junit.jupiter:junit-jupiter', enabling useJUnitPlatform() on {}", maybeTestTask.get().getName()); enableJunit5ForTestTask(maybeTestTask.get()); }); }); TaskProvider<CheckJUnitDependencies> task = project.getTasks().register("checkJUnitDependencies", CheckJUnitDependencies.class); project.getTasks().findByName(JavaPlugin.TEST_TASK_NAME).dependsOn(task); }); }
Source:
public synchronized Optional<CommandMapping> get(String alias, @Nullable CommandSource source) { List<CommandMapping> results = this.commands.get(alias.toLowerCase()); Optional<CommandMapping> result = Optional.empty(); if (results.size() == 1) { result = Optional.of(results.get(0)); } else if (results.size() > 1) { result = disambiguatorFunc.disambiguate(source, alias, results); } if (source != null) { result = result.filter(m -> m.getCallable().testPermission(source)); } return result; }

Target:
public synchronized Optional<CommandMapping> get(String alias, @Nullable CommandSource source) { List<CommandMapping> results = this.commands.get(alias.toLowerCase()); Optional<CommandMapping> result = Optional.empty(); if (results.size() == 1) { result = Optional.of(results.get(0)); } else if (results.size() > 1) { result = this.disambiguatorFunc.disambiguate(source, alias, results); } if (source != null) { result = result.filter(m -> m.getCallable().testPermission(source)); } return result; }
Source:
private static long bytesToMb(long bytes) { return bytes / 1024L / 1024L; }

Target:
private static int bytesToMb(long bytes) { return (int) (bytes / 1024L / 1024L); }
Source:
void getThreadData_failed_dataIsPresentThrowableIsAvailable() throws InterruptedException { DataCarrier expectedData = initializeThread(); expectedData.exception = Optional.of(new NullPointerException("This fails badly")); CountDownLatch doneSignal = new CountDownLatch(1); DataCarrier actionHandlerData = new DataCarrier(); DataCarrier completionHandlerData = new DataCarrier(); service.execAsync(service.getThreadData(), () -> actionHandler(actionHandlerData, expectedData.exception), (t) -> completionHandler(doneSignal, completionHandlerData, t)); doneSignal.await(); assertReturnedData(completionHandlerData, expectedData); expectedData.exception = Optional.empty(); assertReturnedData(actionHandlerData, expectedData); }

Target:
void getThreadData_failed_dataIsPresentThrowableIsAvailable() throws InterruptedException { DataCarrier expectedData = initializeThread(); expectedData.exception = Optional.of(new NullPointerException("This fails badly")); CountDownLatch doneSignal = new CountDownLatch(1); DataCarrier actionHandlerData = new DataCarrier(); DataCarrier completionHandlerData = new DataCarrier(); service.execAsync(service.getThreadData(), () -> actionHandler(actionHandlerData, expectedData.exception), (t) -> completionHandler(doneSignal, completionHandlerData, t)); doneSignal.await(); assertActionHandlerData(actionHandlerData, expectedData); assertCompletionHandlerData(completionHandlerData, expectedData); }
Source:
public boolean undo() { if (!history.undoIsPossible()) { return false; } UndoState lastStep = history.backward(); if (lastStep != null) { internFormula = lastStep.internFormulaState.createInternFormulaFromState(); internFormula.generateExternFormulaStringAndInternExternMapping(context); internFormula.updateInternCursorPosition(); updateTextAndCursorFromInternFormula(); } formulaEditorFragment.refreshFormulaPreviewString(internFormula.getExternFormulaString()); return true; }

Target:
public boolean undo() { if (!history.undoIsPossible()) { return false; } UndoState previousState = history.backward(); if (previousState != null) { internFormula = previousState.internFormulaState.createInternFormulaFromState(); internFormula.generateExternFormulaStringAndInternExternMapping(context); internFormula.updateInternCursorPosition(); updateTextAndCursorFromInternFormula(); } formulaEditorFragment.refreshFormulaPreviewString(internFormula.getExternFormulaString()); return true; }
Source:
public void doInit() { if (Recipes.recyclerBlacklist != null && ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { ItemRegistryApiculture beeItems = ModuleApiculture.getItems(); Recipes.recyclerBlacklist.add(Recipes.inputFactory.forStack(new ItemStack(beeItems.beeQueenGE))); Recipes.recyclerBlacklist.add(Recipes.inputFactory.forStack(new ItemStack(beeItems.beePrincessGE))); } else { Log.error("IC2 Recipes.recyclerBlacklist not found."); } Circuits.energyElectricChoke1 = new CircuitElectricChoke("electric.choke.1"); Circuits.energyElectricEfficiency1 = new CircuitElectricEfficiency("electric.efficiency.1"); Circuits.energyElectricBoost1 = new CircuitElectricBoost("electric.boost.1", 4, 10); Circuits.energyElectricBoost2 = new CircuitElectricBoost("electric.boost.2", 7, 20); blocks.electricalEngine.init(); blocks.generator.init(); }

Target:
public void doInit() { if (ModuleHelper.isEnabled(ForestryModuleUids.APICULTURE)) { if (Recipes.recyclerBlacklist != null) { ItemRegistryApiculture beeItems = ModuleApiculture.getItems(); Recipes.recyclerBlacklist.add(Recipes.inputFactory.forStack(new ItemStack(beeItems.beeQueenGE))); Recipes.recyclerBlacklist.add(Recipes.inputFactory.forStack(new ItemStack(beeItems.beePrincessGE))); } else { Log.error("IC2 Recipes.recyclerBlacklist not found."); } } Circuits.energyElectricChoke1 = new CircuitElectricChoke("electric.choke.1"); Circuits.energyElectricEfficiency1 = new CircuitElectricEfficiency("electric.efficiency.1"); Circuits.energyElectricBoost1 = new CircuitElectricBoost("electric.boost.1", 4, 10); Circuits.energyElectricBoost2 = new CircuitElectricBoost("electric.boost.2", 7, 20); getBlocks().electricalEngine.init(); getBlocks().generator.init(); }
Source:
private void setValues(Map<Symbol, Object> sourceMap, Map<String, Object> targetMap) { if (sourceMap != null) { for (Map.Entry<Symbol, Object> entry : sourceMap.entrySet()) { final String key = entry.getKey().toString(); final Object value = entry.getValue(); targetMap.put(key, value); } } }

Target:
private void setValues(Map<Symbol, Object> sourceMap, Map<String, Object> targetMap) { if (sourceMap != null) { for (Map.Entry<Symbol, Object> entry : sourceMap.entrySet()) { targetMap.put(entry.getKey().toString(), entry.getValue()); } } }
Source:
public Object getCellValueByEvaluatingFormula(String fileLocation, String cellLocation) throws IOException { Object cellValue; FileInputStream inputStream = new FileInputStream(new File(fileLocation)); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); FormulaEvaluator evaluator = workbook.getCreationHelper() .createFormulaEvaluator(); CellAddress cellAddress = new CellAddress(cellLocation); Row row = sheet.getRow(cellAddress.getRow()); Cell cell = row.getCell(cellAddress.getColumn()); switch (evaluator.evaluateFormulaCell(cell)) { case BOOLEAN: cellValue = cell.getBooleanCellValue(); break; case NUMERIC: cellValue = cell.getNumericCellValue(); break; case STRING: cellValue = cell.getStringCellValue(); break; default: cellValue = null; } workbook.close(); return cellValue; }

Target:
public Object getCellValueByEvaluatingFormula(String fileLocation, String cellLocation) throws IOException { Object cellValue = new Object(); FileInputStream inputStream = new FileInputStream(new File(fileLocation)); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); FormulaEvaluator evaluator = workbook.getCreationHelper() .createFormulaEvaluator(); CellAddress cellAddress = new CellAddress(cellLocation); Row row = sheet.getRow(cellAddress.getRow()); Cell cell = row.getCell(cellAddress.getColumn()); if (cell.getCellType() == CellType.FORMULA) { switch (evaluator.evaluateFormulaCell(cell)) { case BOOLEAN: cellValue = cell.getBooleanCellValue(); break; case NUMERIC: cellValue = cell.getNumericCellValue(); break; case STRING: cellValue = cell.getStringCellValue(); break; default: cellValue = null; } } workbook.close(); return cellValue; }
Source:
public List<CourseAttributes> getCoursesForStudentAccount(String googleId) throws EntityDoesNotExistException { List<StudentAttributes> studentDataList = studentsLogic.getStudentsForGoogleId(googleId); if (studentDataList.isEmpty()) { throw new EntityDoesNotExistException("Student with Google ID " + googleId + " does not exist"); } List<String> courseIds = new ArrayList<>(); for (StudentAttributes s : studentDataList) { if (!getCourse(s.course).isCourseDeleted()) { courseIds.add(s.course); } } return coursesDb.getCourses(courseIds); }

Target:
public List<CourseAttributes> getCoursesForStudentAccount(String googleId) throws EntityDoesNotExistException { List<StudentAttributes> studentDataList = studentsLogic.getStudentsForGoogleId(googleId); if (studentDataList.isEmpty()) { throw new EntityDoesNotExistException("Student with Google ID " + googleId + " does not exist"); } List<String> courseIds = studentDataList.stream() .filter(student -> !getCourse(student.course).isCourseDeleted()) .map(StudentAttributes::getCourse) .collect(Collectors.toList()); return coursesDb.getCourses(courseIds); }
Source:
private void processAddedPages(ApplicationSentListingMessage applicationSentListingMessage) { List<WebkitPage> pages = new ArrayList<WebkitPage>(); pages.addAll(driver.getPages()); for (WebkitPage p : driver.getPages()) { applicationSentListingMessage.getPages().remove(p); } if (applicationSentListingMessage.getPages().size() == 0) { throw new WebDriverException(applicationSentListingMessage.getPages().size() + " new pages."); } WebkitPage newOne = Collections.max(applicationSentListingMessage.getPages()); pages.addAll(applicationSentListingMessage.getPages()); driver.setPages(pages); if (driver.getPages().size() == 0) { } else if (newOne.isITunesAd()) { } else { WebkitPage focus = newOne; if (session != null) { waitForWindowSwitchingAnimation(); driver.switchTo(focus); } else { driver.switchTo(focus); } } }

Target:
private void processAddedPages(ApplicationSentListingMessage applicationSentListingMessage) { List<WebkitPage> pages = new ArrayList<WebkitPage>(driver.getPages()); for (WebkitPage p : driver.getPages()) { applicationSentListingMessage.getPages().remove(p); } WebkitPage newOne = Collections.max(applicationSentListingMessage.getPages()); pages.addAll(applicationSentListingMessage.getPages()); driver.setPages(pages); if (driver.getPages().size() > 0 && !newOne.isITunesAd()) { WebkitPage focus = newOne; if (session != null) { waitForWindowSwitchingAnimation(); driver.switchTo(focus); } else { driver.switchTo(focus); } } }
Source:
protected void configure() { super.configure(); WaitAllStrategy waitStrategy = new WaitAllStrategy(); waitStrategy = waitStrategy.withStrategy( new HttpWaitStrategy() .forPath("/pools/default") .forPort(MGMT_PORT) .withBasicCredentials(username, password) .forStatusCode(200) .forResponsePredicate(response -> { try { return Optional.of(MAPPER.readTree(response)) .map(n -> n.at("/nodes/0/status")) .map(JsonNode::asText) .map("healthy"::equals) .orElse(false); } catch (IOException e) { logger().error("Unable to parse response: " + response, e); return false; } }) ); if (enabledServices.contains(CouchbaseService.QUERY)) { waitStrategy = waitStrategy.withStrategy( new HttpWaitStrategy() .forPath("/admin/ping") .forPort(QUERY_PORT) .withBasicCredentials(username, password) .forStatusCode(200) ); } waitingFor(waitStrategy); }

Target:
protected void configure() { super.configure(); WaitAllStrategy waitStrategy = new WaitAllStrategy(); waitStrategy = waitStrategy.withStrategy( new HttpWaitStrategy() .forPath("/pools/default") .forPort(MGMT_PORT) .withBasicCredentials(username, password) .forStatusCode(200) .forResponsePredicate(response -> { try { return Optional.of(MAPPER.readTree(response)) .map(n -> n.at("/nodes/0/status")) .map(JsonNode::asText) .map("healthy"::equals) .orElse(false); } catch (IOException e) { logger().error("Unable to parse response: {}", response, e); return false; } }) ); if (enabledServices.contains(CouchbaseService.QUERY)) { waitStrategy = waitStrategy.withStrategy( new HttpWaitStrategy() .forPath("/admin/ping") .forPort(QUERY_PORT) .withBasicCredentials(username, password) .forStatusCode(200) ); } waitingFor(waitStrategy); }
Source:
private void run(String[] argv) throws Exception { MaxwellBootstrapUtilityConfig config = new MaxwellBootstrapUtilityConfig(argv); if ( config.log_level != null ) { MaxwellLogging.setLevel(config.log_level); } ConnectionPool connectionPool = getConnectionPool(config); try ( final Connection connection = connectionPool.getConnection() ) { if ( config.abortBootstrapID != null ) { removeBootstrapRow(connection, config.abortBootstrapID); return; } long rowId; if ( config.monitorBootstrapID != null ) rowId = config.monitorBootstrapID; else { Long totalRows = calculateRowCount(connection, config.databaseName, config.tableName); rowId = insertBootstrapStartRow(connection, config.databaseName, config.tableName, totalRows); } monitorProgress(connection, rowId); } catch ( SQLException e ) { LOGGER.error("failed to connect to mysql server @ " + config.getConnectionURI()); LOGGER.error(e.getLocalizedMessage()); System.exit(1); } }

Target:
private void run(String[] argv) throws Exception { MaxwellBootstrapUtilityConfig config = new MaxwellBootstrapUtilityConfig(argv); if ( config.log_level != null ) { MaxwellLogging.setLevel(config.log_level); } ConnectionPool connectionPool = getConnectionPool(config); try ( final Connection connection = connectionPool.getConnection() ) { if ( config.abortBootstrapID != null ) { getInsertedRowsCount(connection, config.abortBootstrapID); removeBootstrapRow(connection, config.abortBootstrapID); return; } long rowId; if ( config.monitorBootstrapID != null ) { getInsertedRowsCount(connection, config.monitorBootstrapID); rowId = config.monitorBootstrapID; } else { Long totalRows = calculateRowCount(connection, config.databaseName, config.tableName); rowId = insertBootstrapStartRow(connection, config.databaseName, config.tableName, totalRows); } try { monitorProgress(connection, rowId); } catch ( MissingBootstrapRowException e ) { LOGGER.error("bootstrap aborted."); Runtime.getRuntime().halt(1); } } catch ( SQLException e ) { LOGGER.error("failed to connect to mysql server @ " + config.getConnectionURI()); LOGGER.error(e.getLocalizedMessage()); System.exit(1); } }
Source:
public void getNextOffsetAndMin() { Node node = mock(Node.class); Bounds bounds = new BoundsImpl(new BoundImpl(100d, 100d), new BoundImpl(300d, 200d)); List<Node> nodes = new ArrayList<Node>(); View view = mock(View.class); when(node.getContent()).thenReturn(view); when(view.getBounds()).thenReturn(bounds); nodes.add(node); when(graph.nodes()).thenReturn(nodes); double[] next = canvasLayoutUtils.getNext(canvasHandler, newNodeWidth, newNodeHeight, offsetX, offsetY, canvasMinX, canvasMinY); double nextX = next[0]; double nextY = next[1]; assertTrue(nextX > (newNodeWidth + offsetX)); assertTrue(nextY > (newNodeHeight + offsetY)); }

Target:
public void getNextOffsetAndMin() { Node node = mock(Node.class); Bounds bounds = new BoundsImpl(new BoundImpl(100d, 100d), new BoundImpl(300d, 200d)); List<Node> nodes = new ArrayList<Node>(); View view = mock(View.class); when(node.getContent()).thenReturn(view); when(view.getBounds()).thenReturn(bounds); nodes.add(node); when(graph.nodes()).thenReturn(nodes); final Point2D min = new Point2D(canvasMin.getX(), canvasMin.getY()); double[] next = canvasLayoutUtils.getNext(canvasHandler, NEW_NODE_HEIGHT, offset, min); double nextX = next[0]; double nextY = next[1]; assertTrue(nextX > (NEW_NODE_WIDTH + offset.getX())); assertTrue(nextY > (NEW_NODE_HEIGHT + offset.getY())); }
Source:
private void populateReviews(List<TaskReview> reviewContainers) throws NumberFormatException { for (ITask review : reviews) { int codeReviewVal = Integer .parseInt(review.getAttribute(Messages.TaskEditorReviewsPart_CodeReviewAttribute)); int verifiedVal = Integer.parseInt(review.getAttribute(Messages.TaskEditorReviewsPart_VerifiedAttribute)); boolean incoming = false; if (review.getSynchronizationState() == ITask.SynchronizationState.INCOMING) { hasIncoming = true; incoming = true; } reviewContainers.add( new TaskReview(review.getSummary(), codeReviewVal, verifiedVal, "", incoming, review.getUrl())); } }

Target:
private void populateReviews(List<TaskReview> reviewContainers) throws NumberFormatException { for (ITask review : reviews) { reviewContainers.add(new TaskReview(review)); } }
Source:
private CompiledQuery repairTables(SqlExecutionContext executionContext) throws SqlException { CharSequence tok; tok = SqlUtil.fetchNext(lexer); if (tok == null || !Chars.equalsLowerCaseAscii(tok, "table")) { throw SqlException.$(lexer.lastTokenPosition(), "'table' expected"); } do { tok = SqlUtil.fetchNext(lexer); if (tok == null || Chars.equals(tok, ',')) { throw SqlException.$(lexer.getPosition(), "table name expected"); } if (Chars.isQuoted(tok)) { tok = GenericLexer.unquote(tok); } tableExistsOrFail(lexer.lastTokenPosition(), tok, executionContext); try { TableWriter writer = engine.getWriter(executionContext.getCairoSecurityContext(), tok); engine.migrateNullFlag(writer, executionContext.getCairoSecurityContext(), tok); writer.close(); } catch (CairoException e) { LOG.info().$("table busy [table=").$(tok).$(", e=").$((Sinkable) e).$(']').$(); throw SqlException.$(lexer.lastTokenPosition(), "table '").put(tok).put("' is busy"); } tok = SqlUtil.fetchNext(lexer); } while (tok != null && Chars.equals(tok, ',')); return compiledQuery.ofRepair(); }

Target:
private CompiledQuery repairTables(SqlExecutionContext executionContext) throws SqlException { CharSequence tok; tok = SqlUtil.fetchNext(lexer); if (tok == null || !Chars.equalsLowerCaseAscii(tok, "table")) { throw SqlException.$(lexer.lastTokenPosition(), "'table' expected"); } do { tok = SqlUtil.fetchNext(lexer); if (tok == null || Chars.equals(tok, ',')) { throw SqlException.$(lexer.getPosition(), "table name expected"); } if (Chars.isQuoted(tok)) { tok = GenericLexer.unquote(tok); } tableExistsOrFail(lexer.lastTokenPosition(), tok, executionContext); try { engine.getWriter(executionContext.getCairoSecurityContext(), tok).close(); engine.migrateNullFlag(executionContext.getCairoSecurityContext(), tok); } catch (CairoException e) { LOG.info().$("table busy [table=").$(tok).$(", e=").$((Sinkable) e).$(']').$(); throw SqlException.$(lexer.lastTokenPosition(), "table '").put(tok).put("' is busy"); } tok = SqlUtil.fetchNext(lexer); } while (tok != null && Chars.equals(tok, ',')); return compiledQuery.ofRepair(); }
Source:
public boolean advance() throws IOException { if (isRejectError) { return true; } boolean validationResult = validateResultSet(rs); if (!validationResult) { return false; } boolean hasNext = false; try { hasNext = rs.next(); } catch (SQLException e) { if (dieOnError) { throw new IOException(); } LOGGER.warn(I18N_MESSAGES.getMessage("error.resultSetIssue"), e); } if (hasNext) { current = converter.convertToAvro(rs); result.totalCount++; result.successCount++; } return hasNext; }

Target:
public boolean advance() throws IOException { if (isRejectError) { return true; } boolean validationResult = validateResultSet(rs); if (!validationResult) { return false; } boolean hasNext = false; try { hasNext = rs.next(); } catch (SQLException e) { if (dieOnError) { throw new IOException(e); } LOGGER.warn(I18N_MESSAGES.getMessage("error.resultSetIssue"), e); } if (hasNext) { current = converter.convertToAvro(rs); result.totalCount++; result.successCount++; } return hasNext; }
Source:
public String toString() { String result = new String(bout.toByteArray(), StandardCharsets.UTF_8); if (fmt.equals(Depiction.SVG_FMT)) { result = result.replaceAll("\"([-+0-9.]+)px\"", "\"$1mm\""); } if (fmt.equals(Depiction.EPS_FMT)) { String nl = System.getProperty("line.separator"); String split[] = result.split(nl,2); if( split.length > 1 && split[0].startsWith("%!PS-") ) { String boundingBox; if( this.dim != null ) { boundingBox = "%%BoundingBox: 0 0 " + dim.width + " " + dim.height + nl; } else { boundingBox = ""; } if(!split[0].contains("EPS") && !boundingBox.equals("")) { split[0] += " EPSF-3.0"; } result = split[0] + nl + boundingBox + split[1]. replaceFirst("(\\d+ ){4}setmargins", "0 0 0 0 setmargins"). replaceFirst("(\\d+ ){2}setpagesize", dim.width + " " + dim.height + " setpagesize"); } } return result; }

Target:
public String toString() { String result = new String(bout.toByteArray(), StandardCharsets.UTF_8); if (fmt.equals(Depiction.SVG_FMT)) { result = result.replaceAll("\"([-+0-9.]+)px\"", "\"$1mm\""); } else if (fmt.equals(Depiction.EPS_FMT)) { String nl; if( result.contains("\r\n")) { nl = "\r\n"; } else if( result.contains("\r")) { nl = "\r"; } else { nl = "\n"; } String split[] = result.split(nl,2); if( split.length > 1 && split[0].startsWith("%!PS-") ) { String boundingBox; if( this.dim != null ) { boundingBox = "%%BoundingBox: 0 0 " + dim.width + " " + dim.height + nl; } else { boundingBox = ""; } if(!split[0].contains("EPS") && !boundingBox.equals("")) { split[0] += " EPSF-3.0"; } result = split[0] + nl + boundingBox + split[1]. replaceFirst("(\\d+ ){4}setmargins", "0 0 0 0 setmargins"). replaceFirst("(\\d+ ){2}setpagesize", dim.width + " " + dim.height + " setpagesize"); } } return result; }
Source:
protected void executeQueryCommand() { Map<String, Network> clusterNetworksByName = networkDao .getAllForCluster(getParameters().getId()) .stream() .collect(Collectors.toMap(Network::getName, Function.identity())); Set<String> outOfSyncVdsNames = interfaceDao .getAllInterfacesByClusterId(getParameters().getId()) .stream() .map(iface -> new Pair<>(iface.getVdsName(), util.calculateNetworkImplementationDetails(iface, clusterNetworksByName.get(iface.getNetworkName())))) .filter(pair -> pair.getSecond() != null && pair.getSecond().isManaged() && !pair.getSecond().isInSync()) .map(Pair::getFirst) .collect(Collectors.toSet()); StringBuilder names = new StringBuilder(); outOfSyncVdsNames.forEach(name -> names.append("\n").append(name)); getQueryReturnValue().setReturnValue(names.toString()); }

Target:
protected void executeQueryCommand() { Map<String, Network> clusterNetworksByName = networkDao .getAllForCluster(getParameters().getId()) .stream() .collect(Collectors.toMap(Network::getName, Function.identity())); List<String> outOfSyncVdsNames = interfaceDao .getAllInterfacesByClusterId(getParameters().getId()) .stream() .map(iface -> new Pair<>(iface.getVdsName(), util.calculateNetworkImplementationDetails(iface, clusterNetworksByName.get(iface.getNetworkName())))) .filter(pair -> pair.getSecond() != null && pair.getSecond().isManaged() && !pair.getSecond().isInSync()) .map(Pair::getFirst) .collect(Collectors.toSet()) .stream() .sorted() .collect(Collectors.toList()); StringBuilder names = new StringBuilder(); outOfSyncVdsNames.forEach(name -> names.append("\n").append(name)); getQueryReturnValue().setReturnValue(names.toString()); }
Source:
private DateTime parseShortDate(String dateString) { if (StringUtils.isNotBlank(dateString)) { return new DateTime(RassStringToJavaShortDateTimeAdapter.parseToDateTime(dateString).toDate()); } else { return null; } }

Target:
private DateTime parseShortDate(String dateString) { if (StringUtils.isNotBlank(dateString)) { return RassStringToJavaShortDateTimeAdapter.parseToDateTime(dateString); } else { return null; } }
Source:
private Object getConstraintKey(PConstraint constraint) { if (constraint instanceof TypeConstraint) { return ((TypeConstraint) constraint).getEquivalentJudgement(); } return constraint; }

Target:
private Object getConstraintKey(PConstraint constraint) { if (constraint instanceof ITypeConstraint) { return ((ITypeConstraint) constraint).getEquivalentJudgement(); } return constraint; }
Source:
public void loadStaffInOffice(final int officeId) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManager.getStaffInOffice(officeId) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<List<Staff>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); try { if (e instanceof HttpException) { String errorMessage = ((HttpException) e).response().errorBody() .string(); getMvpView().showError(MFErrorParser.parseError(errorMessage) .getErrors().get(0).getDefaultUserMessage()); } } catch (Throwable throwable) { RxJavaPlugins.getInstance().getErrorHandler().handleError(e); } } @Override public void onNext(List<Staff> staffs) { getMvpView().showProgressbar(false); getMvpView().showStaffInOffice(staffs, officeId); } })); }

Target:
public void loadStaffInOffice(final int officeId) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManager.getStaffInOffice(officeId) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<List<Staff>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); getMvpView().showError(MFErrorParser.errorMessage(e)); } @Override public void onNext(List<Staff> staffs) { getMvpView().showProgressbar(false); getMvpView().showStaffInOffice(staffs, officeId); } })); }
Source:
public void rejectInvalidJsonObjectsInResultArray() throws Exception { JsonObject result = new JsonObject(); JsonObject testObject = new JsonObject(); JsonArray results = new JsonArray(); for(int i = 1; i<=3; i++) { JsonObject element = new JsonObject(); element.addProperty("experiment_accession", "e"+ i); element.addProperty("contrast_id", "c"+ i); element.addProperty("bioentity_identifier", "id"+ i); element.addProperty("species", "org"+ i); element.addProperty("p_value", 1.11); element.addProperty("fold_change", -1.12); element.addProperty("t_statistic", 0.0); element.addProperty("keyword_symbol", i); results.add(element); } results.add(testObject); testObject.addProperty("experiment accession","e"+4); testObject.addProperty("contrast_id", "c"+4); testObject.addProperty("bioentity_identifier", "id"+4); testObject.addProperty("species", "org"+4); testObject.addProperty("p_value", 1.14); testObject.addProperty("fold_change", -1.14); testObject.addProperty("t_statistic", 0.0); testObject.addProperty("keyword_symbol", 4); result.add("results", results); List<DiffAnalytics> expression = subject.parseDifferentialResults(result); assertThat(expression,hasSize(3)); }

Target:
public void rejectInvalidJsonObjectsInResultArray() throws Exception { JsonObject result = buildJsonObject(3,true); List<DiffAnalytics> expression = subject.parseDifferentialResults(result); assertThat(expression,hasSize(3)); }
Source:
public static ExecutorService createLocalExecutor(Cache<?, ?> masterCacheNode) { String nodeName = masterCacheNode != null ? masterCacheNode.getCacheManager().getCacheManagerConfiguration().transport().nodeName() : ""; return Executors.newSingleThreadExecutor( new DefaultThreadFactory(null, Thread.NORM_PRIORITY, DefaultThreadFactory.DEFAULT_PATTERN, nodeName, "DefaultExecutorService")); }

Target:
public static ExecutorService createLocalExecutor(Cache<?, ?> masterCacheNode) { String nodeName = masterCacheNode != null ? SecurityActions.getConfiguredNodeName(masterCacheNode) : null; return Executors.newSingleThreadExecutor( new DefaultThreadFactory(null, Thread.NORM_PRIORITY, DefaultThreadFactory.DEFAULT_PATTERN, nodeName, "DefaultExecutorService")); }
Source:
public void testMultiThreadMultiKeyPull() throws InterruptedException, TimeoutException, ExecutionException { final int numPullThreads = 8; final int numPullPerThread = 1000; final CountDownLatch countDownLatch = new CountDownLatch(numPullThreads); final Runnable[] threads = new Runnable[numPullThreads]; final AtomicBoolean correctResultReturned = new AtomicBoolean(true); for (int index = 0; index < numPullThreads; ++index) { final int threadIndex = index; threads[index] = () -> { for (int pull = 0; pull < numPullPerThread; ++pull) { final List<Integer> keyList = new ArrayList<>(3); keyList.add((threadIndex + pull) % 4); keyList.add((threadIndex + pull + 1)); keyList.add((threadIndex + pull + 2) % 4); final List<Integer> vals = worker.pull(keyList); for (int listIndex = 0; listIndex < 3; ++listIndex) { final Integer val = vals.get(listIndex); if (val == null || !val.equals(keyList.get(listIndex))) { correctResultReturned.set(false); break; } } } countDownLatch.countDown(); }; } ThreadUtils.runConcurrently(threads); final boolean allThreadsFinished = countDownLatch.await(60, TimeUnit.SECONDS); worker.close(CLOSE_TIMEOUT); assertTrue(MSG_THREADS_SHOULD_FINISH, allThreadsFinished); assertTrue(MSG_RESULT_ASSERTION, correctResultReturned.get()); }

Target:
public void testMultiThreadMultiKeyPull() throws InterruptedException, TimeoutException, ExecutionException { final int numPullThreads = 8; final int numKeys = 4; final int numPullPerThread = 1000; final int numKeysPerPull = 3; final CountDownLatch countDownLatch = new CountDownLatch(numPullThreads); final Runnable[] threads = new Runnable[numPullThreads]; final AtomicBoolean correctResultReturned = new AtomicBoolean(true); for (int index = 0; index < numPullThreads; ++index) { final int threadIndex = index; threads[index] = () -> { for (int pull = 0; pull < numPullPerThread; ++pull) { final List<Integer> keyList = new ArrayList<>(numKeysPerPull); for (int keyIndex = 0; keyIndex < numKeysPerPull; ++keyIndex) { keyList.add((threadIndex + pull + keyIndex) % numKeys); } final List<Integer> vals = worker.pull(keyList); for (int listIndex = 0; listIndex < keyList.size(); ++listIndex) { final Integer val = vals.get(listIndex); if (val == null || !val.equals(keyList.get(listIndex))) { correctResultReturned.set(false); break; } } } countDownLatch.countDown(); }; } ThreadUtils.runConcurrently(threads); final boolean allThreadsFinished = countDownLatch.await(60, TimeUnit.SECONDS); worker.close(CLOSE_TIMEOUT); assertTrue(MSG_THREADS_SHOULD_FINISH, allThreadsFinished); assertTrue(MSG_RESULT_ASSERTION, correctResultReturned.get()); }
Source:
public void visitNode(AstNode node) { AstNode singleIfChild = singleIfChild(node); if(singleIfChild != null && !hasElseOrElsif(singleIfChild)){ addIssue(singleIfChild, this, "Merge this if statement with the enclosing one."); } }

Target:
public void visitNode(AstNode node) { AstNode singleIfChild = singleIfChild(node); if(singleIfChild != null && !hasElseOrElsif(singleIfChild)){ addIssue(singleIfChild, this, "Merge this \"if\" statement with the enclosing one."); } }
Source:
private void releaseExecutor(Execution execution) { executorsSemaphore.release(); if (currentlyProcessing.remove(execution) == null) { LOG.error("Released execution was not found in collection of executions currently being processed. Should never happen."); statsRegistry.registerUnexpectedError(); } if(pollAfterCompletion && currentlyProcessing.isEmpty()) { triggerCheckForDueExecutions(); } }

Target:
private void releaseExecutor(Execution execution) { executorsSemaphore.release(); if (currentlyProcessing.remove(execution) == null) { LOG.error("Released execution was not found in collection of executions currently being processed. Should never happen."); statsRegistry.registerUnexpectedError(); } if (pollAfterCompletion && lastPollAcquiredAllAvailableExecutors) { triggerCheckForDueExecutions(); } }
Source:
public StringBuilder getCsvDetailedFeedbackResponseCommentsRow(FeedbackResponseAttributes response) { List<FeedbackResponseCommentAttributes> frcList = this.responseComments.get(response.getId()); StringBuilder commentRow = new StringBuilder(200); for (FeedbackResponseCommentAttributes frc : frcList) { commentRow.append("," + frc.giverEmail + "," + SanitizationHelper.desanitizeFromHtml( frc.commentText.getValue().substring(3, frc.commentText.getValue().length() - 4))); } return commentRow; }

Target:
public StringBuilder getCsvDetailedFeedbackResponseCommentsRow(FeedbackResponseAttributes response) { List<FeedbackResponseCommentAttributes> frcList = this.responseComments.get(response.getId()); StringBuilder commentRow = new StringBuilder(200); for (FeedbackResponseCommentAttributes frc : frcList) { commentRow.append("," + instructorEmailNameTable.get(frc.giverEmail) + "," + getTextFromComment(frc.commentText)); } return commentRow; }
Source:
public void startSignIn(@NonNull final IdpResponse response, @NonNull String password) { if (!response.isSuccessful()) { setResult(Resource.<IdpResponse>forFailure(response.getError())); return; } if (!response.getProviderType().equals(EmailAuthProvider.PROVIDER_ID)) { throw new IllegalStateException( "This handler can only be used with the email provider"); } setResult(Resource.<IdpResponse>forLoading()); final String email = response.getEmail(); getAuth().createUserWithEmailAndPassword(email, password) .continueWithTask(new ProfileMerger(response)) .addOnFailureListener(new TaskFailureLogger(TAG, "Error creating user")) .addOnSuccessListener(new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult result) { setResult(Resource.forSuccess(response)); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { if (e instanceof FirebaseAuthUserCollisionException) { ProviderUtils.fetchTopProvider(getAuth(), email) .addOnSuccessListener(new StartWelcomeBackFlow(email)); } else { setResult(Resource.<IdpResponse>forFailure(e)); } } }); }

Target:
public void startSignIn(@NonNull final IdpResponse response, @NonNull String password) { if (!response.isSuccessful()) { setResult(Resource.<IdpResponse>forFailure(response.getError())); return; } if (!response.getProviderType().equals(EmailAuthProvider.PROVIDER_ID)) { throw new IllegalStateException( "This handler can only be used with the email provider"); } setResult(Resource.<IdpResponse>forLoading()); final String email = response.getEmail(); getAuth().createUserWithEmailAndPassword(email, password) .continueWithTask(new ProfileMerger(response)) .addOnFailureListener(new TaskFailureLogger(TAG, "Error creating user")) .addOnSuccessListener(new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult result) { setResult(Resource.forSuccess(response)); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { if (e instanceof FirebaseAuthUserCollisionException) { ProviderUtils.fetchTopProvider(getAuth(), email) .addOnSuccessListener(new StartWelcomeBackFlow(email)) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { setResult(Resource.<IdpResponse>forFailure(e)); } }); } else { setResult(Resource.<IdpResponse>forFailure(e)); } } }); }
Source:
public THIS as(LogicalTypeAnnotation type) { this.logicalTypeAnnotation = type; return self(); }

Target:
public THIS as(LogicalTypeAnnotation type) { this.logicalTypeAnnotation = type; this.newLogicalTypeSet = true; return self(); }
Source:
public void testValidate() { DispoAnnotationData annotation = new DispoAnnotationData(); annotation.setResolutionType("Modify_Code"); annotation.setResolution(""); DispoResolutionValidator validator = new DispoResolutionValidator(); validator.validate(annotation); Assert.assertTrue(annotation.getIsAnalyze()); Assert.assertTrue(!annotation.getIsResolutionValid()); annotation.setResolution("something"); validator.validate(annotation); Assert.assertTrue(annotation.getIsAnalyze()); Assert.assertTrue(annotation.getIsResolutionValid()); annotation.setResolutionType("nonesense"); validator.validate(annotation); Assert.assertTrue(!annotation.getIsAnalyze()); Assert.assertTrue(annotation.getIsResolutionValid()); }

Target:
public void testValidate() { DispoAnnotationData annotation = new DispoAnnotationData(); annotation.setResolutionType(ANALYZE_CODE); annotation.setResolution(""); DispoResolutionValidator validator = new DispoResolutionValidator(); validator.validate(annotation); Assert.assertTrue(annotation.getIsAnalyze()); Assert.assertTrue(!annotation.getIsResolutionValid()); annotation.setResolution("something"); validator.validate(annotation); Assert.assertTrue(annotation.getIsAnalyze()); Assert.assertTrue(annotation.getIsResolutionValid()); annotation.setResolutionType("non-essense"); validator.validate(annotation); Assert.assertTrue(!annotation.getIsAnalyze()); Assert.assertTrue(annotation.getIsResolutionValid()); }