auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { System.out.println("Running DownloadMediaUseCase"); IFileDownloader.Callback callback = new IFileDownloader.Callback() { @Override public void onError(FileDownloadException ex) { mCallback.onError(ex); } @Override public void onSuccess(List<Media> syncMedias) { int numOfSyncedFiles = saveDownloadedMedia(syncMedias); List<Media> allMedias = mMediaRepository.getAll(); removeNotDownloadedMedia(syncMedias, allMedias); mCallback.onSuccess(numOfSyncedFiles); } }; List<Media> medias = mFileDownloader.init( PreferencesState.getInstance().getDriveRootFolderUid(), mProgramRepository.getUserProgram().getId(), callback); if (medias != null && !medias.isEmpty()) { if (mConnectivityManager.isDeviceOnline()) { mFileDownloader.download(medias, callback); } else { System.out.println(this.getClass().getSimpleName() + ": No wifi connection available. Media will not be synced"); } } }

Target:
public void run() { System.out.println("Running DownloadMediaUseCase"); final List<Media> currentMedias = mMediaRepository.getAll(); if (mConnectivityManager.isDeviceOnline()) { mFileDownloader.download(currentMedias, PreferencesState.getInstance().getDriveRootFolderUid(), mProgramRepository.getUserProgram().getCode(), new IFileDownloader.Callback() { @Override public void onError(FileDownloadException ex) { mCallback.onError(ex); } @Override public void onSuccess(List<Media> syncMedias) { int numOfSyncedFiles = saveDownloadedMedia(syncMedias); removeNotDownloadedMedia(syncMedias, currentMedias); mCallback.onSuccess(numOfSyncedFiles); } }); } else { System.out.println(this.getClass().getSimpleName() + ": No wifi connection available. Media will not be synced"); } }
Source:
@Override public int getTotalNodes() { IntMetricImpl totalNodes = sysreg.intMetric("TotalNodes", null); totalNodes.add(1); return totalNodes.value(); }

Target:
@Override public int getTotalNodes() { return 1; }
Source:
public void abandon(AbandonInput in) throws RestApiException { try { abandon.get().apply(change, in); } catch (OrmException e) { throw new RestApiException("Cannot abandon change", e); } catch (IOException e) { throw new RestApiException("Cannot abandon review", e); } }

Target:
public void abandon(AbandonInput in) throws RestApiException { try { abandon.get().apply(change, in); } catch (OrmException e) { throw new RestApiException("Cannot abandon change", e); } catch (IOException e) { throw new RestApiException("Cannot abandon change", e); } }
Source:
static String camelize(String s, boolean upper) { if (StringUtils.contains(s, '_')) { StringBuilder builder = new StringBuilder(); for (String part : StringUtils.split(s, '_')) { builder.append(StringUtils.capitalize(StringUtils.lowerCase(part))); } s = builder.toString(); } else if (StringUtils.isAllUpperCase(s)) { s = StringUtils.lowerCase(s); } else { StringBuilder builder = new StringBuilder(); for (String part : StringUtils.splitByCharacterTypeCamelCase(s)) { builder.append(StringUtils.capitalize(StringUtils.lowerCase(part))); } s = builder.toString(); } if (upper) { return StringUtils.capitalize(s); } else { return StringUtils.uncapitalize(s); } }

Target:
static String camelize(String s, boolean upper) { if (StringUtils.contains(s, '_')) { StringBuilder builder = new StringBuilder(); for (String part : StringUtils.split(StringUtils.lowerCase(s), '_')) { builder.append(StringUtils.capitalize(part)); } s = builder.toString(); if (upper) { return StringUtils.capitalize(s); } else { return StringUtils.uncapitalize(s); } } StringBuilder builder = new StringBuilder(); String[] parts = StringUtils.splitByCharacterTypeCamelCase(s); if (StringUtils.isAllUpperCase(parts[0]) && upper) { builder.append(parts[0]); } else if (upper) { builder.append(StringUtils.capitalize(StringUtils.lowerCase(parts[0]))); } else { builder.append(StringUtils.lowerCase(parts[0])); } for (String part : ArrayUtils.subarray(parts, 1, parts.length)) { if (StringUtils.isAllUpperCase(part)) { builder.append(part); } else { builder.append(StringUtils.capitalize(StringUtils.lowerCase(part))); } } return builder.toString(); }
Source:
public void pullTest() throws Exception { String jsFileName = "app.js"; String htmlFileName = "file.html"; String readmeTxtFileName = "readme-txt"; String folderWithPlainFilesPath = "plain-files"; String currentTimeInMillis = Long.toString(System.currentTimeMillis()); projectExplorer.waitProjectExplorer(); git.importJavaApp(testRepo.getHtmlUrl(), PROJECT_NAME, BLANK); prepareFilesForTest(jsFileName); prepareFilesForTest(htmlFileName); prepareFilesForTest(folderWithPlainFilesPath + "/" + readmeTxtFileName); prepareFilesForTest(folderWithPlainFilesPath + "/README.md"); testRepo.changeFileContent(jsFileName, currentTimeInMillis); testRepo.changeFileContent(htmlFileName, currentTimeInMillis); testRepo.changeFileContent( String.format("%s/%s", folderWithPlainFilesPath, readmeTxtFileName), currentTimeInMillis); performPull(); git.waitGitStatusBarWithMess( String.format("Successfully pulled from %s", testRepo.getHtmlUrl())); checkPullAfterUpdatingContent(readmeTxtFileName, currentTimeInMillis); checkPullAfterUpdatingContent(htmlFileName, currentTimeInMillis); checkPullAfterUpdatingContent(readmeTxtFileName, currentTimeInMillis); testRepo.deleteFolder(Paths.get(folderWithPlainFilesPath), "remove file"); performPull(); notificationsPopupPanel.waitPopupPanelsAreClosed(); checkPullAfterRemovingContent( readmeTxtFileName, String.format("/%s/%s/%s", PROJECT_NAME, folderWithPlainFilesPath, readmeTxtFileName)); checkPullAfterRemovingContent( "README.md", String.format("/%s/%s/%s", PROJECT_NAME, folderWithPlainFilesPath, "README.md")); }

