auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected StreamProcessor createStreamProcessor(final String pId, Map<String, String> map, final CountDownLatch waitStart, final CountDownLatch waitStop) { map.put(ApplicationConfig.PROCESSOR_ID, pId); Config config = new MapConfig(map); JobCoordinator jobCoordinator = Util.getObj(new JobCoordinatorConfig(config).getJobCoordinatorFactoryClassName(), JobCoordinatorFactory.class).getJobCoordinator(config); StreamProcessorLifecycleListener listener = new StreamProcessorLifecycleListener() { @Override public void onStart() { if (waitStart != null) { waitStart.countDown(); } LOG.info("onStart is called for pid=" + pId); } @Override public void onShutdown() { if (waitStop != null) { waitStop.countDown(); } LOG.info("onShutdown is called for pid=" + pId); } @Override public void onFailure(Throwable t) { LOG.info("onFailure is called for pid=" + pId); } }; StreamProcessor processor = new StreamProcessor(config, new HashMap<>(), (StreamTaskFactory) TestStreamTask::new, listener, jobCoordinator); return processor; }

Target:
protected StreamProcessor createStreamProcessor(final String pId, Map<String, String> map, final CountDownLatch waitStart, final CountDownLatch waitStop) { map.put(ApplicationConfig.PROCESSOR_ID, pId); Config config = new MapConfig(map); String jobCoordinatorFactoryClassName = new JobCoordinatorConfig(config).getJobCoordinatorFactoryClassName(); JobCoordinator jobCoordinator = Util.getObj(jobCoordinatorFactoryClassName, JobCoordinatorFactory.class).getJobCoordinator(config); StreamProcessorLifecycleListener listener = new StreamProcessorLifecycleListener() { @Override public void onStart() { if (waitStart != null) { waitStart.countDown(); } LOG.info("onStart is called for pid=" + pId); } @Override public void onShutdown() { if (waitStop != null) { waitStop.countDown(); } LOG.info("onShutdown is called for pid=" + pId); } @Override public void onFailure(Throwable t) { LOG.info("onFailure is called for pid=" + pId); } }; StreamProcessor processor = new StreamProcessor(config, new HashMap<>(), (StreamTaskFactory) TestStreamTask::new, listener, jobCoordinator); return processor; }
Source:
public void getReportTemplateHome_shouldCreateADirectoryUnderTheOpenmrsApplicationDataDirectoryIfGPValueIsRelative() throws Exception { File openmrsApplicationDataDirectory = temporaryFolder.newFolder("openmrs_home"); OpenmrsUtil.setApplicationDataDirectory(openmrsApplicationDataDirectory.getAbsolutePath()); administrationService.setGlobalProperty(RadiologyConstants.GP_MRRT_REPORT_TEMPLATE_DIR, "mrrt_templates"); File templateHome = radiologyProperties.getReportTemplateHome(); assertNotNull(templateHome); assertThat(templateHome.exists(), is(true)); assertThat(templateHome.getParentFile() .getName(), is(openmrsApplicationDataDirectory.getName())); }

Target:
public void getReportTemplateHome_shouldCreateADirectoryUnderTheOpenmrsApplicationDataDirectoryIfGPValueIsRelative() throws Exception { File openmrsApplicationDataDirectory = temporaryFolder.newFolder("openmrs_home"); OpenmrsUtil.setApplicationDataDirectory(openmrsApplicationDataDirectory.getAbsolutePath()); administrationService.setGlobalProperty(RadiologyConstants.GP_MRRT_REPORT_TEMPLATE_DIR, "mrrt_templates"); File templateHome = radiologyProperties.getReportTemplateHome(); File templateHomeFromGP = new File(administrationService.getGlobalProperty(RadiologyConstants.GP_MRRT_REPORT_TEMPLATE_DIR)); assertNotNull(templateHome); assertThat(templateHome.exists(), is(true)); assertThat(templateHome.getName(), is(templateHomeFromGP.getName())); assertThat(templateHome.getParentFile() .getName(), is(openmrsApplicationDataDirectory.getName())); }
Source:
private void processProbe(LookupSource lookupSource) { if (probe == null) { return; } Counter lookupPositionsConsidered = new Counter(); while (true) { if (probe.getPosition() >= 0) { if (!joinCurrentPosition(lookupSource, lookupPositionsConsidered)) { break; } if (!currentProbePositionProducedRow) { currentProbePositionProducedRow = true; if (!outerJoinCurrentPosition(lookupSource)) { break; } } } currentProbePositionProducedRow = false; if (!advanceProbePosition(lookupSource)) { break; } statisticsCounter.recordProbe(joinSourcePositions); joinSourcePositions = 0; } }

Target:
private void processProbe(LookupSource lookupSource) { verify(probe != null); DriverYieldSignal yieldSignal = operatorContext.getDriverContext().getYieldSignal(); while (!yieldSignal.isSet()) { if (probe.getPosition() >= 0) { if (!joinCurrentPosition(lookupSource, yieldSignal)) { break; } if (!currentProbePositionProducedRow) { currentProbePositionProducedRow = true; if (!outerJoinCurrentPosition(lookupSource)) { break; } } } currentProbePositionProducedRow = false; if (!advanceProbePosition(lookupSource)) { break; } statisticsCounter.recordProbe(joinSourcePositions); joinSourcePositions = 0; } }
Source:
public void testUnionAndFilter() throws Exception { runSimpleTests(); }

Target:
public void testUnionAndFilter() throws Exception { Optional<TajoResultSetBase[]> existing = runSimpleTests(); verifyResultStats(existing, 5L); }
Source:
private void cancel() { setConfirmWindow(null); }

Target:
private void cancel() { }
Source:
public boolean isRedirectRequested(HttpResponse httpResponse, HttpContext httpContext) { return proxiedHandler.isRedirectRequested(httpResponse, httpContext); }

Target:
public boolean isRedirectRequested(HttpResponse httpResponse, HttpContext httpContext) { return proxiedHandler != null ? proxiedHandler.isRedirectRequested(httpResponse, httpContext) : false; }
Source:
private static String readLamiFile(String filename) { String fileContent = ""; try { URL url = new URL("platform:/plugin/org.eclipse.tracecompass.analysis.lami.core.tests/testfiles/" + filename); try (InputStream inputStream = url.openConnection().getInputStream()) { BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); fileContent = in.lines().collect(Collectors.joining()); } } catch (IOException e) { e.printStackTrace(); } return fileContent; }

