auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void test_casting() { assertEquals(Stream.empty().map(Guavate.casting(Integer.class)).collect(toList()), ImmutableList.of()); List<Number> baseList = Arrays.asList(1, 2, 3); List<Integer> castList = baseList.stream().map(Guavate.casting(Integer.class)).collect(toList()); assertEquals(castList, ImmutableList.of(1, 2, 3)); List<Number> baseListMixed = Arrays.asList(1, 2f, 3); assertThrows( ClassCastException.class, () -> baseListMixed.stream().map(Guavate.casting(Short.class)).collect(toList())); }

Target:
public void test_casting() { assertEquals(Stream.empty().map(Guavate.casting(Integer.class)).collect(toList()), ImmutableList.of()); List<Number> baseList = Arrays.asList(1, 2, 3); List<Integer> castList = baseList.stream().map(Guavate.casting(Integer.class)).collect(toList()); assertEquals(castList, baseList); List<Number> baseListMixed = ImmutableList.of(1, 2f, 3); assertThrows( ClassCastException.class, () -> baseListMixed.stream().map(Guavate.casting(Short.class)).collect(toList())); }
Source:
public void updateStudent(String courseId, String email, String newName, String newTeamName, String newSectionName, String newEmail, String newGoogleId, String newComments, boolean hasDocument, boolean keepUpdateTimestamp) throws InvalidParametersException, EntityDoesNotExistException { Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseId); Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, email); verifyStudentExists(courseId, email); CourseStudent courseStudent = getCourseStudentEntityForEmail(courseId, email); if (courseStudent != null) { boolean isEmailChanged = !email.equals(newEmail); String lastName = StringHelper.splitName(newName)[1]; if (isEmailChanged) { CourseStudent newCourseStudent = new CourseStudent(newEmail, newName, newGoogleId, newComments, courseId, newTeamName, newSectionName); try { updateStudentChangeEmail(newCourseStudent, lastName, courseStudent, hasDocument, keepUpdateTimestamp, courseId, email); } catch (EntityAlreadyExistsException e) { StudentAttributes existingStudent = (StudentAttributes) e.existingEntity; String error = ERROR_UPDATE_EMAIL_ALREADY_USED + existingStudent.getName() + "/" + existingStudent.getEmail(); throw new InvalidParametersException(error); } } else { updateStudentDetails(newName, newTeamName, newSectionName, newEmail, newGoogleId, newComments, hasDocument, keepUpdateTimestamp, courseStudent, lastName); } } log.info(Const.SystemParams.COURSE_BACKUP_LOG_MSG + courseId); getPm().close(); }

Target:
public void updateStudent(String courseId, String email, String newName, String newTeamName, String newSectionName, String newEmail, String newGoogleId, String newComments, boolean hasDocument, boolean keepUpdateTimestamp) throws InvalidParametersException, EntityDoesNotExistException { Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseId); Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, email); verifyStudentExists(courseId, email); CourseStudent courseStudent = getCourseStudentEntityForEmail(courseId, email); if (courseStudent != null) { boolean isEmailChanged = !email.equals(newEmail); String lastName = StringHelper.splitName(newName)[1]; if (isEmailChanged) { CourseStudent newCourseStudent = new CourseStudent(newEmail, newName, newGoogleId, newComments, courseId, newTeamName, newSectionName); recreateStudentWithNewEmail(newCourseStudent, lastName, courseStudent, hasDocument, keepUpdateTimestamp, courseId, email); } else { updateStudentDetails(newName, newTeamName, newSectionName, newGoogleId, newComments, hasDocument, keepUpdateTimestamp, courseStudent, lastName); } } log.info(Const.SystemParams.COURSE_BACKUP_LOG_MSG + courseId); getPm().close(); }
Source:
public void testMerge() { List<Result<Object>> resultsBefore = Arrays.asList( new Result<Object>(DateTimes.of("2011-01-01"), 1L), new Result<Object>(DateTimes.of("2011-01-01"), 2L) ); Iterable<Result<Object>> expectedResults = Collections.singletonList( new Result<Object>(DateTimes.of("2011-01-01"), 3L) ); Iterable<Result<Object>> resultsAfter = CombiningIterable.create( resultsBefore, (r1, r2) -> r1.getTimestamp().compareTo(r2.getTimestamp()), (arg1, arg2) -> { if (arg1 == null) { return arg2; } if (arg2 == null) { return arg1; } return new Result<>( arg1.getTimestamp(), ((Long) arg1.getValue()).longValue() + ((Long) arg2.getValue()).longValue() ); } ); Iterator<Result<Object>> it1 = expectedResults.iterator(); Iterator<Result<Object>> it2 = resultsAfter.iterator(); while (it1.hasNext() && it2.hasNext()) { Result r1 = it1.next(); Result r2 = it2.next(); Assert.assertEquals(r1.getTimestamp(), r2.getTimestamp()); Assert.assertEquals(r1.getValue(), r2.getValue()); } }

Target:
public void testMerge() { List<Result<Object>> resultsBefore = Arrays.asList( new Result<>(DateTimes.of("2011-01-01"), 1L), new Result<>(DateTimes.of("2011-01-01"), 2L) ); Iterable<Result<Object>> expectedResults = Collections.singletonList( new Result<>(DateTimes.of("2011-01-01"), 3L) ); Iterable<Result<Object>> resultsAfter = CombiningIterable.create( resultsBefore, Comparator.comparing(Result::getTimestamp), (arg1, arg2) -> { if (arg1 == null) { return arg2; } if (arg2 == null) { return arg1; } return new Result<>( arg1.getTimestamp(), ((Long) arg1.getValue()).longValue() + ((Long) arg2.getValue()).longValue() ); } ); Iterator<Result<Object>> it1 = expectedResults.iterator(); Iterator<Result<Object>> it2 = resultsAfter.iterator(); while (it1.hasNext() && it2.hasNext()) { Result r1 = it1.next(); Result r2 = it2.next(); Assert.assertEquals(r1.getTimestamp(), r2.getTimestamp()); Assert.assertEquals(r1.getValue(), r2.getValue()); } }
Source:
public AzureTemplateOptions secrets(Iterable<? extends Secrets> secrets) { this.secrets = (secrets == null) ? null : ImmutableList.copyOf(checkNotNull(secrets, "secrets")); return this; }

