auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void addStorageCell( int newStorageCellID ) { this.storageCellDimensionIDs.add( newStorageCellID ); DimensionManager.registerDimension( newStorageCellID, AEConfig.instance.storageProviderID ); NetworkHandler.instance.sendToAll( new PacketNewStorageDimension( newStorageCellID ) ); String[] values = new String[this.storageCellDimensionIDs.size()]; for( int x = 0; x < this.storageCellDimensionIDs.size(); x++ ) { values[x] = String.valueOf( this.storageCellDimensionIDs.get( x ) ); } this.storageCellIDsProperty().set( values ); this.config.save(); }

Target:
public void addStorageCell( int newStorageCellID ) { this.storageCellDimensionIDs.add( newStorageCellID ); DimensionManager.registerDimension( newStorageCellID, AEConfig.instance.storageProviderID ); NetworkHandler.instance.sendToAll( new PacketNewStorageDimension( newStorageCellID ) ); String[] values = new String[this.storageCellDimensionIDs.size()]; for( int x = 0; x < values.length; x++ ) { values[x] = String.valueOf( this.storageCellDimensionIDs.get( x ) ); } this.storageCellIDsProperty().set( values ); this.config.save(); }
Source:
public void setUserFlag(int flag) { assert(0<= flag); assert(flag<=7); mFlags = (mFlags & ~0b111) | flag; }

