auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public AxisAlignedBB getMinecartCollisionBox(EntityMinecart cart) { return cart.getEntityBoundingBox().expand(MinecartHooks.COLLISION_EXPANSION, 0, MinecartHooks.COLLISION_EXPANSION); }

Target:
public AxisAlignedBB getMinecartCollisionBox(EntityMinecart cart) { double yaw = Math.toRadians(cart.rotationYaw); double diff = ((CART_LENGTH - CART_WIDTH) / 2.0) + MinecartHooks.COLLISION_EXPANSION; double x = diff * Math.abs(Math.cos(yaw)); double z = diff * Math.abs(Math.sin(yaw)); return cart.getEntityBoundingBox().expand(x, MinecartHooks.COLLISION_EXPANSION, z); }
Source:
private SourceDocument parseRecord(String record) { StringBuilder builder = new StringBuilder(); ObjectMapper mapper = new ObjectMapper(); WashingtonPostObject recordObj = null; try { recordObj = mapper .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .registerModule(new Jdk8Module()) .readValue(record, WashingtonPostObject.class); } catch (IOException e) { LOG.warn("No unique ID or published date for this record, ignored..."); return null; } id = recordObj.id(); published_date = recordObj.published_date(); if (recordObj.contents != null && recordObj.contents.isPresent()) { for (WashingtonPostObject.Content contentObj : recordObj.contents.get()) { if (contentObj.type() != null && contentObj.type().isPresent() && contentObj.content() != null && contentObj.content().isPresent()) { if (CONTENT_TYPE_TAG.contains(contentObj.type().get())) { builder.append(removeTags(contentObj.content().get().trim())).append("\n"); } } else { LOG.warn("No type or content tag defined in Article " + id + ", ignored this file."); } } } content = builder.toString(); return this; }

Target:
private SourceDocument parseRecord(String record) { StringBuilder builder = new StringBuilder(); ObjectMapper mapper = new ObjectMapper(); WashingtonPostObject wapoObj = null; try { wapoObj = mapper .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .registerModule(new Jdk8Module()) .readValue(record, WashingtonPostObject.class); } catch (IOException e) { LOG.warn("No unique ID or published date for this record, ignored..."); return null; } id = wapoObj.id(); published_date = wapoObj.published_date(); if (JsonParser.isFieldAvailable(wapoObj.contents())) { for (WashingtonPostObject.Content contentObj : wapoObj.contents().get()) { if (JsonParser.isFieldAvailable(contentObj.type()) && JsonParser.isFieldAvailable(contentObj.content())) { if (CONTENT_TYPE_TAG.contains(contentObj.type().get())) { builder.append(removeTags(contentObj.content().get().trim())).append("\n"); } } else { LOG.warn("No type or content tag defined in Article " + id + ", ignored this file."); } } } content = builder.toString(); return this; }
Source:
private void logBrokerVersion() { final String currentActiveBrokerPackageName = mBrokerProxy.getCurrentActiveBrokerPackageName(); if (!StringExtensions.IsNullOrBlank(currentActiveBrokerPackageName)) { String brokerRelatedInfoLogging = "The active broker is: " + currentActiveBrokerPackageName; if (mBrokerProxy.isBrokerWithPRTSupport(currentActiveBrokerPackageName)) { brokerRelatedInfoLogging += ". The active broker version is: " + AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION + ". It contains PRT support."; } else { brokerRelatedInfoLogging += " The active broker version is: v1. It doesn't " + "contain PRT support"; } Logger.v(TAG, brokerRelatedInfoLogging); } }

Target:
private void logBrokerVersion() { final String currentActiveBrokerPackageName = mBrokerProxy.getCurrentActiveBrokerPackageName(); if (StringExtensions.IsNullOrBlank(currentActiveBrokerPackageName)) { Logger.i(TAG, "Broker app package name is empty.", ""); return; } String brokerAppVersion; try { brokerAppVersion = mBrokerProxy.getBrokerAppVersion(currentActiveBrokerPackageName); } catch (final PackageManager.NameNotFoundException e) { brokerAppVersion = "N/A"; } final String brokerLogging = "Broker app is: " + currentActiveBrokerPackageName + ";Broker app version: " + brokerAppVersion; Logger.i(TAG, brokerLogging, ""); }
Source:
public List<String> getScopes() { return Arrays.asList("openid", "email", "profile", groupsNameParameter, alfioGroupsNameParameter); }

Target:
public List<String> getScopes() { return List.of("openid", "email", "profile", groupsNameParameter, alfioGroupsNameParameter); }
Source:
private static void checkLxmlXsltCall(SubscriptionContext ctx) { CallExpression callExpression = (CallExpression) ctx.syntaxNode(); if (checkCallExpressionFqn(callExpression, LXML_XSLT)) { RegularArgument argument = TreeUtils.argumentByKeyword("access_control", callExpression.arguments()); if (argument != null) { CallExpression xsltAclCall = getArgValueAsCallExpression(argument); if (xsltAclCall != null && checkCallExpressionFqn(xsltAclCall, LXML_ACCESS_CONTROL)) { RegularArgument readNetwork = TreeUtils.argumentByKeyword("read_network", xsltAclCall.arguments()); if (readNetwork == null || !Expressions.isFalsy(readNetwork.expression())) { ctx.addIssue(xsltAclCall, MESSAGE).secondary(callExpression, MESSAGE); } } } else { ctx.addIssue(callExpression, MESSAGE); } } }

Target:
private static void checkLxmlXsltCall(SubscriptionContext ctx) { CallExpression callExpression = (CallExpression) ctx.syntaxNode(); if (checkCallExpressionFqn(callExpression, LXML_XSLT)) { RegularArgument argument = TreeUtils.argumentByKeyword("access_control", callExpression.arguments()); if (argument != null) { CallExpression xsltAclCall = getArgValueAsCallExpression(argument); if (xsltAclCall != null && checkCallExpressionFqn(xsltAclCall, LXML_ACCESS_CONTROL)) { RegularArgument readNetwork = TreeUtils.argumentByKeyword("read_network", xsltAclCall.arguments()); if (readNetwork == null || !Expressions.isFalsy(readNetwork.expression())) { ctx.addIssue(xsltAclCall, MESSAGE).secondary(callExpression, null); } } } else { ctx.addIssue(callExpression, MESSAGE); } } }
Source:
public IndexSelector(String prefix, IndexStrategy strategy) { this.prefix = prefix; this.strategy = strategy; this.unit = UNIT_MAP.get(strategy); if (unit == null) { throw new UnsupportedOperationException("This is a programming mistake, please check your code!"); } }