Target:
public void pullTest() throws Exception { String jsFileName = "app.js"; String htmlFileName = "file.html"; String readmeTxtFileName = "readme-txt"; String readmeMdFileName = "README.md"; String folderWithPlainFilesPath = "plain-files"; String currentTimeInMillis = Long.toString(System.currentTimeMillis()); projectExplorer.waitProjectExplorer(); git.importJavaApp(testRepo.getHtmlUrl(), PROJECT_NAME, BLANK); prepareFilesForTest(jsFileName); prepareFilesForTest(htmlFileName); prepareFilesForTest(folderWithPlainFilesPath + "/" + readmeTxtFileName); prepareFilesForTest(folderWithPlainFilesPath + "/" + readmeMdFileName); testRepo.changeFileContent(jsFileName, currentTimeInMillis); testRepo.changeFileContent(htmlFileName, currentTimeInMillis); testRepo.changeFileContent( String.format("%s/%s", folderWithPlainFilesPath, readmeTxtFileName), currentTimeInMillis); performPull(); git.waitGitStatusBarWithMess( String.format("Successfully pulled from %s", testRepo.getHtmlUrl())); checkPullAfterUpdatingContent(readmeTxtFileName, currentTimeInMillis); checkPullAfterUpdatingContent(htmlFileName, currentTimeInMillis); checkPullAfterUpdatingContent(readmeTxtFileName, currentTimeInMillis); testRepo.deleteFolder(Paths.get(folderWithPlainFilesPath), "remove file"); performPull(); notificationsPopupPanel.waitPopupPanelsAreClosed(); checkPullAfterRemovingContent( readmeTxtFileName, String.format("/%s/%s/%s", PROJECT_NAME, folderWithPlainFilesPath, readmeTxtFileName)); checkPullAfterRemovingContent( "README.md", String.format("/%s/%s/%s", PROJECT_NAME, folderWithPlainFilesPath, readmeMdFileName)); }
Source:
protected void executeCommand() { storage_pool_iso_map domainPoolMap = TransactionSupport.executeInNewTransaction( new TransactionMethod<storage_pool_iso_map>() { @Override public storage_pool_iso_map runInTransaction() { storage_pool_iso_map domainPoolMap = new storage_pool_iso_map(getRecoveryStoragePoolParametersData() .getNewMasterDomainId(), getRecoveryStoragePoolParametersData().getStoragePoolId(), StorageDomainStatus.Active); DbFacade.getInstance().getStoragePoolIsoMapDao().save(domainPoolMap); return domainPoolMap; } }); getStoragePool().setstatus(StoragePoolStatus.Problematic); try { if (StorageHelperDirector.getInstance().getItem(getStorageDomain().getstorage_type()) .ConnectStorageToDomainByVdsId(getNewMaster(false), getVds().getId())) { super.executeCommand(); } else { getReturnValue().setFault(new VdcFault(new VdcBLLException(VdcBllErrors.StorageServerConnectionError, "Failed to connect storage"), VdcBllErrors.StorageServerConnectionError)); } } finally { if (!reconstructOpsSucceeded) { getCompensationContext().snapshotNewEntity(domainPoolMap); getCompensationContext().stateChanged(); } } }

Target:
protected void executeCommand() { storage_pool_iso_map domainPoolMap = TransactionSupport.executeInNewTransaction( new TransactionMethod<storage_pool_iso_map>() { @Override public storage_pool_iso_map runInTransaction() { storage_pool_iso_map domainPoolMap = new storage_pool_iso_map(getRecoveryStoragePoolParametersData() .getNewMasterDomainId(), getRecoveryStoragePoolParametersData().getStoragePoolId(), StorageDomainStatus.Active); DbFacade.getInstance().getStoragePoolIsoMapDao().save(domainPoolMap); return domainPoolMap; } }); getStoragePool().setstatus(StoragePoolStatus.Problematic); try { if (StorageHelperDirector.getInstance().getItem(getStorageDomain().getstorage_type()) .ConnectStorageToDomainByVdsId(getNewMaster(false), getVds().getId())) { super.executeCommand(); } else { getReturnValue().setFault(new VdcFault(new VdcBLLException(VdcBllErrors.StorageServerConnectionError, "Failed to connect storage"), VdcBllErrors.StorageServerConnectionError)); } } finally { if (!reconstructOpsSucceeded) { DbFacade.getInstance().getStoragePoolIsoMapDao().remove(new StoragePoolIsoMapId(getRecoveryStoragePoolParametersData() .getNewMasterDomainId(), getRecoveryStoragePoolParametersData().getStoragePoolId())); } } }
Source:
private void configureLanguageSelection(Preferences preferences) { languageComboBox.setItems(FXCollections.observableArrayList(LanguageInfo.getAllDisplayNames())); String language = preferences.getLanguage().getLanguage(); languageComboBox.getSelectionModel().select(LanguageInfo.getIndexByLanguageCode(language)); languageComboBox.setDisable(false); languageComboBox.setOnAction(event -> onLanguageSelected(preferences)); }

Target:
private void configureLanguageSelection(Preferences preferences) { languageComboBox.setButtonCell(new StringListCell<>(languageInfo -> i18n.get(languageInfo.getDisplayNameKey()))); languageComboBox.setCellFactory(param -> new StringListCell<>(languageInfo -> i18n.get(languageInfo.getDisplayNameKey()))); languageComboBox.setItems(FXCollections.observableArrayList(LanguageInfo.values())); LanguageInfo languageInfo = preferences.getLocalization().getLanguage(); languageComboBox.getSelectionModel().select(languageInfo.ordinal()); }
Source:
public void adsTrackingOptOutOasis() { networkTrafficInterceptor.startIntercepting(); Boolean noKikimoraRequestFound = false; Boolean noKruxRequestFound = false; String url = appendTrackingOptOutParameters(urlBuilder.getUrlForPage(new Page(TEST_WIKI, TEST_PAGE))); AdsBaseObject adsBaseObject = new AdsBaseObject(driver, url); try { adsBaseObject.wait.forSuccessfulResponseByUrlPattern(networkTrafficInterceptor, KIKIMORA_PATTERN); } catch (TimeoutException exception) { noKikimoraRequestFound = true; } try { adsBaseObject.wait.forSuccessfulResponseByUrlPattern(networkTrafficInterceptor, KRUX_PATTERN); } catch (TimeoutException exception) { noKruxRequestFound = true; } assertTrue(noKikimoraRequestFound); assertTrue(noKruxRequestFound); }