Target:
public void setUserFlag(int flag) { mFlags = setFlagInInt(mFlags, flag); }
Source:
private byte getHopLimit(String upstreamIface) { try { int upstreamHopLimit = Integer.parseUnsignedInt( mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit")); upstreamHopLimit++; return (byte) Integer.max(upstreamHopLimit, 254); } catch (Exception e) return RaParams.DEFAULT_HOPLIMIT; }

Target:
private byte getHopLimit(String upstreamIface) { try { int upstreamHopLimit = Integer.parseUnsignedInt( mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit")); upstreamHopLimit++; return (byte) Integer.max(upstreamHopLimit, 255); } catch (Exception e) { mLog.e("Failed to find upstream interface hop limit", e); } return RaParams.DEFAULT_HOPLIMIT; }
Source:
public SnomedRf2ExportModel(@Nullable final String refSetId) { super(); clientBranch = BranchPathUtils.createActivePath(SnomedPackage.eINSTANCE); releaseType = ContentSubType.SNAPSHOT; refSetsToExport = true; modulesToExport = Sets.newHashSet(); userId = ApplicationContext.getInstance().getService(ICDOConnectionManager.class).getUserId(); unsetEffectiveTimeLabel = ""; namespace = SnomedExporterUtil.getCountryAndNameSpaceElement(); SnomedRefSetIndexEntry indexEntry = getRefsetIndexEntry(refSetId); if (indexEntry != null) { refSetIds = newHashSet(indexEntry.getId()); singleRefSetExport = true; coreComponentsToExport = false; settings = SnomedExporterUtil.createSettings(singleton(indexEntry)); } else { refSetIds = newHashSet(); singleRefSetExport = false; coreComponentsToExport = true; settings = Sets.newHashSet(); } setExportPath(initExportPath()); }

Target:
public SnomedRf2ExportModel(@Nullable final String refSetId) { super(); clientBranch = BranchPathUtils.createActivePath(SnomedPackage.eINSTANCE); releaseType = ContentSubType.SNAPSHOT; refSetsToExport = true; modulesToExport = Sets.newHashSet(); userId = ApplicationContext.getInstance().getService(ICDOConnectionManager.class).getUserId(); unsetEffectiveTimeLabel = ""; countryAndNamespaceId = SnomedExporterUtil.getCountryAndNameSpaceId(); SnomedRefSetIndexEntry indexEntry = getRefsetIndexEntry(refSetId); if (indexEntry != null) { refSetIds = newHashSet(indexEntry.getId()); singleRefSetExport = true; coreComponentsToExport = false; settings = SnomedExporterUtil.createSettings(singleton(indexEntry)); } else { refSetIds = newHashSet(); singleRefSetExport = false; coreComponentsToExport = true; settings = Sets.newHashSet(); } setExportPath(initExportPath()); }
Source:
private void verifyRateSensor(final String metricNamePrefix, final String description, final SensorCreator sensorCreator) { setupStreamsMetricsMock(metricNamePrefix); StreamsMetricsImpl.addAmountRateMetricToSensor(sensor, STATE_LEVEL_GROUP, tags, metricNamePrefix, description); replayAndVerify(sensorCreator); }

Target:
private void verifyRateSensor(final String metricNamePrefix, final String description, final SensorCreator sensorCreator) { setupStreamsMetricsMock(metricNamePrefix); StreamsMetricsImpl.addRateOfSumMetricToSensor(sensor, STATE_LEVEL_GROUP, tags, metricNamePrefix, description); replayCallAndVerify(sensorCreator); }
Source:
public State as(Class<? extends State> target) { if (target == OnOffType.class) { return equals(ZERO) ? OnOffType.OFF : OnOffType.ON; } else if (target == PercentType.class) { return new PercentType(toBigDecimal().multiply(new BigDecimal(100))); } else if (target == UpDownType.class) { if (equals(ZERO)) { return UpDownType.UP; } else if (toBigDecimal().compareTo(new BigDecimal(1)) == 0) { return UpDownType.DOWN; } else { return UnDefType.UNDEF; } } else if (target == OpenClosedType.class) { if (equals(ZERO)) { return OpenClosedType.CLOSED; } else if (toBigDecimal().compareTo(new BigDecimal(1)) == 0) { return OpenClosedType.OPEN; } else { return UnDefType.UNDEF; } } else if (target == HSBType.class) { return new HSBType(DecimalType.ZERO, PercentType.ZERO, new PercentType(this.toBigDecimal().multiply(new BigDecimal(100)))); } else { return StateConverterUtil.defaultConversion(this, target); } }

Target:
public State as(Class<? extends State> target) { if (target == OnOffType.class) { return equals(ZERO) ? OnOffType.OFF : OnOffType.ON; } else if (target == PercentType.class) { return new PercentType(toBigDecimal().multiply(BigDecimal.valueOf(100))); } else if (target == UpDownType.class) { if (equals(ZERO)) { return UpDownType.UP; } else if (toBigDecimal().compareTo(BigDecimal.valueOf(1)) == 0) { return UpDownType.DOWN; } else { return UnDefType.UNDEF; } } else if (target == OpenClosedType.class) { if (equals(ZERO)) { return OpenClosedType.CLOSED; } else if (toBigDecimal().compareTo(BigDecimal.valueOf(1)) == 0) { return OpenClosedType.OPEN; } else { return UnDefType.UNDEF; } } else if (target == HSBType.class) { return new HSBType(DecimalType.ZERO, PercentType.ZERO, new PercentType(this.toBigDecimal().multiply(BigDecimal.valueOf(100)))); } else { return StateConverterUtil.defaultConversion(this, target); } }
Source:
public void create(Run run) throws Exception { MavenWorkspaceRepository repo = run.getPlugin(MavenWorkspaceRepository.class); if (repo == null) { run.addBasicPlugin(new MavenWorkspaceRepository()); } }

Target:
public void create(Run run) throws Exception { Workspace workspace = run.getWorkspace(); MavenWorkspaceRepository repo = workspace.getPlugin(MavenWorkspaceRepository.class); if (repo == null) { workspace.addBasicPlugin(new MavenWorkspaceRepository()); } }
Source:
private void handleOverReplicatedContainer(final ContainerInfo container, final Set<ContainerReplica> replicas) { final ContainerID id = container.containerID(); final int replicationFactor = container.getReplicationFactor().getNumber(); final int deficit = replicas.size() - replicationFactor - inflightDeletion.getOrDefault(id, Collections.emptyList()).size(); if (deficit > 0) { final Map<UUID, ContainerReplica> uniqueReplicas = new LinkedHashMap<>(); replicas.stream() .filter(r -> compareState(container.getState(), r.getState())) .forEach(r -> uniqueReplicas .putIfAbsent(r.getOriginDatanodeId(), r)); final List<ContainerReplica> eligibleReplicas = new ArrayList<>(replicas); eligibleReplicas.removeAll(uniqueReplicas.values()); final List<ContainerReplica> unhealthyReplicas = eligibleReplicas .stream() .filter(r -> !compareState(container.getState(), r.getState())) .collect(Collectors.toList()); eligibleReplicas.removeAll(unhealthyReplicas); eligibleReplicas.addAll(0, unhealthyReplicas); inflightDeletion.computeIfAbsent(id, k -> new ArrayList<>()); for (int i = 0; i < deficit; i++) { sendDeleteCommand(container, eligibleReplicas.get(i).getDatanodeDetails(), true); } } }

Target:
private void handleOverReplicatedContainer(final ContainerInfo container, final Set<ContainerReplica> replicas) { final ContainerID id = container.containerID(); final int replicationFactor = container.getReplicationFactor().getNumber(); final int excess = replicas.size() - replicationFactor - inflightDeletion.getOrDefault(id, Collections.emptyList()).size(); if (excess > 0) { LOG.info("Container is over replicated. Expected replica count" + " is {}, but found {}.", id, replicationFactor, replicationFactor + excess); final Map<UUID, ContainerReplica> uniqueReplicas = new LinkedHashMap<>(); replicas.stream() .filter(r -> compareState(container.getState(), r.getState())) .forEach(r -> uniqueReplicas .putIfAbsent(r.getOriginDatanodeId(), r)); final List<ContainerReplica> eligibleReplicas = new ArrayList<>(replicas); eligibleReplicas.removeAll(uniqueReplicas.values()); final List<ContainerReplica> unhealthyReplicas = eligibleReplicas .stream() .filter(r -> !compareState(container.getState(), r.getState())) .collect(Collectors.toList()); eligibleReplicas.removeAll(unhealthyReplicas); eligibleReplicas.addAll(0, unhealthyReplicas); for (int i = 0; i < excess; i++) { sendDeleteCommand(container, eligibleReplicas.get(i).getDatanodeDetails(), true); } } }
Source:
} catch (HibernateException ex) { LOG.error("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); }

Target:
} catch (HibernateException ex) { LOG.error("Initial SessionFactory creation failed." + ex.getLocalizedMessage(), ex); throw new ExceptionInInitializerError(ex); }
Source:
public void exampleFuture3(Vertx vertx, Future<Void> startFuture) { FileSystem fs = vertx.fileSystem(); Future<Void> fut1 = Future.future(); Future<Void> fut2 = Future.future(); fs.createFile("/foo", fut1.completer()); fut1.compose(string -> { fs.writeFile("/foo", Buffer.buffer(), fut2.completer()); }, fut2); fut2.compose(integer -> { fs.move("/foo", "/bar", startFuture.completer()); }, startFuture); }

Target:
public void exampleFuture3(Vertx vertx, Future<Void> startFuture) { FileSystem fs = vertx.fileSystem(); Future<Void> fut1 = Future.future(); Future<Void> fut2 = Future.future(); fs.createFile("/foo", fut1.completer()); fut1.compose(v -> { fs.writeFile("/foo", Buffer.buffer(), fut2.completer()); }, fut2); fut2.compose(v -> { fs.move("/foo", "/bar", startFuture.completer()); }, startFuture); }
Source:
public void visitNode(Tree tree) { if(!hasSemantic()) { return; } ClassTree classTree = (ClassTree) tree; Type superType = classTree.symbol().superClass(); IdentifierTree className = classTree.simpleName(); if(className == null || superType == null || !(superType.is("java.io.OutputStream") || superType.is("java.io.FilterOutputStream"))) { return; } Optional<MethodTree> writeByteIntInt = classTree.members() .stream() .filter(m -> m.is(Tree.Kind.METHOD)) .map(m -> (MethodTree) m) .filter(WRITE_BYTES_INT_INT::matches) .findFirst(); if(!writeByteIntInt.isPresent()) { reportIssue(className, "Provide an override of \"write(byte[],int,int)\" for this class."); } }

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } ClassTree classTree = (ClassTree) tree; Type superType = classTree.symbol().superClass(); IdentifierTree className = classTree.simpleName(); if (className == null || classTree.symbol().isAbstract() || superType == null || !(superType.is("java.io.OutputStream") || superType.is("java.io.FilterOutputStream"))) { return; } Optional<MethodTree> writeByteIntInt = findMethod(classTree, WRITE_BYTES_INT_INT); Optional<MethodTree> writeInt = findMethod(classTree, WRITE_INT); if (!writeByteIntInt.isPresent()) { String message = "Provide an override of \"write(byte[],int,int)\" for this class."; if (writeInt.isPresent()) { MethodTree writeIntTree = writeInt.get(); if (writeIntTree.block().body().isEmpty()) { message = "Provide an empty override of \"write(byte[],int,int)\" for this class as well."; } } reportIssue(className, message); } }
Source:
private List<ProcessResult> process(TaskSource taskSource, Schema schema, int processorCount) { List<Future<ProcessResult>> futures = new ArrayList<>(); List<ProcessResult> joined = new ArrayList<>(); try { log.info("Start bulk processing"); showProgress(0, processorCount); for (int i=0; i < processorCount; i++) { futures.add(startProcessor(taskSource, schema, i)); } for (int i=0; i < processorCount; i++) { try { joined.add(futures.get(i).get()); showProgress(i + 1, processorCount); } catch (ExecutionException ex) { throw Throwables.propagate(ex.getCause()); } catch (InterruptedException ex) { throw new ExecuteInterruptedException(ex); } } return joined; } finally { for (int i=joined.size(); i < futures.size(); i++) { futures.get(i).cancel(true); } } }

Target:
private List<ProcessResult> process(TaskSource taskSource, Schema schema, int processorCount) { List<Future<ProcessResult>> futures = new ArrayList<>(); List<ProcessResult> joined = new ArrayList<>(); try { log.info("Start bulk processing"); showProgress(processorCount); for (int i=0; i < processorCount; i++) { futures.add(startProcessor(taskSource, schema, i)); } for (int i=0; i < processorCount; i++) { try { joined.add(futures.get(i).get()); showProgress(processorCount); } catch (ExecutionException ex) { throw Throwables.propagate(ex.getCause()); } catch (InterruptedException ex) { throw new ExecuteInterruptedException(ex); } } return joined; } finally { for (int i=joined.size(); i < futures.size(); i++) { futures.get(i).cancel(true); } } }
Source:
public void testFiveNodeK1TwoRacks() throws JSONException { TestDescription td = getBoringDescription(5, 6, 1, 2, 1); subTestDescription(td, false); }

Target:
public void testFiveNodeK1TwoRacks() throws JSONException { TestDescription td = getBoringDescription(5, 6, 1, 1, 2); subTestDescription(td, false); }
Source:
public void testCurrentLogFileNameIsEmptyAndAppenderUsesArchivedNameInstead() throws Exception { final Logger root = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); final FileAppenderFactory<ILoggingEvent> appenderFactory = new FileAppenderFactory<>(); appenderFactory.setArchivedLogFilenamePattern(folder.newFile("test-archived-name-%d.log").toString()); final Appender<ILoggingEvent> appender = appenderFactory.build(root.getLoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory()); RollingFileAppender<ILoggingEvent> rollingAppender = (RollingFileAppender<ILoggingEvent>) ((AsyncAppender) appender).getAppender("file-appender"); String file = rollingAppender.getFile(); String dateSuffic = LocalDateTime.now().format(DateTimeFormatter.ofPattern("YYYY-MM-dd")); String[] split = file.split("/"); Assert.assertEquals("test-archived-name-" + dateSuffic + ".log", split[split.length-1]); }

Target:
public void testCurrentLogFileNameIsEmptyAndAppenderUsesArchivedNameInstead() throws Exception { final FileAppenderFactory<ILoggingEvent> appenderFactory = new FileAppenderFactory<>(); appenderFactory.setArchivedLogFilenamePattern(folder.newFile("test-archived-name-%d.log").toString()); final FileAppender<ILoggingEvent> rollingAppender = appenderFactory.buildAppender(new LoggerContext()); final String file = rollingAppender.getFile(); final String dateSuffix = LocalDateTime.now().format(DateTimeFormatter.ofPattern("YYYY-MM-dd")); final String name = Files.getNameWithoutExtension(file); Assert.assertEquals("test-archived-name-" + dateSuffix, name); }
Source:
public Map<String, String> getFilteredSubnetWithCidr(String environmentCrn, Stack stack, String networkId, Collection<String> subnetIds) { Credential credential = credentialService.getCredentialByEnvCrn(environmentCrn); ExtendedCloudCredential cloudCredential = extendedCloudCredentialConverter.convert(credential); Map<String, String> filter = new HashMap<>(); NetworkFilterProvider networkFilterProvider = networkFilterProviderMap.get(CloudPlatform.valueOf(stack.getCloudPlatform())); if (networkFilterProvider != null) { filter = networkFilterProvider.provide(stack.getNetwork(), networkId, subnetIds); } CloudNetworks cloudNetworks = cloudParameterService.getCloudNetworks(cloudCredential, stack.getRegion(), stack.getPlatformvariant(), filter); LOGGER.debug("Received Cloud networks for region [{}]: {}", stack.getRegion(), cloudNetworks.getCloudNetworkResponses().get(stack.getRegion())); return cloudNetworks.getCloudNetworkResponses().getOrDefault(stack.getRegion(), Collections.emptySet()).stream() .filter(cloudNetwork -> { String[] splittedNetworkId = cloudNetwork.getId().split("/"); String cloudNetworkId = splittedNetworkId[splittedNetworkId.length - 1]; return networkId.equals(cloudNetworkId) || networkId.equals(cloudNetwork.getName()); }) .flatMap(cloudNetwork -> cloudNetwork.getSubnetsMeta().stream()) .filter(cloudSubnet -> StringUtils.isNoneBlank(cloudSubnet.getId(), cloudSubnet.getCidr())) .filter(cloudSubnet -> subnetIds.contains(cloudSubnet.getId()) || subnetIds.contains(cloudSubnet.getName())) .collect(Collectors.toMap(CloudSubnet::getId, CloudSubnet::getCidr)); }

Target:
public Map<String, String> getFilteredSubnetWithCidr(String environmentCrn, Stack stack, String networkId, Collection<String> subnetIds) { Credential credential = credentialService.getCredentialByEnvCrn(environmentCrn); ExtendedCloudCredential cloudCredential = extendedCloudCredentialConverter.convert(credential); Map<String, String> filter = getFilter(stack, networkId, subnetIds); CloudNetworks cloudNetworks = cloudParameterService.getCloudNetworks(cloudCredential, stack.getRegion(), stack.getPlatformvariant(), filter); LOGGER.debug("Received Cloud networks for region [{}]: {}", stack.getRegion(), cloudNetworks.getCloudNetworkResponses().get(stack.getRegion())); return cloudNetworks.getCloudNetworkResponses().getOrDefault(stack.getRegion(), Collections.emptySet()).stream() .filter(cloudNetwork -> { String[] splittedNetworkId = cloudNetwork.getId().split("/"); String cloudNetworkId = splittedNetworkId[splittedNetworkId.length - 1]; return networkId.equals(cloudNetworkId) || networkId.equals(cloudNetwork.getName()); }) .flatMap(cloudNetwork -> cloudNetwork.getSubnetsMeta().stream()) .filter(cloudSubnet -> StringUtils.isNoneBlank(cloudSubnet.getId(), cloudSubnet.getCidr())) .filter(cloudSubnet -> subnetIds.contains(cloudSubnet.getId()) || subnetIds.contains(cloudSubnet.getName())) .collect(Collectors.toMap(CloudSubnet::getId, CloudSubnet::getCidr)); }
Source:
private void finishAndRecordTimings() { timeBag.finishGlobalStage("Finished"); StringBuilder timingsToLog = new StringBuilder(); timingsToLog.append("TxRecovery Status and Timings [txs=").append(txCnt.get()); for (String stageTiming : timeBag.stagesTimings()) timingsToLog.append(", ").append(stageTiming); timingsToLog.append("]"); log.info(timingsToLog.toString()); }

Target:
private void finishAndRecordTimings() { timeBag.finishGlobalStage("Finished"); StringBuilder timingsToLog = new StringBuilder(); timingsToLog.append("TxRecovery Status and Timings [txs=").append(preparedTxCnt.get()); for (String stageTiming : timeBag.stagesTimings()) timingsToLog.append(", ").append(stageTiming); timingsToLog.append("]"); log.info(timingsToLog.toString()); }
Source:
private void loanCompleteMessageNotify(WeChatMessageNotify weChatMessageNotify) { if (weChatMessageNotify.getBusinessId() == null) { logger.info("[MQ WeChatMessageNotify] type:{} BusinessId is null", weChatMessageNotify.getWeChatMessageType()); return; } LoanModel loanModel = loanMapper.findById(weChatMessageNotify.getBusinessId()); List<String> notifyLoginNames = loanCompleteNotifyUser.stream() .filter(mobile -> userMapper.findByLoginNameOrMobile(mobile) != null) .map(mobile -> userMapper.findByLoginNameOrMobile(mobile).getLoginName()) .collect(Collectors.toList()); notifyLoginNames.stream() .forEach(s -> { if (fetchOpenId(s) == null){ return; } weChatClient.sendTemplateMessage(WeChatMessageType.LOAN_COMPLETE, Maps.newHashMap(ImmutableMap.<String, String>builder() .put("openid", fetchOpenId(s)) .put("first", String.format("%s满标通知（运营内部）。", loanModel.getName())) .put("keyword1", convertCentToTenThousandString(loanModel.getLoanAmount())) .put("keyword2", "已满标") .put("keyword3", new DateTime(loanModel.getRaisingCompleteTime()).toString("yyyy-MM-dd HH:mm")) .put("remark", String.format("%s上线的%s天投资项目已满，30分钟内将完成复核。", new DateTime(loanModel.getFundraisingStartTime()).toString("yyyy-MM-dd HH:mm"), loanModel.getDuration())) .build())); }); }

Target:
private void loanCompleteMessageNotify(WeChatMessageNotify weChatMessageNotify) { if (weChatMessageNotify.getBusinessId() == null) { logger.info("[MQ WeChatMessageNotify] type:{} BusinessId is null", weChatMessageNotify.getWeChatMessageType()); return; } LoanModel loanModel = loanMapper.findById(weChatMessageNotify.getBusinessId()); List<String> notifyLoginNames = loanCompleteNotifyUser.stream() .filter(mobile -> userMapper.findByLoginNameOrMobile(mobile) != null) .map(mobile -> userMapper.findByLoginNameOrMobile(mobile).getLoginName()) .collect(Collectors.toList()); notifyLoginNames.stream() .filter(s -> fetchOpenId(s) != null) .forEach(s -> weChatClient.sendTemplateMessage(WeChatMessageType.LOAN_COMPLETE, Maps.newHashMap(ImmutableMap.<String, String>builder() .put("openid", fetchOpenId(s)) .put("first", String.format("%s满标通知（运营内部）。", loanModel.getName())) .put("keyword1", convertCentToTenThousandString(loanModel.getLoanAmount())) .put("keyword2", "已满标") .put("keyword3", new DateTime(loanModel.getRaisingCompleteTime()).toString("yyyy-MM-dd HH:mm")) .put("remark", String.format("%s上线的%s天投资项目已满，30分钟内将完成复核。", new DateTime(loanModel.getFundraisingStartTime()).toString("yyyy-MM-dd HH:mm"), loanModel.getDuration())) .build()))); }
Source:
private void discardChanges(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, CoreText.DiscardChangesOperation_discardingChanges, pathsByRepository.size() * 2); boolean errorOccurred = false; for (Entry<Repository, Collection<String>> entry : pathsByRepository .entrySet()) { Repository repository = entry.getKey(); Collection<String> paths = entry.getValue(); try { discardChanges(repository, paths, progress); } catch (GitAPIException e) { errorOccurred = true; Activator.logError( CoreText.DiscardChangesOperation_discardFailed, e); } progress.worked(1); try { ProjectUtil.refreshRepositoryResources(repository, paths, progress.newChild(1)); } catch (CoreException e) { errorOccurred = true; Activator.logError( CoreText.DiscardChangesOperation_refreshFailed, e); } } if (errorOccurred) { IStatus status = Activator.error( CoreText.DiscardChangesOperation_discardFailedSeeLog, null); throw new CoreException(status); } }

Target:
private void discardChanges(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, CoreText.DiscardChangesOperation_discardingChanges, pathsByRepository.size() * 2); boolean errorOccurred = false; for (Entry<Repository, Collection<String>> entry : pathsByRepository .entrySet()) { Repository repository = entry.getKey(); Collection<String> paths = entry.getValue(); try { discardChanges(repository, paths, progress.newChild(1)); } catch (GitAPIException e) { errorOccurred = true; Activator.logError( CoreText.DiscardChangesOperation_discardFailed, e); } try { ProjectUtil.refreshRepositoryResources(repository, paths, progress.newChild(1)); } catch (CoreException e) { errorOccurred = true; Activator.logError( CoreText.DiscardChangesOperation_refreshFailed, e); } } if (errorOccurred) { IStatus status = Activator.error( CoreText.DiscardChangesOperation_discardFailedSeeLog, null); throw new CoreException(status); } }
Source:
public static Fs fromJar(URL url) { try { if (url.toURI().getPath().contains(" ")) { try { url = new URL(url.toURI().getPath().replace(" ", "%20")); } catch (MalformedURLException e) { e.printStackTrace(); } } return new JarFs(new File(url.toURI().getPath())); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }

Target:
public static Fs fromJar(URL url) { try { return new JarFs(new File(url.toURI().getPath())); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
Source:
public static Archive<?> deploy() { WebArchive war = TestUtil.prepareArchive(ResourceClassProcessorNotAppliedTest.class.getSimpleName()); war.addClass(ResourceClassProcessorNotAppliedTest.class); war.addClass(PortProviderUtil.class); war.addClass(ResourceClassProcessorNotAppliedImplementation.class); war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( new SocketPermission(PortProviderUtil.getHost(), "connect,resolve"), new PropertyPermission("org.jboss.resteasy.port", "read"), new RuntimePermission("getenv.RESTEASY_PORT"), new PropertyPermission("ipv6", "read"), new PropertyPermission("node", "read"), new RuntimePermission("getClassLoader"), new PropertyPermission("arquillian.*", "read"), new RuntimePermission("accessDeclaredMembers"), new ReflectPermission("suppressAccessChecks") ), "permissions.xml"); return TestUtil.finishContainerPrepare(war, null, ResourceClassProcessorPureEndPoint.class); }

Target:
public static Archive<?> deploy() { WebArchive war = TestUtil.prepareArchive(ResourceClassProcessorNotAppliedTest.class.getSimpleName()); war.addClass(ResourceClassProcessorNotAppliedTest.class); war.addClass(PortProviderUtil.class); war.addClass(ResourceClassProcessorNotAppliedImplementation.class); war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( new SocketPermission(PortProviderUtil.getHost(), "connect,resolve"), new PropertyPermission("org.jboss.resteasy.port", "read"), new RuntimePermission("getenv.RESTEASY_PORT"), new PropertyPermission("ipv6", "read"), new PropertyPermission("node", "read"), new PropertyPermission("arquillian.*", "read"), new RuntimePermission("accessDeclaredMembers"), new ReflectPermission("suppressAccessChecks") ), "permissions.xml"); return TestUtil.finishContainerPrepare(war, null, ResourceClassProcessorPureEndPoint.class); }
Source:
public GetShard(String name) { super(name); setIdentifier("shard"); setDescription("Gets the name of the shard you're in"); setUsage("/shard <name>"); setArguments(0, 1); }

Target:
public GetShard(String name) { super(name); setIdentifier("shard"); setDescription("Gets the name of the shard you're in."); setUsage("/shard <player>"); setArguments(0, 1); }
Source:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (!isLegacyCall) { ModelNode op = operation.clone(); PathAddress target = context.getCurrentAddress().getParent(); OperationStepHandler removeHandler; try { context.readResourceFromRoot(target.append(CommonAttributes.JGROUP_DISCOVERY_GROUP, context.getCurrentAddressValue())); target = target.append(CommonAttributes.JGROUP_DISCOVERY_GROUP, context.getCurrentAddressValue()); removeHandler = JGroupDiscoveryGroupRemove.LEGACY_INSTANCE; } catch(Resource.NoSuchResourceException ex) { target = target.append(CommonAttributes.SOCKET_DISCOVERY_GROUP, context.getCurrentAddressValue()); removeHandler = SocketDiscoveryGroupRemove.LEGACY_INSTANCE; } op.get(OP_ADDR).set(target.toModelNode()); context.addStep(op, removeHandler, OperationContext.Stage.MODEL, true); } super.execute(context, operation); }

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (!isLegacyCall) { ModelNode op = operation.clone(); PathAddress target = context.getCurrentAddress().getParent(); OperationStepHandler removeHandler; try { context.readResourceFromRoot(target.append(CommonAttributes.JGROUPS_DISCOVERY_GROUP, context.getCurrentAddressValue()), false); target = target.append(CommonAttributes.JGROUPS_DISCOVERY_GROUP, context.getCurrentAddressValue()); removeHandler = JGroupsDiscoveryGroupRemove.LEGACY_INSTANCE; } catch(Resource.NoSuchResourceException ex) { target = target.append(CommonAttributes.SOCKET_DISCOVERY_GROUP, context.getCurrentAddressValue()); removeHandler = SocketDiscoveryGroupRemove.LEGACY_INSTANCE; } op.get(OP_ADDR).set(target.toModelNode()); context.addStep(op, removeHandler, OperationContext.Stage.MODEL, true); } super.execute(context, operation); }
Source:
public FlairActions(RestClient restClient) { this.restClient = restClient; this.user = null; }