Target:
public IndexSelector(String prefix, IndexStrategy strategy) { this.prefix = prefix; this.strategy = strategy; this.unit = UNIT_MAP.get(strategy); if (unit == null) { throw new UnsupportedOperationException("This is a programming mistake, please check the mapping for strategy=" + strategy.name()); } }
Source:
public static String getFileName(final Path rootDir, final Path filePath) throws IOException{ return rootDir.relativize(filePath).toString().replace("\\", "/"); }

Target:
public static String getFileName(final Path rootDir, final Path filePath) { return rootDir.relativize(filePath).toString().replace("\\", "/"); }
Source:
public void init() { inEventCount = 0; removeEventCount = 0; eventArrived = false; innerAssertionsPassed = false; eventTimeStamp = 0; count.set(0); averageValue = Double.valueOf(0); totalValue = Double.valueOf(0); }

Target:
public void init() { inEventCount = 0; removeEventCount = 0; eventArrived = false; innerAssertionsPassed = false; eventTimeStamp = 0; count.set(0); averageValue = 0.0; totalValue = 0.0; }
Source:
public void testEmptyTable() throws Exception { String tableName = "empty_table"; session.execute(format("CREATE TABLE %s.%s (key text PRIMARY KEY)", KEYSPACE, tableName)); EmbeddedCassandra.refreshSizeEstimates(KEYSPACE, tableName); List<TokenSplit> splits = splitManager.getSplits(KEYSPACE, tableName); assertEquals(splits.size(), 1); }

Target:
public void testEmptyTable() throws Exception { String tableName = "empty_table"; session.execute(format("CREATE TABLE %s.%s (key text PRIMARY KEY)", KEYSPACE, tableName)); EmbeddedCassandra.refreshSizeEstimates(KEYSPACE, tableName); List<TokenSplit> splits = splitManager.getSplits(KEYSPACE, tableName); assertEquals(splits.size(), 1); session.execute(format("DROP TABLE %s.%s", KEYSPACE, tableName)); }
Source:
public void onPause() { super.onPause(); SubscriptionManager.from(getActivity()).removeOnSubscriptionsChangedListener( mOnSubscriptionsChangeListener); }

Target:
public void onPause() { SubscriptionManager.from(getActivity()).removeOnSubscriptionsChangedListener( mOnSubscriptionsChangeListener); super.onPause(); }
Source:
private static void addNetworkInterfaceProperties(XmlRpcStruct struct, VmNetworkInterface vmInterface, VmDevice vmDevice, String nicModel, Version clusterVersion) { struct.add(VdsProperties.Type, vmDevice.getType()); struct.add(VdsProperties.Device, vmDevice.getDevice()); if (vmInterface.getNetworkName() != null) { struct.add(VdsProperties.network, vmInterface.getNetworkName()); } struct.add(VdsProperties.linkState, vmInterface.isLinked() ? "up" : "down"); addAddress(vmDevice, struct); struct.add(VdsProperties.mac_addr, vmInterface.getMacAddress()); addBootOrder(vmDevice, struct); struct.add(VdsProperties.SpecParams, vmDevice.getSpecParams()); struct.add(VdsProperties.DeviceId, String.valueOf(vmDevice.getId().getDeviceId())); struct.add(VdsProperties.nic_type, nicModel); if (vmInterface.isPortMirroring()) { List<String> networks = new ArrayList<String>(); networks.add(vmInterface.getNetworkName()); struct.add(VdsProperties.portMirroring, networks); } addNetworkFiltersToNic(struct, clusterVersion); }

Target:
private static void addNetworkInterfaceProperties(XmlRpcStruct struct, VmNetworkInterface vmInterface, VmDevice vmDevice, String nicModel, Version clusterVersion) { struct.add(VdsProperties.Type, vmDevice.getType()); struct.add(VdsProperties.Device, vmDevice.getDevice()); if (vmInterface.getNetworkName() != null) { struct.add(VdsProperties.network, vmInterface.getNetworkName()); } boolean linkingSupported = Config.<Boolean> GetValue(ConfigValues.NetworkLinkingSupported, clusterVersion.getValue()); if (linkingSupported) { struct.add(VdsProperties.linkActive, String.valueOf(vmInterface.isLinked())); } addAddress(vmDevice, struct); struct.add(VdsProperties.mac_addr, vmInterface.getMacAddress()); addBootOrder(vmDevice, struct); struct.add(VdsProperties.SpecParams, vmDevice.getSpecParams()); struct.add(VdsProperties.DeviceId, String.valueOf(vmDevice.getId().getDeviceId())); struct.add(VdsProperties.nic_type, nicModel); if (vmInterface.isPortMirroring()) { List<String> networks = new ArrayList<String>(); networks.add(vmInterface.getNetworkName()); struct.add(VdsProperties.portMirroring, networks); } addNetworkFiltersToNic(struct, clusterVersion); }
Source:
private void parseTestTools(PendingCertifiedProductEntity product, PendingCertificationResultEntity cert, int toolColumnBegin) { for(CSVRecord row : getRecord()) { String testToolName = row.get(toolColumnBegin).trim(); String testToolVersion = row.get(toolColumnBegin+1).trim(); if(!StringUtils.isEmpty(testToolName)) { PendingCertificationResultTestToolEntity ttEntity = new PendingCertificationResultTestToolEntity(); ttEntity.setTestToolName(testToolName); ttEntity.setTestToolVersion(testToolVersion); TestToolDTO testTool = testToolDao.getByName(testToolName); if(testTool != null) { if(testTool.isRetired() && product.getIcs() == false) { product.getErrorMessages().add("Test tool '" + testToolName + "' has been retired for a product with ICS=false. Please remove it from the upload file and add a different test tool if necessary."); } ttEntity.setTestToolId(testTool.getId()); } cert.getTestTools().add(ttEntity); } } }

