auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
TreeMap<Key,Value> consume(SortedKeyValueIterator<Key,Value> skvi, IteratorTestInput testInput) throws IOException { final TreeMap<Key,Value> data = new TreeMap<>(); final Range origRange = testInput.getRange(); int reseekCount = random.nextInt(RESEEK_INTERVAL); int i = 0; while (skvi.hasTop()) { data.put(skvi.getTopKey(), skvi.getTopValue()); if (i % RESEEK_INTERVAL == reseekCount) { Key reSeekStartKey = skvi.getTopKey(); skvi = skvi.deepCopy(new SimpleIteratorEnvironment()); final Range newRange = new Range(reSeekStartKey, false, origRange.getEndKey(), origRange.isEndKeyInclusive()); log.debug("Re-seeking to {}", newRange); skvi.seek(newRange, Collections.<ByteSequence> emptySet(), false); } else { skvi.next(); } i++; } return data; }

Target:
TreeMap<Key,Value> consume(SortedKeyValueIterator<Key,Value> skvi, IteratorTestInput testInput) throws IOException { final TreeMap<Key,Value> data = new TreeMap<>(); final Range origRange = testInput.getRange(); int reseekCount = random.nextInt(RESEEK_INTERVAL); int i = 0; while (skvi.hasTop()) { data.put(skvi.getTopKey(), skvi.getTopValue()); if (i % RESEEK_INTERVAL == reseekCount) { Key reSeekStartKey = skvi.getTopKey(); skvi = IteratorTestUtil.instantiateIterator(testInput); final SortedKeyValueIterator<Key,Value> sourceCopy = IteratorTestUtil.createSource(testInput); skvi.init(sourceCopy, testInput.getIteratorOptions(), new SimpleIteratorEnvironment()); final Range newRange = new Range(reSeekStartKey, false, origRange.getEndKey(), origRange.isEndKeyInclusive()); log.debug("Re-seeking to {}", newRange); skvi.seek(newRange, Collections.<ByteSequence> emptySet(), false); } else { skvi.next(); } i++; } return data; }
Source:
private void initializeInternationalModules(BranchContext context) { if (internationalModuleIds.isEmpty()) { SnomedRequests.prepareSearchConcept() .filterByActive(true) .filterByEcl(String.format("<<%s", SnomedConstants.Concepts.IHTSDO_MAINTAINED_MODULE)) .build() .execute(context) .forEach(concept -> internationalModuleIds.add(concept.getId())); } }

Target:
private void initializeInternationalModules(BranchContext context) { if (internationalModuleIds.isEmpty()) { SnomedRequests.prepareSearchConcept() .all() .filterByActive(true) .filterByEcl(String.format("<<%s", SnomedConstants.Concepts.IHTSDO_MAINTAINED_MODULE)) .build() .execute(context) .forEach(concept -> internationalModuleIds.add(concept.getId())); } }
Source:
public void testLiveDispute() throws IOException, OmiseException { Request<Dispute> request = new Dispute.UpdateRequestBuilder(LIVETEST_DISPUTE) .message("Proofs and other information...") .metadata("description", "DESCRIPTION") .metadata("invoice_id", "inv_N1ayTWJ2FV") .build(); Dispute dispute = client.sendRequest(request, Dispute.class); System.out.println("updated dispute: " + dispute.getId()); assertEquals("DESCRIPTION", dispute.getMetadata().get("description")); assertEquals("inv_N1ayTWJ2FV", dispute.getMetadata().get("invoice_id")); }

Target:
public void testLiveDispute() throws IOException, OmiseException { Request<Dispute> request = new Dispute.UpdateRequestBuilder(LIVETEST_DISPUTE) .message("Proofs and other information...") .metadata("description", "DESCRIPTION") .metadata("invoice_id", "inv_N1ayTWJ2FV") .build(); Dispute dispute = client.sendRequest(request, Dispute.class); System.out.println("updated dispute: " + dispute.getId()); assertEquals(LIVETEST_DISPUTE, dispute.getId()); assertEquals("DESCRIPTION", dispute.getMetadata().get("description")); assertEquals("inv_N1ayTWJ2FV", dispute.getMetadata().get("invoice_id")); }
Source:
public PrefValue<String> surroundSelection() { return string("surround_selection", EDITOR_SURROUND_SELECTION_QUOTES); }

Target:
public PrefValue<String> surroundSelection() { return string("surround_selection", EDITOR_SURROUND_SELECTION_QUOTES_AND_BRACKETS); }
Source:
static void call(ChangeInfo changeInfo, RevisionInfo revisionInfo) { if (ChangeGlue.onSubmitChange(changeInfo, revisionInfo)) { final Change.Id changeId = changeInfo.legacy_id(); if (revisionInfo.commit().otherBranchCommit().equalsIgnoreCase("different branch commit")) { boolean reply = Window .confirm("You are about to merge change from a different branch.\n " + "Do you want to continue?"); if (reply == true) { ChangeApi.submit(changeId.get(), revisionInfo.name(), new GerritCallback<SubmitInfo>() { public void onSuccess(SubmitInfo result) { redisplay(); } public void onFailure(Throwable err) { if (SubmitFailureDialog.isConflict(err)) { new SubmitFailureDialog(err.getMessage()).center(); } else { super.onFailure(err); } redisplay(); } private void redisplay() { Gerrit.display(PageLinks.toChange(changeId)); } }); } else { Gerrit.display(PageLinks.toChange(changeId)); } } else { ChangeApi.submit(changeId.get(), revisionInfo.name(), new GerritCallback<SubmitInfo>() { public void onSuccess(SubmitInfo result) { redisplay(); } public void onFailure(Throwable err) { if (SubmitFailureDialog.isConflict(err)) { new SubmitFailureDialog(err.getMessage()).center(); } else { super.onFailure(err); } redisplay(); } private void redisplay() { Gerrit.display(PageLinks.toChange(changeId)); } }); } } }