Target:
public AzureTemplateOptions secrets(Iterable<? extends Secrets> secrets) { for (Secrets secret : checkNotNull(secrets, "secrets")) checkNotNull(secret, "secrets can not be empty"); this.secrets = ImmutableList.copyOf(secrets); return this; }
Source:
public String withdrawFunds(WithdrawFundsParams params) throws IOException { if (params instanceof RippleWithdrawFundsParams) { RippleWithdrawFundsParams xrpParams = (RippleWithdrawFundsParams) params; return withdrawFunds( xrpParams.currency, xrpParams.amount, xrpParams.address, xrpParams.tag); } else if (params instanceof MoneroWithdrawFundsParams) { MoneroWithdrawFundsParams xmrParams = (MoneroWithdrawFundsParams) params; return withdrawFunds( xmrParams.currency, xmrParams.amount, xmrParams.address, xmrParams.paymentId); } else if (params instanceof DefaultWithdrawFundsParams) { DefaultWithdrawFundsParams defaultParams = (DefaultWithdrawFundsParams) params; return withdrawFunds(defaultParams.currency, defaultParams.amount, defaultParams.address); } throw new IllegalStateException("Don't know how to withdraw: " + params); }

Target:
public String withdrawFunds(WithdrawFundsParams params) throws IOException { if (params instanceof RippleWithdrawFundsParams) { RippleWithdrawFundsParams xrpParams = (RippleWithdrawFundsParams) params; return withdrawFunds( xrpParams.getCurrency(), xrpParams.getAmount(), xrpParams.getAddress(), xrpParams.getTag()); } else if (params instanceof MoneroWithdrawFundsParams) { MoneroWithdrawFundsParams xmrParams = (MoneroWithdrawFundsParams) params; return withdrawFunds( xmrParams.getCurrency(), xmrParams.getAmount(), xmrParams.getAddress(), xmrParams.getPaymentId()); } else if (params instanceof DefaultWithdrawFundsParams) { DefaultWithdrawFundsParams defaultParams = (DefaultWithdrawFundsParams) params; return withdrawFunds(defaultParams.getCurrency(), defaultParams.getAmount(), defaultParams.getAddress()); } throw new IllegalStateException("Don't know how to withdraw: " + params); }
Source:
public static MobileNodeType getMobileNodeType(String mobileNodeType) { if (StringUtils.isEmpty(mobileNodeType)) { } for (MobileNodeType node : MobileNodeType.values()) { if (node.getAsString().equalsIgnoreCase(mobileNodeType)) { return node; } } StringBuilder errorMsg = new StringBuilder(); errorMsg.append("MobileNodeType '"); errorMsg.append(mobileNodeType).append("\' did not match any mobileNodeTypes supported by SeLion.\n"); errorMsg.append("Supported mobileNodes are : [").append(MobileNodeType.getSupportedMobileNodesAsCSV()); errorMsg.append("]."); IllegalArgumentException e = new IllegalArgumentException(errorMsg.toString()); throw e; }

Target:
public static MobileNodeType getMobileNodeType(String mobileNodeType) { for (MobileNodeType node : MobileNodeType.values()) { if (node.getAsString().equalsIgnoreCase(mobileNodeType)) { return node; } } StringBuilder errorMsg = new StringBuilder(); errorMsg.append("MobileNodeType '"); errorMsg.append(mobileNodeType).append("\' did not match any mobileNodeTypes supported by SeLion.\n"); errorMsg.append("Supported mobileNodes are : [").append(MobileNodeType.getSupportedMobileNodesAsCSV()); errorMsg.append("]."); IllegalArgumentException e = new IllegalArgumentException(errorMsg.toString()); throw e; }
Source:
protected TaggedValuePointable isDuplicateKeys(TaggedValuePointable key, Set<TaggedValuePointable> pointables) { for (TaggedValuePointable tvp : pointables) { if (tvp != null && FunctionHelper.arraysEqual(tvp, key)) { return tvp; } } return null; }

Target:
private TaggedValuePointable isDuplicateKeys(TaggedValuePointable key, Set<TaggedValuePointable> pointables) { for (TaggedValuePointable tvp : pointables) { if (tvp != null && FunctionHelper.arraysEqual(tvp, key)) { return tvp; } } return null; }
Source:
public static Keyspace getKeyspace() { return keyspace; }

Target:
protected static Keyspace getKeyspace() { return keyspace; }
Source:
default AsyncQueryDAO getAsyncQueryDAO() { return new DefaultAsyncQueryDAO(); }

Target:
default AsyncQueryDAO getAsyncQueryDAO() { return null; }
Source:
public void testConnectAPIEscapedMode() throws Exception { PowerMockito.doReturn(XBeeMode.API_ESCAPE).when(xbeeDevice, "determineConnectionMode"); try { xbeeDevice.connect(); } catch (XBeeException e) { fail("This exception shouldn't be thrown now."); } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } assertEquals(xbeeDevice.getOperatingMode(), XBeeMode.API_ESCAPE); }

Target:
public void testConnectAPIEscapedMode() throws Exception { PowerMockito.doReturn(OperatingMode.API_ESCAPE).when(xbeeDevice, "determineConnectionMode"); try { xbeeDevice.open(); } catch (XBeeException e) { fail("This exception shouldn't be thrown now."); } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } assertTrue(xbeeDevice.isOpen()); assertTrue(dataReader.isRunning()); assertEquals(xbeeDevice.getOperatingMode(), OperatingMode.API_ESCAPE); }
Source:
public void testCreateFailConstructor() { PluginDescriptor pluginDescriptor = mock(DefaultPluginDescriptor.class); when(pluginDescriptor.getPluginClass()).thenReturn(AnotherFailTestPlugin.class.getName()); PluginWrapper pluginWrapper = mock(PluginWrapper.class); when(pluginWrapper.getDescriptor()).thenReturn(pluginDescriptor); when(pluginWrapper.getPluginClassLoader()).thenReturn(getClass().getClassLoader()); DefaultPluginFactory instance = new DefaultPluginFactory(); Plugin result = instance.create(pluginWrapper); assertNull(result); }