Target:
private void parseTestTools(PendingCertifiedProductEntity product, PendingCertificationResultEntity cert, int toolColumnBegin) { for(CSVRecord row : getRecord()) { String testToolName = row.get(toolColumnBegin).trim(); String testToolVersion = row.get(toolColumnBegin+1).trim(); if(!StringUtils.isEmpty(testToolName)) { PendingCertificationResultTestToolEntity ttEntity = new PendingCertificationResultTestToolEntity(); ttEntity.setTestToolName(testToolName); ttEntity.setTestToolVersion(testToolVersion); TestToolDTO testTool = testToolDao.getByName(testToolName); if(testTool != null) { ttEntity.setTestToolId(testTool.getId()); } cert.getTestTools().add(ttEntity); } } }
Source:
private MetadataCache handleMetadataResponse(MetadataResponse metadataResponse, Predicate<MetadataResponse.TopicMetadata> topicsToRetain) { Set<String> internalTopics = new HashSet<>(); List<MetadataResponse.PartitionMetadata> partitions = new ArrayList<>(); for (MetadataResponse.TopicMetadata metadata : metadataResponse.topicMetadata()) { if (!topicsToRetain.test(metadata)) continue; if (metadata.error() == Errors.NONE) { if (metadata.isInternal()) internalTopics.add(metadata.topic()); for (MetadataResponse.PartitionMetadata partitionMetadata : metadata.partitionMetadata()) { updatePartitionInfo(metadata.topic(), partitionMetadata, metadataResponse.hasReliableLeaderEpochs(), partitions::add); if (partitionMetadata.error.exception() instanceof InvalidMetadataException) { log.debug("Requesting metadata update for partition due to error {}", partitionMetadata.topicPartition, partitionMetadata.error); requestUpdate(); } } } else if (metadata.error().exception() instanceof InvalidMetadataException) { log.debug("Requesting metadata update for topic due to error {}", metadata.topic(), metadata.error()); requestUpdate(); } } return new MetadataCache(metadataResponse.clusterId(), metadataResponse.brokersById(), partitions, metadataResponse.topicsByError(Errors.TOPIC_AUTHORIZATION_FAILED), metadataResponse.topicsByError(Errors.INVALID_TOPIC_EXCEPTION), internalTopics, metadataResponse.controller()); }

Target:
private MetadataCache handleMetadataResponse(MetadataResponse metadataResponse, Predicate<MetadataResponse.TopicMetadata> topicsToRetain) { Set<String> internalTopics = new HashSet<>(); List<MetadataResponse.PartitionMetadata> partitions = new ArrayList<>(); for (MetadataResponse.TopicMetadata metadata : metadataResponse.topicMetadata()) { if (!topicsToRetain.test(metadata)) continue; if (metadata.error() == Errors.NONE) { if (metadata.isInternal()) internalTopics.add(metadata.topic()); for (MetadataResponse.PartitionMetadata partitionMetadata : metadata.partitionMetadata()) { updateLatestMetadata(partitionMetadata, metadataResponse.hasReliableLeaderEpochs()) .ifPresent(partitions::add); if (partitionMetadata.error.exception() instanceof InvalidMetadataException) { log.debug("Requesting metadata update for partition due to error {}", partitionMetadata.topicPartition, partitionMetadata.error); requestUpdate(); } } } else if (metadata.error().exception() instanceof InvalidMetadataException) { log.debug("Requesting metadata update for topic due to error {}", metadata.topic(), metadata.error()); requestUpdate(); } } return new MetadataCache(metadataResponse.clusterId(), metadataResponse.brokersById(), partitions, metadataResponse.topicsByError(Errors.TOPIC_AUTHORIZATION_FAILED), metadataResponse.topicsByError(Errors.INVALID_TOPIC_EXCEPTION), internalTopics, metadataResponse.controller()); }
Source:
private boolean canAttackerRetreatPartialAmphib() { if (Properties.getPartialAmphibiousRetreat(battleState.getGameData())) { final List<Unit> landUnits = CollectionUtils.getMatches( battleState.getUnits(BattleState.Side.OFFENSE), Matches.unitIsLand()); for (final Unit unit : landUnits) { if (!unit.getWasAmphibious()) { return true; } } } return false; }

Target:
private boolean canAttackerRetreatPartialAmphib() { if (!Properties.getPartialAmphibiousRetreat(battleState.getGameData())) { return false; } return battleState.getUnits(BattleState.Side.OFFENSE).stream() .filter(Matches.unitIsLand()) .anyMatch(Predicate.not(Unit::getWasAmphibious)); }
Source:
protected void update(float percent) { if (nfcNdefMessage == null) { return; } NdefMessage message = null; try { message = NfcHandler.createMessage(nfcNdefMessage.interpretString(sprite), spinnerSelection); } catch (InterpretationException e) { Log.d(getClass().getSimpleName(), "Couldn't create message", e); } StageActivity.addNfcTagMessageToDeque(message); }

Target:
protected void update(float percent) { if (nfcNdefMessage == null) { return; } try { NdefMessage message = NfcHandler.createMessage(nfcNdefMessage.interpretString(sprite), nfcTagNdefSpinnerSelection); StageActivity.addNfcTagMessageToDeque(message); } catch (Exception e) { Log.d(TAG, "No new message was added to the Deque", e); } }
Source:
void initFrontend() { Frontend.initEventsHandler(frontendEventsHandler); Frontend.getFrontendFailureEvent().addListener(frontendFailureEventListener); Frontend.getFrontendNotLoggedInEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { user.logout(); frontendFailureEventListener.hide(); } }); Frontend.setFilterQueries(filterFrontendQueries()); }

Target:
void initFrontend() { Frontend.initEventsHandler(frontendEventsHandler); Frontend.getFrontendFailureEvent().addListener(frontendFailureEventListener); Frontend.getFrontendNotLoggedInEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { user.logout(); } }); Frontend.setFilterQueries(filterFrontendQueries()); }
Source:
private static void test(final String isodate) { System.out.println("----------------------------------"); try { Date date = DateParser.parse(isodate); System.out.println(">> " + isodate); System.out.println(">> " + date.toString() + " [" + date.getTime() + "]"); final String isodateRoundTrip = DateParser.getIsoDate(date); System.out.println(">> " + isodateRoundTrip); final Date orig = DateParser.parse(isodate); final Date roundTrip = DateParser.parse(isodateRoundTrip); assertDatesAreClose(orig, roundTrip); } catch (DateParser.InvalidDateException ex) { System.err.println(isodate + " is invalid"); System.err.println(ex.getMessage()); } System.out.println("----------------------------------"); }