Target:
public FlairActions(RestClient restClient) { this.restClient = restClient; }
Source:
private ModelDependencyProviderRegistry createRegistryWithCustomResolver() { final ModelDependencyProviderRegistry registry = new ModelDependencyProviderRegistry() { @Override public Set<URI> getDependencies(URI uri) { final String uriString = uri.toPlatformString(false); final String baseUriString = uriString.substring(0, uriString.lastIndexOf("/")); final String file1UriString = baseUriString + "/" + MODEL_FILE1; final String file2UriString = baseUriString + "/" + MODEL_FILE2; final URI file1Uri = URI.createPlatformResourceURI(file1UriString, false); final URI file2Uri = URI.createPlatformResourceURI(file2UriString, false); return Sets.newHashSet(file1Uri, file2Uri); } }; return registry; }

Target:
private ModelDependencyProviderRegistry createRegistryWithCustomResolver() { final ModelDependencyProviderRegistry registry = new ModelDependencyProviderRegistry() { @Override public Set<URI> getDependencies(URI uri) { final String uriString = uri.toPlatformString(false); final String baseUriString = uriString.substring(0, uriString.lastIndexOf("/")); final String file1UriString = baseUriString + "/" + MODEL_FILE1; final String file2UriString = baseUriString + "/" + MODEL_FILE2; final URI file1Uri = URI.createPlatformResourceURI(file1UriString, false); final URI file2Uri = URI.createPlatformResourceURI(file2UriString, false); final LinkedHashSet<URI> dependencies = Sets.newLinkedHashSet(); dependencies.add(file1Uri); dependencies.add(file2Uri); return dependencies; } }; return registry; }
Source:
public RowMapper<C> specialize(ResultSet rs, StatementContext ctx) throws SQLException { Constructor<C> constructor; try { constructor = clazz.getDeclaredConstructor(); } catch (ReflectiveOperationException e) { throw new EntityMemberAccessException("Unable to get constructor for " + clazz, e); } constructor.setAccessible(true); List<MemberSetter<C>> setters = new ArrayList<>(); for (int colIndex = rs.getMetaData().getColumnCount(); colIndex >= 1; colIndex--) { String columnLabel = rs.getMetaData().getColumnLabel(colIndex); JpaMember member = jpaClass.lookupMember(columnLabel); if (member != null) { Type memberType = member.getType(); ColumnMapper<?> columnMapper = ctx.findColumnMapperFor(memberType) .orElseThrow(() -> new NoSuchMapperException("No column mapper for " + memberType)); setters.add(obj -> member.write(obj, columnMapper.map(rs, columnLabel, ctx))); } } return (r, c) -> { C obj; try { obj = constructor.newInstance(); } catch (ReflectiveOperationException e) { throw new EntityMemberAccessException("Unable to invoke " + constructor, e); } for (MemberSetter<C> setter : setters) { setter.mapAndSetMember(obj); } return obj; }; }