Target:
public void adsTrackingOptOutOasis() { networkTrafficInterceptor.startIntercepting(); Boolean noKikimoraRequestFound = false; Boolean noKruxRequestFound = false; String url = appendTrackingOptOutParameters(urlBuilder.getUrlForPage(new Page(TEST_WIKI, TEST_PAGE))); AdsBaseObject adsBaseObject = new AdsBaseObject(driver, url); try { adsBaseObject.wait.forSuccessfulResponseByUrlPattern(networkTrafficInterceptor, KIKIMORA_PATTERN); } catch (TimeoutException exception) { noKikimoraRequestFound = true; } try { adsBaseObject.wait.forSuccessfulResponseByUrlPattern(networkTrafficInterceptor, KRUX_PATTERN); } catch (TimeoutException exception) { noKruxRequestFound = true; } Assertion.assertTrue( noKikimoraRequestFound, "Kikimora tracking is not disabled, request to Data Warehouse was found" ); Assertion.assertTrue( noKruxRequestFound, "Krux tracking is not disabled, request to Krux services was found" ); }
Source:
long gtk_draw (long widget, long cairo) { boolean overlayScrolling = !OS.GTK_OVERLAY_SCROLLING_DISABLED && GTK.GTK_VERSION >= OS.VERSION(3, 16, 0); if (OS.G_OBJECT_TYPE(widget) == OS.swt_fixed_get_type() && overlayScrolling) { if ((style & SWT.V_SCROLL) != 0) { GtkAllocation verticalBarAlloc = new GtkAllocation (); GTK.gtk_widget_get_allocation(getVerticalBar().handle, verticalBarAlloc); GdkRectangle r2 = new GdkRectangle (); GDK.gdk_cairo_get_clip_rectangle (cairo, r2); if (r2.width == verticalBarAlloc.width && r2.height == verticalBarAlloc.height) { return 0; } } if ((style & SWT.H_SCROLL) != 0) { GtkAllocation horizontalBarAlloc = new GtkAllocation (); GTK.gtk_widget_get_allocation(getVerticalBar().handle, horizontalBarAlloc); GdkRectangle r2 = new GdkRectangle (); GDK.gdk_cairo_get_clip_rectangle (cairo, r2); if (r2.width == horizontalBarAlloc.width && r2.height == horizontalBarAlloc.height) { return 0; } } } return super.gtk_draw(widget, cairo); }

Target:
long gtk_draw (long widget, long cairo) { boolean overlayScrolling = !OS.GTK_OVERLAY_SCROLLING_DISABLED && GTK.GTK_VERSION >= OS.VERSION(3, 16, 0); if (overlayScrolling && OS.G_OBJECT_TYPE(widget) == OS.swt_fixed_get_type()) { if ((style & SWT.V_SCROLL) != 0 && verticalBar != null) { GtkAllocation verticalBarAlloc = new GtkAllocation(); GTK.gtk_widget_get_allocation(verticalBar.handle, verticalBarAlloc); GdkRectangle rect = new GdkRectangle(); GDK.gdk_cairo_get_clip_rectangle(cairo, rect); if (rect.width == verticalBarAlloc.width && rect.height == verticalBarAlloc.height) { return 0; } } if ((style & SWT.H_SCROLL) != 0 && horizontalBar != null) { GtkAllocation horizontalBarAlloc = new GtkAllocation(); GTK.gtk_widget_get_allocation(horizontalBar.handle, horizontalBarAlloc); GdkRectangle rect = new GdkRectangle(); GDK.gdk_cairo_get_clip_rectangle(cairo, rect); if (rect.width == horizontalBarAlloc.width && rect.height == horizontalBarAlloc.height) { return 0; } } } return super.gtk_draw(widget, cairo); }
Source:
public void run(ProgressMonitor pm) { activeFilter.initialise(pm,source); IntegerUnion nextViewSelection = new IntegerUnion(); int rowCount = table.getRowCount(); pm.startTask(getTaskName(), 100); for(int viewId=0;viewId<rowCount;viewId++) { if(activeFilter.isSelected(table.getRowSorter().convertRowIndexToModel(viewId), source)) { nextViewSelection.add(viewId); pm.progressTo(viewId / rowCount * 100); if(pm.isCancelled()) { return; } } } pm.endTask(); Iterator<Integer> intervals = nextViewSelection.getValueRanges().iterator(); try { table.getSelectionModel().setValueIsAdjusting(true); table.clearSelection(); while(intervals.hasNext()) { int begin = intervals.next(); int end = intervals.next(); table.addRowSelectionInterval(begin, end); if(pm.isCancelled()) { return; } } }finally { table.getSelectionModel().setValueIsAdjusting(false); } }

Target:
public void run(ProgressMonitor pm) { try { runFilter(pm); } finally { filterRunning.set(false); } }
Source:
public ConnectorPageSource createPageSource(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorSplit split, List<ColumnHandle> columns) { requireNonNull(split, "partitionChunk is null"); PinotSplit pinotSplit = checkType(split, PinotSplit.class, "split"); checkArgument(pinotSplit.getConnectorId().equals(connectorId), "split is not for this connector"); List<PinotColumnHandle> handles = new ArrayList<>(); if (columns.isEmpty()) { handles.add(new PinotColumnHandle(this.connectorId, pinotSplit.getTimeColumn().getName(), pinotSplit.getTimeColumn().getType(), 0)); } else { for (ColumnHandle handle : columns) { handles.add(checkType(handle, PinotColumnHandle.class, "handle")); } } return new PinotPageSource(this.pinotConfig, this.pinotQueryClient, pinotSplit, handles); }

Target:
public ConnectorPageSource createPageSource(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorSplit split, List<ColumnHandle> columns) { requireNonNull(split, "partitionChunk is null"); PinotSplit pinotSplit = checkType(split, PinotSplit.class, "split"); ImmutableList.Builder<PinotColumnHandle> handlesBuilder = ImmutableList.builder(); if (columns.isEmpty()) { handlesBuilder.add(new PinotColumnHandle(pinotSplit.getTimeColumn().getName(), pinotSplit.getTimeColumn().getType(), 0)); } else { columns.forEach(handle -> handlesBuilder.add(checkType(handle, PinotColumnHandle.class, "handle"))); } return new PinotPageSource(pinotConfig, pinotQueryClient, pinotSplit, handlesBuilder.build()); }
Source:
public AsyncJobStatusDTO refreshPoolsForProduct( @PathParam("owner_key") String ownerKey, @PathParam("product_id") String productId, @QueryParam("lazy_regen") @DefaultValue("true") boolean lazyRegen) throws JobException { if (config.getBoolean(ConfigProperties.STANDALONE)) { log.warn("Ignoring refresh pools request due to standalone config."); return null; } final Owner owner = this.getOwnerByKey(ownerKey); final Product product = this.fetchProduct(owner, productId); return this.translator.translate( jobManager.queueJob( RefreshPoolsForProductJob.createJobConfig(product, lazyRegen) ), AsyncJobStatusDTO.class); }