Target:
private static void test(final String isodate) { Date date = DateParser.parse(isodate); final String isodateRoundTrip = DateParser.getIsoDate(date); final Date orig = DateParser.parse(isodate); final Date roundTrip = DateParser.parse(isodateRoundTrip); assertDatesAreClose(orig, roundTrip); }
Source:
public void cleanUpSchemaMutationLockTablesState() throws Exception { Set<TableReference> tables = lockTables.getAllLockTables(); java.util.Optional<TableReference> tableToKeep = tables.stream().findFirst(); if (!tableToKeep.isPresent()) { log.info("No lock tables to clean up."); return; } tables.remove(tableToKeep.get()); if (tables.size() > 0) { dropTablesInternal(tables); log.info("Dropped tables [{}]", UnsafeArg.of("table names", tables.toString())); } schemaMutationLock.cleanLockState(); log.info("Reset the schema mutation lock in table [{}]", UnsafeArg.of("table name", tableToKeep.get().toString())); }

Target:
public void cleanUpSchemaMutationLockTablesState() throws Exception { Set<TableReference> tables = lockTables.getAllLockTables(); java.util.Optional<TableReference> tableToKeep = tables.stream().findFirst(); if (!tableToKeep.isPresent()) { log.info("No lock tables to clean up."); return; } tables.remove(tableToKeep.get()); if (tables.size() > 0) { dropTablesInternal(tables); log.info("Dropped tables [{}]", UnsafeArg.of("table names", tables)); } schemaMutationLock.cleanLockState(); log.info("Reset the schema mutation lock in table [{}]", UnsafeArg.of("table name", tableToKeep.get().toString())); }
Source:
public static FormatterBuilder createFormatterBuilder(Properties formatterProperties) throws Exception { FormatterBuilder builder; AbstractFormatterFactory factory; if (formatterProperties.size() > 0) { String formatterClass = formatterProperties.getProperty("formatter"); String format = formatterProperties.getProperty("format", "csv"); Class<?> classz = Class.forName(formatterClass); Class<?>[] ctorParmTypes = new Class[]{ String.class, Properties.class }; Constructor<?> ctor = classz.getDeclaredConstructor(ctorParmTypes); Object[] ctorParms = new Object[]{ format, formatterProperties }; factory = new AbstractFormatterFactory() { @Override public Formatter create(String formatName, Properties props) { try { return (Formatter) ctor.newInstance(ctorParms); } catch (Exception e) { e.printStackTrace(); return null; } } }; builder = new FormatterBuilder(format, formatterProperties); } else { factory = new VoltCSVFormatterFactory(); Properties props = new Properties(); factory.create("csv", props); builder = new FormatterBuilder("csv", props); } builder.setFormatterFactory(factory); return builder; }