Target:
private static String readLamiFile(String filename) { String fileContent = ""; try { URL url = new URL("platform:/plugin/org.eclipse.tracecompass.analysis.lami.core.tests/testfiles/" + filename); try (InputStream inputStream = url.openConnection().getInputStream()) { BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); fileContent = in.lines().collect(Collectors.joining()); } } catch (IOException e) { fail(e.getMessage()); } return fileContent; }
Source:
public PoolBehavior(Node node, boolean createChannel) { this.node = node; if (!createChannel) { this.channel = null; this.writePromise = null; } else { this.channel = mock(DriverChannel.class); EventLoop eventLoop = mock(EventLoop.class); ChannelConfig config = mock(DefaultSocketChannelConfig.class); this.writePromise = DirectThreadEventExecutor.INSTANCE.newPromise(); when(channel.write(any(Message.class), anyBoolean(), anyMap(), any(ResponseCallback.class))) .thenAnswer( invocation -> { ResponseCallback callback = invocation.getArgument(3); callback.onStreamIdAssigned(1); callbackFuture.complete(callback); return writePromise; }); ChannelFuture closeFuture = mock(ChannelFuture.class); when(channel.closeFuture()).thenReturn(closeFuture); when(channel.eventLoop()).thenReturn(eventLoop); when(channel.config()).thenReturn(config); } }

Target:
public PoolBehavior(Node node, boolean createChannel) { this.node = node; if (!createChannel) { this.channel = null; this.writePromise = null; } else { this.channel = mock(DriverChannel.class); EventLoop eventLoop = mock(EventLoop.class); ChannelConfig config = mock(DefaultSocketChannelConfig.class); this.writePromise = ImmediateEventExecutor.INSTANCE.newPromise(); when(channel.write(any(Message.class), anyBoolean(), anyMap(), any(ResponseCallback.class))) .thenAnswer( invocation -> { ResponseCallback callback = invocation.getArgument(3); callback.onStreamIdAssigned(1); callbackFuture.complete(callback); return writePromise; }); ChannelFuture closeFuture = mock(ChannelFuture.class); when(channel.closeFuture()).thenReturn(closeFuture); when(channel.eventLoop()).thenReturn(eventLoop); when(channel.config()).thenReturn(config); } }
Source:
public void testUDPconnection() throws Exception { Subject<byte[], byte[]> sub = PublishSubject.create(); SimpleChan simpleadapter = new SimpleChan(sub); TestAwaitableObserver<byte[]> monitor = new TestAwaitableObserver<>(); sub.subscribe(monitor); int port; ServerFrontEnd udpSrv = null; int chances = RETRIES; boolean ready = false; do { chances --; port = rand.nextInt(100) + 8000; try { udpSrv = ServerFrontEnd.udp(simpleadapter, port); udpSrv.startAsync().awaitRunning(); ready = true; } catch (IllegalStateException e) { if (chances <= 0) throw e; } } while (!ready); sendMSG(MSG.getBytes(), port); monitor.awaitOnNext(1, TIMEOUT); assertThat("msg was received", monitor.getOnNextEvents().get(0), equalTo(MSG.getBytes())); udpSrv.stopAsync().awaitTerminated(); }

Target:
public void testUDPconnection() throws Exception { Subject<byte[], byte[]> sub = PublishSubject.create(); SimpleChan simpleadapter = new SimpleChan(sub); TestAwaitableObserver<byte[]> monitor = new TestAwaitableObserver<>(); sub.subscribe(monitor); Pair<ServerFrontEnd, Integer> cnxn = connect(simpleadapter, null); ServerFrontEnd udpSrv = cnxn.getLeft(); int port = cnxn.getRight(); sendMSG(MSG.getBytes(), port); monitor.awaitOnNext(1, TIMEOUT); assertThat("msg was received", monitor.getOnNextEvents().get(0), equalTo(MSG.getBytes())); udpSrv.stopAsync().awaitTerminated(); }
Source:
public void testActionWithPostActionParameters() throws InterruptedException, IOException, ActionNotFoundException { taskID = createTestTask(); activateTrigger(); assertTrue(waitForTaskExecution(taskID)); List<TaskTestObject> fetchedTaskTestObjects = tasksTestService.getTaskTestObjects(); List<TaskTestObject> expectedTaskTestObject = prepareExpectedTaskTestObject(); deleteTask(taskID); removeChannels(channelsDataService.retrieveAll()); assertTrue(fetchedTaskTestObjects.contains(expectedTaskTestObject.get(0))); assertTrue(fetchedTaskTestObjects.contains(expectedTaskTestObject.get(1))); assertTrue(fetchedTaskTestObjects.contains(expectedTaskTestObject.get(2))); }

Target:
public void testActionWithPostActionParameters() throws InterruptedException, IOException, ActionNotFoundException { taskID = createTestTask(); activateTrigger(); assertTrue(waitForTaskExecution(taskID)); List<TaskTestObject> fetchedTaskTestObjects = tasksTestService.getTaskTestObjects(); List<TaskTestObject> expectedTaskTestObject = prepareExpectedTaskTestObject(); assertTrue(fetchedTaskTestObjects.contains(expectedTaskTestObject.get(0))); assertTrue(fetchedTaskTestObjects.contains(expectedTaskTestObject.get(1))); assertTrue(fetchedTaskTestObjects.contains(expectedTaskTestObject.get(2))); }
Source:
private boolean isDotGit(byte[] buf, int p) { if (ignoreCase || windows) return toLower(buf[p]) == 'g' && toLower(buf[p + 1]) == 'i' && toLower(buf[p + 2]) == 't'; return buf[p] == 'g' && buf[p + 1] == 'i' && buf[p + 2] == 't'; }

Target:
private boolean isDotGit(byte[] buf, int p) { if (windows) return toLower(buf[p]) == 'g' && toLower(buf[p + 1]) == 'i' && toLower(buf[p + 2]) == 't'; return buf[p] == 'g' && buf[p + 1] == 'i' && buf[p + 2] == 't'; }
Source:
public void testDeleteTempFileAfterUpload() throws IOException { String key = getRandomString(); final TransferObserver observer = transferUtility.upload(key, inputStream); observer.setTransferListener(new TransferListener() { @Override public void onStateChanged(int id, TransferState state) { Log.d(TAG, "onStateChanged: " + id + ", " + state); switch (state) { case COMPLETED: assertFalse(new File(observer.getAbsoluteFilePath()).exists()); break; } } @Override public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) { Log.i(TAG, String.format("onProgressChanged: %d, total: %d, current: %d", id, bytesTotal, bytesCurrent)); } @Override public void onError(int id, Exception exception) { Log.e(TAG, "Error during upload: " + id, exception); } }); }