Target:
static void call(ChangeInfo changeInfo, RevisionInfo revisionInfo) { if (ChangeGlue.onSubmitChange(changeInfo, revisionInfo)) { final Change.Id changeId = changeInfo.legacy_id(); if (revisionInfo.commit().otherBranchCommit() == true) { boolean reply = Window .confirm("You are about to merge change from a different branch.\n " + "Do you want to continue?"); if (reply == true) { submitChange(changeInfo, revisionInfo); } else { Gerrit.display(PageLinks.toChange(changeId)); } } else { submitChange(changeInfo, revisionInfo); } } }
Source:
protected Point locateOnParent(Point suggestedLocation, int suggestedSide, IFigure borderItem) { Rectangle headerBounds = getParentPackageFigure().getHeader(); if (suggestedSide == PositionConstants.NORTH && !isOnHeader(suggestedLocation, headerBounds)) { setBorderItemOffset(new Dimension(originalBorderItemOffset.width, headerBounds.height)); } else { setBorderItemOffset(originalBorderItemOffset); } Point result = super.locateOnParent(suggestedLocation, suggestedSide, borderItem); setBorderItemOffset(originalBorderItemOffset); return result; }

Target:
protected Point locateOnParent(Point suggestedLocation, int suggestedSide, IFigure borderItem) { PackageFigure parent = getParentPackageFigure(); Rectangle headerBounds = parent == null ? null : parent.getHeader(); if (headerBounds != null && suggestedSide == PositionConstants.NORTH && !isOnHeader(suggestedLocation, headerBounds)) { setBorderItemOffset(new Dimension(originalBorderItemOffset.width, headerBounds.height)); } else { setBorderItemOffset(originalBorderItemOffset); } Point result = super.locateOnParent(suggestedLocation, suggestedSide, borderItem); setBorderItemOffset(originalBorderItemOffset); return result; }
Source:
public boolean startServer() { if (serverStarting) { LOGGER.info("[ws] JabRefWebsocketServer is already starting"); return false; } else if (serverStarted) { LOGGER.info("[ws] JabRefWebsocketServer has already been started"); return false; } else { LOGGER.info("[ws] JabRefWebsocketServer is starting up..."); serverStarting = true; addShutdownHook(); setConnectionLostTimeout(connectionLostTimeoutValue); start(); return true; } }

Target:
public synchronized boolean startServer() { if (serverStarting) { LOGGER.info("[ws] JabRefWebsocketServer is already starting"); return false; } if (serverStarted) { LOGGER.info("[ws] JabRefWebsocketServer has already been started"); return false; } LOGGER.debug("[ws] JabRefWebsocketServer is starting up..."); serverStarting = true; addShutdownHook(); setConnectionLostTimeout(connectionLostTimeoutValue); start(); return true; }
Source:
public void whenOffsetIsCommittedNextSessionStartsFromNextEventAfterCommitted() throws Exception { rangeClosed(0, 3) .forEach(x -> publishEvent(eventType.getName(), "{\"blah\":\"foo" + x + "\"}")); final TestStreamingClient client = TestStreamingClient .create(URL, subscription.getId(), "stream_limit=2") .start(); waitFor(() -> assertThat(client.getBatches(), hasSize(2))); assertThat(client.getBatches().get(0), equalToBatchIgnoringToken(singleEventBatch("0", "0", eventType.getName(), ImmutableMap.of("blah", "foo0"), "Stream started"))); System.out.println(client.getBatches().get(1)); System.out.println(singleEventBatch("0", "1", eventType.getName(), ImmutableMap.of("blah", "foo1"))); assertThat(client.getBatches().get(1), equalToBatchIgnoringToken(singleEventBatch("0", "1", eventType.getName(), ImmutableMap.of("blah", "foo1")))); commitCursors(subscription.getId(), ImmutableList.of(client.getBatches().get(1).getCursor())); waitFor(() -> assertThat(client.isRunning(), is(false))); client.start(); waitFor(() -> assertThat(client.getBatches(), hasSize(2))); assertThat(client.getBatches().get(0), equalToBatchIgnoringToken(singleEventBatch("0", "2", eventType.getName(), ImmutableMap.of("blah", "foo2"), "Stream started"))); assertThat(client.getBatches().get(1), equalToBatchIgnoringToken(singleEventBatch("0", "3", eventType.getName(), ImmutableMap.of("blah", "foo3")))); }

Target:
public void whenOffsetIsCommittedNextSessionStartsFromNextEventAfterCommitted() throws Exception { rangeClosed(0, 3) .forEach(x -> publishEvent(eventType.getName(), "{\"blah\":\"foo" + x + "\"}")); final TestStreamingClient client = TestStreamingClient .create(URL, subscription.getId(), "stream_limit=2") .start(); waitFor(() -> assertThat(client.getBatches(), hasSize(2))); assertThat(client.getBatches().get(0), equalToBatchIgnoringToken(singleEventBatch("0", "0", eventType.getName(), ImmutableMap.of("blah", "foo0"), "Stream started"))); assertThat(client.getBatches().get(1), equalToBatchIgnoringToken(singleEventBatch("0", "1", eventType.getName(), ImmutableMap.of("blah", "foo1")))); commitCursors(subscription.getId(), ImmutableList.of(client.getBatches().get(1).getCursor())); waitFor(() -> assertThat(client.isRunning(), is(false))); client.start(); waitFor(() -> assertThat(client.getBatches(), hasSize(2))); assertThat(client.getBatches().get(0), equalToBatchIgnoringToken(singleEventBatch("0", "2", eventType.getName(), ImmutableMap.of("blah", "foo2"), "Stream started"))); assertThat(client.getBatches().get(1), equalToBatchIgnoringToken(singleEventBatch("0", "3", eventType.getName(), ImmutableMap.of("blah", "foo3")))); }
Source:
protected void onHandleIntent(@Nullable Intent intent) { Log.d(TAG, "Starting File upload service"); resources = getResources(); editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); if (intent != null) { Operation operation = (Operation) intent.getExtras().getSerializable(resources. getString(R.string.intent_extra_operation_object)); try { downloadFile(operation); } catch (AndroidAgentException e) { Log.d(TAG, e.getLocalizedMessage()); } } this.stopSelf(); }

Target:
protected void onHandleIntent(@Nullable Intent intent) { if (Constants.DEBUG_MODE_ENABLED) { Log.d(TAG, "Starting File upload service"); } resources = getResources(); editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); if (intent != null) { Operation operation = (Operation) intent.getExtras().getSerializable(resources. getString(R.string.intent_extra_operation_object)); try { downloadFile(operation); } catch (AndroidAgentException e) { Log.e(TAG, e.getLocalizedMessage()); } } this.stopSelf(); }
Source:
public void longWrite() throws Exception { AlluxioURI filePath = new AlluxioURI(PathUtils.uniqPath()); final int length = 2; try (FileOutStream os = sFileSystem.createFile(filePath, CreateFilePOptions.newBuilder() .setWriteType(mWriteType.toProto()).setRecursive(true).build())) { os.write((byte) 0); Thread.sleep(ServerConfiguration.getMs(PropertyKey.WORKER_BLOCK_HEARTBEAT_INTERVAL_MS)); os.write((byte) 1); } if (mWriteType.getAlluxioStorageType().isStore()) { FileOutStreamTestUtils.checkFileInAlluxio(sFileSystem, filePath, length); } if (mWriteType.getUnderStorageType().isSyncPersist()) { FileOutStreamTestUtils.checkFileInUnderStorage(sFileSystem, filePath, length); } }