Target:
public static FormatterBuilder createFormatterBuilder(Properties formatterProperties) throws Exception { FormatterBuilder builder; AbstractFormatterFactory factory; if (formatterProperties.size() > 0) { String formatterClass = formatterProperties.getProperty("formatter"); String format = formatterProperties.getProperty("format", "csv"); Class<?> classz = Class.forName(formatterClass); Class<?>[] ctorParmTypes = new Class[]{ String.class, Properties.class }; Constructor<?> ctor = classz.getDeclaredConstructor(ctorParmTypes); Object[] ctorParms = new Object[]{ format, formatterProperties }; factory = new AbstractFormatterFactory() { @Override public Formatter create(String formatName, Properties props) { try { return (Formatter) ctor.newInstance(ctorParms); } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to create formatter " + formatName); return null; } } }; builder = new FormatterBuilder(format, formatterProperties); } else { factory = new VoltCSVFormatterFactory(); Properties props = new Properties(); factory.create("csv", props); builder = new FormatterBuilder("csv", props); } builder.setFormatterFactory(factory); return builder; }
Source:
public void normal() { final TestObserver<Integer> ts = new TestObserver<Integer>(); Observable.range(1, 5).mergeWith( Completable.fromAction(new Action() { @Override public void run() throws Exception { ts.onNext(100); } }) ) .subscribe(ts); ts.assertResult(1, 2, 3, 4, 5, 100); }

Target:
public void normal() { final TestObserver<Integer> to = new TestObserver<Integer>(); Observable.range(1, 5).mergeWith( Completable.fromAction(new Action() { @Override public void run() throws Exception { to.onNext(100); } }) ) .subscribe(to); to.assertResult(1, 2, 3, 4, 5, 100); }
Source:
private final int defaultPort = fromEnvironment(BROKER_PORT, null) == null ? BrokerTestUtils.getPort() : Integer.valueOf(fromEnvironment(BROKER_PORT, null)); private int port; private String hostName = fromEnvironment(BROKER_HOSTNAME, "localhost"); private String adminUri = fromEnvironment(BROKER_ADMIN_URI, null); private ConnectionFactory connectionFactory; private String user = fromEnvironment(BROKER_USER, GUEST); private String password = fromEnvironment(BROKER_PW, GUEST); private String adminUser = fromEnvironment(BROKER_ADMIN_USER, GUEST); private String adminPassword = fromEnvironment(BROKER_ADMIN_PW, GUEST); private boolean purgeAfterEach; private String fromEnvironment(String key, String defaultValue) { String environmentValue = environmentOverrides.get(key); if (!StringUtils.hasText(environmentValue)) { environmentValue = System.getenv(key); } if (StringUtils.hasText(environmentValue)) { return environmentValue; } else { return defaultValue; } }

Target:
public int getPort() { return this.port; }
Source:
public void testMerge() throws Throwable { String tableName = testName.getMethodName(); String tableNameMM = testName.getMethodName() + "_MM"; String tableNameMerge = testName.getMethodName() + "_Merge"; String tableNameMergeMM = testName.getMethodName() + "_MergeMM"; WarehouseInstance.Tuple incrementalDump; WarehouseInstance.Tuple bootStrapDump = primary.dump(primaryDbName, null); replica.load(replicatedDbName, bootStrapDump.dumpLocation) .run("REPL STATUS " + replicatedDbName) .verifyResult(bootStrapDump.lastReplicationId); insertForMerge(tableName, tableNameMerge, false); incrementalDump = verifyIncrementalLoad(Lists.newArrayList("select last_update_user from " + tableName, "select key from " + tableNameMerge, "select ID from " + tableNameMerge), Lists.newArrayList(new String[] {"creation", "creation", "creation", "creation", "creation", "creation", "creation", "merge_update", "merge_insert", "merge_insert"}, new String[] {"1", "2", "3", "4", "5", "6"}, new String[] {"1", "4", "7", "8", "8", "11"}), bootStrapDump.lastReplicationId); }

Target:
public void testMerge() throws Throwable { String tableName = testName.getMethodName(); String tableNameMerge = testName.getMethodName() + "_Merge"; WarehouseInstance.Tuple incrementalDump; WarehouseInstance.Tuple bootStrapDump = primary.dump(primaryDbName, null); replica.load(replicatedDbName, bootStrapDump.dumpLocation) .run("REPL STATUS " + replicatedDbName) .verifyResult(bootStrapDump.lastReplicationId); insertForMerge(tableName, tableNameMerge, false); incrementalDump = verifyIncrementalLoad(Lists.newArrayList("select last_update_user from " + tableName + " order by last_update_user", "select ID from " + tableNameMerge + " order by ID"), Lists.newArrayList(new String[] {"creation", "creation", "creation", "creation", "creation", "creation", "creation", "merge_update", "merge_insert", "merge_insert"}, new String[] {"1", "4", "7", "8", "8", "11"}), bootStrapDump.lastReplicationId); }
Source:
private CommandContext createCommandContext(GlusterVolumeEntity volume, GlusterVolumeOptionEntity option) { Step setOptionStep = addSubStep(StepEnum.EXECUTING, StepEnum.SETTING_GLUSTER_OPTION, getOptionValues(volume, option)); ExecutionContext setOptionCtx = new ExecutionContext(); setOptionCtx.setMonitored(true); setOptionCtx.setStep(setOptionStep); return dupContext().setExecutionContext(setOptionCtx); }

Target:
private CommandContext createCommandContext(GlusterVolumeEntity volume, GlusterVolumeOptionEntity option) { Step setOptionStep = addSubStep(StepEnum.EXECUTING, StepEnum.SETTING_GLUSTER_OPTION, getOptionValues(volume, option)); ExecutionContext setOptionCtx = new ExecutionContext(); setOptionCtx.setMonitored(true); setOptionCtx.setStep(setOptionStep); return dupContext().withExecutionContext(setOptionCtx); }
Source:
public static boolean isValid(Date expirationDate) { DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.getDefault()); Date currentDate = new Date(); String formattedDate = dateFormat.format(currentDate); SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.getDefault()); try { currentDate = format.parse(formattedDate); } catch (ParseException e) { Log.d(TAG, "Date parsing failed." + e); } boolean isExpired = currentDate.after(expirationDate); boolean isEqual = currentDate.equals(expirationDate); if (isExpired == true || isEqual == true) { return true; } return false; }

Target:
public static boolean isValid(Date expirationDate) { Date currentDate = new Date(); String formattedDate = dateFormat.format(currentDate); currentDate = convertDate(formattedDate); boolean isExpired = currentDate.after(expirationDate); boolean isEqual = currentDate.equals(expirationDate); if (isExpired == true || isEqual == true) { return true; } return false; }
Source:
public static void saveAllResources(ResourceSet resourceSet, Map<?, ?> options, StorageTraversal leftTraversal, StorageTraversal rightTraversal, StorageTraversal originTraversal) { EList<Resource> resources = resourceSet.getResources(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); final Set<Resource> wsResources = Sets.newHashSet(); final Set<Resource> nonWsResources = Sets.newHashSet(); for (Resource resource : resources) { String projectName = new Path(resource.getURI().toPlatformString(true)).segment(0); IProject project = root.getProject(projectName); if (project != null && project.isAccessible()) { wsResources.add(resource); } else { nonWsResources.add(resource); } } for (Resource resource : wsResources) { saveResource(resource, options); } resources.removeAll(wsResources); for (Resource resource : nonWsResources) { String absolutePath = getAbsolutePath(resource, leftTraversal, rightTraversal, originTraversal); URI fileURI = URI.createFileURI(absolutePath); resource.setURI(fileURI); } for (Resource resource : nonWsResources) { saveResource(resource, options); } }

Target:
public static void saveAllResources(ResourceSet resourceSet, Map<?, ?> options, StorageTraversal leftTraversal, StorageTraversal rightTraversal, StorageTraversal originTraversal) { List<Resource> resources = Lists.newArrayList(Iterables.filter(resourceSet.getResources(), new Predicate<Resource>() { public boolean apply(Resource input) { return supportsOutput(input); } })); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); final Set<Resource> wsResources = Sets.newHashSet(); final Set<Resource> nonWsResources = Sets.newHashSet(); for (Resource resource : resources) { String projectName = new Path(resource.getURI().toPlatformString(true)).segment(0); IProject project = root.getProject(projectName); if (project != null && project.isAccessible()) { wsResources.add(resource); } else { nonWsResources.add(resource); } } for (Resource resource : wsResources) { saveResource(resource, options); } resources.removeAll(wsResources); for (Resource resource : nonWsResources) { String absolutePath = getAbsolutePath(resource, leftTraversal, rightTraversal, originTraversal); URI fileURI = URI.createFileURI(absolutePath); resource.setURI(fileURI); } for (Resource resource : nonWsResources) { saveResource(resource, options); } }
Source:
public SearchServiceClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; }

Target:
public SearchServiceClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; }
Source:
public Builder(RetryConfig baseConfig) { this.maxAttempts = baseConfig.maxAttempts; this.retryOnExceptionPredicate = baseConfig.retryOnExceptionPredicate; this.retryOnResultPredicate = baseConfig.retryOnResultPredicate; this.intervalBiFunction = baseConfig.intervalBiFunction; this.retryExceptions = baseConfig.retryExceptions; this.ignoreExceptions = baseConfig.ignoreExceptions; }

Target:
public Builder(RetryConfig baseConfig) { this.maxAttempts = baseConfig.maxAttempts; this.retryOnExceptionPredicate = baseConfig.retryOnExceptionPredicate; this.retryOnResultPredicate = baseConfig.retryOnResultPredicate; this.retryExceptions = baseConfig.retryExceptions; this.ignoreExceptions = baseConfig.ignoreExceptions; if (baseConfig.intervalFunction != null) { this.intervalFunction = baseConfig.intervalFunction; } else { this.intervalBiFunction = baseConfig.intervalBiFunction; } }
Source:
private int initializeAppResources(CommCareApp app) { try { currentApp = app; currentApp.initializeStylizer(); if(currentApp.initializeApplication()) { return STATE_READY; } else { return STATE_CORRUPTED; } } catch(Exception e) { Log.i("FAILURE", "Problem with loading"); Log.i("FAILURE", "E: " + e.getMessage()); e.printStackTrace(); ExceptionReportTask ert = new ExceptionReportTask(); ert.execute(e); return STATE_CORRUPTED; } }