Target:
public void testDeleteTempFileAfterUpload() throws IOException { final String key = getRandomString(); observer = transferUtility.upload(key, inputStream); File file = new File(observer.getAbsoluteFilePath()); assertTrue(file.exists()); Context context = InstrumentationRegistry.getInstrumentation().getContext(); TransferStatusUpdater transferStatusUpdater = TransferStatusUpdater.getInstance(context); transferStatusUpdater.updateState(observer.getId(), TransferState.COMPLETED); assertFalse(file.exists()); }
Source:
public static void main(String[] args) throws Exception { Configuration conf = CachedConfiguration.getInstance(); FileSystem fs = FileSystem.get(conf); Opts opts = new Opts(); opts.parseArgs(SplitLarge.class.getName(), args); for (String file : opts.files) { AccumuloConfiguration aconf = DefaultConfiguration.getInstance(); CryptoService cryptoService = CryptoServiceFactory.newInstance(aconf); Path path = new Path(file); CachableBlockFile.Reader rdr = new CachableBlockFile.Reader(fs, path, conf, null, null, aconf, cryptoService); try (Reader iter = new RFile.Reader(rdr)) { if (!file.endsWith(".rf")) { throw new IllegalArgumentException("File must end with .rf"); } String smallName = file.substring(0, file.length() - 3) + "_small.rf"; String largeName = file.substring(0, file.length() - 3) + "_large.rf"; int blockSize = (int) aconf.getAsBytes(Property.TABLE_FILE_BLOCK_SIZE); try ( Writer small = new RFile.Writer(new BCFile.Writer(fs.create(new Path(smallName)), null, "gz", conf, aconf, cryptoService), blockSize); Writer large = new RFile.Writer(new BCFile.Writer(fs.create(new Path(largeName)), null, "gz", conf, aconf, cryptoService), blockSize)) { small.startDefaultLocalityGroup(); large.startDefaultLocalityGroup(); iter.seek(new Range(), new ArrayList<>(), false); while (iter.hasTop()) { Key key = iter.getTopKey(); Value value = iter.getTopValue(); if (key.getSize() + value.getSize() < opts.maxSize) { small.append(key, value); } else { large.append(key, value); } iter.next(); } } } } }

Target:
public static void main(String[] args) throws Exception { Configuration conf = CachedConfiguration.getInstance(); FileSystem fs = FileSystem.get(conf); Opts opts = new Opts(); opts.parseArgs(SplitLarge.class.getName(), args); for (String file : opts.files) { AccumuloConfiguration aconf = DefaultConfiguration.getInstance(); CryptoService cryptoService = ConfigurationTypeHelper.getClassInstance(null, opts.cryptoClass, CryptoService.class, new NoCryptoService()); Path path = new Path(file); CachableBlockFile.Reader rdr = new CachableBlockFile.Reader(fs, path, conf, null, null, aconf, cryptoService); try (Reader iter = new RFile.Reader(rdr)) { if (!file.endsWith(".rf")) { throw new IllegalArgumentException("File must end with .rf"); } String smallName = file.substring(0, file.length() - 3) + "_small.rf"; String largeName = file.substring(0, file.length() - 3) + "_large.rf"; int blockSize = (int) aconf.getAsBytes(Property.TABLE_FILE_BLOCK_SIZE); try ( Writer small = new RFile.Writer(new BCFile.Writer(fs.create(new Path(smallName)), null, "gz", conf, aconf, cryptoService), blockSize); Writer large = new RFile.Writer(new BCFile.Writer(fs.create(new Path(largeName)), null, "gz", conf, aconf, cryptoService), blockSize)) { small.startDefaultLocalityGroup(); large.startDefaultLocalityGroup(); iter.seek(new Range(), new ArrayList<>(), false); while (iter.hasTop()) { Key key = iter.getTopKey(); Value value = iter.getTopValue(); if (key.getSize() + value.getSize() < opts.maxSize) { small.append(key, value); } else { large.append(key, value); } iter.next(); } } } } }
Source:
public static HCatSchema toHiveSchema(Schema schema, HCatSchema tableSchema) { List<HCatFieldSchema> fields = Lists.newArrayList(); for (Schema.Field field : schema.getFields()) { String name = field.getName(); try { Preconditions.checkNotNull(tableSchema.get(name), "Missing field %s in table schema", name); fields.add(new HCatFieldSchema(name, getType(name, field.getSchema()), "")); } catch (HCatException e) { LOG.error("Failed to create HCatFieldSchema field of type from schema", name, field.getSchema().getType()); } } return new HCatSchema(fields); }

Target:
public static HCatSchema toHiveSchema(Schema schema, HCatSchema tableSchema) { List<HCatFieldSchema> fields = Lists.newArrayList(); for (Schema.Field field : schema.getFields()) { String name = field.getName(); try { HCatFieldSchema hCatFieldSchema = tableSchema.get(name); Preconditions.checkNotNull(hCatFieldSchema, "Missing field %s in table schema", name); PrimitiveTypeInfo hiveType = hCatFieldSchema.getTypeInfo(); PrimitiveTypeInfo type = getType(name, field.getSchema()); if (hiveType != type) { LOG.warn("The given schema for the field does not match the schema from the table. " + "The schema for field be used.", type, name, hiveType, hiveType, name); } fields.add(hCatFieldSchema); } catch (HCatException e) { LOG.error("Failed to create HCatFieldSchema field of type from schema", name, field.getSchema().getType()); } } return new HCatSchema(fields); }
Source:
String getSortedJsonStringValueFromResource(Resource resource) { final Object obj; try { obj = OBJECT_MAPPER.treeToValue(resource.getPropertyBag() , Object.class); final String sortedJson = OBJECT_MAPPER.writeValueAsString(obj); return sortedJson; } catch (JsonProcessingException e) { throw new IllegalStateException("Failed to obtain serialized sorted json"); } }

Target:
String getSortedJsonStringValueFromResource(Resource resource) { final Object obj; try { obj = OBJECT_MAPPER.treeToValue(resource.getPropertyBag(), Object.class); return OBJECT_MAPPER.writeValueAsString(obj); } catch (JsonProcessingException e) { throw new IllegalStateException("Failed to obtain serialized sorted json"); } }
Source:
private void reload(final InputStream stream) { final BufferedInputStream bufferedStream = new BufferedInputStream( stream, BUFFER_SIZE ); final AlertGroup group; try { group = _objectMapper.readValue(bufferedStream, AlertGroup.class); } catch (final IOException e) { throw new RuntimeException("Could not load alerts", e); } final ImmutableMap.Builder<UUID, Alert> mapBuilder = ImmutableMap.builder(); for (final SerializedAlert fsAlert : group.getAlerts()) { final StringArgGenerator uuidGen = Generators.nameBasedGenerator(_organization.getId()); final UUID uuid = fsAlert.getUUID().orElseGet(() -> computeUUID(uuidGen, fsAlert)); final MetricsQuery query; if (group.getVersion() == 0) { query = new DefaultMetricsQuery.Builder() .setQuery(fsAlert.getQuery().toString()) .setFormat(MetricsQueryFormat.KAIROS_DB) .build(); } else { throw new IllegalArgumentException(String.format("Unhandled alert version %d", group.getVersion())); } final Alert alert = new DefaultAlert.Builder() .setId(uuid) .setName(fsAlert.getName()) .setDescription(fsAlert.getDescription()) .setEnabled(fsAlert.isEnabled()) .setOrganization(_organization) .setQuery(query) .setAdditionalMetadata(fsAlert.getAdditionalMetadata()) .build(); mapBuilder.put(uuid, alert); } synchronized (this) { _alerts = mapBuilder.build(); } }