Target:
public void longWrite() throws Exception { AlluxioURI filePath = new AlluxioURI(PathUtils.uniqPath()); final int length = 2; try (FileOutStream os = mFileSystem.createFile(filePath, CreateFilePOptions.newBuilder() .setWriteType(mWriteType.toProto()).setRecursive(true).build())) { os.write((byte) 0); Thread.sleep(ServerConfiguration.getMs(PropertyKey.WORKER_BLOCK_HEARTBEAT_INTERVAL_MS) * 2); os.write((byte) 1); } if (mWriteType.getAlluxioStorageType().isStore()) { FileOutStreamTestUtils.checkFileInAlluxio(mFileSystem, filePath, length); } if (mWriteType.getUnderStorageType().isSyncPersist()) { FileOutStreamTestUtils.checkFileInUnderStorage(mFileSystem, filePath, length); } }
Source:
private void reconfigureKafkaConsumer(final boolean forceSeek) { if (eventConsumer == null) { throw new IllegalStateException( "kafkaConsumer should not be null when calling reconfigureKafkaConsumer method"); } final Set<TopicPartition> newAssignment = offsets.keySet().stream() .filter(o -> !this.releasingPartitions.containsKey(o)) .collect(Collectors.toSet()); if (forceSeek) { try { eventConsumer.reassign(Collections.emptyList()); } catch (final NakadiException | InvalidCursorException ex) { throw new NakadiRuntimeException(ex); } } final Set<TopicPartition> currentKafkaAssignment = eventConsumer.getAssignment().stream() .map(tp -> new TopicPartition(tp.getTopic(), String.valueOf(tp.getPartition()))) .collect(Collectors.toSet()); getLog().info("Changing kafka assignment from to {}", Arrays.deepToString(currentKafkaAssignment.toArray()), Arrays.deepToString(newAssignment.toArray())); if (!currentKafkaAssignment.equals(newAssignment)) { try { final Map<TopicPartition, Timeline> temporaryMapping = loadPartitionsMapping(newAssignment); final List<NakadiCursor> cursors = new ArrayList<>(); for (final TopicPartition pk : newAssignment) { final NakadiCursor beforeFirstAvailable = getBeforeFirstCursor(temporaryMapping, pk); offsets.get(pk).ensureDataAvailable(beforeFirstAvailable); cursors.add(offsets.get(pk).getSentOffset()); } eventConsumer.reassign(cursors); } catch (NakadiException | InvalidCursorException ex) { throw new NakadiRuntimeException(ex); } } }

Target:
private void reconfigureKafkaConsumer(final boolean forceSeek) { if (eventConsumer == null) { throw new IllegalStateException( "kafkaConsumer should not be null when calling reconfigureKafkaConsumer method"); } final Set<TopicPartition> newAssignment = offsets.keySet().stream() .filter(o -> !this.releasingPartitions.containsKey(o)) .collect(Collectors.toSet()); if (forceSeek) { try { eventConsumer.reassign(Collections.emptyList()); } catch (final NakadiException | InvalidCursorException ex) { throw new NakadiRuntimeException(ex); } } final Set<TopicPartition> currentAssignment = eventConsumer.getAssignment().stream() .map(tp -> new TopicPartition(tp.getTopic(), String.valueOf(tp.getPartition()))) .collect(Collectors.toSet()); getLog().info("Changing kafka assignment from to {}", Arrays.deepToString(currentAssignment.toArray()), Arrays.deepToString(newAssignment.toArray())); if (!currentAssignment.equals(newAssignment)) { try { final Map<TopicPartition, Timeline> temporaryMapping = loadPartitionsMapping(newAssignment); final List<NakadiCursor> cursors = new ArrayList<>(); for (final TopicPartition pk : newAssignment) { final NakadiCursor beforeFirstAvailable = getBeforeFirstCursor(temporaryMapping, pk); offsets.get(pk).ensureDataAvailable(beforeFirstAvailable); cursors.add(offsets.get(pk).getSentOffset()); } eventConsumer.reassign(cursors); } catch (NakadiException | InvalidCursorException ex) { throw new NakadiRuntimeException(ex); } } }
Source:
public void shutdown() throws Exception { FulltextProvider.instance( db ).close(); }

Target:
public void shutdown() throws Exception { provider.close(); }
Source:
public void run() { Collection<BaragonServiceState> state = stateDatastore.getGlobalState(); int version = stateDatastore.getStateVersion().or(-1); LOG.info("Baragon version: {}", version); for (BaragonStatePersister baragonStatePersister: loader) { baragonStatePersister.persist(state, version); } }