Target:
private int initializeAppResources(CommCareApp app) { try { currentApp = app; if (currentApp.initializeApplication()) { return STATE_READY; } else { return STATE_CORRUPTED; } } catch (Exception e) { Log.i("FAILURE", "Problem with loading"); Log.i("FAILURE", "E: " + e.getMessage()); e.printStackTrace(); ExceptionReportTask ert = new ExceptionReportTask(); ert.execute(e); return STATE_CORRUPTED; } }
Source:
public DataNode(Datacenter datacenter, JSONObject jsonObject, ClusterMapConfig clusterMapConfig) throws JSONException { if (logger.isTraceEnabled()) { logger.trace("DataNode " + jsonObject.toString()); } this.datacenter = datacenter; this.hostname = getFullyQualifiedDomainName(jsonObject.getString("hostname")); this.port = jsonObject.getInt("port"); try { ResourceStatePolicyFactory resourceStatePolicyFactory = Utils .getObj(clusterMapConfig.clusterMapResourceStatePolicyFactory, this, HardwareState.valueOf(jsonObject.getString("hardwareState")), clusterMapConfig); this.dataNodeStatePolicy = resourceStatePolicyFactory.getResourceStatePolicy(); } catch (Exception e) { logger.error("Error creating resource state policy when instantiating a datanode " + e); throw new IllegalStateException( "Error creating resource state policy when instantiating a datanode: " + hostname + " " + port, e); } JSONArray diskJSONArray = jsonObject.getJSONArray("disks"); this.disks = new ArrayList<Disk>(diskJSONArray.length()); for (int i = 0; i < diskJSONArray.length(); ++i) { this.disks.add(new Disk(this, diskJSONArray.getJSONObject(i), clusterMapConfig)); } this.rawCapacityInBytes = calculateRawCapacityInBytes(); this.ports = new HashMap<PortType, Integer>(); this.ports.put(PortType.PLAINTEXT, port); populatePorts(jsonObject); this.rackId = jsonObject.has("rackId")? jsonObject.getInt("rackId") : null; validate(); }

Target:
public DataNode(Datacenter datacenter, JSONObject jsonObject, ClusterMapConfig clusterMapConfig) throws JSONException { if (logger.isTraceEnabled()) { logger.trace("DataNode " + jsonObject.toString()); } this.datacenter = datacenter; this.hostname = getFullyQualifiedDomainName(jsonObject.getString("hostname")); this.port = jsonObject.getInt("port"); try { ResourceStatePolicyFactory resourceStatePolicyFactory = Utils .getObj(clusterMapConfig.clusterMapResourceStatePolicyFactory, this, HardwareState.valueOf(jsonObject.getString("hardwareState")), clusterMapConfig); this.dataNodeStatePolicy = resourceStatePolicyFactory.getResourceStatePolicy(); } catch (Exception e) { logger.error("Error creating resource state policy when instantiating a datanode " + e); throw new IllegalStateException( "Error creating resource state policy when instantiating a datanode: " + hostname + " " + port, e); } JSONArray diskJSONArray = jsonObject.getJSONArray("disks"); this.disks = new ArrayList<Disk>(diskJSONArray.length()); for (int i = 0; i < diskJSONArray.length(); ++i) { this.disks.add(new Disk(this, diskJSONArray.getJSONObject(i), clusterMapConfig)); } this.rawCapacityInBytes = calculateRawCapacityInBytes(); this.ports = new HashMap<PortType, Integer>(); this.ports.put(PortType.PLAINTEXT, port); populatePorts(jsonObject); if (jsonObject.has("rackId")) { this.rackId = jsonObject.getLong("rackId"); if (this.rackId < 0) { throw new IllegalStateException("Invalid rackId : " + this.rackId + " is less than 0"); } } else { this.rackId = MissingRackId; } validate(); }
Source:
public int get(PageId pageId, int pageOffset, byte[] buffer, int bufferOffset) throws IOException, PageNotFoundException { Preconditions.checkArgument(pageOffset >= 0, "page offset should be non-negative"); Preconditions.checkArgument(buffer.length >= bufferOffset, "page offset %s should be " + "less or equal than buffer length %s", bufferOffset, buffer.length); Path p = getFilePath(pageId); if (!Files.exists(p)) { throw new PageNotFoundException(p.toString()); } long fileLen = p.toFile().length(); Preconditions.checkArgument(pageOffset <= fileLen, "page offset %s exceeded page size %s", pageOffset, fileLen); try (RandomAccessFile localFile = new RandomAccessFile(p.toString(), "r")) { localFile.skipBytes(pageOffset); return localFile.read(buffer, bufferOffset, (int) Math.min(fileLen - pageOffset, buffer.length - bufferOffset)); } }

Target:
public int get(PageId pageId, int pageOffset, byte[] buffer, int bufferOffset) throws IOException, PageNotFoundException { Preconditions.checkArgument(pageOffset >= 0, "page offset should be non-negative"); Preconditions.checkArgument(buffer.length >= bufferOffset, "page offset %s should be " + "less or equal than buffer length %s", bufferOffset, buffer.length); Path p = getFilePath(pageId); if (!Files.exists(p)) { throw new PageNotFoundException(p.toString()); } long pageLength = p.toFile().length(); Preconditions.checkArgument(pageOffset <= pageLength, "page offset %s exceeded page size %s", pageOffset, pageLength); try (RandomAccessFile localFile = new RandomAccessFile(p.toString(), "r")) { int bytesSkipped = localFile.skipBytes(pageOffset); if (pageOffset != bytesSkipped) { throw new IOException( String.format("Failed to read page %s (%s) from offset %s: %s bytes skipped", pageId, p, pageOffset, bytesSkipped)); } int bytesRead = 0; int bytesLeft = (int) Math.min(pageLength - pageOffset, buffer.length - bufferOffset); while (bytesLeft >= 0) { int bytes = localFile.read(buffer, bufferOffset + bytesRead, bytesLeft); if (bytes < 0) { break; } bytesRead += bytes; bytesLeft -= bytes; } return bytesRead; } }
Source:
public PathData getPathData() { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); int count = Gdip.GraphicsPath_GetPointCount(handle); byte[] gdipTypes = new byte[count]; float[] points = new float[count * 2]; Gdip.GraphicsPath_GetPathTypes(handle, gdipTypes, count); Gdip.GraphicsPath_GetPathPoints(handle, points, count); byte[] types = new byte[count * 2]; int index = 0, typesIndex = 0; while (index < count) { byte type = gdipTypes[index]; boolean close = false; switch (type & Gdip.PathPointTypePathTypeMask) { case Gdip.PathPointTypeStart: types[typesIndex++] = SWT.PATH_MOVE_TO; close = (type & Gdip.PathPointTypeCloseSubpath) != 0; index += 1; break; case Gdip.PathPointTypeLine: types[typesIndex++] = SWT.PATH_LINE_TO; close = (type & Gdip.PathPointTypeCloseSubpath) != 0; index += 1; break; case Gdip.PathPointTypeBezier: types[typesIndex++] = SWT.PATH_CUBIC_TO; close = (gdipTypes[index + 2] & Gdip.PathPointTypeCloseSubpath) != 0; index += 3; break; default: index++; } if (close) { types[typesIndex++] = SWT.PATH_CLOSE; } } if (typesIndex != types.length) { byte[] newTypes = new byte[typesIndex]; System.arraycopy(types, 0, newTypes, 0, typesIndex); types = newTypes; } PathData result = new PathData(); result.types = types; result.points = DPIUtil.autoScaleDown(points); return result; }