Target:
public RowMapper<C> specialize(ResultSet rs, StatementContext ctx) throws SQLException { Constructor<C> constructor; try { constructor = clazz.getDeclaredConstructor(); } catch (ReflectiveOperationException e) { throw new EntityMemberAccessException("Unable to get constructor for " + clazz, e); } constructor.setAccessible(true); List<MemberSetter<C>> setters = new ArrayList<>(); for (int colIndex = rs.getMetaData().getColumnCount(); colIndex >= 1; colIndex--) { String columnLabel = rs.getMetaData().getColumnLabel(colIndex); JpaMember member = jpaClass.lookupMember(columnLabel); if (member != null) { Type memberType = member.getType(); ColumnMapper<?> columnMapper = ctx.findColumnMapperFor(memberType) .orElseThrow(() -> new NoSuchMapperException("No column mapper for " + memberType)); final int columnIndex = colIndex; setters.add(obj -> member.write(obj, columnMapper.map(rs, columnIndex, ctx))); } } return (r, c) -> { C obj; try { obj = constructor.newInstance(); } catch (ReflectiveOperationException e) { throw new EntityMemberAccessException("Unable to invoke " + constructor, e); } for (MemberSetter<C> setter : setters) { setter.mapAndSetMember(obj); } return obj; }; }
Source:
public void scrollToIndex(int index) { ListModel<Object> model = getModel(); double scrollRatio; if (model != null) { if (index < 0 || index > model.getSize() - 1) { throw new IndexOutOfBoundsException("Illegal index: " + index); } scrollRatio = (double) index / model.getSize(); } else { int rowCount = getRows().getChildren().size(); if (index < 0 || index > rowCount - 1) { throw new IndexOutOfBoundsException("Illegal index: " + index); } scrollRatio = (double) index / rowCount; } response(new AuInvoke(this, "_scrollToIndex", index, scrollRatio)); }