Target:
public AsyncJobStatusDTO refreshPoolsForProduct( @PathParam("owner_key") String ownerKey, @PathParam("product_id") String productId, @QueryParam("lazy_regen") @DefaultValue("true") boolean lazyRegen) throws JobException { if (config.getBoolean(ConfigProperties.STANDALONE)) { log.warn("Ignoring refresh pools request due to standalone config."); return null; } Owner owner = this.getOwnerByKey(ownerKey); Product product = this.fetchProduct(owner, productId); JobConfig config = RefreshPoolsForProductJob .createJobConfig() .setProduct(product) .setLazy(lazyRegen); AsyncJobStatus status = jobManager.queueJob(config); return this.translator.translate(status, AsyncJobStatusDTO.class); }
Source:
public RealmObjectSchema addField(String fieldName, Class<?> fieldType, FieldAttribute... attributes) { FieldMetaData metadata = SUPPORTED_SIMPLE_FIELDS.get(fieldType); if (metadata == null) { if (SUPPORTED_LINKED_FIELDS.containsKey(fieldType)) { throw new IllegalArgumentException("Use addLinkField() instead to add fields that link to other RealmObjects: " + fieldName); } else { throw new IllegalArgumentException(String.format("Realm doesn't support this field type: %s(%s)", fieldName, fieldType)); } } checkNewFieldName(fieldName); boolean nullable = metadata.defaultNullable; if (containsAttribute(attributes, FieldAttribute.REQUIRED) || containsAttribute(attributes, FieldAttribute.PRIMARY_KEY)) { nullable = false; } if (containsAttribute(attributes, FieldAttribute.PRIMARY_KEY) && metadata.realmType.equals(RealmFieldType.STRING)) { nullable = true; } long columnIndex = table.addColumn(metadata.realmType, fieldName, nullable); try { addModifiers(fieldName, attributes); } catch (Exception e) { table.removeColumn(columnIndex); throw e; } return this; }

Target:
public RealmObjectSchema addField(String fieldName, Class<?> fieldType, FieldAttribute... attributes) { FieldMetaData metadata = SUPPORTED_SIMPLE_FIELDS.get(fieldType); if (metadata == null) { if (SUPPORTED_LINKED_FIELDS.containsKey(fieldType)) { throw new IllegalArgumentException("Use addLinkField() instead to add fields that link to other RealmObjects: " + fieldName); } else { throw new IllegalArgumentException(String.format("Realm doesn't support this field type: %s(%s)", fieldName, fieldType)); } } checkNewFieldName(fieldName); boolean nullable = metadata.defaultNullable; if (containsAttribute(attributes, FieldAttribute.REQUIRED)) { nullable = false; } long columnIndex = table.addColumn(metadata.realmType, fieldName, nullable); try { addModifiers(fieldName, attributes); } catch (Exception e) { table.removeColumn(columnIndex); throw e; } return this; }
Source:
protected NetworkState doTaskBackground(Void... params) { NetworkState out = NetworkState.CONNECTED; if (!isOnline(this.c)) { out = NetworkState.DISCONNECTED; } else if (!pingSuccess(googleURL)) { out = NetworkState.CAPTIVE_PORTAL; } else if (!pingCC(commcareURL)) { out = NetworkState.COMMCARE_BLOCKED; } return out; }

Target:
protected NetworkState doTaskBackground(Void... params) { if (!isOnline(this.c) || !pingSuccess(googleURL)) { return NetworkState.DISCONNECTED; } return pingCC(); }
Source:
public synchronized void setEntryIsLive() { if (readyForPlayback) { logger.debug("Attention - READY_FOR_PLAYBACK already raised"); return; } if (!entryRegistered) { logger.error("setReadyForPlayback called but stream is unregistered"); return ; } TimerTask setMediaServerTask = new TimerTask() { @Override public void run() { logger.info("Initial timer task running [" + liveEntry.id + "] - PLAYABLE"); setEntryMediaServer(liveEntry, index, KalturaLiveEntryStatus.PLAYABLE); readyForPlayback = true; } }; timer = new Timer("register-" + liveEntry.id, true); timer.schedule(setMediaServerTask, 0); logger.debug("Scheduled initial timer [" + liveEntry.id + "]"); }

Target:
public synchronized void setEntryIsLive() { if (isReadyForPlayback()) { logger.info("setEntryIsLive was called - IsLive is already on"); return; } TimerTask setMediaServerTask = new TimerTask() { @Override public void run() { if(!isEntryRegistered()) { logger.info("Entry's not registered, can't call setEntryMediaServer"); return; } logger.info("Initial timer task running [" + liveEntry.id + "] - PLAYABLE"); setEntryMediaServer(liveEntry, index, KalturaLiveEntryStatus.PLAYABLE); readyForPlayback = true; } }; timer = new Timer("register-" + liveEntry.id, true); timer.schedule(setMediaServerTask, 0); logger.debug("Scheduled initial timer [" + liveEntry.id + "]"); }
Source:
public boolean intersectsWith(RectF rectangle) { Canvas canvas = new Canvas(); canvas.setBitmap(getBitmapOfCurrentLayer()); Rect rectangleBoundsCanvas = canvas.getClipBounds(); return rectangleBoundsCanvas.left < rectangle.right && rectangle.left < rectangleBoundsCanvas.right && rectangleBoundsCanvas.top < rectangle.bottom && rectangle.top < rectangleBoundsCanvas.bottom; }

Target:
public boolean intersectsWith(RectF rectangle) { return 0 < rectangle.right && rectangle.left < getWidth() && 0 < rectangle.bottom && rectangle.top < getHeight(); }
Source:
public void typedRealmAndDynamicRealmShareTheSameCache() { RealmConfiguration config1 = configFactory.createConfigurationBuilder() .name("same_name") .build(); RealmConfiguration config2 = configFactory.createConfigurationBuilder() .name("same_name") .initialData(new Realm.Transaction() { @Override public void execute(Realm realm) { fail(); } }) .build(); DynamicRealm dynamicRealm = DynamicRealm.getInstance(config1); Realm realm = null; try { realm = Realm.getInstance(config2); fail(); } catch (IllegalArgumentException ignored) { } finally { dynamicRealm.close(); if (realm != null) { realm.close(); } } }

Target:
public void typedRealmAndDynamicRealmShareTheSameCache() { final String DB_NAME = "same_name.realm"; RealmConfiguration config1 = configFactory.createConfigurationBuilder() .name(DB_NAME) .build(); RealmConfiguration config2 = configFactory.createConfigurationBuilder() .name(DB_NAME) .initialData(new Realm.Transaction() { @Override public void execute(Realm realm) { fail(); } }) .build(); DynamicRealm dynamicRealm = DynamicRealm.getInstance(config1); Realm realm = null; try { realm = Realm.getInstance(config2); fail(); } catch (IllegalArgumentException ignored) { } finally { dynamicRealm.close(); if (realm != null) { realm.close(); } } }
Source:
public void testCompoundJoin() { final Schema schema = getExampleSchema(); final QueryPostprocessDataContext dc = new QueryPostprocessDataContext() { @Override protected DataSet materializeMainSchemaTable(Table table, Column[] columns, int maxRows) { Object[] values = new Object[columns.length]; for (int i = 0; i < columns.length; i++) { values[i] = columns[i].getColumnNumber(); } DataSetHeader header = new SimpleDataSetHeader(columns); DefaultRow row = new DefaultRow(header, values); return new InMemoryDataSet(row); } @Override protected String getMainSchemaName() throws MetaModelException { return "MetaModelSchema"; } @Override protected Schema getMainSchema() throws MetaModelException { return schema; } }; Query query = dc.parseQuery("SELECT c.contributor_id,p.project_id from contributor c INNER JOIN role r ON c.contributor_id=r.contributor_id INNER JOIN project p ON p.project_id=r.project_id"); System.out.println(query); assertEquals("SELECT c.contributor_id, p.project_id FROM MetaModelSchema.contributor c INNER JOIN MetaModelSchema.role r ON c.contributor_id = r.contributor_id INNER JOIN MetaModelSchema.project p ON p.project_id = r.project_id", query.toSql()); }