Target:
public void testCreateFailConstructor() { PluginDescriptor pluginDescriptor = mock(PluginDescriptor.class); when(pluginDescriptor.getPluginClass()).thenReturn(AnotherFailTestPlugin.class.getName()); PluginWrapper pluginWrapper = mock(PluginWrapper.class); when(pluginWrapper.getDescriptor()).thenReturn(pluginDescriptor); when(pluginWrapper.getPluginClassLoader()).thenReturn(getClass().getClassLoader()); DefaultPluginFactory instance = new DefaultPluginFactory(); Plugin result = instance.create(pluginWrapper); assertNull(result); }
Source:
public static String getPlainText(String str) { if (!TextUtils.isEmpty(str) && isHtml(str)) { HtmlToPlainText formatter = new HtmlToPlainText(); Document feedDescription = Jsoup.parse(str); str = StringUtils.trim(formatter.getPlainText(feedDescription)); } return str; }

Target:
public static String getPlainText(String str) { if (!TextUtils.isEmpty(str) && isHtml(str)) { HtmlToPlainText formatter = new HtmlToPlainText(); Document feedDescription = Jsoup.parse(str); str = StringUtils.trim(formatter.getPlainText(feedDescription)); } else if (TextUtils.isEmpty(str)) { str = ""; } return str; }
Source:
public void testDuplicateBatchAppend() throws Exception { HTableDescriptor hdt = TEST_UTIL .createTableDescriptor(name.getTableName(), HColumnDescriptor.DEFAULT_MIN_VERSIONS, 3, HConstants.FOREVER, HColumnDescriptor.DEFAULT_KEEP_DELETED); Map<String, String> kvs = new HashMap<>(); kvs.put(SleepAtFirstRpcCall.SLEEP_TIME_CONF_KEY, "2000"); hdt.addCoprocessor(SleepAtFirstRpcCall.class.getName(), null, 1, kvs); TEST_UTIL.createTable(hdt, new byte[][] { ROW }).close(); Configuration c = new Configuration(TEST_UTIL.getConfiguration()); c.setInt(HConstants.HBASE_CLIENT_PAUSE, 50); c.setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 1500); try (Connection connection = ConnectionFactory.createConnection(c); Table table = connection.getTableBuilder(name.getTableName(), null). setOperationTimeout(3 * 1000).build()) { Append append = new Append(ROW); append.addColumn(HBaseTestingUtility.fam1, QUALIFIER, VALUE); Object[] results = new Object[1]; table.batch(Collections.singletonList(append), results); Cell[] cells = ((Result) results[0]).rawCells(); assertEquals(1, cells.length); assertKey(cells[0], ROW, HBaseTestingUtility.fam1, QUALIFIER, VALUE); Result readResult = table.get(new Get(ROW)); cells = readResult.rawCells(); assertEquals(1, cells.length); assertKey(cells[0], ROW, HBaseTestingUtility.fam1, QUALIFIER, VALUE); } }

Target:
public void testDuplicateBatchAppend() throws Exception { TableDescriptorBuilder.ModifyableTableDescriptor mtd = TEST_UTIL .createModifyableTableDescriptor(name.getTableName(), ColumnFamilyDescriptorBuilder.DEFAULT_MIN_VERSIONS, 3, HConstants.FOREVER, ColumnFamilyDescriptorBuilder.DEFAULT_KEEP_DELETED); Map<String, String> kvs = new HashMap<>(); kvs.put(SleepAtFirstRpcCall.SLEEP_TIME_CONF_KEY, "2000"); mtd.setCoprocessor(CoprocessorDescriptorBuilder .newBuilder(SleepAtFirstRpcCall.class.getName()) .setPriority(1) .setProperties(kvs) .build()); TEST_UTIL.createTable(mtd, new byte[][] { ROW }).close(); Configuration c = new Configuration(TEST_UTIL.getConfiguration()); c.setInt(HConstants.HBASE_CLIENT_PAUSE, 50); c.setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 1500); try (Connection connection = ConnectionFactory.createConnection(c); Table table = connection.getTableBuilder(name.getTableName(), null). setOperationTimeout(3 * 1000).build()) { Append append = new Append(ROW); append.addColumn(HBaseTestingUtility.fam1, QUALIFIER, VALUE); Object[] results = new Object[1]; table.batch(Collections.singletonList(append), results); Cell[] cells = ((Result) results[0]).rawCells(); assertEquals(1, cells.length); assertKey(cells[0], ROW, HBaseTestingUtility.fam1, QUALIFIER, VALUE); Result readResult = table.get(new Get(ROW)); cells = readResult.rawCells(); assertEquals(1, cells.length); assertKey(cells[0], ROW, HBaseTestingUtility.fam1, QUALIFIER, VALUE); } }
Source:
protected View onCreateAnswerView(Context context, FormEntryPrompt prompt, int answerFontSize) { ViewGroup answerView = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.url_widget_answer, null); openUrlButton = answerView.findViewById(R.id.url_button); stringAnswer = answerView.findViewById(R.id.url_answer_text); if (prompt.isReadOnly()) { openUrlButton.setVisibility(GONE); } else { openUrlButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); openUrlButton.setOnClickListener(v -> { if (MultiClickGuard.allowClick(QuestionWidget.class.getName())) { onButtonClick(openUrlButton.getId()); } }); } stringAnswer.setTextColor(new ThemeUtils(context).getColorOnSurface()); stringAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); String s = prompt.getAnswerText(); if (s != null) { stringAnswer.setText(s); uri = Uri.parse(stringAnswer.getText().toString()); } return answerView; }

Target:
protected View onCreateAnswerView(Context context, FormEntryPrompt prompt, int answerFontSize) { binding = UrlWidgetAnswerBinding.inflate(((Activity) context).getLayoutInflater()); View answerView = binding.getRoot(); if (prompt.isReadOnly()) { binding.urlButton.setVisibility(GONE); } else { binding.urlButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); binding.urlButton.setOnClickListener(v -> onButtonClick()); } binding.urlAnswerText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); binding.urlAnswerText.setText(prompt.getAnswerText()); return answerView; }
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartSignalEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartSignalEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertSignalEventExecutionSet(emptyTop.getExecutionSet(), EMPTY_VALUE, NON_INTERRUPTING, ""); assertDataIOSet(emptyTop.getDataIOSet(), EMPTY_VALUE); }