Target:
public void scrollToIndex(int index) { ListModel<Object> model = getModel(); int rowCount = model != null ? model.getSize() : getRows().getChildren().size(); if (index < 0 || index > rowCount - 1) { throw new IndexOutOfBoundsException("Illegal index: " + index); } response(new AuInvoke(this, "scrollToIndex", index, (double) index / rowCount)); }
Source:
public static void validateNodeId(Cluster cluster, HostMatcher matcher, int nodeId) { if(isSingleLocalCluster(cluster, matcher)) { cluster.getNodeById(nodeId); return; } List<String> errors = Lists.newArrayList(); for(Node node: cluster.getNodes()) { if(nodeId == node.getId()) { if(!matcher.match(node)) { errors.add(node.briefToString() + " selected as current node " + nodeId + " failed to match"); } }else { if(matcher.match(node)) { errors.add(node.briefToString() + " matched, though the expected node is " + nodeId); } } } if(!errors.isEmpty()) { if(errors.size() == 1) { throw new VoldemortApplicationException(errors.get(0)); } else { throw new VoldemortApplicationException(" Number of Validation failures " + errors.size() + ". Details : " + Arrays.toString(errors.toArray())); } } else { logger.info("Node Id Validation succeeded. Node Id " + nodeId); } }

Target:
public static void validateNodeId(Cluster cluster, HostMatcher matcher, int nodeId) { logger.info(" Using Matcher " + matcher.getDebugInfo()); cluster.getNodeById(nodeId); if(isSingleLocalCluster(cluster, matcher)) { return; } List<String> errors = Lists.newArrayList(); for(Node node: cluster.getNodes()) { if(nodeId == node.getId()) { if(!matcher.match(node)) { errors.add(node.briefToString() + " selected as current node " + nodeId + " failed to match"); } }else { if(matcher.match(node)) { errors.add(node.briefToString() + " matched, though the expected node is " + nodeId); } } } if(!errors.isEmpty()) { String errorMessage = " Number of Validation failures " + errors.size() + ". Details : " + Arrays.toString(errors.toArray()); logger.error(errorMessage); if(errors.size() == 1) { throw new VoldemortApplicationException(errors.get(0)); } else { throw new VoldemortApplicationException(errorMessage); } } else { logger.info("Node Id Validation succeeded. Node Id " + nodeId); } }
Source:
public ArrayOfDoublesSketch apply(final int nominalEntries, final int numberOfValues, final ArrayOfDoublesSketch[] sketches) { switch (this) { case UNION: final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().setNominalEntries(nominalEntries) .setNumberOfValues(numberOfValues).buildUnion(); for (final ArrayOfDoublesSketch sketch : sketches) { union.update(sketch); } return union.getResult(); case INTERSECT: final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder() .setNominalEntries(nominalEntries).setNumberOfValues(numberOfValues).buildIntersection(); for (final ArrayOfDoublesSketch sketch : sketches) { intersection.update(sketch, COMBINER); } return intersection.getResult(); case NOT: if (sketches.length < 1) { throw new IAE("A-Not-B requires at least 1 sketch"); } if (sketches.length == 1) { return sketches[0]; } ArrayOfDoublesSketch result = sketches[0]; for (int i = 1; i < sketches.length; i++) { final ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().setNumberOfValues(numberOfValues) .buildAnotB(); aNotB.update(result, sketches[i]); result = aNotB.getResult(); } return result; default: throw new IAE("Unknown sketch operation %s", this.toString()); } }