Target:
public void testCompoundJoin() { final Schema schema = getExampleSchema(); final QueryPostprocessDataContext dc = new QueryPostprocessDataContext() { @Override protected DataSet materializeMainSchemaTable(Table table, Column[] columns, int maxRows) { throw new UnsupportedOperationException("This method is not used"); } @Override protected String getMainSchemaName() throws MetaModelException { return "MetaModelSchema"; } @Override protected Schema getMainSchema() throws MetaModelException { return schema; } }; Query query = dc.parseQuery("SELECT c.contributor_id,p.project_id from contributor c INNER JOIN role r ON c.contributor_id=r.contributor_id INNER JOIN project p ON p.project_id=r.project_id"); assertEquals("SELECT c.contributor_id, p.project_id FROM MetaModelSchema.contributor c INNER JOIN MetaModelSchema.role r ON c.contributor_id = r.contributor_id INNER JOIN MetaModelSchema.project p ON p.project_id = r.project_id", query.toSql()); }
Source:
private boolean isTokenValid(UserResetTokenDTO userResetToken) { Date checkDate = userResetToken.getCreationDate(); Instant now = Instant.now(); return (!checkDate.toInstant().isBefore(now.minus(24 , ChronoUnit.HOURS))) && (checkDate.toInstant().isBefore(now)); }

Target:
private boolean isTokenValid(UserResetTokenDTO userResetToken) { Date checkDate = userResetToken.getCreationDate(); Instant now = Instant.now(); return (!checkDate.toInstant().isBefore(now.minus(Integer.parseInt(env.getProperty("resetLinkExpirationTimeInHours")), ChronoUnit.HOURS))) && (checkDate.toInstant().isBefore(now)); }
Source:
public void evaluate_shouldReturnAllPatientsThatHaveTakenAnyofListedDrugs() throws Exception { List drugSetList = new ArrayList<Concept>(); drugSetList.add(new Concept(88)); drugSetList.add(new Concept(792)); drugSetList.add(new Concept(20)); cohortDefinition.setDrugSets(drugSetList); cohortDefinition.setWhich("ANY"); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); System.out.println("Taking Drugs Any" + cohort.getMemberIds() + " " + cohortDefinition+ "==="); Assert.assertTrue(cohort.contains(2)); Assert.assertTrue(cohort.contains(21)); Assert.assertTrue(cohort.contains(22)); Assert.assertEquals(3, cohort.size()); }

Target:
public void evaluate_shouldReturnAllPatientsThatHaveTakenAnyofListedDrugs() throws Exception { List drugSetList = new ArrayList<Concept>(); drugSetList.add(new Concept(88)); drugSetList.add(new Concept(792)); cohortDefinition.setDrugSets(drugSetList); cohortDefinition.setWhich("ANY"); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); Assert.assertTrue(cohort.contains(2)); Assert.assertTrue(cohort.contains(7)); Assert.assertEquals(2, cohort.size()); }
Source:
public void validPropertiesUnsupportedVersion() { DevicePropertiesUtils utils = mockDevicePropertiesUtils(); List<ValidationError> errors = utils.validateProperties(Version.v3_2, VmDeviceGeneralType.DISK, "bootable=true"); assertFalse(errors.isEmpty()); assertEquals(ValidationFailureReason.UNSUPPORTED_VERSION, errors.get(0).getReason()); }

Target:
public void validPropertiesUnsupportedVersion() { DevicePropertiesUtils utils = mockDevicePropertiesUtils(); List<ValidationError> errors = utils.validateProperties(Version.v3_2, VmDeviceGeneralType.DISK, utils.convertProperties("bootable=true")); validateFailure(errors, ValidationFailureReason.UNSUPPORTED_VERSION); }
Source:
private void restartVmsWithLeaseIfNeeded(List<VmDynamic> vms) { if (vms.isEmpty()) { return; } int skippedIterations = Config.<Integer>getValue(ConfigValues.NumberVdsRefreshesBeforeRetryToStartUnknownVms); autoRestartUnknownVmsIteration = (autoRestartUnknownVmsIteration + 1) % (skippedIterations + 1); if (autoRestartUnknownVmsIteration != 0) { return; } resourceManager.getEventListener().restartVmsWithLease(vms.stream() .map(VmDynamic::getId) .filter(vmId -> resourceManager.getVmManager(vmId).getLeaseStorageDomainId() != null) .collect(Collectors.toList())); }

Target:
private void restartVmsWithLeaseIfNeeded(List<VmDynamic> vms) { if (vms.isEmpty() || !autoStartVmsWithLeasesLock.tryLock()) { return; } try { int skippedIterations = Config.<Integer>getValue(ConfigValues.NumberVdsRefreshesBeforeRetryToStartUnknownVms); autoRestartUnknownVmsIteration++; if (autoRestartUnknownVmsIteration % (skippedIterations + 1) == 0) { resourceManager.getEventListener().restartVmsWithLease(vms.stream() .map(VmDynamic::getId) .filter(vmId -> resourceManager.getVmManager(vmId).getLeaseStorageDomainId() != null) .collect(Collectors.toList())); } } finally { autoStartVmsWithLeasesLock.unlock(); } }
Source:
static ParquetMetadata readSummaryMetadata(Configuration configuration, Path basePath, boolean skipRowGroups) throws IOException { Path summaryFile = new Path(basePath, PARQUET_METADATA_FILE); Path summaryFileLight = new Path(basePath, PARQUET_COMMON_METADATA_FILE); FileSystem fileSystem = basePath.getFileSystem(configuration); if (skipRowGroups && fileSystem.exists(summaryFileLight)) { if (Log.INFO) LOG.info("reading summary file: " + summaryFileLight); return readFooter(configuration, summaryFileLight, filter(skipRowGroups)); } else if (fileSystem.exists(summaryFile)) { if (Log.INFO) LOG.info("reading summary file: " + summaryFile); return readFooter(configuration, summaryFile, filter(skipRowGroups)); } else { return null; } }