Target:
private void reload(final InputStream stream) { final BufferedInputStream bufferedStream = new BufferedInputStream( stream, BUFFER_SIZE ); final AlertGroup group; try { group = _objectMapper.readValue(bufferedStream, AlertGroup.class); } catch (final IOException e) { throw new RuntimeException("Could not load alerts", e); } final ImmutableMap.Builder<UUID, Alert> mapBuilder = ImmutableMap.builder(); for (final SerializedAlert fsAlert : group.getAlerts()) { final StringArgGenerator uuidGen = Generators.nameBasedGenerator(_organization.getId()); final UUID uuid = fsAlert.getUUID().orElseGet(() -> computeUUID(uuidGen, fsAlert)); final MetricsQuery query; if (group.getVersion() == 0) { query = new DefaultMetricsQuery.Builder() .setQuery(fsAlert.getQuery().toString()) .setFormat(MetricsQueryFormat.KAIROS_DB) .build(); } else { throw new IllegalArgumentException(String.format("Unhandled alert version %d", group.getVersion())); } final Alert alert = new DefaultAlert.Builder() .setId(uuid) .setName(fsAlert.getName()) .setDescription(fsAlert.getDescription()) .setEnabled(fsAlert.isEnabled()) .setOrganization(_organization) .setQuery(query) .setAdditionalMetadata(fsAlert.getAdditionalMetadata()) .build(); mapBuilder.put(uuid, alert); } _alerts = mapBuilder.build(); }
Source:
Mono<Response<IndexDocumentsResult>> indexWithResponse(IndexBatch<?> batch, Context context) { return restClient.documents() .indexWithRestResponseAsync(batch, context) .handle((res, sink) -> { if (res.getStatusCode() == 207) { IndexBatchException ex = new IndexBatchException(res.getValue()); sink.error(ex); } else { sink.next(res); } }); }

Target:
Mono<Response<IndexDocumentsResult>> indexWithResponse(IndexBatch<?> batch, Context context) { return restClient.documents() .indexWithRestResponseAsync(batch, context) .handle((res, sink) -> { if (res.getStatusCode() == HttpStatus.SC_MULTI_STATUS) { IndexBatchException ex = new IndexBatchException(res.getValue()); sink.error(ex); } else { sink.next(res); } }); }
Source:
private XmlRpcStruct generateOptions() { XmlRpcStruct options = new XmlRpcStruct(); options.add(VdsProperties.connectivityCheck, Boolean.toString(getParameters().isCheckConnectivity())); if (getParameters().isCheckConnectivity()) { int connectivityTimeout = getParameters().getConectivityTimeout(); if (connectivityTimeout <= 0) { connectivityTimeout = Config.<Integer> GetValue(ConfigValues.NetworkConnectivityCheckTimeoutInSeconds); } options.add(VdsProperties.connectivityTimeout, connectivityTimeout); } return options; }

Target:
private XmlRpcStruct generateOptions() { XmlRpcStruct options = new XmlRpcStruct(); options.add(VdsProperties.connectivityCheck, Boolean.toString(getParameters().isCheckConnectivity())); if (getParameters().isCheckConnectivity()) { options.add(VdsProperties.connectivityTimeout, getParameters().getConectivityTimeout()); } return options; }
Source:
protected void persistYamlInfoForShutdownHook(YamlLoader loader, String agentHome) throws IOException{ ObjectOutputStream oos = null; FileOutputStream fout = null; YamlConfig config = loader.getYamlConfiguration(); List<Slave> slaveList = config.getSlaves(); List<String> hosts = new ArrayList<String>(); String[] slaveAgentList = null; for(Slave host: slaveList){ for (String str : host.getHosts()) { hosts.add(str); } } slaveAgentList = hosts.toArray(new String[hosts.size()]); BasicYamlConfig agentConfig = new BasicYamlConfig(config.getJumbuneJobName(), config.getMaster().getHost(), config.getMaster().getAgentPort()); agentConfig.setUser(config.getMaster().getUser()); agentConfig.setRsaFile(config.getMaster().getRsaFile()); agentConfig.setDsaFile(config.getMaster().getDsaFile()); agentConfig.setSlaves(slaveAgentList); agentConfig.setTmpDir(config.getsJumbuneHome()); try{ File file = new File(loader.getjHome()+YAML_FILE); if(file.exists()){ file.delete(); } fout = new FileOutputStream(loader.getjHome()+YAML_FILE, true); oos = new ObjectOutputStream(fout); oos.writeObject(agentConfig); }finally{ if(oos != null){ oos.close(); } } RemotingUtil.sendYamlInfoToAgent(loader, agentConfig); }