Target:
public ArrayOfDoublesSketch apply(final int nominalEntries, final int numberOfValues, final ArrayOfDoublesSketch[] sketches) { final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().setNominalEntries(nominalEntries) .setNumberOfValues(numberOfValues).buildUnion(); for (final ArrayOfDoublesSketch sketch : sketches) { union.update(sketch); } return union.getResult(); }
Source:
public ZestStatement deepCopy() { ZestConditional copy=new ZestConditional(getIndex()); copy.rootExpression=(ZestExpressionElement)rootExpression.deepCopy(); ArrayList<ZestStatement> ifList=new ArrayList<>(); for(ZestStatement stmt:ifStatements) copy.ifStatements.add(stmt.deepCopy()); ArrayList<ZestStatement> elseList=new ArrayList<>(); for(ZestStatement stmt:elseStatements) copy.elseStatements.add(stmt.deepCopy()); copy.elseStatements=elseList; copy.ifStatements=ifList; return copy; }

Target:
public ZestStatement deepCopy() { ZestConditional copy=new ZestConditional(getIndex()); copy.rootExpression=(ZestExpressionElement)rootExpression.deepCopy(); ArrayList<ZestStatement> ifList=new ArrayList<>(); for(ZestStatement stmt:ifStatements){ copy.ifStatements.add(stmt.deepCopy()); } ArrayList<ZestStatement> elseList=new ArrayList<>(); for(ZestStatement stmt:elseStatements){ copy.elseStatements.add(stmt.deepCopy()); } copy.elseStatements=elseList; copy.ifStatements=ifList; return copy; }
Source:
public void validateBaseEncodedURLTest() throws UnsupportedEncodingException, Base64DecoderException { String goodUrlBase = "<LINK_2>"; String goodUrl = Base64.encode(goodUrlBase.getBytes("UTF-8")); assertEquals(goodUrlBase, SigningUtil.decodeUrl(goodUrl)); String badUrlBase = "<LINK_1>"; String badUrl = Base64.encode(badUrlBase.getBytes("UTF-8")); boolean didFail = false; try { SigningUtil.decodeUrl(badUrl); } catch (RuntimeException e) { didFail = true; } assertTrue(didFail); }