Target:
public void run() { try { Collection<BaragonServiceState> state = stateDatastore.getGlobalState(); Optional<Integer> maybeVersion = stateDatastore.getStateVersion(); if (maybeVersion.isPresent()) { int version = maybeVersion.get(); LOG.info("Baragon version: {}", version); for (BaragonStatePersister baragonStatePersister: loader) { baragonStatePersister.persist(state, version); } } } catch (Exception e) { LOG.error("Caught exception when persisting baragon service state", e); exceptionNotifier.notify(e, null); } }
Source:
public Run<?, ?> resolve(Job<?, ?> job) { File f = getPermalinkFile(job); Run<?,?> b=null; try { String target = readSymlink(f); if (target!=null) { int n = Integer.parseInt(Util.getFileName(target)); if (n==RESOLVES_TO_NONE) return null; b = job.getBuildByNumber(n); if (b!=null && apply(b)) return b; if (b==null) b=job.getNearestOldBuild(n); } } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Failed to read permalink cache:" + f, e); } catch (NumberFormatException e) { LOGGER.log(Level.WARNING, "Failed to parce the buuild number in permalink cache:" + f, e); } catch (IOException e) { } if (b==null) { b = job.getLastBuild(); } b = find(b); updateCache(job,b); return b; }

Target:
public Run<?, ?> resolve(Job<?, ?> job) { File f = getPermalinkFile(job); Run<?,?> b=null; try { String target = readSymlink(f); if (target!=null) { int n = Integer.parseInt(Util.getFileName(target)); if (n==RESOLVES_TO_NONE) return null; b = job.getBuildByNumber(n); if (b!=null && apply(b)) return b; if (b==null) b=job.getNearestOldBuild(n); } } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Failed to read permalink cache:" + f, e); } catch (NumberFormatException e) { LOGGER.log(Level.WARNING, "Failed to parse the build number in the permalink cache:" + f, e); } catch (IOException e) { } if (b==null) { b = job.getLastBuild(); } b = find(b); updateCache(job,b); return b; }
Source:
public void testSinkTaskPutPrimitive() throws Exception { Map<String, String> props = createProps(); HdfsSinkTask task = new HdfsSinkTask(); String key = "key"; Schema schema = Schema.INT32_SCHEMA; int record = 12; Collection<SinkRecord> sinkRecords = new ArrayList<>(); for (TopicPartition tp: assignment) { for (long offset = 0; offset < 7; offset++) { SinkRecord sinkRecord = new SinkRecord(tp.topic(), tp.partition(), Schema.STRING_SCHEMA, key, schema, record, offset); sinkRecords.add(sinkRecord); } } task.initialize(context); task.start(props); task.put(sinkRecords); task.stop(); AvroData avroData = task.getAvroData(); long[] validOffsets = {-1, 2, 5}; for (TopicPartition tp : assignment) { String directory = tp.topic() + "/" + "partition=" + String.valueOf(tp.partition()); for (int j = 1; j < validOffsets.length; ++j) { long startOffset = validOffsets[j - 1] + 1; long endOffset = validOffsets[j]; Path path = new Path(FileUtils.committedFileName(url, topicsDir, directory, tp, startOffset, endOffset, extension, ZERO_PAD_FMT)); Collection<Object> records = schemaFileReader.readData(conf, path); long size = endOffset - startOffset + 1; assertEquals(records.size(), size); for (Object avroRecord : records) { assertEquals(avroRecord, 12); } } } }

Target:
public void testSinkTaskPutPrimitive() throws Exception { Map<String, String> props = createProps(); HdfsSinkTask task = new HdfsSinkTask(); final String key = "key"; final Schema schema = Schema.INT32_SCHEMA; final int record = 12; Collection<SinkRecord> sinkRecords = new ArrayList<>(); for (TopicPartition tp: assignment) { for (long offset = 0; offset < 7; offset++) { SinkRecord sinkRecord = new SinkRecord(tp.topic(), tp.partition(), Schema.STRING_SCHEMA, key, schema, record, offset); sinkRecords.add(sinkRecord); } } task.initialize(context); task.start(props); task.put(sinkRecords); task.stop(); AvroData avroData = task.getAvroData(); long[] validOffsets = {-1, 2, 5}; for (TopicPartition tp : assignment) { String directory = tp.topic() + "/" + "partition=" + String.valueOf(tp.partition()); for (int j = 1; j < validOffsets.length; ++j) { long startOffset = validOffsets[j - 1] + 1; long endOffset = validOffsets[j]; Path path = new Path(FileUtils.committedFileName(url, topicsDir, directory, tp, startOffset, endOffset, extension, ZERO_PAD_FMT)); Collection<Object> records = schemaFileReader.readData(conf, path); long size = endOffset - startOffset + 1; assertEquals(records.size(), size); for (Object avroRecord : records) { assertEquals(avroRecord, record); } } } }
Source:
public ValidationResult validateSpaceRequirements(Collection<DiskImage> diskImages) { MultipleStorageDomainsValidator sdValidator = createMultipleStorageDomainsValidator(diskImages); ValidationResult result = sdValidator.allDomainsExistAndActive(); if (!result.isValid()) { return result; } result = sdValidator.allDomainsWithinThresholds(); if (!result.isValid()) { return result; } if (params.getCopyCollapse()) { return sdValidator.allDomainsHaveSpaceForClonedDisks(diskImages); } result = sdValidator.allDomainsHaveSpaceForDisksWithSnapshots(diskImages); if (!result.isValid()) { return result; } return ValidationResult.VALID; }

Target:
public ValidationResult validateSpaceRequirements(Collection<DiskImage> diskImages) { MultipleStorageDomainsValidator sdValidator = createMultipleStorageDomainsValidator(diskImages); ValidationResult result = sdValidator.allDomainsExistAndActive(); if (!result.isValid()) { return result; } result = sdValidator.allDomainsWithinThresholds(); if (!result.isValid()) { return result; } if (params.getCopyCollapse()) { return sdValidator.allDomainsHaveSpaceForClonedDisks(diskImages); } return sdValidator.allDomainsHaveSpaceForDisksWithSnapshots(diskImages); }
Source:
private void addOptions() { Option help = Option.builder(HELP_SHORT_OPT) .longOpt(HELP_LONG_OPT) .desc(Messages.HELP_DESC) .build(); final Option maxClassLength = addArgument(MAX_CLASS_LENGTH_OPT, Messages.MAX_CLASS_LENGTH_DESC); final Option maxClosureLength = addArgument(MAX_CLOSURE_LENGTH_OPT, Messages.MAX_CLOSURE_LENGTH_DESC); final Option maxFileLength = addArgument(MAX_FILE_LENGTH_OPT, Messages.MAX_FILE_LENGTH_DESC); final Option maxFunctionLength = addArgument(MAX_FUNCTION_LENGTH_OPT, Messages.MAX_FUNCTION_LENGTH_DESC); final Option maxLineLength = addArgument(MAX_LINE_LENGTH_SHORT_OPT, MAX_LINE_LENGTH_LONG_OPT, Messages.MAX_LINE_LENGTH_DESC); final Option maxNameLength = addArgument(MAX_NAME_LENGTH_OPT, Messages.MAX_NAME_LENGTH_DESC); final Option maxStructLength = addArgument(MAX_STRUCT_LENGTH_OPT, Messages.MAX_STRUCT_LENGTH_DESC); final Option maxSeverity = addArgument(MAX_SEVERITY_OPT, Messages.MAX_SEVERITY_DESC); final Option debug = Option.builder(DEBUG_OPT) .desc(Messages.DEBUG_DESC) .build(); options = new Options(); options.addOption(help); options.addOption(maxClassLength); options.addOption(maxClosureLength); options.addOption(maxFileLength); options.addOption(maxFunctionLength); options.addOption(maxLineLength); options.addOption(maxNameLength); options.addOption(maxStructLength); options.addOption(maxSeverity); options.addOption(debug); }

Target:
private void addOptions() { Option help = Option.builder(HELP_SHORT_OPT) .longOpt(HELP_LONG_OPT) .desc(Messages.HELP_DESC) .build(); final Option maxClassLength = addArgument(MAX_CLASS_LENGTH_OPT, Messages.MAX_CLASS_LENGTH_DESC); final Option maxClosureLength = addArgument(MAX_CLOSURE_LENGTH_OPT, Messages.MAX_CLOSURE_LENGTH_DESC); final Option maxFileLength = addArgument(MAX_FILE_LENGTH_OPT, Messages.MAX_FILE_LENGTH_DESC); final Option maxFunctionLength = addArgument(MAX_FUNCTION_LENGTH_OPT, Messages.MAX_FUNCTION_LENGTH_DESC); final Option maxLineLength = addArgument(MAX_LINE_LENGTH_SHORT_OPT, MAX_LINE_LENGTH_LONG_OPT, Messages.MAX_LINE_LENGTH_DESC); final Option maxNameLength = addArgument(MAX_NAME_LENGTH_OPT, Messages.MAX_NAME_LENGTH_DESC); final Option maxStructLength = addArgument(MAX_STRUCT_LENGTH_OPT, Messages.MAX_STRUCT_LENGTH_DESC); final Option maxSeverity = addArgument(MAX_SEVERITY_OPT, Messages.MAX_SEVERITY_DESC); final Option debug = Option.builder() .longOpt(DEBUG_OPT) .desc(Messages.DEBUG_DESC) .build(); options = new Options(); options.addOption(help); options.addOption(maxClassLength); options.addOption(maxClosureLength); options.addOption(maxFileLength); options.addOption(maxFunctionLength); options.addOption(maxLineLength); options.addOption(maxNameLength); options.addOption(maxStructLength); options.addOption(maxSeverity); options.addOption(debug); }
Source:
public void put(PageId pageId, byte[] page) throws IOException { Path p = getFilePath(pageId); if (!Files.exists(p)) { Files.createDirectories(Preconditions.checkNotNull(p.getParent(), "parent")); Files.createFile(p); } try (FileOutputStream fos = new FileOutputStream(p.toFile(), false)) { fos.write(page); } mSize.incrementAndGet(); }

Target:
public void put(PageId pageId, byte[] page) throws IOException { Path p = getFilePath(pageId); if (!Files.exists(p)) { Path parent = Preconditions.checkNotNull(p.getParent(), "parent of cache file should not be null"); Files.createDirectories(parent); Files.createFile(p); } try (FileOutputStream fos = new FileOutputStream(p.toFile(), false)) { fos.write(page); } mSize.incrementAndGet(); }
Source:
public void test_clone_longPath() throws IOException, InterruptedException { testGitClient.clone_().url(workspace.localMirror()).repositoryName("origin").longPath(true).execute(); assertThat("true", is(getConfigValue(workspace.getGitFileDir(), "core.longpaths"))); }

Target:
public void test_clone_longPath() throws IOException, InterruptedException { testGitClient.clone_().url(workspace.localMirror()).repositoryName("origin").longPath(true).execute(); CliGitCommand cmd = new CliGitCommand(testGitClient); assertThat((getConfigValue(cmd, "core.longpaths"))[0], is("true")); }
Source:
private Account updateAccount(String URL, String selector, String name) throws IOException { String response = urlopen.open(URL); Document dResponse = Jsoup.parse(response); List<Transaction> transactions = new ArrayList<>(); String institute = ""; String subInstitute = ""; for (Element e : dResponse.select(selector)) { if (e.hasClass("GroupRow")) { institute = e.children().first().text(); } else if (e.hasClass("GroupMemberRow") || e.hasClass("SubRow")) { Elements elements = e.children(); if (elements.size() == 6) { if (elements.get(2).text().isEmpty()) { } else { transactions.add(new Transaction(elements.get(5).text(), institute + subInstitute + "\n — " + elements.get(1).text(), Helpers.parseBalance(elements.get(2).text()))); subInstitute = ""; } } else if (elements.size() >= 7) { transactions.add(new Transaction(elements.get(6).text(), institute + "\n — " + elements.get(1).text(), Helpers.parseBalance(elements.get(4).text()))); } } } balance = new BigDecimal(0); for (Transaction t : transactions) balance = balance.add(t.getAmount()); Account account = new Account(name, balance, name, Account.REGULAR, ""); account.setTransactions(transactions); return account; }

Target:
private Account updateAccount(String URL, String selector, String name) throws IOException { String response = urlopen.open(URL); Document dResponse = Jsoup.parse(response); List<Transaction> transactions = new ArrayList<>(); String institute = ""; String subInstitute = ""; for (Element e : dResponse.select(selector)) { if (e.hasClass("GroupRow")) { institute = e.children().first().text(); } else if (e.hasClass("GroupMemberRow") || e.hasClass("SubRow")) { Elements elements = e.children(); if (elements.size() == 6) { if (elements.get(2).text().isEmpty()) { } else { transactions.add(new Transaction(elements.get(5).text(), institute + subInstitute + "\n — " + elements.get(1).text(), Helpers.parseBalance(elements.get(2).text()))); subInstitute = ""; } } else if (elements.size() >= 7) { transactions.add(new Transaction(elements.get(6).text(), institute + "\n — " + elements.get(1).text(), Helpers.parseBalance(elements.get(4).text()))); } } } balance = BigDecimal.ZERO; for (Transaction t : transactions) balance = balance.add(t.getAmount()); Account account = new Account(name, balance, name, Account.REGULAR, ""); account.setTransactions(transactions); return account; }
Source:
public String toSparkString(){ return typeDescriptor.toSparkString(); }

Target:
public String toSparkString() { return typeDescriptor.getSQLstring(); }
Source:
public void setProxy() { final String appClass = "org.wikipedia.WikipediaApp"; try { if (useTor()) { WebkitProxy.setProxy(appClass, this, null, PROXY_HOST, PROXY_PORT); } else { WebkitProxy.resetProxy(appClass, this); } } catch (Exception e) { e.printStackTrace(); } }

Target:
public void setProxy() { if (!enableTorToggle()) { return; } final String appClass = getClass().getCanonicalName(); try { if (Prefs.useTor()) { WebkitProxy.setProxy(appClass, this, null, PROXY_HOST, PROXY_PORT); } } catch (Exception e) { e.printStackTrace(); } }
Source:
void init() { entityManager = EntityManagerHolder.getInstance().getThreadLocal().get(); if (entityManager == null) { entityManager = entityManagerFactory.createEntityManager(); EntityManagerHolder.getInstance().getThreadLocal().set(entityManager); } entityName = entityManager.getMetamodel().entity(entityType).getName(); }

Target:
void init() { entityName = em().getMetamodel().entity(entityType).getName(); }
Source:
public ListenableFuture<?> lendPagesSpatialIndex(Supplier<PagesSpatialIndex> pagesSpatialIndex) { requireNonNull(pagesSpatialIndex, "pagesSpatialIndex is null"); if (activeProbeOperators.getFreeFuture().isDone()) { return NOT_BLOCKED; } List<SettableFuture<PagesSpatialIndex>> settableFutures; synchronized (this) { this.pagesSpatialIndex = pagesSpatialIndex; settableFutures = ImmutableList.copyOf(pagesSpatialIndexFutures); pagesSpatialIndexFutures.clear(); } for (SettableFuture<PagesSpatialIndex> settableFuture : settableFutures) { settableFuture.set(pagesSpatialIndex.get()); } return activeProbeOperators.getFreeFuture(); }

Target:
public ListenableFuture<?> lendPagesSpatialIndex(Supplier<PagesSpatialIndex> pagesSpatialIndex) { requireNonNull(pagesSpatialIndex, "pagesSpatialIndex is null"); if (activeProbeOperators.getFreeFuture().isDone()) { return NOT_BLOCKED; } List<SettableFuture<PagesSpatialIndex>> settableFutures; synchronized (this) { verify(this.pagesSpatialIndex == null); this.pagesSpatialIndex = pagesSpatialIndex; settableFutures = ImmutableList.copyOf(pagesSpatialIndexFutures); pagesSpatialIndexFutures.clear(); } for (SettableFuture<PagesSpatialIndex> settableFuture : settableFutures) { settableFuture.set(pagesSpatialIndex.get()); } return activeProbeOperators.getFreeFuture(); }
Source:
private void checkPermissions() { if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1001); } else { int i = 1; } }