Target:
static ParquetMetadata readSummaryMetadata(Configuration configuration, Path basePath, boolean skipRowGroups) throws IOException { Path metadataFile = new Path(basePath, PARQUET_METADATA_FILE); Path commonMetaDataFile = new Path(basePath, PARQUET_COMMON_METADATA_FILE); FileSystem fileSystem = basePath.getFileSystem(configuration); if (skipRowGroups && fileSystem.exists(commonMetaDataFile)) { if (Log.INFO) LOG.info("reading summary file: " + commonMetaDataFile); return readFooter(configuration, commonMetaDataFile, filter(skipRowGroups)); } else if (fileSystem.exists(metadataFile)) { if (Log.INFO) LOG.info("reading summary file: " + metadataFile); return readFooter(configuration, metadataFile, filter(skipRowGroups)); } else { return null; } }
Source:
public void testRWZKConnectionLost() throws Exception { ZooKeeper zk = ZooKeeperClient.newBuilder() .connectString(zkUtil.getZooKeeperConnectString()) .sessionTimeoutMs(10000) .build(); try { ReplicationWorker rw = new ReplicationWorker(zk, baseConf, getBookie(0)); rw.start(); for (int i = 0; i < 10; i++) { if (rw.isRunning()) { break; } Thread.sleep(1000); } assertTrue("Replication worker should be running", rw.isRunning()); stopZKCluster(); Thread.sleep(1000); startZKCluster(); assertTrue("Replication worker should still be running", rw.isRunning()); } finally { zk.close(); } }

Target:
public void testRWZKConnectionLost() throws Exception { ZooKeeper zk = ZooKeeperClient.newBuilder() .connectString(zkUtil.getZooKeeperConnectString()) .sessionTimeoutMs(10000) .build(); try { ReplicationWorker rw = new ReplicationWorker(zk, baseConf, getBookie(0)); rw.start(); for (int i = 0; i < 10; i++) { if (rw.isRunning()) { break; } Thread.sleep(1000); } assertTrue("Replication worker should be running", rw.isRunning()); stopZKCluster(); for (int i = 0; i < 10; i++) { if (!zk.getState().isConnected()) { break; } Thread.sleep(1000); } assertFalse(zk.getState().isConnected()); startZKCluster(); assertTrue("Replication worker should still be running", rw.isRunning()); } finally { zk.close(); } }
Source:
public Properties trackScreenView(@NonNull String screenName, @Nullable String courseId, @Nullable String action) { SegmentAnalyticsEvent aEvent = new SegmentAnalyticsEvent(); aEvent.setAppNameContext(); if (!TextUtils.isEmpty(action)) { aEvent.properties.put(Keys.ACTION, action); } if (!TextUtils.isEmpty(courseId)) { aEvent.properties.put(Keys.COURSE_ID, courseId); } tracker.screen("", screenName, aEvent.properties); addCategoryToBiEvents(aEvent.properties, Values.SCREEN, screenName); tracker.track(screenName, aEvent.properties); return aEvent.properties; }

Target:
public Properties trackScreenView(@NonNull String screenName, @Nullable String courseId, @Nullable String action) { return trackScreenView(screenName, courseId, action, null); }
Source:
private void appendUserScriptsTo(StringBuilder stringBuilder) throws IOException { try { List<String> passiveFunctionNames = new ArrayList<String>(); this.extensionScript .getScripts(ExtensionFrontEndScanner.SCRIPT_TYPE_CLIENT_PASSIVE) .stream() .filter(script -> script.isEnabled()) .map(script -> script.getFile()) .map(file -> file.toPath()) .map(scriptFileName -> readFromFile(scriptFileName)) .map(code -> wrapInFunction(code, passiveFunctionNames)) .forEach(code -> stringBuilder.append(code)); stringBuilder .append("const SCRIPTS = [ " + String.join(", ", passiveFunctionNames) + "];"); } catch (UncheckedIOException e) { throw new IOException(e); } }

Target:
private void appendUserScriptsTo(StringBuilder stringBuilder) throws IOException { try { List<String> passiveFunctionNames = new ArrayList<String>(); this.extensionScript .getScripts(ExtensionFrontEndScanner.SCRIPT_TYPE_CLIENT_PASSIVE) .stream() .filter(script -> script.isEnabled()) .map(script -> script.getContents()) .map(code -> wrapInFunction(code, passiveFunctionNames)) .forEach(code -> stringBuilder.append(code)); stringBuilder .append("const SCRIPTS = [ " + String.join(", ", passiveFunctionNames) + "];"); } catch (UncheckedIOException e) { throw new IOException(e); } }
Source:
public ReentrantLock getLock() { return lock; }

Target:
ReentrantLock getLock() { return lock; }
Source:
public Object execute(final ExecutionEvent event) throws ExecutionException { final Repository[] repos = getRepositoriesFor(getProjectsForSelectedResources(event)); final Shell shell = getShell(event); IResource[] resourcesInScope; try { IResource[] selectedResources = getSelectedResources(event); IWorkbenchPart part = getPart(event); resourcesInScope = GitScopeUtil.getRelatedChanges(part, selectedResources); } catch (InterruptedException e) { return null; } CommitUI commitUi = new CommitUI(shell, repos[0], resourcesInScope, false); commitUi.commit(); if (commitUi.isExecutePush()) { executePushCommand(HandlerUtil.getCurrentSelection(event)); } return null; }

Target:
public Object execute(final ExecutionEvent event) throws ExecutionException { final Repository[] repos = getRepositoriesFor(getProjectsForSelectedResources(event)); final Shell shell = getShell(event); IResource[] resourcesInScope; try { IResource[] selectedResources = getSelectedResources(event); IWorkbenchPart part = getPart(event); resourcesInScope = GitScopeUtil.getRelatedChanges(part, selectedResources); } catch (InterruptedException e) { return null; } CommitUI commitUi = new CommitUI(shell, repos[0], resourcesInScope, false); commitUi.commit(); if (commitUi.isExecutePush()) executePushCommand(HandlerUtil.getCurrentSelection(event)); return null; }
Source:
protected ConnectorPageSource createLookupPageSource(SplitInfo splitInfo, List<String> outputColumnNames) { IndexedTable indexedTable = indexedData.getIndexedTable( splitInfo.getTableName(), schemaNameToScaleFactor(splitInfo.getSchemaName()), ImmutableSet.copyOf(splitInfo.getLookupColumnNames())) .orElseThrow(() -> new IllegalArgumentException("Index is not present")); List<Type> lookupColumnTypes = types(splitInfo.getTableName(), splitInfo.getLookupColumnNames()); RecordSet keyRecordSet = new ListBasedRecordSet(splitInfo.getKeys(), lookupColumnTypes); RecordSet outputRecordSet = lookupIndexKeys(keyRecordSet, indexedTable, outputColumnNames); return new RecordPageSource(outputRecordSet); }