Target:
protected void persistYamlInfoForShutdownHook(YamlLoader loader, String agentHome) throws IOException{ ObjectOutputStream oos = null; FileOutputStream fout = null; YamlConfig config = loader.getYamlConfiguration(); List<String> hosts = new ArrayList<String>(); String[] slaveAgentList = null; for(Slave host: config.getSlaves()){ for (String str : host.getHosts()) { hosts.add(str); } } slaveAgentList = hosts.toArray(new String[hosts.size()]); BasicYamlConfig agentConfig = new BasicYamlConfig(config.getJumbuneJobName(), config.getMaster().getHost(), config.getMaster().getAgentPort()); agentConfig.setUser(config.getMaster().getUser()); agentConfig.setRsaFile(config.getMaster().getRsaFile()); agentConfig.setDsaFile(config.getMaster().getDsaFile()); agentConfig.setSlaves(slaveAgentList); agentConfig.setTmpDir(config.getsJumbuneHome()); try{ String yamlFile = loader.getjHome()+YAML_FILE; File file = new File(yamlFile); if(file.exists()){ file.delete(); } fout = new FileOutputStream(yamlFile, true); oos = new ObjectOutputStream(fout); oos.writeObject(agentConfig); }finally{ if(oos != null){ oos.close(); } } RemotingUtil.sendYamlInfoToAgent(loader, agentConfig); }
Source:
void sendReadCommand(Replica to, ReadCallback readCallback, boolean speculative) { ReadCommand command = this.command; if (to.isTransient()) { command = command.copyAsTransientQuery(to); } if (Tracing.isTracing()) { String type; if (speculative) type = to.isFull() ? "speculative full" : "speculative transient"; else type = to.isFull() ? "full" : "transient"; Tracing.trace("Enqueuing data read to {}", type, to); } if (to.isSelf()) { try (ReadExecutionController executionController = command.executionController(); UnfilteredPartitionIterator iterator = command.executeLocally(executionController)) { readCallback.response(command.createResponse(iterator)); } } else { MessageOut<ReadCommand> message = command.createMessage(); if (command.isTrackingRepairedStatus() && to.isFull()) message = message.withParameter(ParameterType.TRACK_REPAIRED_DATA, MessagingService.ONE_BYTE); MessagingService.instance().sendRRWithFailure(message, to.endpoint(), readCallback); } }

Target:
void sendReadCommand(Replica to, ReadCallback readCallback, boolean speculative) { ReadCommand command = this.command; if (to.isSelf()) { StageManager.getStage(Stage.READ).maybeExecuteImmediately(new StorageProxy.LocalReadRunnable(command, readCallback)); return; } if (to.isTransient()) { command = command.copyAsTransientQuery(to); } if (Tracing.isTracing()) { String type; if (speculative) type = to.isFull() ? "speculative full" : "speculative transient"; else type = to.isFull() ? "full" : "transient"; Tracing.trace("Enqueuing data read to {}", type, to); } MessageOut<ReadCommand> message = command.createMessage(); if (command.isTrackingRepairedStatus() && to.isFull()) message = message.withParameter(ParameterType.TRACK_REPAIRED_DATA, MessagingService.ONE_BYTE); MessagingService.instance().sendRRWithFailure(message, to.endpoint(), readCallback); }
Source:
public Boolean getEmailVerified() { if (emailVerified == null) { if (status == AccountStatus.ENABLED) { return Boolean.TRUE; } else if (status == AccountStatus.UNVERIFIED) { return Boolean.FALSE; } } return emailVerified; }

Target:
public Boolean getEmailVerified() { return emailVerified; }
Source:
public CapturesToolWindow(@NotNull final Project project) { myProject = project; DefaultTreeModel model = new DefaultTreeModel(new DefaultMutableTreeNode()); myTree = new SimpleTree(model); myTree.setRootVisible(false); myComponent = new JBScrollPane(myTree); myComponent.setBorder(BorderFactory.createEmptyBorder()); myStructure = new CapturesTreeStructure(myProject); myBuilder = new AbstractTreeBuilder(myTree, model, myStructure, null); Disposer.register(this, myBuilder); Disposer.register(project, this); myBuilder.initRootNode(); myBuilder.getInitialized().doWhenDone(new Runnable() { @Override public void run() { myBuilder.getUi().expandAll(null); } }); myTree.addHierarchyListener(this); CaptureService.getInstance(myProject).addListener(this); CaptureService.getInstance(myProject).update(); myStructure.update(); myTree.setPopupGroup(getPopupActions(), "Context"); myTree.putClientProperty(DataManager.CLIENT_PROPERTY_DATA_PROVIDER, this); }

Target:
public CapturesToolWindow(@NotNull final Project project) { myProject = project; DefaultTreeModel model = new DefaultTreeModel(new DefaultMutableTreeNode()); myTree = new SimpleTree(model); myTree.setRootVisible(false); myComponent = ScrollPaneFactory.createScrollPane(myTree); myStructure = new CapturesTreeStructure(myProject); myBuilder = new AbstractTreeBuilder(myTree, model, myStructure, null); Disposer.register(this, myBuilder); Disposer.register(project, this); myBuilder.initRootNode(); myBuilder.getInitialized().doWhenDone(new Runnable() { @Override public void run() { myBuilder.getUi().expandAll(null); } }); myTree.addHierarchyListener(this); CaptureService.getInstance(myProject).addListener(this); CaptureService.getInstance(myProject).update(); myStructure.update(); myTree.setPopupGroup(getPopupActions(), "Context"); myTree.putClientProperty(DataManager.CLIENT_PROPERTY_DATA_PROVIDER, this); }
Source:
public static void run() throws Exception { initializeTest(); checkSubset(getClassloaderDescriptors(null), new String[] { "Ljava/lang/String;", "Ljava/util/TreeSet;" }, "Missing entries for null classloader."); checkEq(getClassloaderDescriptors(null), getClassloaderDescriptors(Object.class.getClassLoader()), "Object not in bcp!"); checkSubset(getClassloaderDescriptors(Test1946.class.getClassLoader()), new String[] { "Lart/Test1946;", "Lart/Test1946$TMP1;", "Lart/Test1946$TMP2;", "Lart/Test1946$TMP3;" }, "Missing entries for current class classloader."); checkEq(getClassloaderDescriptors(makeClassLoaderFrom(TEST_CLASSES, ClassLoader.getSystemClassLoader())), new String[] { "LA;", "LB;", "LC;", "LD;", "LE;" }, "Unexpected classes in custom classloader"); checkEq(getClassloaderDescriptors(makeClassLoaderFrom(TEST_CLASSES, Object.class.getClassLoader())), new String[] { "LA;", "LB;", "LC;", "LD;", "LE;" }, "Unexpected classes in custom classloader"); checkEq(getClassloaderDescriptors(makeClassLoaderFrom(TEST_CLASSES, Test1946.class.getClassLoader())), new String[] { "LA;", "LB;", "LC;", "LD;", "LE;" }, "Unexpected classes in custom classloader"); checkEq(getClassloaderDescriptors(makeClassLoaderFrom(Arrays.asList(TEST_CLASSES, TEST_CLASSES), Test1946.class.getClassLoader())), new String[] { "LA;", "LB;", "LC;", "LD;", "LE;" }, "Unexpected classes in custom classloader"); System.out.println("Passed!"); }

Target:
public static void run() { System.out.println("Failed! This should not be run. The test is in src-art/art/Test1946.java"); }
Source:
public List<String> getApplicableMethodNames() { return METHODS; }