Target:
private void checkPermissions() { if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CHECK_PERMISSIONS); } }
Source:
public void traverse() { Transformation transformation = solutionSpace.getTop(); double score = getScore(transformation); Transformation bestTransformation = transformation; double bestScore = score; progress(0d); Map<Long, Double> transformationIDToScore = new HashMap<Long, Double>(); transformationIDToScore.put(transformation.getIdentifier(), score); for (int step = 1; step <= steps; ++step) { LongArrayList list = transformation.getPredecessors(); for (int i = 0; i < list.size(); i++) { long id = list.getQuick(i); if (transformationIDToScore.containsKey(id)) continue; Transformation predecessor = solutionSpace.getTransformation(id); transformationIDToScore.put(id, getScore(predecessor)); } transformationIDToScore.remove(transformation.getIdentifier()); ExponentialMechanism<Long> expMechanism = new ExponentialMechanism<Long>(transformationIDToScore, epsilonSearch / ((double) steps), ExponentialMechanism.defaultPrecision, deterministic); long id = expMechanism.sample(); transformation = solutionSpace.getTransformation(id); score = transformationIDToScore.get(id); if (score > bestScore) { bestTransformation = transformation; bestScore = score; } progress((double)step / (double)steps); } assureChecked(bestTransformation); }

Target:
public void traverse() { Transformation pivot = solutionSpace.getTop(); double score = getScore(pivot); Transformation bestTransformation = pivot; double bestScore = score; progress(0d); Map<Long, Double> transformationIDToScore = new HashMap<Long, Double>(); transformationIDToScore.put(pivot.getIdentifier(), score); for (int step = 1; step <= steps; ++step) { LongArrayList list = pivot.getPredecessors(); for (int i = 0; i < list.size(); i++) { long id = list.getQuick(i); if (transformationIDToScore.containsKey(id)) continue; Transformation predecessor = solutionSpace.getTransformation(id); transformationIDToScore.put(id, getScore(predecessor)); } transformationIDToScore.remove(pivot.getIdentifier()); ExponentialMechanism<Long> expMechanism = new ExponentialMechanism<Long>(transformationIDToScore, epsilonSearch / ((double) steps), ExponentialMechanism.defaultPrecision, deterministic); long id = expMechanism.sample(); pivot = solutionSpace.getTransformation(id); score = transformationIDToScore.get(id); if (score > bestScore) { bestTransformation = pivot; bestScore = score; } progress((double)step / (double)steps); } assureChecked(bestTransformation); }
Source:
public void apply(Project project) { project.getPluginManager().withPlugin("java", plugin -> { JniExtension jniExtension = project.getExtensions().create("jni", JniExtension.class); jniExtension.getGeneratedHeadersDirectory().convention(project.getLayout().getBuildDirectory().dir("generated/jni-headers")); JniCompilerArguments compilerArguments = new JniCompilerArguments(jniExtension.getGeneratedHeadersDirectory()); TaskContainer tasks = project.getTasks(); TaskProvider<JavaCompile> compileJavaProvider = tasks.named("compileJava", JavaCompile.class); RemoveGeneratedNativeHeaders removeGeneratedNativeHeaders = project.getObjects().newInstance(RemoveGeneratedNativeHeaders.class, compilerArguments.getGeneratedHeadersDirectory()); configureCompileJava(compilerArguments, removeGeneratedNativeHeaders, compileJavaProvider); configureIncludePath( tasks, compileJavaProvider.map(compileJava -> compilerArguments.getGeneratedHeadersDirectory()) ); }); }