Target:
public void validateBaseEncodedURLTest() throws UnsupportedEncodingException, Base64DecoderException { String goodUrlBase = "<LINK_2>"; String goodUrl = Base64.encode(goodUrlBase.getBytes("UTF-8")); assertEquals(goodUrlBase, SigningUtil.decodeUrl(goodUrl)); assertWhitelistURLFailure("<LINK_1>"); assertWhitelistURLFailure("<LINK_0>"); }
Source:
public void visitAnnotation(DetailAST ast) { if (ast.getParent().getParent().getType() != TokenTypes.ANNOTATION_DEF) { classContext.visitAnnotationType(ast); } }

Target:
public void visitAnnotation(DetailAST ast) { classContext.visitAnnotationType(ast); }
Source:
IssueManager(Project project, LiveIssueCache liveIssueCache) { myProject = project; this.liveIssueCache = liveIssueCache; project.getMessageBus().connect().subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectClosing(@NotNull Project project) { try { if (project == myProject) { liveIssueCache.flushAll(); } } catch (Exception e) { Logger.getInstance(getClass()).error("Cannot flush issues", e); } } }); }

Target:
IssueManager(Project project, LiveIssueCache liveIssueCache) { myProject = project; this.liveIssueCache = liveIssueCache; project.getMessageBus().connect().subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectClosing(@NotNull Project project) { try { if (project == myProject) { liveIssueCache.flushAll(); } } catch (Exception e) { LOGGER.error("Cannot flush issues", e); } } }); }
Source:
public void setEnabled(boolean enabled) { asTextBox().setEnabled(enabled); if (enabled) { asTextBox().getElement().getStyle().setBackgroundColor("#ffffff"); } else { asTextBox().getElement().getStyle().setBackgroundColor("#e5e5e5"); } }

Target:
public void setEnabled(boolean enabled) { asTextBox().setEnabled(enabled); }
Source:
public List<ConnectorTableLayoutResult> getTableLayouts(ConnectorSession session, ConnectorTableHandle table, Constraint<ColumnHandle> constraint, Optional<Set<ColumnHandle>> desiredColumns) { InformationSchemaTableHandle handle = checkTableHandle(table); TupleDomain<ColumnHandle> predicate = constraint.getSummary(); Optional<Stream<Map<ColumnHandle, NullableValue>>> partitions = getPartitions(session, handle.getSchemaTableName(), handle.getCatalogName(), predicate); if (partitions.isPresent()) { List<TupleDomain<ColumnHandle>> partitionsTupleDomains = partitions.get() .filter(constraint.predicate()) .map(TupleDomain::fromFixedValues) .collect(toImmutableList()); if (partitionsTupleDomains.isEmpty()) { return ImmutableList.of(); } predicate = predicate.intersect(TupleDomain.columnWiseUnion(partitionsTupleDomains)); } ConnectorTableLayout layout = new ConnectorTableLayout( new InformationSchemaTableLayoutHandle(handle, predicate), Optional.empty(), predicate, Optional.empty(), Optional.empty(), Optional.empty(), ImmutableList.of()); return ImmutableList.of(new ConnectorTableLayoutResult(layout, constraint.getSummary())); }