Target:
public List<String> getApplicableMethodNames() { return methods; }
Source:
public String post(@SpringBean("patientService") PatientService patientService, @RequestParam(value = "causeOfDeath", required = false) String causeOfDeath, @RequestParam(value = "dead", required = false) Boolean dead, @RequestParam(value = "deathDate", required = false) Date deathDate, @RequestParam("patientId") Patient patient, UiUtils ui, @RequestParam(value = "returnUrl", required = false) String returnUrl) { try { Date date = new Date(); if (dead != null && StringUtils.isNotBlank(causeOfDeath) && deathDate != null && !deathDate.before(patient.getBirthdate()) && !deathDate.after(date)) { patient.setDead(dead); patient.setCauseOfDeath(Context.getConceptService().getConceptByUuid(causeOfDeath)); patient.setDeathDate(deathDate); } else { patient.setDeathDate(null); patient.setDead(false); patient.setCauseOfDeath(null); } patientService.savePatient(patient); if (patient.isDead() && patient.getDeathDate() != null) { actionAfterDeath(patient, patient.getDeathDate()); } return "redirect:" + ui.pageLink("coreapps", "clinicianfacing/patient", SimpleObject.create("patientId", patient.getId(), "returnUrl", returnUrl)); } catch (APIException e) { log.error(e.getMessage(), e); return "redirect:" + ui.pageLink("coreapps", "markPatientDead", SimpleObject.create("patientId", patient.getId(), "returnUrl", returnUrl)); } }

Target:
public String post(@SpringBean("patientService") PatientService patientService, @RequestParam(value = "causeOfDeath", required = false) String causeOfDeath, @RequestParam(value = "dead", required = false) Boolean dead, @RequestParam(value = "deathDate", required = false) Date deathDate, @RequestParam("patientId") Patient patient, UiUtils ui, @RequestParam(value = "returnUrl", required = false) String returnUrl) { try { Date date = new Date(); if (dead != null && StringUtils.isNotBlank(causeOfDeath) && deathDate != null && !deathDate.before(patient.getBirthdate()) && !deathDate.after(date)) { patient.setDead(dead); patient.setCauseOfDeath(Context.getConceptService().getConceptByUuid(causeOfDeath)); patient.setDeathDate(deathDate); } else { patient.setDeathDate(null); patient.setDead(false); patient.setCauseOfDeath(null); } patientService.savePatient(patient); if (patient.isDead() && patient.getDeathDate() != null) { closeActiveVisitsAfterDeath(patient); } return "redirect:" + ui.pageLink("coreapps", "clinicianfacing/patient", SimpleObject.create("patientId", patient.getId(), "returnUrl", returnUrl)); } catch (APIException e) { log.error(e.getMessage(), e); return "redirect:" + ui.pageLink("coreapps", "markPatientDead", SimpleObject.create("patientId", patient.getId(), "returnUrl", returnUrl)); } }
Source:
protected QueryParameters makeQueryParametersForExecution(String hql) { final HQLQueryPlan entityGraphHintedQueryPlan; if ( entityGraphQueryHint == null) { entityGraphHintedQueryPlan = null; } else { entityGraphHintedQueryPlan = new HQLQueryPlan( hql, false, getProducer().getLoadQueryInfluencers().getEnabledFilters(), getProducer().getFactory(), entityGraphQueryHint ); } QueryParameters queryParameters = new QueryParameters( getQueryParameterBindings(), getLockOptions(), queryOptions, true, isReadOnly(), cacheable, cacheRegion, comment, dbHints, null, optionalObject, optionalEntityName, optionalId, resultTransformer ); if ( entityGraphHintedQueryPlan != null ) { queryParameters.setQueryPlan( entityGraphHintedQueryPlan ); } else if ( this instanceof QueryImpl ) { QueryImpl hqlQuery = (QueryImpl) this; if ( hql.equals( hqlQuery.getQueryString() ) ) { queryParameters.setQueryPlan( hqlQuery.getQueryPlan() ); } } if ( passDistinctThrough != null ) { queryParameters.setPassDistinctThrough( passDistinctThrough ); } return queryParameters; }

Target:
protected QueryParameters makeQueryParametersForExecution(String hql) { final HQLQueryPlan entityGraphHintedQueryPlan; if ( entityGraphQueryHint == null) { entityGraphHintedQueryPlan = null; } else { entityGraphHintedQueryPlan = new HQLQueryPlan( hql, false, getProducer().getLoadQueryInfluencers().getEnabledFilters(), getProducer().getFactory(), entityGraphQueryHint ); } QueryParameters queryParameters = new QueryParameters( getQueryParameterBindings(), getLockOptions(), queryOptions, true, isReadOnly(), cacheable, cacheRegion, comment, dbHints, null, optionalObject, optionalEntityName, optionalId, resultTransformer ); appendQueryPlanToQueryParameters( hql, queryParameters, entityGraphHintedQueryPlan ); if ( passDistinctThrough != null ) { queryParameters.setPassDistinctThrough( passDistinctThrough ); } return queryParameters; }
Source:
private void registerInstances(Collection<InstanceMonitor> instances) throws JMException { synchronized (_instanceMonitorMap) { for (InstanceMonitor monitor : instances) { String instanceName = monitor.getInstanceName(); String beanName = getInstanceBeanName(instanceName); unregister(getObjectName(beanName)); monitor.register(); _instanceMonitorMap.put(instanceName, monitor); } } }

Target:
private void registerInstances(Collection<InstanceMonitor> instances) throws JMException { synchronized (_instanceMonitorMap) { for (InstanceMonitor monitor : instances) { String instanceName = monitor.getInstanceName(); InstanceMonitor removedMonitor = _instanceMonitorMap.remove(instanceName); if (removedMonitor != null) { removedMonitor.unregister(); } monitor.register(); _instanceMonitorMap.put(instanceName, monitor); } } }
Source:
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { RoleBasedAuthorizationStrategy strategy = (RoleBasedAuthorizationStrategy)source; Map<String, RoleMap> maps = strategy.getRoleMaps(); for (Map.Entry<String, RoleMap> map : maps.entrySet()) { RoleMap roleMap = map.getValue(); writer.startNode("roleMap"); writer.addAttribute("type", map.getKey()); for (Map.Entry<Role, Set<String>> grantedRole : roleMap.getGrantedRoles().entrySet()) { Role role = grantedRole.getKey(); if (role != null) { writer.startNode("role"); writer.addAttribute("name", role.getName()); writer.addAttribute("pattern", role.getPattern().pattern()); writer.startNode("permissions"); for (Permission permission : role.getPermissions()) { if(permission!=null) { writer.startNode("permission"); writer.setValue(permission.getId()); writer.endNode(); } else{ throw new NullPointerException("Cannot process the permissions as they have been incorrectly configured in the script"); } } writer.endNode(); writer.startNode("assignedSIDs"); for (String sid : grantedRole.getValue()) { writer.startNode("sid"); writer.setValue(sid); writer.endNode(); } writer.endNode(); writer.endNode(); } } writer.endNode(); } }