Target:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartSignalEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartSignalEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertSignalEventExecutionSet(emptyTop.getExecutionSet(), EMPTY_VALUE, NON_INTERRUPTING, EMPTY_VALUE); assertDataIOSet(emptyTop.getDataIOSet(), EMPTY_VALUE); }
Source:
private void standPlayer(EntityRef entity) { ClientComponent clientComp = entity.getComponent(ClientComponent.class); GazeMountPointComponent gazeMountPointComponent = clientComp.character.getComponent(GazeMountPointComponent.class); float height = clientComp.character.getComponent(CharacterMovementComponent.class).height; float eyeHeight = gazeMountPointComponent.translate.getY(); Vector3f pos = entity.getComponent(LocationComponent.class).getWorldPosition(); CharacterCollider collider = physics.getCharacterCollider(clientComp.character); Vector3f to = new Vector3f(pos.x, pos.y + height, pos.z); SweepCallback callback = collider.sweep(pos, to, VERTICAL_PENETRATION_LEEWAY, -1f); if (callback.hasHit()) { entity.send(new NotificationMessageEvent("Cannot stand here!", entity)); return; } movementDebugCommands.playerHeight(localPlayer.getClientEntity(), height / 0.5f); movementDebugCommands.playerEyeHeight(localPlayer.getClientEntity(), eyeHeight / 0.5f); clientComp.character.send(new SetMovementModeEvent(MovementMode.WALKING)); }

Target:
private void standPlayer(EntityRef entity) { ClientComponent clientComp = entity.getComponent(ClientComponent.class); GazeMountPointComponent gazeMountPointComponent = clientComp.character.getComponent(GazeMountPointComponent.class); float height = clientComp.character.getComponent(CharacterMovementComponent.class).height; float eyeHeight = gazeMountPointComponent.translate.getY(); Vector3f pos = entity.getComponent(LocationComponent.class).getWorldPosition(); CharacterCollider collider = physics.getCharacterCollider(clientComp.character); Vector3f to = new Vector3f(pos.x, pos.y + (1 - crouchFraction) * height / crouchFraction, pos.z); SweepCallback callback = collider.sweep(pos, to, VERTICAL_PENETRATION_LEEWAY, -1f); if (callback.hasHit()) { entity.send(new NotificationMessageEvent("Cannot stand up here!", entity)); return; } movementDebugCommands.playerHeight(localPlayer.getClientEntity(), height / crouchFraction); movementDebugCommands.playerEyeHeight(localPlayer.getClientEntity(), eyeHeight / crouchFraction); clientComp.character.send(new SetMovementModeEvent(MovementMode.WALKING)); }
Source:
public void execute(SensorContext context) { Set<String> reports = Sets.newHashSet(context.config().getStringArray(JavaScriptPlugin.LCOV_REPORT_PATHS)); if (context.config().hasKey(JavaScriptPlugin.TS_LCOV_REPORT_PATHS)) { LOG.warn("The use of " + JavaScriptPlugin.TS_LCOV_REPORT_PATHS + " for coverage import is deprecated, use " + JavaScriptPlugin.LCOV_REPORT_PATHS + " instead!"); reports.addAll(Arrays.asList(context.config().getStringArray(JavaScriptPlugin.TS_LCOV_REPORT_PATHS))); } List<File> lcovFiles = reports.stream() .map(report -> getIOFile(context.fileSystem().baseDir(), report)) .filter(Objects::nonNull) .collect(Collectors.toList()); if (lcovFiles.isEmpty()) { LOG.warn("No coverage information will be saved because all LCOV files cannot be found."); return; } saveCoverageFromLcovFiles(context, lcovFiles); }

Target:
public void execute(SensorContext context) { Set<String> reports = new HashSet<>(Arrays.asList(context.config().getStringArray(JavaScriptPlugin.LCOV_REPORT_PATHS))); if (context.config().hasKey(JavaScriptPlugin.TS_LCOV_REPORT_PATHS)) { LOG.warn("The use of " + JavaScriptPlugin.TS_LCOV_REPORT_PATHS + " for coverage import is deprecated, use " + JavaScriptPlugin.LCOV_REPORT_PATHS + " instead."); reports.addAll(Arrays.asList(context.config().getStringArray(JavaScriptPlugin.TS_LCOV_REPORT_PATHS))); } List<File> lcovFiles = reports.stream() .map(report -> getIOFile(context.fileSystem().baseDir(), report)) .filter(Objects::nonNull) .collect(Collectors.toList()); if (lcovFiles.isEmpty()) { LOG.warn("No coverage information will be saved because all LCOV files cannot be found."); return; } saveCoverageFromLcovFiles(context, lcovFiles); }
Source:
private void killInstances(SchedulerDriver driver, int toKill) { if (toKill == 0) return; if (toKill >= crateInstances.size()) { markForceShutdown(driver); } int killed = 0; LOGGER.debug("Too many instances running. Killing tasks", toKill); for (CrateInstance crateInstance : crateInstances) { if (killed == toKill) { break; } LOGGER.info("Kill task {}", crateInstance.taskId()); driver.killTask(taskID(crateInstance.taskId())); killed++; } }