Target:
public List<ConnectorTableLayoutResult> getTableLayouts(ConnectorSession session, ConnectorTableHandle table, Constraint<ColumnHandle> constraint, Optional<Set<ColumnHandle>> desiredColumns) { if (constraint.getSummary().isNone()) { return ImmutableList.of(); } InformationSchemaTableHandle handle = checkTableHandle(table); Set<QualifiedTablePrefix> prefixes = calculatePrefixesWithSchemaName(session, constraint.getSummary(), constraint.predicate()); if (isTablesEnumeratingTable(handle.getSchemaTableName())) { Set<QualifiedTablePrefix> tablePrefixes = calculatePrefixesWithTableName(session, prefixes, constraint.getSummary(), constraint.predicate()); if (tablePrefixes.size() <= MAX_PREFIXES_COUNT) { prefixes = tablePrefixes; } } if (prefixes.size() > MAX_PREFIXES_COUNT) { prefixes = ImmutableSet.of(new QualifiedTablePrefix(catalogName)); } ConnectorTableLayout layout = new ConnectorTableLayout(new InformationSchemaTableLayoutHandle(handle, prefixes)); return ImmutableList.of(new ConnectorTableLayoutResult(layout, constraint.getSummary())); }
Source:
public List<MessageItem> onDisconnect() { int messageSize = 0; List<MessageItem> items = null; synchronized(sendBufferLock) { for(Map<Integer, MessageWrapper> queue : startedByPrio) { if(items == null) items = new ArrayList<>(); for(MessageWrapper wrapper : queue.values()) { items.add(wrapper.getItem()); messageSize += wrapper.getLength(); } queue.clear(); } sendBufferUsed -= messageSize; if(sendBufferUsed != 0) { Logger.warning(this, "Possible leak in transport code: Buffer size not empty after disconnecting on "+this+" for "+pn+" after removing "+messageSize+" total was "+sendBufferUsed); sendBufferUsed = 0; } } return items; }

Target:
public List<MessageItem> onDisconnect() { int messageSize = 0; final List<MessageItem> items = new ArrayList<>(); synchronized(sendBufferLock) { for(Map<Integer, MessageWrapper> queue : startedByPrio) { for(MessageWrapper wrapper : queue.values()) { items.add(wrapper.getItem()); messageSize += wrapper.getLength(); } queue.clear(); } sendBufferUsed -= messageSize; if(sendBufferUsed != 0) { Logger.warning(this, "Possible leak in transport code: Buffer size not empty after disconnecting on "+this+" for "+pn+" after removing "+messageSize+" total was "+sendBufferUsed); sendBufferUsed = 0; } } return items; }
Source:
public void afterClass() throws Exception { String testClassName = this.getShortClassName(); System.out.println("AfterClass: " + testClassName + " of TestListenerCallbackBatchMode called."); _manager.disconnect(); deleteCluster(clusterName); }

Target:
public void afterClass() throws Exception { _manager.disconnect(); deleteCluster(clusterName); }
Source:
public @NonNull Query setAlternativesAsExact(AlternativesAsExact[] types) { if (types == null || types.length == 0) { set(KEY_ALTERNATIVES_AS_EXACT, null); } else { List<String> stringList = new ArrayList<>(types.length); for (AlternativesAsExact type : types) { switch (type) { case IGNORE_PLURALS: stringList.add("ignorePlurals"); break; case MULTI_WORDS_SYNONYM: stringList.add("multiWordsSynonym"); break; case SINGLE_WORD_SYNONYM: stringList.add("singleWordSynonym"); break; } } String alternatives = TextUtils.join(",", stringList); set(KEY_ALTERNATIVES_AS_EXACT, alternatives); } return this; }

Target:
public @NonNull Query setAlternativesAsExact(AlternativesAsExact[] types) { if (types == null) { set(KEY_ALTERNATIVES_AS_EXACT, null); } else { List<String> stringList = new ArrayList<>(types.length); for (AlternativesAsExact type : types) { switch (type) { case IGNORE_PLURALS: stringList.add("ignorePlurals"); break; case MULTI_WORDS_SYNONYM: stringList.add("multiWordsSynonym"); break; case SINGLE_WORD_SYNONYM: stringList.add("singleWordSynonym"); break; } } String alternatives = TextUtils.join(",", stringList); set(KEY_ALTERNATIVES_AS_EXACT, alternatives); } return this; }
Source:
public void beforeTest() throws IOException { Mockito.mockitoSession().initMocks(this); request = PowerMockito.mock(HttpRequest.class); response = PowerMockito.mock(HttpResponse.class); client = PowerMockito.mock(DatabaseClient.class); BufferedReader reader = new BufferedReader(new StringReader("{}")); PowerMockito.when(request.getReader()).thenReturn(reader); responseOut = new StringWriter(); writerOut = new BufferedWriter(responseOut); PowerMockito.when(response.getWriter()).thenReturn(writerOut); logHandler.clear(); }

Target:
public void beforeTest() throws IOException { Mockito.mockitoSession().initMocks(this); request = PowerMockito.mock(HttpRequest.class); response = PowerMockito.mock(HttpResponse.class); client = PowerMockito.mock(DatabaseClient.class); responseOut = new StringWriter(); writerOut = new BufferedWriter(responseOut); PowerMockito.when(response.getWriter()).thenReturn(writerOut); logHandler.clear(); }
Source:
public void onReceive(Context context, Intent intent) { int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1); if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction()) && WifiManager.WIFI_STATE_ENABLED == wifiState) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(new Intent(context, ServedService.class)); } else { context.startService(new Intent(context, ServedService.class)); } } }

Target:
public void onReceive(Context context, Intent intent) { int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1); if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction()) && WifiManager.WIFI_STATE_ENABLED == wifiState) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(new Intent(context, WifiService.class)); } else { context.startService(new Intent(context, WifiService.class)); } } }
Source:
public DefaultCompilationResponse(final Boolean successful, final List<String> mavenOutput, final Path workingDir, final List<String> targetContent, final List<String> projectDependencies, final String requestUUID) { this.successful = successful; if(mavenOutput != null) { this.mavenOutput = new ArrayList<>(mavenOutput); }else{ this.mavenOutput = Collections.emptyList(); } this.workingDir = workingDir; if(targetContent != null) { this.targetContent = new ArrayList<>(targetContent); }else{ this.targetContent = Collections.emptyList(); } if(projectDependencies != null) { this.projectDependencies = new ArrayList<>(projectDependencies); }else{ this.projectDependencies = Collections.emptyList(); } this.requestUUID = requestUUID; }

Target:
public DefaultCompilationResponse(final Boolean successful, final List<String> mavenOutput, final Path workingDir, final List<String> targetContent, final List<String> projectDependencies, final String requestUUID) { this.successful = successful; this.mavenOutput = nullToEmpty(mavenOutput); this.workingDir = workingDir; this.targetContent = nullToEmpty(targetContent); this.projectDependencies = nullToEmpty(projectDependencies); this.requestUUID = requestUUID; }