Target:
protected ConnectorPageSource createLookupPageSource(SplitInfo splitInfo, List<String> outputColumnNames) { IndexedTable indexedTable = indexedData.getIndexedTable( splitInfo.getTableName(), schemaNameToScaleFactor(splitInfo.getSchemaName()), ImmutableSet.copyOf(splitInfo.getLookupColumnNames())) .orElseThrow(() -> new IllegalArgumentException(String.format("No such index: %s%s", splitInfo.getTableName(), splitInfo.getLookupColumnNames()))); List<Type> lookupColumnTypes = types(splitInfo.getTableName(), splitInfo.getLookupColumnNames()); RecordSet keyRecordSet = new ListBasedRecordSet(splitInfo.getKeys(), lookupColumnTypes); RecordSet outputRecordSet = lookupIndexKeys(keyRecordSet, indexedTable, outputColumnNames); return new RecordPageSource(outputRecordSet); }
Source:
public void enterTopLevel(TopLevelContext topLevelCtx) { List<IdentifierContext> names = DeclarationListener.getConstantNames(topLevelCtx); names.forEach( ctx -> { String constantName = CharFormatUtil.unescapeIdentifier(ctx.getText()); Location location = ListenerUtil.getContextStartLocation(ctx); if (CharFormatUtil.isEnclosedInBackticks(ctx.getText())) { location.column += 1; } if (CharFormatUtil.isKPrefixed(constantName)) { printer.warn(Rules.CONSTANT_K_PREFIX, Messages.CONSTANT + Messages.NAME + Messages.K_PREFIXED, location); } } ); }

Target:
public void enterTopLevel(TopLevelContext topLevelCtx) { List<IdentifierContext> names = DeclarationListener.getConstantNames(topLevelCtx); names.forEach( ctx -> { String constantName = CharFormatUtil.unescapeIdentifier(ctx.getText()); Location location = ListenerUtil.getIdentifierStartLocation(ctx); if (CharFormatUtil.isKPrefixed(constantName)) { printer.warn(Rules.CONSTANT_K_PREFIX, Messages.CONSTANT + Messages.NAME + Messages.K_PREFIXED, location); } } ); }
Source:
public RelBuilder scan(Iterable<String> tableNames) { final List<String> names = Lists.newArrayList(tableNames); final RelOptTable relOptTable = relOptSchema.getTableForMember(names); if (relOptTable == null) { throw Static.RESOURCE.tableNotFound(Joiner.on(".").join(names)).ex(); } final RelNode scan = scanFactory.createScan(cluster, relOptTable); push(scan); return this; }

Target:
public RelBuilder scan(Iterable<String> tableNames) { final List<String> names = ImmutableList.copyOf(tableNames); final RelOptTable relOptTable = relOptSchema.getTableForMember(names); if (relOptTable == null) { throw Static.RESOURCE.tableNotFound(Joiner.on(".").join(names)).ex(); } final RelNode scan = scanFactory.createScan(cluster, relOptTable); push(scan); return this; }
Source:
public void testStaledCompletion() throws InterruptedException { long txnId = m_mpTxnEgo.getTxnId(); TransactionTask[] firstFrag = new TransactionTask[SITE_COUNT]; for (int i = 0; i < SITE_COUNT; i++) { firstFrag[i] = createFrag(m_localTxnEgo[i].getTxnId(), txnId, m_txnTaskQueues.get(i)); addTask(firstFrag[i], m_txnTaskQueues.get(i), m_expectedOrders.get(i)); } TransactionTask comp = null; for (int i = 0; i < SITE_COUNT - 1; i++) { comp = createCompletion(firstFrag[i].getTransactionState(), firstFrag[i].getTxnId(), m_txnTaskQueues.get(i)); addTask(comp, m_txnTaskQueues.get(i), null); } long seq = m_repairGenerator.getNextSeqNum(); for (int i = 0; i < SITE_COUNT; i++) { comp = createRepairCompletion(firstFrag[i].getTransactionState(), firstFrag[i].getTxnId(), m_txnTaskQueues.get(i), seq, true); addTask(comp, m_txnTaskQueues.get(i), m_expectedOrders.get(i)); } flushBacklog(firstFrag); for (int i = SITE_COUNT - 1; i < SITE_COUNT; i++) { comp = createCompletion(firstFrag[i].getTransactionState(), firstFrag[i].getTxnId(), m_txnTaskQueues.get(i)); addTask(comp, m_txnTaskQueues.get(i), null); } verify(); }

Target:
public void testStaledCompletion() throws InterruptedException { long txnId = m_mpTxnEgo.getTxnId(); TransactionTask[] firstFrag = new TransactionTask[SITE_COUNT]; for (int i = 0; i < SITE_COUNT; i++) { firstFrag[i] = createFrag(m_localTxnEgo[i].getTxnId(), txnId, m_txnTaskQueues.get(i)); addTask(firstFrag[i], m_txnTaskQueues.get(i), m_expectedOrders.get(i)); } TransactionTask comp = null; for (int i = 0; i < SITE_COUNT - 1; i++) { comp = createCompletion(firstFrag[i].getTransactionState(), firstFrag[i].getTxnId(), m_txnTaskQueues.get(i)); addTask(comp, m_txnTaskQueues.get(i), null); } long seq = m_repairGenerator.getNextSeqNum(); for (int i = 0; i < SITE_COUNT; i++) { comp = createRepairCompletion(firstFrag[i].getTransactionState(), firstFrag[i].getTxnId(), m_txnTaskQueues.get(i), seq, false); addTask(comp, m_txnTaskQueues.get(i), m_expectedOrders.get(i)); } flushBacklog(firstFrag); for (int i = SITE_COUNT - 1; i < SITE_COUNT; i++) { comp = createCompletion(firstFrag[i].getTransactionState(), firstFrag[i].getTxnId(), m_txnTaskQueues.get(i)); addTask(comp, m_txnTaskQueues.get(i), null); } verify(); }
Source:
public void emptySpoilerTest() throws Exception { final String xml = "<spoiler xmlns='urn:xmpp:spoiler:0'/>"; SpoilerManager m = SpoilerManager.getInstanceFor(connection); SpoilerElement empty = m.createSpoiler(); assertNull(empty.getHint()); assertNull(empty.getLanguage()); assertXMLEqual(xml, empty.toXML().toString()); XmlPullParser parser = TestUtils.getParser(xml); SpoilerElement parsed = new SpoilerProvider().parse(parser); assertXMLEqual(xml, parsed.toXML().toString()); }