Target:
public void apply(Project project) { project.getPluginManager().withPlugin("java", plugin -> { JniExtension jniExtension = project.getExtensions().create("jni", JniExtension.class); jniExtension.getGeneratedHeadersDirectory().convention(project.getLayout().getBuildDirectory().dir("generated/jni-headers")); JniCompilerArguments compilerArguments = new JniCompilerArguments(jniExtension.getGeneratedHeadersDirectory()); TaskContainer tasks = project.getTasks(); TaskProvider<JavaCompile> compileJavaProvider = tasks.named("compileJava", JavaCompile.class); RemoveGeneratedNativeHeaders removeGeneratedNativeHeaders = project.getObjects().newInstance(RemoveGeneratedNativeHeaders.class, compilerArguments.getGeneratedHeadersDirectory()); configureCompileJava(compilerArguments, removeGeneratedNativeHeaders, compileJavaProvider); configureIncludePath( tasks, compilerArguments.getGeneratedHeadersDirectory(), compileJavaProvider ); }); }
Source:
private Properties buildKafkaProperties(final List<Broker> brokers) { final Properties props = new Properties(); props.put("bootstrap.servers", buildBootstrapServers(brokers)); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArrayDeserializer"); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArrayDeserializer"); return props; }

Target:
private Properties buildKafkaProperties(final List<Broker> brokers) { final Properties props = new Properties(); props.put("bootstrap.servers", buildBootstrapServers(brokers)); return props; }
Source:
public LeaseExpirationTimer(Supplier<NanoTime> clock) { this.clock = clock; this.lastRefreshTime = new AtomicReference<>(clock.get()); }