Target:
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { RoleBasedAuthorizationStrategy strategy = (RoleBasedAuthorizationStrategy)source; Map<String, RoleMap> maps = strategy.getRoleMaps(); for (Map.Entry<String, RoleMap> map : maps.entrySet()) { RoleMap roleMap = map.getValue(); writer.startNode("roleMap"); writer.addAttribute("type", map.getKey()); for (Map.Entry<Role, Set<String>> grantedRole : roleMap.getGrantedRoles().entrySet()) { Role role = grantedRole.getKey(); if (role != null) { writer.startNode("role"); writer.addAttribute("name", role.getName()); writer.addAttribute("pattern", role.getPattern().pattern()); writer.startNode("permissions"); for (Permission permission : role.getPermissions()) { writer.startNode("permission"); writer.setValue(permission.getId()); writer.endNode(); } writer.endNode(); writer.startNode("assignedSIDs"); for (String sid : grantedRole.getValue()) { writer.startNode("sid"); writer.setValue(sid); writer.endNode(); } writer.endNode(); writer.endNode(); } } writer.endNode(); } }
Source:
private Category(String name, Type type) { Objects.nonNull(name); Objects.nonNull(type); this.name = name; this.type = type; }

Target:
private Category(String name, Type type) { this.name = name; this.type = type; }
Source:
public void init() throws ServletException { ServerConfigurationService scs = (ServerConfigurationService) ComponentManager.get(ServerConfigurationService.class); if(scs != null) { DEFAULT_LIST_PAGE_SIZE = scs.getInt("citations.default.list.page.size", 50); } else { logger.warn("Failed to get default list page size as ServerConfigurationService is null. Defaulting to " + DEFAULT_LIST_PAGE_SIZE); } }

Target:
public void init() throws ServletException { ServerConfigurationService scs = (ServerConfigurationService) ComponentManager.get(ServerConfigurationService.class); if(scs != null) { defaultListPageSize = scs.getInt("citations.default.list.page.size", 50); } else { logger.warn("Failed to get default list page size as ServerConfigurationService is null. Defaulting to " + defaultListPageSize); defaultListPageSize = 50; } }
Source:
protected String createHttpRequestURL() { String bugUrl = getUrlSuffix(); LoginToken token = ((BugzillaRestHttpClient) getClient()).getLoginToken(); if (token != null && bugUrl.length() > 0) { if (!bugUrl.endsWith("?")) { bugUrl += "&"; } bugUrl += "token=" + token.getToken(); } else { String apiKey = ((BugzillaRestHttpClient) getClient()).getApiKey(); if (apiKey != null && bugUrl.length() > 0) { if (!bugUrl.endsWith("?")) { bugUrl += "&"; } bugUrl += "api_key=" + apiKey; } } return baseUrl() + bugUrl; }

Target:
protected String createHttpRequestURL() { String bugUrl = getUrlSuffix(); if (bugUrl.length() > 0 && authenticationRequired) { RepositoryLocation location = getClient().getLocation(); if (Boolean.parseBoolean(location.getProperty(IBugzillaRestConstants.REPOSITORY_USE_API_KEY))) { bugUrl += MessageFormat.format("{1}Bugzilla_api_key={0}", new Object[] { location.getProperty(IBugzillaRestConstants.REPOSITORY_API_KEY), bugUrl.endsWith("?") ? "" : "&" }); } else { if (!bugUrl.endsWith("?")) { bugUrl += "&"; } UserCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY); if (credentials == null) { throw new IllegalStateException("Authentication requested without valid credentials"); } bugUrl += MessageFormat.format("Bugzilla_login={0}&Bugzilla_password={1}", new Object[] { credentials.getUserName(), credentials.getPassword() }); } } return baseUrl() + bugUrl; }
Source:
private Map<String, String> configProperties() { Map<String, String> props = new HashMap<>(); props.put("connector.class", "JdbcSourceConnector"); props.put(CONNECTION_URL_CONFIG, MSSQL_URL); props.put(CONNECTION_USER_CONFIG, "sa"); props.put(CONNECTION_PASSWORD_CONFIG, "reallyStrongPwd123"); props.put(TABLE_WHITELIST_CONFIG, MSSQL_Table); props.put(TIMESTAMP_COLUMN_NAME_CONFIG, "start_time"); props.put(TOPIC_PREFIX_CONFIG, "test-"); props.put(POLL_INTERVAL_MS_CONFIG, "30"); props.put("tasks.max", Integer.toString(TASKS_MAX)); props.put("key.converter", StringConverter.class.getName()); props.put("value.converter", StringConverter.class.getName()); props.put("confluent.topic.bootstrap.servers", connect.kafka().bootstrapServers()); props.put("confluent.topic.replication.factor", "1"); return props; }

Target:
private Map<String, String> configProperties() { Map<String, String> props = new HashMap<>(); props.put(CONNECTOR_CLASS_CONFIG, "JdbcSourceConnector"); props.put(CONNECTION_URL_CONFIG, MSSQL_URL); props.put(CONNECTION_USER_CONFIG, "sa"); props.put(CONNECTION_PASSWORD_CONFIG, "reallyStrongPwd123"); props.put(TABLE_WHITELIST_CONFIG, MSSQL_Table); props.put(TIMESTAMP_COLUMN_NAME_CONFIG, "start_time"); props.put(TOPIC_PREFIX_CONFIG, "test-"); props.put(POLL_INTERVAL_MS_CONFIG, "30"); props.put(TASKS_MAX_CONFIG, Integer.toString(TASKS_MAX)); props.put(KEY_CONVERTER_CLASS_CONFIG, StringConverter.class.getName()); props.put(VALUE_CONVERTER_CLASS_CONFIG, StringConverter.class.getName()); return props; }
Source:
public boolean press(List<KeyStroke> potentialKeyStrokes, Event event) { KeySequence errorSequence = null; Collection<Binding> errorMatch = null; KeySequence sequenceBeforeKeyStroke = state; for (Iterator<KeyStroke> iterator = potentialKeyStrokes.iterator(); iterator.hasNext();) { KeySequence sequenceAfterKeyStroke = KeySequence.getInstance(sequenceBeforeKeyStroke, iterator.next()); if (isPartialMatch(sequenceAfterKeyStroke)) { incrementState(sequenceAfterKeyStroke); return true; } else if (isPerfectMatch(sequenceAfterKeyStroke)) { final ParameterizedCommand cmd = getPerfectMatch(sequenceAfterKeyStroke); for (IKeyBindingDispatcherInterceptor interceptor : fInterceptors) { if (interceptor.interceptExecutePerfectMatch(cmd, event)) { return false; } } try { return executeCommand(cmd, event) || !sequenceBeforeKeyStroke.isEmpty(); } catch (final CommandException e) { return true; } } else if ((keyAssistDialog != null) && (keyAssistDialog.getShell() != null) && ((event.keyCode == SWT.ARROW_DOWN) || (event.keyCode == SWT.ARROW_UP) || (event.keyCode == SWT.ARROW_LEFT) || (event.keyCode == SWT.ARROW_RIGHT) || (event.keyCode == SWT.CR) || (event.keyCode == SWT.PAGE_UP) || (event.keyCode == SWT.PAGE_DOWN))) { return false; } else { Collection<Binding> matches = getBindingService().getConflictsFor( sequenceAfterKeyStroke); if (matches != null && !matches.isEmpty()) { errorSequence = sequenceAfterKeyStroke; errorMatch = matches; } } } resetState(true); if (sequenceBeforeKeyStroke.isEmpty() && errorSequence != null) { openKeyAssistShell(errorMatch); } return !sequenceBeforeKeyStroke.isEmpty(); }