Target:
private void killInstances(SchedulerDriver driver, int toKill) { if (toKill == 0) return; if (toKill == crateInstances.size()) { markForceShutdown(driver); } int killed = 0; LOGGER.debug("Too many instances running. Killing tasks", toKill); for (CrateInstance crateInstance : crateInstances) { if (killed == toKill) { break; } LOGGER.info("Kill task {}", crateInstance.taskId()); driver.killTask(taskID(crateInstance.taskId())); killed++; } }
Source:
private static Process runASyncProcess(String[] command, File workingDirectory, Map<String, String> envs, String logFileUuid, boolean logStderr) { LOG.log(Level.INFO, "Run async process: ``{0}''", String.join(" ", command)); String commandFileName = Paths.get(command[0]).getFileName().toString(); String uuid = logFileUuid; if (uuid == null) { uuid = UUID.randomUUID().toString().substring(0, 8) + "-started"; } ProcessBuilder pb = getProcessBuilder(false, command, workingDirectory, envs); pb.redirectErrorStream(true); if (logStderr) { String logFilePath = String.format("%s/%s-%s.stderr", workingDirectory, commandFileName, uuid); pb.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFilePath))); } Process process = null; try { process = pb.start(); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to run async process ", e); } return process; }

Target:
private static Process runASyncProcess(String[] command, File workingDirectory, Map<String, String> envs, String logFileUuid, boolean logStderr) { LOG.log(Level.INFO, "Running async process: ``{0}''''", String.join(" ", command)); String commandFileName = Paths.get(command[0]).getFileName().toString(); String uuid = logFileUuid; if (uuid == null) { uuid = UUID.randomUUID().toString().substring(0, 8) + "-started"; } ProcessBuilder pb = getProcessBuilder(false, command, workingDirectory, envs); pb.redirectErrorStream(true); if (logStderr) { String logFilePath = String.format("%s/%s-%s.stderr", workingDirectory, commandFileName, uuid); pb.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFilePath))); } Process process = null; try { process = pb.start(); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to run async process", e); } return process; }
Source:
public ARXRandomForestConfiguration getRandomForestConfiguration() { if (this.configRandomForest == null || this.configCurrent == null) { this.configRandomForest = ARXRandomForestConfiguration.create(); this.configCurrent = this.configRandomForest; } return this.configRandomForest; }

Target:
public ARXRandomForestConfiguration getRandomForestConfiguration() { if (this.configRandomForest == null) { this.configRandomForest = ARXRandomForestConfiguration.create(); } return this.configRandomForest; }
Source:
public int hashCode() { return Utils.hashcode(new Object[]{uuid}); }

Target:
public int hashCode() { return uuid.hashCode(); }
Source:
public List<A> createEntities(Collection<A> entitiesToAdd) throws InvalidParametersException { Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, entitiesToAdd); List<A> entitiesToUpdate = new ArrayList<A>(); List<E> entities = new ArrayList<E>(); for (A entityToAdd : entitiesToAdd) { entityToAdd.sanitizeForSaving(); if (!entityToAdd.isValid()) { throw new InvalidParametersException(entityToAdd.getInvalidityInfo()); } if (hasEntity(entityToAdd)) { entitiesToUpdate.add(entityToAdd); } else { E entity = entityToAdd.toEntity(); entities.add(entity); } log.info(entityToAdd.getBackupIdentifier()); } ofy().save().entities(entities).now(); return entitiesToUpdate; }

Target:
public List<A> createEntities(Collection<A> entitiesToAdd) throws InvalidParametersException { Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, entitiesToAdd); List<A> entitiesToUpdate = new ArrayList<>(); List<E> entities = new ArrayList<>(); for (A entityToAdd : entitiesToAdd) { entityToAdd.sanitizeForSaving(); if (!entityToAdd.isValid()) { throw new InvalidParametersException(entityToAdd.getInvalidityInfo()); } if (hasEntity(entityToAdd)) { entitiesToUpdate.add(entityToAdd); } else { E entity = entityToAdd.toEntity(); entities.add(entity); } } saveEntities(entities, entitiesToAdd); return entitiesToUpdate; }
Source:
public void testBackupStatic() throws Exception { final int SERVER_COUNT = 3; final int[] clientPorts = new int[SERVER_COUNT]; StringBuilder sb = new StringBuilder(); String server; for (int i = 0; i < SERVER_COUNT; i++) { clientPorts[i] = PortAssignment.unique(); server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":participant;localhost:" + clientPorts[i]; sb.append(server + "\n"); } String currentQuorumCfgSection = sb.toString(); MainThread[] mt = new MainThread[SERVER_COUNT]; String[] staticFileContent = new String[SERVER_COUNT]; String[] staticBackupContent = new String[SERVER_COUNT]; for (int i = 0; i < SERVER_COUNT; i++) { mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false); Assert.assertNull("static file backup shouldn't exist before bootup", mt[i].getFileByName("zoo.cfg.bak")); staticFileContent[i] = getFileContent(mt[i].confFile); mt[i].start(); } for (int i = 0; i < SERVER_COUNT; i++) { Assert.assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT)); File backupFile = mt[i].getFileByName("zoo.cfg.bak"); Assert.assertNotNull("static file backup should exist", backupFile); staticBackupContent[i] = getFileContent(backupFile); Assert.assertEquals(staticFileContent[i], staticBackupContent[i]); } for (int i = 0; i < SERVER_COUNT; i++) { mt[i].shutdown(); } }