Target:
public LeaseExpirationTimer(Supplier<NanoTime> clock) { this.clock = clock; this.lastRefreshTime = clock.get(); }
Source:
private static ArrayList<Unit> unitList(final Unit... units) { return new ArrayList<Unit>(List.of(units)); }

Target:
private static ArrayList<Unit> unitList(final Unit... units) { return new ArrayList<>(List.of(units)); }
Source:
protected Connection connection() { if (conn == null && connProvider != null) { conn = connProvider.get(); } return conn; }

Target:
protected Connection connection() { if (conn == null) { if (connProvider != null) { conn = connProvider.get(); } else { throw new IllegalStateException("No connection provided"); } } return conn; }
Source:
static WeightedTerm parseVectorElement(String vectorElement) { Matcher match = TERM_PATTERN.matcher(vectorElement); if (match.find()) { String text = match.group(1); int value = Integer.parseInt(match.group(2)); return new WeightedTerm(text, value); } else { throw new RuntimeException(); } }

Target:
static WeightedTerm parseVectorElement(String vectorElement) { Matcher match = TERM_PATTERN.matcher(vectorElement); if (match.find()) { String text = match.group(1); int value = Integer.parseInt(match.group(2)); return new WeightedTerm(text, value); } else { throw new TaxonomyRemoteServiceInvalidBehaviorException("Invalid syntax: " + vectorElement); } }
Source:
public void close() throws ProcessorStateException { unregisterAllStoresWithChangelogReader(); RuntimeException firstException = null; if (!stores.isEmpty()) { log.debug("Closing its state manager and all the registered state stores: {}", stores); for (final Map.Entry<String, StateStoreMetadata> entry : stores.entrySet()) { final StateStore store = entry.getValue().stateStore; log.trace("Closing store {}", store.name()); try { store.close(); } catch (final RuntimeException exception) { if (firstException == null) { if (exception instanceof StreamsException) firstException = exception; else firstException = new ProcessorStateException( format("%sFailed to close state store %s", logPrefix, store.name()), exception); } log.error("Failed to close state store {}: ", store.name(), exception); } } stores.clear(); } if (firstException != null) { throw firstException; } }

Target:
public void close() throws ProcessorStateException { log.debug("Closing its state manager and all the registered state stores: {}", stores); changelogReader.unregister(getAllChangelogTopicPartitions(), false); RuntimeException firstException = null; if (!stores.isEmpty()) { for (final Map.Entry<String, StateStoreMetadata> entry : stores.entrySet()) { final StateStore store = entry.getValue().stateStore; log.trace("Closing store {}", store.name()); try { store.close(); } catch (final RuntimeException exception) { if (firstException == null) { if (exception instanceof StreamsException) firstException = exception; else firstException = new ProcessorStateException( format("%sFailed to close state store %s", logPrefix, store.name()), exception); } log.error("Failed to close state store {}: ", store.name(), exception); } } stores.clear(); } if (firstException != null) { throw firstException; } }
Source:
public synchronized void dispose() { synchronized (this) { if (fFileInput != null) { try { fFileInput.close(); } catch (IOException e) { Activator.getInstance().logError("Error disposing trace. File: " + getPath(), e); } } } super.dispose(); }

Target:
public synchronized void dispose() { if (fFileInput != null) { try { fFileInput.close(); } catch (IOException e) { Activator.getInstance().logError("Error disposing trace. File: " + getPath(), e); } } super.dispose(); }
Source:
private void askAddToIndex(final String path, final String fileName) { final ProjectConfigDto project = appContext.getCurrentProject().getRootProject(); Map<String, List<String>> attributes = project.getAttributes(); if (!(attributes.containsKey("vcs.provider.name") && attributes.get("vcs.provider.name").contains("git"))) { return; } ConfirmCallback confirmCallback = new ConfirmCallback() { @Override public void accepted() { String filePath = path.substring(project.getName().length() + 2); try { gitServiceClient .add(project, false, Collections.singletonList(filePath), new RequestCallback<Void>() { @Override protected void onSuccess(Void result) { notificationManager .notify("Git", localizationConstant.actionNewFileAddToIndexNotification(fileName)); } @Override protected void onFailure(Throwable exception) { notificationManager.notify("Git", exception.getMessage()); } }); } catch (WebSocketException e) { e.printStackTrace(); } } }; CancelCallback cancelCallback = new CancelCallback() { @Override public void cancelled() { } }; dialogFactory.createConfirmDialog(localizationConstant.actionNewFileAddToIndexTitle(), localizationConstant.actionNewFileAddToIndexText(fileName), confirmCallback, cancelCallback).show(); }