Target:
public boolean press(List<KeyStroke> potentialKeyStrokes, Event event) { KeySequence errorSequence = null; Collection<Binding> errorMatch = null; KeySequence sequenceBeforeKeyStroke = state; for (KeyStroke keyStroke : potentialKeyStrokes) { KeySequence sequenceAfterKeyStroke = KeySequence.getInstance(sequenceBeforeKeyStroke, keyStroke); if (isPartialMatch(sequenceAfterKeyStroke)) { incrementState(sequenceAfterKeyStroke); return true; } else if (isPerfectMatch(sequenceAfterKeyStroke)) { final ParameterizedCommand cmd = getPerfectMatch(sequenceAfterKeyStroke); for (IKeyBindingInterceptor interceptor : fInterceptors) { if (interceptor.executeCommand(cmd, event)) { return false; } } try { return executeCommand(cmd, event) || !sequenceBeforeKeyStroke.isEmpty(); } catch (final CommandException e) { return true; } } else if ((keyAssistDialog != null) && (keyAssistDialog.getShell() != null) && ((event.keyCode == SWT.ARROW_DOWN) || (event.keyCode == SWT.ARROW_UP) || (event.keyCode == SWT.ARROW_LEFT) || (event.keyCode == SWT.ARROW_RIGHT) || (event.keyCode == SWT.CR) || (event.keyCode == SWT.PAGE_UP) || (event.keyCode == SWT.PAGE_DOWN))) { return false; } else { Collection<Binding> matches = getBindingService().getConflictsFor( sequenceAfterKeyStroke); if (matches != null && !matches.isEmpty()) { errorSequence = sequenceAfterKeyStroke; errorMatch = matches; } } } resetState(true); if (sequenceBeforeKeyStroke.isEmpty() && errorSequence != null) { openKeyAssistShell(errorMatch); } return !sequenceBeforeKeyStroke.isEmpty(); }
Source:
public static int getAmountAvailable(Campaign campaign, AmmoType ammoType) { if (campaign.getCampaignOptions().useAmmoByType()) { Predicate<Part> predicate; if (AmmoBin.ALLOWED_BY_TYPE.contains(ammoType.getAmmoType())) { predicate = part -> { return part instanceof AmmoStorage && ammoType.equalsAmmoTypeOnly(((AmmoStorage) part).getType()) && ammoType.getMunitionType() == ((AmmoType) ((AmmoStorage) part).getType()).getMunitionType(); }; } else { predicate = part -> { return part instanceof AmmoStorage && ammoType.equals(((AmmoStorage) part).getType()) && ammoType.getMunitionType() == ((AmmoType) ((AmmoStorage) part).getType()).getMunitionType(); }; } AmmoStorage a = (AmmoStorage) campaign.findSparePart(predicate); return a != null ? a.getShots() : 0; } else { return campaign.streamSpareParts() .filter(part -> part instanceof AmmoStorage && part.isPresent()) .mapToInt(part -> { AmmoStorage a = (AmmoStorage)part; AmmoType aType = (AmmoType)a.getType(); if (aType.equals(ammoType) && ammoType.getMunitionType() == aType.getMunitionType()) { return a.getShots(); } else if (isCompatibleAmmo(campaign, aType, ammoType) && ammoType.getRackSize() != 0) { return (a.getShots() * aType.getRackSize()) / ammoType.getRackSize(); } return 0; }) .sum(); } }

Target:
public static int getAmountAvailable(Campaign campaign, AmmoType ammoType) { if (campaign.getCampaignOptions().useAmmoByType()) { Predicate<Part> predicate; if (AmmoBin.ALLOWED_BY_TYPE.contains(ammoType.getAmmoType())) { predicate = part -> { return part instanceof AmmoStorage && ammoType.equalsAmmoTypeOnly(((AmmoStorage) part).getType()) && ammoType.getMunitionType() == ((AmmoType) ((AmmoStorage) part).getType()).getMunitionType(); }; } else { predicate = part -> { return part instanceof AmmoStorage && ammoType.equals(((AmmoStorage) part).getType()) && ammoType.getMunitionType() == ((AmmoType) ((AmmoStorage) part).getType()).getMunitionType(); }; } AmmoStorage a = (AmmoStorage) campaign.findSparePart(predicate); return a != null ? a.getShots() : 0; } else { return campaign.streamSpareParts() .filter(part -> part instanceof AmmoStorage && part.isPresent()) .mapToInt(part -> { AmmoStorage a = (AmmoStorage)part; AmmoType aType = (AmmoType)a.getType(); if (aType.equals(ammoType) && (ammoType.getMunitionType() == aType.getMunitionType())) { return a.getShots(); } else if (isCompatibleAmmo(campaign, aType, ammoType) && (ammoType.getRackSize() != 0)) { return (a.getShots() * aType.getRackSize()) / ammoType.getRackSize(); } return 0; }) .sum(); } }
Source:
public boolean isUsingScsiReservation() { return usingScsiReservation; }

Target:
public Boolean isUsingScsiReservation() { return usingScsiReservation; }
Source:
public void verifyQuestionNotPresent(int questionNum) { try { getQuestionResponsesSection(questionNum); throw new RuntimeException("Question " + questionNum + " should not be present."); } catch (NoSuchElementException e) { } }

Target:
public void verifyQuestionNotPresent(int questionNum) { try { getQuestionResponsesSection(questionNum); fail("Question " + questionNum + " should not be present."); } catch (NoSuchElementException e) { } }