Target:
public void testBackupStatic() throws Exception { final int SERVER_COUNT = 3; final int[] clientPorts = new int[SERVER_COUNT]; StringBuilder sb = new StringBuilder(); String server; for (int i = 0; i < SERVER_COUNT; i++) { clientPorts[i] = PortAssignment.unique(); server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":participant;localhost:" + clientPorts[i]; sb.append(server + "\n"); } String currentQuorumCfgSection = sb.toString(); MainThread[] mt = new MainThread[SERVER_COUNT]; String[] staticFileContent = new String[SERVER_COUNT]; String[] staticBackupContent = new String[SERVER_COUNT]; for (int i = 0; i < SERVER_COUNT; i++) { mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false); assertNull("static file backup shouldn't exist before bootup", mt[i].getFileByName("zoo.cfg.bak")); staticFileContent[i] = getFileContent(mt[i].confFile); mt[i].start(); } for (int i = 0; i < SERVER_COUNT; i++) { assertTrue( "waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT)); File backupFile = mt[i].getFileByName("zoo.cfg.bak"); assertNotNull("static file backup should exist", backupFile); staticBackupContent[i] = getFileContent(backupFile); assertEquals(staticFileContent[i], staticBackupContent[i]); } for (int i = 0; i < SERVER_COUNT; i++) { mt[i].shutdown(); } }
Source:
public void visitSwitchStatement(SwitchStatementTree tree) { boolean hasClauseWithoutJump = false; boolean hasDefaultCase = false; List<SwitchClauseTree> branches = new ArrayList<>(); for (int i = 0; i < tree.cases().size(); i++) { SwitchClauseTree caseTree = tree.cases().get(i); boolean isLast = (i == tree.cases().size() - 1); if (caseTree.is(Kind.DEFAULT_CLAUSE)) { hasDefaultCase = true; } if (!caseTree.statements().isEmpty() || isLast) { branches.add(caseTree); } if (!endsWithJump(caseTree) && !isLast) { hasClauseWithoutJump = true; } } if (!hasClauseWithoutJump && hasDefaultCase && allBranchesEquivalent(branches)) { allBranchesDuplicated(tree); } else { checkDuplicatedBranches(branches); } super.visitSwitchStatement(tree); }

Target:
public void visitSwitchStatement(SwitchStatementTree tree) { boolean hasFallthrough = false; boolean hasDefaultCase = false; List<Tree> branches = new ArrayList<>(); for (int i = 0; i < tree.cases().size(); i++) { SwitchClauseTree caseTree = tree.cases().get(i); boolean isLast = (i == tree.cases().size() - 1); if (caseTree.is(Kind.DEFAULT_CLAUSE)) { hasDefaultCase = true; } if (!caseTree.statements().isEmpty() || isLast) { branches.add(caseTree); } if (!endsWithJump(caseTree) && !isLast) { hasFallthrough = true; } } if (!hasFallthrough && hasDefaultCase && allBranchesEquivalent(branches)) { allBranchesDuplicated(tree); } else { checkDuplicatedBranches(branches); } super.visitSwitchStatement(tree); }
Source:
public int getMessageType() { String authorValue = authorText.getText(); if (authorValue.length() == 0 || RawParseUtils.parsePersonIdent(authorValue) == null) return ERROR; String committerValue = committerText.getText(); if (committerValue.length() == 0 || RawParseUtils.parsePersonIdent(committerValue) == null) return ERROR; if (amending && amendingCommitInRemoteBranch) return WARNING; return NONE; }

Target:
public int getMessageType() { return statusType; }
Source:
protected void doExecute() throws Exception { if (skip == true) { return; } if (features == null) { return; } InstallFeatureTask installFeatureTask = (InstallFeatureTask) ant .createTask("antlib:net/wasdev/wlp/ant:install-feature"); if (installFeatureTask == null) { throw new NullPointerException("Install feature task not found."); } installFeatureTask.setInstallDir(installDirectory); installFeatureTask.setServerName(serverName); installFeatureTask.setUserDir(userDirectory); installFeatureTask.setOutputDir(outputDirectory); if (features != null) { installFeatureTask.setAcceptLicense(features.isAcceptLicense()); installFeatureTask.setTo(features.getTo()); installFeatureTask.setWhenFileExists(features.getWhenFileExists()); installFeatureTask.setFeatures(features.getFeatures()); installFeatureTask.setFrom(features.getFrom()); } installFeatureTask.execute(); }

Target:
protected void doExecute() throws Exception { if (skip == true) { return; } if (features == null) { return; } InstallFeatureTask installFeatureTask = (InstallFeatureTask) ant .createTask("antlib:net/wasdev/wlp/ant:install-feature"); if (installFeatureTask == null) { throw new NullPointerException("Install feature task not found."); } installFeatureTask.setInstallDir(installDirectory); installFeatureTask.setServerName(serverName); installFeatureTask.setUserDir(userDirectory); installFeatureTask.setOutputDir(outputDirectory); installFeatureTask.setAcceptLicense(features.isAcceptLicense()); installFeatureTask.setTo(features.getTo()); installFeatureTask.setWhenFileExists(features.getWhenFileExists()); installFeatureTask.setFeatures(features.getFeatures()); installFeatureTask.setFrom(features.getFrom()); installFeatureTask.execute(); }
Source:
static TerminateStrategyConfiguration generateTermination(JTermination jTermination) { TerminateStrategyConfiguration termination = null; if (jTermination instanceof JTerminationIterations) { termination = new IterationsOrDurationStrategyConfiguration(); String duration = parseDuration(((JTerminationIterations) jTermination).getMaxDurationInSeconds()); ((IterationsOrDurationStrategyConfiguration) termination).setDuration(duration); ((IterationsOrDurationStrategyConfiguration) termination).setIterations( (int) ((JTerminationIterations) jTermination).getIterationCount()); ((IterationsOrDurationStrategyConfiguration) termination).setShutdown(new AtomicBoolean(false)); } else if (jTermination instanceof JTerminationDuration) { termination = new IterationsOrDurationStrategyConfiguration(); String duration = parseDuration(((JTerminationDuration) jTermination).getDurationInSeconds()); ((IterationsOrDurationStrategyConfiguration) termination).setDuration(duration); ((IterationsOrDurationStrategyConfiguration) termination).setShutdown(new AtomicBoolean(false)); } else if (jTermination instanceof JTerminationBackground) { termination = new InfiniteTerminationStrategyConfiguration(); } return termination; }

Target:
static TerminateStrategyConfiguration generateTermination(JTermination jTermination) { TerminateStrategyConfiguration termination = null; if (jTermination instanceof JTerminationIterations) { termination = generateIterationTermination((JTerminationIterations) jTermination); } else if (jTermination instanceof JTerminationDuration) { termination = generateDurationTermination((JTerminationDuration) jTermination); } else if (jTermination instanceof JTerminationBackground) { termination = new InfiniteTerminationStrategyConfiguration(); } return termination; }
Source:
private void addGrantsToACL(AccessControlList acl) { String ownerId = acl.getOwner().getId(); acl.addPermission(GroupGranteeURI.ALL_USERS, Permission.READ); acl.addPermission(new EmailAddressGrantee(TEST_ACL_EMAIL), Permission.READ_ACP); acl.addPermission(new CanonicalUserGrantee(ownerId), Permission.WRITE_ACP); }

Target:
private void addGrantsToACL(AccessControlList acl) { String ownerId = acl.getOwner().getId(); acl.addPermission(ALL_USERS, READ); acl.addPermission(new EmailAddressGrantee(TEST_ACL_EMAIL), READ_ACP); acl.addPermission(new CanonicalUserGrantee(ownerId), WRITE_ACP); }
Source:
private static Optional<Comparable> getMeasureValue(Condition condition, QualityGateEvaluator.Measure measure) { Comparable result = null; if (condition.isOnLeakPeriod()) { if (measure.getLeakValue().isPresent()) { switch (measure.getType()) { case BOOL: result = Double.compare(measure.getLeakValue().getAsDouble(), 1.0) == 1; break; case INT: case RATING: result = (int) measure.getLeakValue().getAsDouble(); break; case FLOAT: case PERCENT: result = measure.getLeakValue().getAsDouble(); break; case MILLISEC: case WORK_DUR: result = (long) measure.getLeakValue().getAsDouble(); break; default: throw new IllegalArgumentException("Condition on leak period is not allowed for type " + measure.getType()); } } } else { switch (measure.getType()) { case BOOL: if (measure.getValue().isPresent()) { result = Double.compare(measure.getValue().getAsDouble(), 1.0) == 1; } break; case INT: case RATING: if (measure.getValue().isPresent()) { result = (int) measure.getValue().getAsDouble(); } break; case FLOAT: case PERCENT: if (measure.getValue().isPresent()) { result = measure.getValue().getAsDouble(); } break; case MILLISEC: case WORK_DUR: if (measure.getValue().isPresent()) { result = (long) measure.getValue().getAsDouble(); } break; case LEVEL: case STRING: case DISTRIB: result = measure.getStringValue().orElse(null); break; default: throw new IllegalArgumentException("Condition on leak period is not allowed for type " + measure.getType()); } } return Optional.ofNullable(result); }

Target:
private static Optional<Comparable> getMeasureValue(Condition condition, QualityGateEvaluator.Measure measure) { if (condition.isOnLeakPeriod()) { return Optional.ofNullable(getLeakValue(measure)); } return Optional.ofNullable(getValue(measure)); }
Source:
public void testGetKeyPairWhenResponseIs2xx() throws Exception { HttpRequest get = HttpRequest .builder() .method("GET") .endpoint("<LINK_0>") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); HttpResponse getResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/keypair_details.json")).build(); NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, get, getResponse); assertEquals(apiWhenServersExist.getKeyPairExtensionForZone("az-1.region-a.geo-1").get().get("testkeypair"), new ParseKeyPairTest().expected()); }

Target:
public void testGetKeyPairWhenResponseIs2xx() throws Exception { HttpRequest get = HttpRequest .builder() .method("GET") .endpoint("<LINK_0>") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); HttpResponse getResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/keypair_details.json")).build(); NovaApi apiWhenKeyPairExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, get, getResponse); assertEquals(apiWhenKeyPairExists.getKeyPairExtensionForZone("az-1.region-a.geo-1").get().get("testkeypair"), new ParseKeyPairTest().expected()); }
Source:
public void testSimilarItems() { List<IDValue> recs = target("similarity/I0/I4/I6").request() .accept(MediaType.APPLICATION_JSON_TYPE).get(LIST_ID_VALUE_TYPE); Assert.assertEquals(9, recs.size()); for (int i = 1; i < recs.size(); i++) { Assert.assertTrue(recs.get(i).getValue() <= recs.get(i-1).getValue()); } Assert.assertEquals("I1", recs.get(1).getID()); Assert.assertEquals(0.5571406877613947, recs.get(2).getValue(), DOUBLE_EPSILON); }

Target:
public void testSimilarItems() { List<IDValue> recs = target("similarity/I0/I4/I6").request() .accept(MediaType.APPLICATION_JSON_TYPE).get(LIST_ID_VALUE_TYPE); testTopByValue(9, recs, false); Assert.assertEquals("I1", recs.get(1).getID()); Assert.assertEquals(0.5852498930217405, recs.get(2).getValue(), DOUBLE_EPSILON); }
Source:
public void commandComplete(GcodeCommand command) { if (command.isError() && this.controller.isStreaming() && !this.isPaused()) { try { this.pauseResume(); } catch (Exception e) { GUIHelpers.displayErrorDialog(e.getLocalizedMessage()); } } }

Target:
public void commandComplete(GcodeCommand command) { if (command.isError() && isSendingFile() && !this.isPaused()) { try { this.pauseResume(); } catch (Exception e) { GUIHelpers.displayErrorDialog(e.getLocalizedMessage()); } } }
Source:
public static synchronized void trace(String msg) { if (fTraceFile != null) { return; } long currentTime = System.currentTimeMillis(); StringBuilder message = new StringBuilder("["); message.append(currentTime / 1000); message.append("."); message.append(String.format("%1$03d", currentTime % 1000)); message.append("] "); message.append("[TID="); message.append(String.format("%1$03d", Thread.currentThread().getId())); message.append("] "); message.append(msg); try { fTraceFile.write(message.toString()); fTraceFile.newLine(); fTraceFile.flush(); } catch (IOException e) { Activator.logError("Error writing to log file", e); } }

Target:
public static synchronized void trace(String msg) { if (fTraceFile == null) { return; } long currentTime = System.currentTimeMillis(); StringBuilder message = new StringBuilder("["); message.append(currentTime / 1000); message.append("."); message.append(String.format("%1$03d", currentTime % 1000)); message.append("] "); message.append("[TID="); message.append(String.format("%1$03d", Thread.currentThread().getId())); message.append("] "); message.append(msg); try { fTraceFile.write(message.toString()); fTraceFile.newLine(); fTraceFile.flush(); } catch (IOException e) { Activator.logError("Error writing to log file", e); } }
Source:
public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) throws Exception { Channel ch = ctx.channel(); NewHotRodDecoder decoder = ctx.pipeline().get(NewHotRodDecoder.class); CacheDecodeContext decodeCtx = decoder.decodeCtx; log.debug("Exception caught", t); if (t instanceof DecoderException) { t = t.getCause(); } if (t instanceof HotRodException) { ch.writeAndFlush(((HotRodException) t).response()); } else { ch.writeAndFlush(decodeCtx.createExceptionResponse(t)); } }

Target:
public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) throws Exception { Channel ch = ctx.channel(); HotRodDecoder decoder = ctx.pipeline().get(HotRodDecoder.class); CacheDecodeContext decodeCtx = decoder.decodeCtx; log.debug("Exception caught", t); if (t instanceof DecoderException) { t = t.getCause(); } if (t instanceof HotRodException) { ch.writeAndFlush(((HotRodException) t).response(), ch.voidPromise()); } else { ch.writeAndFlush(decodeCtx.createExceptionResponse(t), ch.voidPromise()); } }
Source:
public void testGetColumnsFromJSONArraySingleEntry() { String json = "{" + "\"array\": " + "[7]" + "}"; YailList expecetdColumn = YailList.makeList(Arrays.asList("array", "7")); YailList expected = YailList.makeList(Collections.singletonList(expecetdColumn)); YailList result = JsonUtil.getColumnsFromJSON(json); assertEquals(expected, result); }