Target:
public PathData getPathData() { if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); PathData result = getPathDataInPixels(); result.points = DPIUtil.autoScaleDown(result.points); return result; }
Source:
public WidgetPageObject createMultiple() { String[] tags = getTags(); String articleContentString = ""; ArticleContent articleContent = new ArticleContent(); articleContent.clear(getArticleName()); for (String tag: tags) { articleContentString += tag + "\n"; } articleContent.push(articleContentString, getArticleName()); return this; }

Target:
public WidgetPageObject createMultiple() { String text = ""; ArticleContent articleContent = new ArticleContent(); articleContent.clear(getArticleName()); for (String tag : getTags()) { text += tag + "\n"; } articleContent.push(text, getArticleName()); return this; }
Source:
public ResponseEntity setModelVersion(String version) { boolean validRequest = version != null && !StringUtils.isEmpty(version); if (validRequest) { try { if (sourceCodeManager.getAvailableVersions().contains(version)) { configurationService.setModelRepositoryVersion(version); } else { return new ResponseEntity(HttpStatus.BAD_REQUEST); } return new ResponseEntity(HttpStatus.NO_CONTENT); } catch (Exception e) { return new ResponseEntity(HttpStatus.BAD_REQUEST); } } return new ResponseEntity(HttpStatus.BAD_REQUEST); }

Target:
public ResponseEntity setModelVersion(String version) { boolean validRequest = !StringUtils.isEmpty(version); if (validRequest) { try { if (sourceCodeManager.getAvailableVersions().contains(version)) { configurationService.setModelRepositoryVersion(version); } else { return new ResponseEntity(HttpStatus.BAD_REQUEST); } return new ResponseEntity(HttpStatus.NO_CONTENT); } catch (Exception e) { return new ResponseEntity(HttpStatus.BAD_REQUEST); } } return new ResponseEntity(HttpStatus.BAD_REQUEST); }
Source:
public static JobExecutorServiceHandler getHandler(final String type) { if (Strings.isNullOrEmpty(type)) { return ElasticJobServiceLoader.getCachedTypedServiceInstance(JobExecutorServiceHandler.class, DEFAULT_HANDLER) .orElseThrow(() -> new JobConfigurationException("The parameter named 'type' is null or empty," + " and cannot find default executor service handler using default type '%s'.", DEFAULT_HANDLER)); } return ElasticJobServiceLoader.getCachedTypedServiceInstance(JobExecutorServiceHandler.class, type) .orElseThrow(() -> new JobConfigurationException("Cannot find executor service handler using type '%s'.", type)); }

Target:
public static JobExecutorServiceHandler getHandler(final String type) { if (Strings.isNullOrEmpty(type)) { return ElasticJobServiceLoader.getCachedTypedServiceInstance(JobExecutorServiceHandler.class, DEFAULT_HANDLER).get(); } return ElasticJobServiceLoader.getCachedTypedServiceInstance(JobExecutorServiceHandler.class, type) .orElseThrow(() -> new JobConfigurationException("Cannot find executor service handler using type '%s'.", type)); }
Source:
private List<Map<String, String>> possibleTablePartitions(String table) { TableId tableId = dialect.parseTableIdentifier(table); String fqn = ExpressionBuilder.create().append(tableId, false).toString(); Map<String, String> partitionWithFqn = new HashMap<>(); partitionWithFqn.put(JdbcSourceConnectorConstants.TABLE_NAME_KEY, fqn); partitionWithFqn.put( JdbcSourceConnectorConstants.OFFSET_PROTOCOL_VERSION_KEY, JdbcSourceConnectorConstants.PROTOCOL_VERSION_ONE ); Map<String, String> partition = Collections.singletonMap( JdbcSourceConnectorConstants.TABLE_NAME_KEY, tableId.tableName() ); return Arrays.asList(partitionWithFqn, partition); }

Target:
private List<Map<String, String>> possibleTablePartitions(String table) { TableId tableId = dialect.parseTableIdentifier(table); return Arrays.asList( OffsetProtocols.sourcePartitionForProtocolV1(tableId), OffsetProtocols.sourcePartitionForProtocolV0(tableId) ); }
Source:
public ServiceAccountCredential(CredentialsScope scope, String id, String description) { super(scope, id, description, null); }

Target:
public ServiceAccountCredential(CredentialsScope scope, String id, String description) { super(scope, id, description); }
Source:
public void testDeleteCardUsingFilter() throws Throwable { this.testYearFilter(); int cardIndex = 0; final int year = 1993; Predicate<BaseballCard> yearPred = new Predicate<BaseballCard>() { @Override public boolean doTest(BaseballCard card) { return card.getYear() == year; } }; this.expectedCards = BBCTTestUtil.filterList(this.allCards, yearPred); this.expectedCards.remove(cardIndex); Assert.assertTrue(this.solo.waitForView(R.id.select_all)); this.solo.clickOnCheckBox(cardIndex + 1); Assert.assertTrue(this.solo.waitForView(R.id.delete_menu)); View deleteMenu = this.activity.findViewById(R.id.delete_menu); Assert.assertNotNull(deleteMenu); TouchUtils.clickView(this, deleteMenu); BBCTTestUtil.waitForToast(this.solo, BBCTTestUtil.DELETE_MESSAGE); ListView lv = (ListView) this.solo.getCurrentActivity().findViewById(android.R.id.list); BBCTTestUtil.assertListViewContainsItems(this.expectedCards, lv); }