Target:
public void emptySpoilerTest() throws Exception { final String xml = "<spoiler xmlns='urn:xmpp:spoiler:0'/>"; Message message = new Message(); SpoilerElement.addSpoiler(message); SpoilerElement empty = message.getExtension(SpoilerElement.ELEMENT, SpoilerManager.NAMESPACE_0); assertNull(empty.getHint()); assertNull(empty.getLanguage()); assertXMLEqual(xml, empty.toXML().toString()); XmlPullParser parser = TestUtils.getParser(xml); SpoilerElement parsed = SpoilerProvider.INSTANCE.parse(parser); assertXMLEqual(xml, parsed.toXML().toString()); }
Source:
public void delta(Delta delta, PersistenceExceptionHandler exceptionHandler) { checkWritesAllowed(); Stopwatch stopwatch = deltaImpl(delta, exceptionHandler); if (LOG.isDebugEnabled()) LOG.debug("Checkpointed delta of memento in {}: " + "updated entities, locations, policies, enrichers, catalog items; " + "removed entities, locations, policies, enrichers catalog items", new Object[] {Time.makeTimeStringRounded(stopwatch), delta.entities().size(), delta.locations().size(), delta.policies().size(), delta.enrichers().size(), delta.catalogItems().size(), delta.removedEntityIds().size(), delta.removedLocationIds().size(), delta.removedPolicyIds().size(), delta.removedEnricherIds().size(), delta.removedCatalogItemIds().size()}); }

Target:
public void delta(Delta delta, PersistenceExceptionHandler exceptionHandler) { checkWritesAllowed(); Stopwatch stopwatch = deltaImpl(delta, exceptionHandler); if (LOG.isDebugEnabled()) LOG.debug("Checkpointed delta of memento in {}: " + "updated entities, locations, policies, enrichers, catalog items; " + "removed entities, locations, policies, enrichers, catalog items", new Object[] {Time.makeTimeStringRounded(stopwatch), delta.entities().size(), delta.locations().size(), delta.policies().size(), delta.enrichers().size(), delta.catalogItems().size(), delta.removedEntityIds().size(), delta.removedLocationIds().size(), delta.removedPolicyIds().size(), delta.removedEnricherIds().size(), delta.removedCatalogItemIds().size()}); }
Source:
private boolean tryFetchLookupSourceProvider() { if (lookupSourceProvider == null) { if (!lookupSourceProviderFuture.isDone()) { return false; } lookupSourceProvider = requireNonNull(getDone(lookupSourceProviderFuture)); statisticsCounter.updateLookupSourcePositions(lookupSourceProvider.withLease(lookupSourceLease -> lookupSourceLease.getLookupSource().getJoinPositionCount())); if (!probeOnOuterSide && !finishing && !finished && lookupSourceProvider.withLease(lookupSourceLease -> lookupSourceLease.hasSpilled() ? false : lookupSourceLease.getLookupSource().isEmpty())) { finishing = true; finished = true; } } return true; }

Target:
private boolean tryFetchLookupSourceProvider() { if (lookupSourceProvider == null) { if (!lookupSourceProviderFuture.isDone()) { return false; } lookupSourceProvider = requireNonNull(getDone(lookupSourceProviderFuture)); statisticsCounter.updateLookupSourcePositions(lookupSourceProvider.withLease(lookupSourceLease -> lookupSourceLease.getLookupSource().getJoinPositionCount())); if (!probeOnOuterSide && lookupSourceProvider.withLease(lookupSourceLease -> lookupSourceLease.getLookupSource().isEmpty())) { finishing = true; } } return true; }
Source:
public void reportsThreadInformation() throws Exception { Runnable fastOne = new FastRunnable(); Runnable slowOne = new SlowRunnable(); Counter created = registry.counter("factory.created"); Counter running = registry.counter("factory.running"); Counter finished = registry.counter("factory.finished"); Thread fastThread = instrumentedFactory.newThread(fastOne); Thread slowThread = instrumentedFactory.newThread(slowOne); assertThat(created.getCount()).isEqualTo(2); assertThat(running.getCount()).isEqualTo(0); assertThat(finished.getCount()).isEqualTo(0); fastThread.start(); slowThread.start(); Thread.sleep(100); assertThat(running.getCount()).isEqualTo(1); assertThat(finished.getCount()).isEqualTo(1); Thread.sleep(1000); assertThat(running.getCount()).isEqualTo(0); assertThat(finished.getCount()).isEqualTo(2); }

Target:
public void reportsThreadInformation() throws Exception { Runnable fastOne = new FastRunnable(); Meter created = registry.meter("factory.created"); Meter terminated = registry.meter("factory.terminated"); assertThat(created.getCount()).isEqualTo(0); assertThat(terminated.getCount()).isEqualTo(0); for (int i = 10; i < 20; i++) { executor.submit(fastOne); } assertThat(created.getCount()).isEqualTo(10); assertThat(terminated.getCount()).isEqualTo(0); executor.shutdown(); assertThat(executor.awaitTermination(1, TimeUnit.SECONDS)).isTrue(); assertThat(terminated.getCount()).isEqualTo(10); }
Source:
private Map<String, DbComponent> getDbFilesByKey() { try (DbSession dbSession = dbClient.openSession(false)) { List<ComponentWithPathDto> componentDtos = dbClient.componentDao().selectFilesWithPathFromProject(dbSession, rootHolder.getRoot().getUuid()); return componentDtos.stream() .map(dto -> new DbComponent(dto.getId(), dto.getDbKey(), dto.uuid(), dto.path())) .collect(Collectors.toMap(DbComponent::getKey, x -> x)); } }

Target:
private Map<String, DbComponent> getDbFilesByKey() { try (DbSession dbSession = dbClient.openSession(false)) { List<ComponentDto> componentDtos = dbClient.componentDao().selectDescendants( dbSession, ComponentTreeQuery.builder() .setBaseUuid(rootHolder.getRoot().getUuid()) .setQualifiers(FILE_QUALIFIERS) .setStrategy(Strategy.LEAVES) .build()); return from(componentDtos) .transform(componentDto -> new DbComponent(componentDto.getId(), componentDto.getDbKey(), componentDto.uuid(), componentDto.path())) .uniqueIndex(DbComponent::getKey); } }
Source:
public FieldValueCounter save(FieldValueCounter fieldValueCounter) { map.put(fieldValueCounter.getName(), fieldValueCounter); return fieldValueCounter; }

Target:
private FieldValueCounter save(FieldValueCounter fieldValueCounter) { map.put(fieldValueCounter.getName(), fieldValueCounter); return fieldValueCounter; }
Source:
public UnitCard(DatabaseAccessor db, Project project, String title, int chapter, int firstVerse, int endVerse, OnTakeDeleteListener listener) { mTitle = title; mFirstVerse = firstVerse; mEndVerse = endVerse; mChapter = chapter; mProject = project; onTakeDeleteListener = listener; refreshTakeCount(db); }

Target:
public UnitCard( DatabaseAccessor db, Project project, String title, int chapter, int firstVerse, int endVerse, OnTakeDeleteListener listener ) { mTitle = title; mFirstVerse = firstVerse; mEndVerse = endVerse; mChapter = chapter; mProject = project; onTakeDeleteListener = listener; databaseAccessor = db; refreshTakeCount(); }