Target:
public void testGetColumnsFromJSONArraySingleEntry() { String json = "{" + "\"array\": " + "[7]" + "}"; YailList expectedColumn = YailList.makeList(Arrays.asList("array", "7")); YailList expected = YailList.makeList(Collections.singletonList(expectedColumn)); YailList result = JsonUtil.getColumnsFromJSON(json); assertEquals(expected, result); }
Source:
public void resetLocalMembership(InstanceRegisteredEvent event) { afterStartUp = true; Member startUpPhaseLocalMember = atomicConsistentHash.get().getMembers().stream() .filter(Member::local) .findFirst() .orElseThrow(() -> new IllegalStateException( "There should be no scenario were the local member does not exist." )); updateMemberships(); atomicConsistentHash.updateAndGet(consistentHash -> consistentHash.without(startUpPhaseLocalMember)); }

Target:
public void resetLocalMembership(InstanceRegisteredEvent event) { registered = true; Member startUpPhaseLocalMember = atomicConsistentHash.get().getMembers().stream() .filter(Member::local) .findFirst() .orElseThrow(() -> new IllegalStateException( "There should be no scenario where the local member does not exist." )); updateMemberships(); atomicConsistentHash.updateAndGet(consistentHash -> consistentHash.without(startUpPhaseLocalMember)); }
Source:
public void testNoServiceFound() throws Exception { when(mockRequest.params(QUERY_PARAM)).thenReturn("xml"); String res = (String) cqlTransformHandler.handle(mockRequest, mockResponse); assertThat(res, is(SERVICE_NOT_FOUND)); }