Target:
public void testDeleteCardUsingFilter() throws Throwable { this.testYearFilter(); int cardIndex = 0; final int year = 1993; Predicate<BaseballCard> yearPred = new Predicate<BaseballCard>() { @Override public boolean doTest(BaseballCard card) { return card.getYear() == year; } }; this.expectedCards = BBCTTestUtil.filterList(this.allCards, yearPred); this.expectedCards.remove(cardIndex); Assert.assertTrue(this.solo.waitForView(R.id.select_all)); this.solo.clickOnCheckBox(cardIndex + 1); Assert.assertTrue(this.solo.waitForView(R.id.delete_menu)); deleteCards(); ListView lv = (ListView) this.solo.getCurrentActivity().findViewById(android.R.id.list); BBCTTestUtil.assertListViewContainsItems(this.expectedCards, lv); }
Source:
private static boolean checkEither(Multimap<Column, Filter> filters, EntityRecordWithColumns record) { for (Map.Entry<Column, Filter> filter : filters.entries()) { Column column = filter.getKey(); if (!record.hasColumn(column.name())) { continue; } @Nullable Object columnValue = columnValue(record, column); boolean matches = checkSingleParameter(filter.getValue(), columnValue, column); if (matches) { return true; } } return filters.isEmpty(); }

Target:
private static boolean checkEither(Multimap<Column, Filter> filters, EntityRecordWithColumns record) { if (filters.isEmpty()) { return true; } boolean result = filters.entries() .stream() .anyMatch(filter -> matches(record, filter)); return result; }
Source:
private boolean hasAnnotation(final MethodNode methodNode) { final List<AnnotationNode> runtimeInvisibleAnnotations = methodNode.invisibleAnnotations; if (runtimeInvisibleAnnotations != null) { for (final AnnotationNode annotation : runtimeInvisibleAnnotations) { if (descType.equals(annotation.desc)) { return true; } } } return false; }

Target:
private boolean hasAnnotation(final MethodNode methodNode) { final List<AnnotationNode> annotations = getAnnotations(methodNode); if (annotations != null) { for (final AnnotationNode annotation : annotations) { if (descType.equals(annotation.desc)) { return true; } } } return false; }
Source:
public void onMachineSelected(final MachineEntity selectedMachine) { this.selectedMachine = selectedMachine; if (cachedMachines.containsKey(selectedMachine.getId())) { appliance.showAppliance(cachedMachines.get(selectedMachine.getId())); return; } if (RUNNING == selectedMachine.getStatus()) { isMachineRunning = true; cachedMachines.put(selectedMachine.getId(), selectedMachine); appliance.showAppliance(selectedMachine); } else { isMachineRunning = false; if (!selectedMachine.getConfig().isDev()) { appliance.showStub(locale.unavailableMachineStarting(selectedMachine.getConfig().getName())); } } }

Target:
public void onMachineSelected(final MachineEntity selectedMachine) { this.selectedMachine = selectedMachine; if (cachedMachines.containsKey(selectedMachine.getId())) { appliance.showAppliance(cachedMachines.get(selectedMachine.getId())); return; } if (RUNNING == selectedMachine.getStatus()) { isMachineRunning = true; cachedMachines.put(selectedMachine.getId(), selectedMachine); appliance.showAppliance(selectedMachine); } else { isMachineRunning = false; final MachineConfig machineConfig = selectedMachine.getConfig(); final boolean isDevMachine = machineConfig.isDev(); final String machineName = machineConfig.getName(); if (!isDevMachine) { appliance.showStub(locale.unavailableMachineStarting(machineName)); } } }
Source:
public boolean isSaveButtonEnabled() { if (Existence.existsImmediately(driver, getSaveButtonDisabled())) { return false; } else if (Existence.existsImmediately(driver, getSaveButton())) { return true; } else { throw new NoSuchElementException("Save button wasn't found."); } }

Target:
public boolean isSaveButtonEnabled() { info("Checking that the save button exists."); if (Existence.existsImmediately(driver, getSaveButtonDisabled())) { info("The save button disabled."); return false; } else if (Existence.existsImmediately(driver, getSaveButton())) { info("The save button exists and enabled."); return true; } else { throw new NoSuchElementException("Save button wasn't found."); } }
Source:
private List<String> getV2CapabilityAdvertisement() { ArrayList<String> caps = new ArrayList<>(); caps.add("version 2"); caps.add(COMMAND_LS_REFS); boolean advertiseRefInWant = transferConfig.isAllowRefInWant() && db.getConfig().getBoolean("uploadpack", null, "advertiserefinwant", true); boolean advertiseSidebandAll = transferConfig.isAdvertiseSidebandAll() && db.getConfig().getBoolean("uploadpack", null, "advertisesidebandall", false); caps.add(COMMAND_FETCH + '=' + (transferConfig.isAllowFilter() ? OPTION_FILTER + ' ' : "") + (advertiseRefInWant ? CAPABILITY_REF_IN_WANT + ' ' : "") + (advertiseSidebandAll ? OPTION_SIDEBAND_ALL + ' ' : "") + (cachedPackUriProvider != null ? "packfile-uris " : "") + OPTION_SHALLOW); caps.add(CAPABILITY_SERVER_OPTION); return caps; }

Target:
private List<String> getV2CapabilityAdvertisement() { ArrayList<String> caps = new ArrayList<>(); caps.add("version 2"); caps.add(COMMAND_LS_REFS); boolean advertiseRefInWant = transferConfig.isAllowRefInWant() && db.getConfig().getBoolean("uploadpack", null, "advertiserefinwant", true); caps.add(COMMAND_FETCH + '=' + (transferConfig.isAllowFilter() ? OPTION_FILTER + ' ' : "") + (advertiseRefInWant ? CAPABILITY_REF_IN_WANT + ' ' : "") + (transferConfig.isAdvertiseSidebandAll() ? OPTION_SIDEBAND_ALL + ' ' : "") + (cachedPackUriProvider != null ? "packfile-uris " : "") + OPTION_SHALLOW); caps.add(CAPABILITY_SERVER_OPTION); return caps; }