Target:
private void askAddToIndex(final String path, final String fileName) { final ProjectConfigDto project = appContext.getCurrentProject().getRootProject(); Map<String, List<String>> attributes = project.getAttributes(); if (!(attributes.containsKey("vcs.provider.name") && attributes.get("vcs.provider.name").contains("git"))) { return; } ConfirmCallback confirmCallback = new ConfirmCallback() { @Override public void accepted() { String filePath = path.substring(project.getName().length() + 2); try { gitServiceClient .add(project, false, Collections.singletonList(filePath), new RequestCallback<Void>() { @Override protected void onSuccess(Void result) { notificationManager .notify(localizationConstant.actionNewFileAddToIndexNotification(fileName)); } @Override protected void onFailure(Throwable exception) { notificationManager.notify(exception.getMessage()); } }); } catch (WebSocketException e) { e.printStackTrace(); } } }; CancelCallback cancelCallback = new CancelCallback() { @Override public void cancelled() { } }; dialogFactory.createConfirmDialog(localizationConstant.actionNewFileAddToIndexTitle(), localizationConstant.actionNewFileAddToIndexText(fileName), confirmCallback, cancelCallback).show(); }
Source:
private void addClearButton(Context context, boolean show) { clearButton = new Button(context); clearButton.setText(Localization.get("button.clear.title")); setStyle(context, clearButton); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParams.gravity = Gravity.END; clearButton.setLayoutParams(layoutParams); clearButton.setPadding(10, 10, 10, 10); clearButton.setVisibility(show ? VISIBLE : GONE); clearButton.setOnClickListener(view -> { clearAnswer(); widgetEntryChanged(); }); addView(clearButton); }

Target:
private void addClearButton(Context context, boolean show) { clearButton = (Button) LayoutInflater.from(context).inflate(R.layout.blue_outlined_button, this, false); clearButton.setText(Localization.get("button.clear.title")); clearButton.setVisibility(show ? VISIBLE : GONE); clearButton.setOnClickListener(view -> { clearAnswer(); widgetEntryChanged(); }); addView(clearButton); }
Source:
public Collection<SingularityTaskShellCommandUpdate> getShellCommandUpdates(SingularityTaskShellCommandRequest shellCommandRequest) { final Function<String, String> requestUri = (host) -> String.format(SHELL_COMMAND_UPDATES_FORMAT, getApiBase(host), shellCommandRequest.getTaskId(), shellCommandRequest.getShellCommand().getName(), shellCommandRequest.getTimestamp()); return getCollection(requestUri, "get shell command history", SHELL_COMMAND_UPDATES); }

Target:
public Collection<SingularityTaskShellCommandUpdate> getShellCommandUpdates(SingularityTaskShellCommandRequest shellCommandRequest) { final Function<String, String> requestUri = (host) -> String.format(SHELL_COMMAND_UPDATES_FORMAT, getApiBase(host), shellCommandRequest.getTaskId(), shellCommandRequest.getShellCommand().getName(), shellCommandRequest.getTimestamp()); return getCollection(requestUri, "get shell command update history", SHELL_COMMAND_UPDATES); }
Source:
public static TaskRunner getTaskRunnerFromTaskType(TaskType taskType) { TaskRunner taskRunner = null; switch (taskType) { case DATA_QUALITY: taskRunner = new DataQualityPipelineTaskRunner(); break; case DETECTION: taskRunner = new DetectionPipelineTaskRunner(); break; case DETECTION_ALERT: taskRunner = new DetectionAlertTaskRunner(); break; case YAML_DETECTION_ONBOARD: taskRunner = new YamlOnboardingTaskRunner(); break; case ANOMALY_DETECTION: taskRunner = new DetectionTaskRunner(); break; case MERGE: break; case MONITOR: taskRunner = new MonitorTaskRunner(); break; default: } return taskRunner; }

Target:
public static TaskRunner getTaskRunnerFromTaskType(TaskType taskType) { TaskRunner taskRunner = null; switch (taskType) { case DATA_QUALITY: taskRunner = new DataQualityPipelineTaskRunner(); break; case DETECTION: taskRunner = new DetectionPipelineTaskRunner(); break; case DETECTION_ALERT: taskRunner = new DetectionAlertTaskRunner(); break; case YAML_DETECTION_ONBOARD: taskRunner = new YamlOnboardingTaskRunner(); break; case MONITOR: taskRunner = new MonitorTaskRunner(); break; default: } return taskRunner; }
Source:
protected void postSaveAction(Guid networkGuid, boolean succeeded) { super.postSaveAction(networkGuid, succeeded); if (!succeeded) { return; } Guid networkId = getNetwork().getId() == null ? networkGuid : getNetwork().getId(); ArrayList<VdcActionParametersBase> actionParameters1 = new ArrayList<VdcActionParametersBase>(); for (NetworkClusterModel networkClusterModel : getClustersToAttach()) { Network tempVar = new Network(); tempVar.setId(networkId); tempVar.setName(getNetwork().getName()); NetworkCluster networkCluster = new NetworkCluster(); networkCluster.setRequired(networkClusterModel.isRequired()); tempVar.setCluster(networkCluster); actionParameters1.add(new AttachNetworkToVdsGroupParameter(networkClusterModel.getEntity(), tempVar)); } Frontend.getInstance().runMultipleAction(VdcActionType.AttachNetworkToVdsGroup, actionParameters1); if ((Boolean) getExport().getEntity() && getSubnetModel().getName().getEntity() != null && !getSubnetModel().getName().getEntity().isEmpty()) { getSubnetModel().setExternalNetwork(getNetwork().getProvidedBy()); getSubnetModel().flush(); Frontend.getInstance().runAction(VdcActionType.AddSubnetToProvider, new AddExternalSubnetParameters(getSubnetModel().getSubnet(), networkId)); } }

Target:
protected void postSaveAction(Guid networkGuid, boolean succeeded) { super.postSaveAction(networkGuid, succeeded); if (!succeeded) { return; } Guid networkId = getNetwork().getId() == null ? networkGuid : getNetwork().getId(); ArrayList<VdcActionParametersBase> actionParameters1 = new ArrayList<VdcActionParametersBase>(); for (NetworkClusterModel networkClusterModel : getClustersToAttach()) { Network tempVar = new Network(); tempVar.setId(networkId); tempVar.setName(getNetwork().getName()); NetworkCluster networkCluster = new NetworkCluster(); networkCluster.setRequired(networkClusterModel.isRequired()); tempVar.setCluster(networkCluster); actionParameters1.add(new AttachNetworkToVdsGroupParameter(networkClusterModel.getEntity(), tempVar)); } Frontend.getInstance().runMultipleAction(VdcActionType.AttachNetworkToVdsGroup, actionParameters1); if ((Boolean) getExport().getEntity() && StringUtils.isNotEmpty(getSubnetModel().getCidr().getEntity())) { getSubnetModel().setExternalNetwork(getNetwork().getProvidedBy()); getSubnetModel().flush(); Frontend.getInstance().runAction(VdcActionType.AddSubnetToProvider, new AddExternalSubnetParameters(getSubnetModel().getSubnet(), networkId)); } }