Target:
public void testNoServiceFound() throws Exception { when(mockRequest.params(QUERY_PARAM)).thenReturn(OTHER_RETURN_ID); String res = Boon.toJson(cqlTransformHandler.handle(mockRequest, mockResponse)); assertThat(res, is(SERVICE_NOT_FOUND)); assertThat(mockResponse.status(), is(HttpStatus.NOT_FOUND_404)); }
Source:
private ByteBuffer doPostTest(HttpRequest postRequest, List<ByteBuffer> contentToSend) throws InterruptedException { EmbeddedChannel channel = createChannel(); notificationSystem.reset(); postRequest.headers().set(RestUtils.Headers.AMBRY_CONTENT_TYPE, "application/octet-stream"); HttpUtil.setKeepAlive(postRequest, false); channel.writeInbound(postRequest); if (contentToSend != null) { for (ByteBuffer content : contentToSend) { channel.writeInbound(new DefaultHttpContent(Unpooled.wrappedBuffer(content))); } channel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT); } if (!notificationSystem.operationCompleted.await(1000, TimeUnit.MILLISECONDS)) { fail("Post did not succeed after 100ms. There is an error or timeout needs to increase"); } assertNotNull("Blob id operated on cannot be null", notificationSystem.blobIdOperatedOn); return router.getActiveBlobs().get(notificationSystem.blobIdOperatedOn).getBlob(); }

Target:
private ByteBuffer doPostTest(HttpRequest postRequest, List<ByteBuffer> contentToSend) throws InterruptedException { EmbeddedChannel channel = createChannel(); notificationSystem.reset(); postRequest.headers().set(RestUtils.Headers.AMBRY_CONTENT_TYPE, "application/octet-stream"); HttpUtil.setKeepAlive(postRequest, false); channel.writeInbound(postRequest); if (contentToSend != null) { for (ByteBuffer content : contentToSend) { channel.writeInbound(new DefaultHttpContent(Unpooled.wrappedBuffer(content))); } channel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT); } if (!notificationSystem.operationCompleted.await(1000, TimeUnit.MILLISECONDS)) { fail("Post did not succeed after 1000ms. There is an error or timeout needs to increase"); } assertNotNull("Blob id operated on cannot be null", notificationSystem.blobIdOperatedOn); return router.getActiveBlobs().get(notificationSystem.blobIdOperatedOn).getBlob(); }
Source:
public static Slice wrappedBuffer(ByteBuffer buffer) { if (buffer.isDirect()) { long address = getAddress(buffer); return new Slice(null, address + buffer.position(), buffer.limit() - buffer.position(), buffer.capacity(), buffer); } if (buffer.hasArray()) { return new Slice(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.limit() - buffer.position()); } throw new IllegalArgumentException("cannot wrap " + buffer.getClass().getName()); }

Target:
public static Slice wrappedBuffer(ByteBuffer buffer) { if (buffer.isDirect()) { long address = getAddress(buffer); return new Slice(null, address + buffer.position(), buffer.remaining(), buffer.capacity(), buffer); } if (buffer.hasArray()) { return new Slice(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); } throw new IllegalArgumentException("cannot wrap " + buffer.getClass().getName()); }
Source:
public void clusterStops() { if (graph.clusterByParentStation) clusterByParentStation(); else clusterByProximity(); }

Target:
public void clusterStops() { switch (graph.stopClusterMode) { case "parentStation": clusterByParentStation(); break; case "proximity": clusterByProximity(); break; default: clusterByProximity(); } }
Source:
public void testReduceRows() { List<SomethingWithLocations> result = dbRule.getSharedHandle() .createQuery("SELECT something.id, name, location FROM something NATURAL JOIN something_location") .reduceRows(LinkedHashMapRowReducer.<Integer, SomethingWithLocations>of((map, rv) -> map.computeIfAbsent(rv.getColumn("id", Integer.class), id -> new SomethingWithLocations(rv.getRow(Something.class))) .locations .add(rv.getColumn("location", String.class)))) .collect(toList()); assertThat(result).containsExactly( new SomethingWithLocations(new Something(1, "tree")).at("outside"), new SomethingWithLocations(new Something(2, "apple")).at("tree").at("pie")); }

Target:
public void testReduceRows() { List<SomethingWithLocations> result = dbRule.getSharedHandle() .createQuery("SELECT something.id, name, location FROM something NATURAL JOIN something_location") .<Integer, SomethingWithLocations>reduceRows((map, rv) -> map.computeIfAbsent(rv.getColumn("id", Integer.class), id -> new SomethingWithLocations(rv.getRow(Something.class))) .locations .add(rv.getColumn("location", String.class))) .collect(toList()); assertThat(result).containsExactly( new SomethingWithLocations(new Something(1, "tree")).at("outside"), new SomethingWithLocations(new Something(2, "apple")).at("tree").at("pie")); }