auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String toString() { int[] types = getTransportTypes(); String transports = (types.length > 0) ? " Transports: " + transportNamesOf(types) : ""; types = getCapabilities(); String capabilities = (types.length > 0 ? " Capabilities: " : ""); for (int i = 0; i < types.length; ) { capabilities += capabilityNameOf(types[i]); if (++i < types.length) capabilities += "&"; } types = BitUtils.unpackBits(mUnwantedNetworkCapabilities); String unwantedCapabilities = (types.length > 0 ? " UnwantedCapabilities: " : ""); unwantedCapabilities += capabilityNamesOf(types); String upBand = ((mLinkUpBandwidthKbps > 0) ? " LinkUpBandwidth>=" + mLinkUpBandwidthKbps + "Kbps" : ""); String dnBand = ((mLinkDownBandwidthKbps > 0) ? " LinkDnBandwidth>=" + mLinkDownBandwidthKbps + "Kbps" : ""); String specifier = (mNetworkSpecifier == null ? "" : " Specifier: <" + mNetworkSpecifier + ">"); String signalStrength = (hasSignalStrength() ? " SignalStrength: " + mSignalStrength : ""); String uids = (null != mUids ? " Uids: <" + mUids + ">" : ""); String establishingAppUid = " EstablishingAppUid: " + mEstablishingVpnAppUid; return "[" + transports + capabilities + upBand + dnBand + specifier + signalStrength + uids + establishingAppUid + unwantedCapabilities + "]"; }

Target:
public String toString() { int[] types = getTransportTypes(); String transports = (types.length > 0) ? " Transports: " + transportNamesOf(types) : ""; types = getCapabilities(); String capabilities = (types.length > 0 ? " Capabilities: " : ""); for (int i = 0; i < types.length; ) { capabilities += capabilityNameOf(types[i]); if (++i < types.length) capabilities += "&"; } types = BitUtils.unpackBits(mUnwantedNetworkCapabilities); String unwantedCapabilities = (types.length > 0 ? " Unwanted: " : ""); unwantedCapabilities += capabilityNamesOf(types); String upBand = ((mLinkUpBandwidthKbps > 0) ? " LinkUpBandwidth>=" + mLinkUpBandwidthKbps + "Kbps" : ""); String dnBand = ((mLinkDownBandwidthKbps > 0) ? " LinkDnBandwidth>=" + mLinkDownBandwidthKbps + "Kbps" : ""); String specifier = (mNetworkSpecifier == null ? "" : " Specifier: <" + mNetworkSpecifier + ">"); String signalStrength = (hasSignalStrength() ? " SignalStrength: " + mSignalStrength : ""); String uids = (null != mUids ? " Uids: <" + mUids + ">" : ""); String establishingAppUid = " EstablishingAppUid: " + mEstablishingVpnAppUid; return "[" + transports + capabilities + unwantedCapabilities + upBand + dnBand + specifier + signalStrength + uids + establishingAppUid + "]"; }
Source:
private void updateGui() { if (getActivity() == null || getActivity().isFinishing()) { return; } RestApi mApi = mActivity.getApi(); if (mApi != null) { mApi.getSystemInfo(this::onReceiveSystemInfo); mApi.getSystemVersion(this::onReceiveSystemVersion); mApi.getConnections(this::onReceiveConnections); } }

Target:
private void updateGui() { MainActivity mainActivity = (MainActivity) getActivity(); if (mainActivity == null) { return; } if (mainActivity.isFinishing()) { return; } RestApi mApi = mainActivity.getApi(); if (mApi != null) { mApi.getSystemInfo(this::onReceiveSystemInfo); mApi.getSystemVersion(this::onReceiveSystemVersion); mApi.getConnections(this::onReceiveConnections); } }
Source:
public void onResume() { checkItemVisibility(); setUpdateIntervalText(); setParallelDownloadsText(UserPreferences.getParallelDownloads()); setEpisodeCacheSizeText(UserPreferences.getEpisodeCacheSize()); setDataFolderText(); GpodnetPreferences.setSyncAttemptListener(() -> ui.getActivity().runOnUiThread( () -> updateLastGpodnetSyncReport( GpodnetPreferences.getLastSyncAttemptResult(), GpodnetPreferences.getLastSyncAttemptTimestamp()))); updateGpodnetPreferenceScreen(); }

Target:
public void onResume() { checkItemVisibility(); setUpdateIntervalText(); setParallelDownloadsText(UserPreferences.getParallelDownloads()); setEpisodeCacheSizeText(UserPreferences.getEpisodeCacheSize()); setDataFolderText(); GpodnetPreferences.registerOnSharedPreferenceChangeListener(gpoddernetListener); updateGpodnetPreferenceScreen(); }
Source:
public IStatus validate(IValidationContext ctx) { IStatus status = null; EObject target = ctx.getTarget(); for (EObject content : target.eContents()) { if (content instanceof IdentifiedElement && !(content instanceof Group || content instanceof ViewpointSpec)) { String elementName = ((IdentifiedElement) content).getName(); if (elementName == null || "".equals(elementName)) { status = ctx.createFailureStatus(getPath(content) + ERROR_MESSAGE); } } } if (status == null) { status = ctx.createSuccessStatus(); } return status; }

Target:
public IStatus validate(IValidationContext ctx) { IStatus status = null; EObject target = ctx.getTarget(); for (EObject content : target.eContents()) { if (content instanceof IdentifiedElement && !(content instanceof Group || content instanceof ViewpointSpec)) { String elementName = ((IdentifiedElement) content).getName(); if (StringUtil.isEmpty(elementName)) { status = ctx.createFailureStatus(getPath(content) + ERROR_MESSAGE); } } } if (status == null) { status = ctx.createSuccessStatus(); } return status; }
Source:
public PlanWithProperties visitTableFinish(TableFinishNode node, PreferredProperties preferredProperties) { PlanNode child = planChild(node, PreferredProperties.any()).getNode(); ExchangeNode gather; if (child instanceof ExchangeNode) { ExchangeNode exchangeNode = (ExchangeNode) child; gather = new ExchangeNode( idAllocator.getNextId(), GATHER, REMOTE_STREAMING, new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), exchangeNode.getOutputVariables()), exchangeNode.getSources(), exchangeNode.getInputs(), true, Optional.empty()); } else { gather = gatheringOrderedExchange(idAllocator.getNextId(), REMOTE_STREAMING, child); } return withDerivedProperties( ChildReplacer.replaceChildren(node, ImmutableList.of(gather)), ImmutableList.of()); }

Target:
public PlanWithProperties visitTableFinish(TableFinishNode node, PreferredProperties preferredProperties) { PlanNode child = planChild(node, PreferredProperties.any()).getNode(); ExchangeNode gather; if (child instanceof ExchangeNode) { ExchangeNode exchangeNode = (ExchangeNode) child; gather = new ExchangeNode( idAllocator.getNextId(), GATHER, REMOTE_STREAMING, new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), exchangeNode.getOutputVariables()), exchangeNode.getSources(), exchangeNode.getInputs(), true, Optional.empty()); } else { gather = ensureSourceOrderingGatheringExchange(idAllocator.getNextId(), REMOTE_STREAMING, child); } return withDerivedProperties( ChildReplacer.replaceChildren(node, ImmutableList.of(gather)), ImmutableList.of()); }
Source:
private void concatResults( final TupleBatchBuffer resultBuffer, final Object[] aggState, final Object key) throws DbException, IOException { int index = 1; for (int agg = 0; agg < aggregators.length; ++agg) { if (aggregators[agg] .getClass() .getName() .equals(StatefulUserDefinedAggregator.class.getName())) { List<TupleBatch> listTb = ltb.get(key); if (listTb.size() > 0) { LOGGER.info("size of tuples for key " + key.toString() + " is " + listTb.size()); aggregators[agg].add(listTb, aggState[agg]); } } aggregators[agg].getResult(resultBuffer, index, aggState[agg]); index += aggregators[agg].getResultSchema().numColumns(); } }

Target:
private void concatResults( final TupleBatchBuffer resultBuffer, final Object[] aggState, final Object key) throws DbException, IOException { int index = 1; for (int agg = 0; agg < aggregators.length; ++agg) { if (aggregators[agg] instanceof StatefulUserDefinedAggregator) { List<TupleBatch> listTb = ltb.get(key); if (listTb.size() > 0) { aggregators[agg].add(listTb); } } aggregators[agg].getResult(resultBuffer, index, aggState[agg]); index += aggregators[agg].getResultSchema().numColumns(); } }
Source:
public T getItem(int index) { DataCommunicator<T> verifiedDataCommunicator = getDataCommunicator(); if (verifiedDataCommunicator.isDefinedSize()) { final int itemCount = this.dataCommunicator.getDataSize(); validateItemIndex(index, itemCount); Optional<T> optionalItem = verifiedDataCommunicator.getDataProvider() .fetch(this.dataCommunicator.buildQuery(index, 1)) .findFirst(); return optionalItem.orElseThrow(() -> new IllegalStateException(String.format( "Item with an index %d is expected to be fetched" + " from backend, but not found", index))); } else { return verifiedDataCommunicator.getActiveItemOnIndex(index); } }

Target:
public T getItem(int index) { return getDataCommunicator().getItem(index); }
Source:
public void doWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { influxDB.createDatabase(database); String source = getSource(server); BatchPoints batchPoints = BatchPoints.database(database).retentionPolicy(retentionPolicy) .tag(TAG_HOSTNAME, source).consistency(writeConsistency).build(); for (Result result : results) { Map<String, Object> fixedValues = new HashMap<String,Object>(); fixedValues.put("_jmx_port", Integer.parseInt(server.getPort())); Map<String, Object> resultValues = result.getValues(); if (resultValues != null) { for (Entry<String, Object> entry : resultValues.entrySet()) { if (!entry.getValue().toString().equals("NaN")) { fixedValues.put(entry.getKey(), entry.getValue()); } } } if (fixedValues.size() > 1) { Map<String, String> resultTagsToApply = buildResultTagMap(result); Point point = Point.measurement(result.getKeyAlias()).time(result.getEpoch(), MILLISECONDS) .tag(resultTagsToApply).fields(fixedValues).build(); batchPoints.point(point); } } influxDB.write(batchPoints); }

Target:
public void doWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { influxDB.createDatabase(database); BatchPoints batchPoints = BatchPoints.database(database).retentionPolicy(retentionPolicy) .tag(TAG_HOSTNAME, server.getSource()).consistency(writeConsistency).build(); for (Result result : results) { HashMap<String, Object> filteredValues = new HashMap(Maps.filterValues(result.getValues(), isNotNaN)); if (!filteredValues.isEmpty()) { filteredValues.put("_jmx_port", Integer.parseInt(server.getPort())); Map<String, String> resultTagsToApply = buildResultTagMap(result); Point point = Point.measurement(result.getKeyAlias()).time(result.getEpoch(), MILLISECONDS) .tag(resultTagsToApply).fields(filteredValues).build(); batchPoints.point(point); } } influxDB.write(batchPoints); }
Source:
public LogEntry newDelegate() throws ResourceDoesNotSupportOperationException { throw new UnsupportedOperationException("method not supported"); }

Target:
public LogEntry newDelegate() throws ResourceDoesNotSupportOperationException { throw new ResourceDoesNotSupportOperationException(); }
Source:
void requestNativeAd( Context context, MediationNativeListener mediationNativeListener, Bundle serverParameters, NativeMediationAdRequest nativeMediationAdRequest, Bundle mediationExtras) { if (!nativeMediationAdRequest.isUnifiedNativeAdRequested()) { Log.e(TAG, "Failed to load ad. Request must be for unified native ads."); if (canInvokeListenerEvent()) mediationNativeListener.onAdFailedToLoad(adapter, AdRequest.ERROR_CODE_INVALID_REQUEST); return; } AdUnitMapper mapper = AdUnitMapper.validateNendAdUnit(serverParameters); if (mapper == null) { if (canInvokeListenerEvent()) mediationNativeListener.onAdFailedToLoad(adapter, AdRequest.ERROR_CODE_INVALID_REQUEST); return; } contextWeakReference = new WeakReference<>(context); this.mediationNativeListener = mediationNativeListener; if (mediationExtras != null) { final NendMediationAdapter.FormatType type = (NendMediationAdapter.FormatType) mediationExtras.getSerializable(KEY_NATIVE_ADS_FORMAT_TYPE); if (type != null) { switch (type) { case TYPE_VIDEO: videoAdLoader = new NativeVideoAdLoader( this, mapper, nativeMediationAdRequest, mediationExtras); videoAdLoader.loadAd(); return; case TYPE_NORMAL: break; default: Log.w(TAG, "Unknown type: "+ type); break; } } } normalAdLoader = new NativeAdLoader( this, new NendAdNativeClient(context, mapper.spotId, mapper.apiKey), nativeMediationAdRequest.getNativeAdOptions()); normalAdLoader.loadAd(); }

Target:
void requestNativeAd( Context context, MediationNativeListener mediationNativeListener, Bundle serverParameters, NativeMediationAdRequest nativeMediationAdRequest, Bundle mediationExtras) { if (!nativeMediationAdRequest.isUnifiedNativeAdRequested()) { Log.e(TAG, "Failed to load ad. Request must be for unified native ads."); if (canInvokeListenerEvent()) mediationNativeListener.onAdFailedToLoad(adapter, AdRequest.ERROR_CODE_INVALID_REQUEST); return; } AdUnitMapper mapper = AdUnitMapper.validateNendAdUnit(serverParameters); if (mapper == null) { if (canInvokeListenerEvent()) mediationNativeListener.onAdFailedToLoad(adapter, AdRequest.ERROR_CODE_INVALID_REQUEST); return; } contextWeakReference = new WeakReference<>(context); this.mediationNativeListener = mediationNativeListener; if (mediationExtras != null && NendMediationAdapter.FormatType.TYPE_VIDEO == mediationExtras.getSerializable(KEY_NATIVE_ADS_FORMAT_TYPE)) { videoAdLoader = new NativeVideoAdLoader(this, mapper, nativeMediationAdRequest, mediationExtras); videoAdLoader.loadAd(); } else { normalAdLoader = new NativeAdLoader( this, new NendAdNativeClient(context, mapper.spotId, mapper.apiKey), nativeMediationAdRequest.getNativeAdOptions()); normalAdLoader.loadAd(); } }
Source:
private void preRenderSetupSimpleBlendMaterials() { dynamicFBM.getFBO(DefaultDynamicFBOs.ReadOnlyGBuffer.getResourceUrn()).setRenderBufferMask(true, true, true); GL11.glEnable(GL_BLEND); GL11.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); GL11.glDepthMask(false); }

Target:
private void preRenderSetupSimpleBlendMaterials() { READ_ONLY_GBUFFER.setRenderBufferMask(true, true, true); GL11.glEnable(GL_BLEND); GL11.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); GL11.glDepthMask(false); }
Source:
private Rule createNewRuleForRow(final int row, final String headCell, final String ruleCell ) { Integer salience = null; if ( this._currentSequentialFlag ) { salience = _currentSalience--; if (salience < _minSalienceTag) { throw new DecisionTableParseException( "Row number is above the max" ); } } final int spreadsheetRow = row + 1; final String name = this._currentRulePrefix + "_" + spreadsheetRow; final Rule rule = new Rule( name, salience, spreadsheetRow ); rule.setComment( " rule values at " + ruleCell + ", header at " + headCell ); return rule; }

Target:
private Rule createNewRuleForRow(final int row, final String headCell, final String ruleCell ) { Integer salience = null; if ( this._currentSequentialFlag ) { salience = _currentSalience--; if (salience < _minSalienceTag) { throw new DecisionTableParseException( "Salience less than the minimum specified on row: " + row ); } } final int spreadsheetRow = row + 1; final String name = this._currentRulePrefix + "_" + spreadsheetRow; final Rule rule = new Rule( name, salience, spreadsheetRow ); rule.setComment( " rule values at " + ruleCell + ", header at " + headCell ); return rule; }
Source:
public Mono<Void> complete(ServiceBusReceivedMessage message) { Objects.requireNonNull(message, "'message' cannot be null."); if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException( "Complete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } else if (message.getLockToken() == null) { return Mono.error(logger.logExceptionAsError(new IllegalArgumentException( "'message.getLockToken()' cannot be null."))); } logger.info("{}: Completing message. Sequence number: {}. Lock: {}. Expiration: {}", entityPath, message.getSequenceNumber(), message.getLockToken(), lockTokenExpirationMap.get(message.getLockToken())); return isLockTokenValid(message.getLockToken()).then( connectionProcessor.flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.complete(message.getLockToken())) .then(Mono.fromRunnable(() -> lockTokenExpirationMap.remove(message.getLockToken())))); }

Target:
public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null); }
Source:
public Map<String, String> getConfig() { if ( injectedConfigNames != null ) { config.clear(); for ( int i = 0; i < injectedConfigNames.size(); i++ ) { config.put( injectedConfigNames.get( i ), injectedConfigValues.get( i ) ); } injectedConfigNames = null; injectedConfigValues = null; } return config; }

Target:
public Map<String, String> getConfig() { applyInjectedProperties(); return config; }
Source:
protected ISecurePreferences getSecurePreferences() { ILock lock = getSecurePreferencesRootLock(); if (lock != null && lock.getDepth() > 0) { throw new RuntimeException("Possible deadlock detected accessing secure storage; aborting request"); } return super.getSecurePreferences(); }

Target:
protected ISecurePreferences getSecurePreferences() { ILock lock = getSecurePreferencesRootLock(); if (lock != null && lock.getDepth() > 0) { try { Thread.sleep(200); } catch (InterruptedException e) { StatusHandler.log(new Status(IStatus.ERROR, RepositoriesUiPlugin.ID_PLUGIN, e.getMessage(), e)); } if (lock.getDepth() > 0) { throw new RuntimeException("Aborting request to prevent deadlock accessing secure storage"); } } return super.getSecurePreferences(); }
Source:
public void processFiles() { if (!this.zipOnly) { this.printZipHeader(); } Set<String> zippedFolders = new HashSet<>(); for (String fileEntry : jobFiles) { String storageLocation = fileEntry[0]; String fileName = fileEntry[1]; if (this.zipOutputStream == null) { openZipStream(); } if (this.directAccessUtil == null) { this.directAccessUtil = new DirectAccessUtil(); } InputStream inputStream = this.directAccessUtil.openDirectAccess(storageLocation); if (inputStream != null && this.zipOutputStream != null) { ZipEntry entry = new ZipEntry(fileName); byte[] bytes = new byte[2 * 8192]; int read = 0; long readSize = 0L; try { if (hasFolder(fileName)) { addFolderToZipStream(getFolderName(fileName), zippedFolders); } this.zipOutputStream.putNextEntry(entry); while ((read = inputStream.read(bytes)) != -1) { this.zipOutputStream.write(bytes, 0, read); readSize += read; } inputStream.close(); this.zipOutputStream.closeEntry(); } catch (IOException ioex) { System.err.println("Faile to compress "+storageLocation); } } else { System.err.println("Failed to access "+storageLocation); } } try { this.zipOutputStream.flush(); this.zipOutputStream.close(); System.out.flush(); System.out.close(); } catch (Exception e) { } }

Target:
public void processFiles() { if (!this.zipOnly) { this.printZipHeader(); } Set<String> zippedFolders = new HashSet<>(); for (String fileEntry : jobFiles) { String storageLocation = fileEntry[0]; String fileName = fileEntry[1]; if (this.zipOutputStream == null) { openZipStream(); } if (this.directAccessUtil == null) { this.directAccessUtil = new DirectAccessUtil(); } InputStream inputStream = this.directAccessUtil.openDirectAccess(storageLocation); if (inputStream != null && this.zipOutputStream != null) { ZipEntry entry = new ZipEntry(fileName); byte[] bytes = new byte[2 * 8192]; int read = 0; long readSize = 0L; try { if (hasFolder(fileName)) { addFolderToZipStream(getFolderName(fileName), zippedFolders); } this.zipOutputStream.putNextEntry(entry); while ((read = inputStream.read(bytes)) != -1) { this.zipOutputStream.write(bytes, 0, read); readSize += read; } inputStream.close(); this.zipOutputStream.closeEntry(); } catch (IOException ioex) { System.err.println("Failed to compress "+storageLocation); } } else { System.err.println("Failed to access "+storageLocation); } } try { this.zipOutputStream.flush(); this.zipOutputStream.close(); System.out.flush(); System.out.close(); } catch (Exception e) { } }
Source:
private NavigableMap<Offset, File> getIndexSegmentDetails(String logSegmentName) { NavigableMap<Offset, File> indexSegmentFileToStartOffset = new TreeMap<>(); File[] indexSegmentFiles = PersistentIndex.getIndexSegmentFilesForLogSegment(dataDir.getAbsolutePath(), logSegmentName); for (File indexSegmentFile : indexSegmentFiles) { indexSegmentFileToStartOffset.put(IndexSegment.getIndexSegmentStartOffset(indexSegmentFile.getName()), indexSegmentFile); } return indexSegmentFileToStartOffset; }

Target:
private SortedMap<Offset, File> getIndexSegmentDetails(String logSegmentName) { SortedMap<Offset, File> indexSegmentStartOffsetToFile = new TreeMap<>(); File[] indexSegmentFiles = PersistentIndex.getIndexSegmentFilesForLogSegment(dataDir.getAbsolutePath(), logSegmentName); for (File indexSegmentFile : indexSegmentFiles) { indexSegmentStartOffsetToFile.put(IndexSegment.getIndexSegmentStartOffset(indexSegmentFile.getName()), indexSegmentFile); } return indexSegmentStartOffsetToFile; }
Source:
private void renameNode() { logger().debug("Renaming Couchbase Node from localhost to " + getContainerIpAddress()); Response response = doHttpRequest(MGMT_PORT, "/node/controller/rename", "POST", new FormBody.Builder() .add("hostname", getInternalIpAddress()) .build(), false ); checkSuccessfulResponse(response, "Could not rename couchbase node"); }

Target:
private void renameNode() { logger().debug("Renaming Couchbase Node from localhost to {}", getContainerIpAddress()); Response response = doHttpRequest(MGMT_PORT, "/node/controller/rename", "POST", new FormBody.Builder() .add("hostname", getInternalIpAddress()) .build(), false ); checkSuccessfulResponse(response, "Could not rename couchbase node"); }
Source:
public static Object valueForStringWithType(String value, VoltType type) { if (type == null || type == VoltType.NULL) { return null; } Object retval = ParameterConverter.tryToMakeCompatible(type.classFromType(), value); assert(ParameterConverter.verifyParameterConversion(retval, type.classFromType())); return retval; }

Target:
public static Object valueForStringWithType(String value, VoltType type) { if (type == VoltType.NULL) { return null; } Object retval = ParameterConverter.tryToMakeCompatible(type.classFromType(), value); assert(ParameterConverter.verifyParameterConversion(retval, type.classFromType())); return retval; }
Source:
private List<Contentlet> getRelatedContentFromIndex(Contentlet contentlet,Relationship rel, User user, boolean respectFrontendRoles)throws DotDataException, DotSecurityException { List<ContentletSearch> contentletSearchList = getRelatedContentSearchFromIndex(contentlet, rel, user, respectFrontendRoles); return contentletSearchList.stream().map(ESContentletAPIImpl::transformContentletSearchToContent).collect(Collectors.toList()); }

Target:
private List<Contentlet> getRelatedContentFromIndex(Contentlet contentlet,Relationship rel, User user, boolean respectFrontendRoles)throws DotDataException, DotSecurityException { List<ContentletSearch> contentletSearchList = getRelatedContentSearchFromIndex(contentlet, rel, user, respectFrontendRoles); return contentletSearchList.stream().map(ESContentletAPIImpl::transformContentletSearchToContent).collect(CollectionsUtils.toImmutableList()); }
Source:
public TestSession getNewSession(Map<String, Object> requestedCapabilities) { LOGGER.entering(); TestSession session = null; try { accessLock.lock(); try { Thread.sleep(3000); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } processParentTunnelCapability(requestedCapabilities); if (sauceApi.getNumberOfTCRunning() <= getMaxNumberOfConcurrentTestSessions()) { session = super.getNewSession(requestedCapabilities); } } finally { accessLock.unlock(); } LOGGER.exiting((session != null) ? session.toString() : null); return session; }

Target:
public TestSession getNewSession(Map<String, Object> requestedCapabilities) { LOGGER.entering(); TestSession session = null; try { Thread.sleep(2000); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } try { accessLock.lock(); processDeprecatedCapabilities(requestedCapabilities); processCredentails(requestedCapabilities); processTunnelIdentifierCapability(requestedCapabilities); processParentTunnelCapability(requestedCapabilities); requestedCapabilities.put(SauceLabsCapability.IDLE_TIMEOUT_CAPABILITY, getTimeOut() / 1000); final int numberOfTCRunning = sauceApi.getNumberOfTCRunning(); if (numberOfTCRunning == -1) { down = true; if (poll = false) { LOGGER.exiting(null); return null; } } if (numberOfTCRunning <= getMaxNumberOfConcurrentTestSessions()) { session = super.getNewSession(requestedCapabilities); } LOGGER.exiting((session != null) ? session.toString() : null); return session; } finally { accessLock.unlock(); } }
Source:
public User getUser(String id) throws NoSuchUserException { User user = connector.getUser(id, sessionData.getAccesstoken()); if (user == null) { throw new NoSuchUserException(id); } return user; }

Target:
public User getUser(String id) { return connector.getUser(id, sessionData.getAccesstoken()); }
Source:
public final Object getAbstractBuildOwner(Run build, Class targetClass) { return build instanceof AbstractBuild ? (AbstractBuild) build : null; }

Target:
private final Object getAbstractBuildOwner(Run build, Class targetClass) { return build instanceof AbstractBuild ? (AbstractBuild) build : null; }
Source:
public void setupTest() { this.mockQuery = Mockito.mock(Query.class); this.mockResult = Mockito.mock(Result.class); this.mockServer = Mockito.mock(Server.class); Mockito.when(this.mockResult.getValues()).thenReturn(ImmutableMap.of("x-att1-x", (Object) "120021")); Mockito.when(this.mockResult.getAttributeName()).thenReturn("X-ATT-X"); Mockito.when(this.mockResult.getClassName()).thenReturn("X-DOMAIN.PKG.CLASS-X"); Mockito.when(this.mockResult.getTypeName()). thenReturn("Type=x-type-x,Group=x-group-x,Other=x-other-x,Name=x-name-x"); Mockito.when(this.mockServer.getLabel()).thenReturn("myhostname"); }

Target:
public void setupTest() { this.mockResult = Mockito.mock(Result.class); Mockito.when(this.mockResult.getValues()).thenReturn(ImmutableMap.of("x-att1-x", (Object) "120021")); Mockito.when(this.mockResult.getAttributeName()).thenReturn("X-ATT-X"); Mockito.when(this.mockResult.getClassName()).thenReturn("X-DOMAIN.PKG.CLASS-X"); Mockito.when(this.mockResult.getTypeName()). thenReturn("Type=x-type-x,Group=x-group-x,Other=x-other-x,Name=x-name-x"); }
Source:
public JobConfig generateConfig(String executionPlanJson) { Map<String, String> configs = new HashMap<>(); configs.put(JobConfig.JOB_NAME(), jobName); List<String> inputs = inEdges.stream().map(edge -> edge.getFormattedSystemStream()).collect(Collectors.toList()); configs.put(TaskConfig.INPUT_STREAMS(), Joiner.on(',').join(inputs)); if (streamGraph.hasWindowOrJoins()) { if ("-1".equals(config.get(TaskConfig.WINDOW_MS(), "-1"))) { long triggerInterval = computeTriggerInterval(); log.info("Using triggering interval: for jobName: {}", triggerInterval, jobName); configs.put(TaskConfig.WINDOW_MS(), String.valueOf(triggerInterval)); } } log.info("Job has generated configs {}", jobName, configs); configs.put(CONFIG_INTERNAL_EXECUTION_PLAN, executionPlanJson); inEdges.stream().filter(StreamEdge::isIntermeidate).forEach(e -> addStreamConfig(e, configs)); String configPrefix = String.format(CONFIG_JOB_PREFIX, jobName); return new JobConfig(Util.rewriteConfig(extractScopedConfig(config, new MapConfig(configs), configPrefix))); }

Target:
public JobConfig generateConfig(String executionPlanJson) { Map<String, String> configs = new HashMap<>(); configs.put(JobConfig.JOB_NAME(), jobName); List<String> inputs = inEdges.stream().map(edge -> edge.getFormattedSystemStream()).collect(Collectors.toList()); configs.put(TaskConfig.INPUT_STREAMS(), Joiner.on(',').join(inputs)); if (streamGraph.hasWindowOrJoins()) { if ("-1".equals(config.get(TaskConfig.WINDOW_MS(), "-1"))) { long triggerInterval = computeTriggerInterval(); log.info("Using triggering interval: for jobName: {}", triggerInterval, jobName); configs.put(TaskConfig.WINDOW_MS(), String.valueOf(triggerInterval)); } } configs.put(CONFIG_INTERNAL_EXECUTION_PLAN, executionPlanJson); inEdges.stream().filter(StreamEdge::isIntermediate).forEach(edge -> addStreamConfig(edge, configs)); log.info("Job has generated configs {}", jobName, configs); String configPrefix = String.format(CONFIG_JOB_PREFIX, jobName); return new JobConfig(Util.rewriteConfig(extractScopedConfig(config, new MapConfig(configs), configPrefix))); }
Source:
private void updateRemoteVideoSurfaceDimensions() { if (mVideoCallScreen == null) { LogUtil.e("VideoCallPresenter.updateRemoteVideoSurfaceDimensions", "mVideoCallScreen is null"); return; } Activity activity = mVideoCallScreen.getVideoCallScreenFragment().getActivity(); if (activity != null) { Point screenSize = new Point(); activity.getWindowManager().getDefaultDisplay().getSize(screenSize); getRemoteVideoSurfaceTexture().setSurfaceDimensions(screenSize); } }

Target:
private void updateRemoteVideoSurfaceDimensions() { Activity activity = mVideoCallScreen.getVideoCallScreenFragment().getActivity(); if (activity != null) { Point screenSize = new Point(); activity.getWindowManager().getDefaultDisplay().getSize(screenSize); getRemoteVideoSurfaceTexture().setSurfaceDimensions(screenSize); } }
Source:
private void addAttributeValue(Metacard metacard, Map.Entry<String, Object> entry) { final Object value = entry.getValue(); LOGGER.trace( "The map key \"{}\" with value \"{}\" is being added to the metacard.", entry.getKey(), value); try { if (value instanceof Serializable) { metacard.setAttribute(new AttributeImpl(entry.getKey(), (Serializable) value)); } else if (value instanceof List) { metacard.setAttribute(new AttributeImpl(entry.getKey(), (List<Serializable>) value)); } else { LOGGER.debug("The value was expected to be Serializable or a list of Serializable items."); } } catch (ClassCastException ex) { LOGGER.debug( "The value was expected to be Serializable or a list of Serializable items. {}", ex); } }

Target:
private void addAttributeValue(Metacard metacard, Map.Entry<String, Object> entry) { final Object value = entry.getValue(); LOGGER.trace( "The map key \"{}\" with value \"{}\" is being added to the metacard.", entry.getKey(), value); if (value instanceof Serializable) { metacard.setAttribute(new AttributeImpl(entry.getKey(), (Serializable) value)); } else if (value instanceof List) { try { metacard.setAttribute(new AttributeImpl(entry.getKey(), (List<Serializable>) value)); } catch (ClassCastException ex) { LOGGER.debug( "The value was expected to be Serializable or a list of Serializable items.", ex); } } else { LOGGER.debug( "The was expected to be Serializable or a list of Serializable items.", value); } }
Source:
private void renderHelmet(ScaledResolution res, float partialTicks) { if (pre(HELMET)) return; ItemStack itemstack = this.mc.player.inventory.armorItemInSlot(3); if (this.mc.gameSettings.thirdPersonView == 0 && itemstack.getItem() != Item.getItemFromBlock(Blocks.AIR)) { if (itemstack.getItem() == Item.getItemFromBlock(Blocks.PUMPKIN)) { renderPumpkinOverlay(res); } else { itemstack.getItem().renderHelmetOverlay(itemstack, mc.player, res, partialTicks); } } post(HELMET); }

Target:
private void renderHelmet(ScaledResolution res, float partialTicks) { if (pre(HELMET)) return; ItemStack itemstack = this.mc.player.inventory.armorItemInSlot(3); if (this.mc.gameSettings.thirdPersonView == 0 && !itemstack.isEmpty()) { Item item = itemstack.getItem(); if (item == Item.getItemFromBlock(Blocks.PUMPKIN)) { renderPumpkinOverlay(res); } else { item.renderHelmetOverlay(itemstack, mc.player, res, partialTicks); } } post(HELMET); }
Source:
private void postCreateBrick(VdcReturnValueBase returnValue) { CreateBrickModel model = (CreateBrickModel) getWindow(); model.stopProgress(); if (returnValue != null && returnValue.getSucceeded()) setWindow(null); }

Target:
private void postCreateBrick(VdcReturnValueBase returnValue) { CreateBrickModel model = (CreateBrickModel) getWindow(); model.stopProgress(); if (returnValue != null && returnValue.getSucceeded()) { setWindow(null); } }
Source:
public static PaletteRoot createPalette() { PaletteRoot root = new PaletteRoot(); IToolManager toolManager = ApplicationGIS.getToolManager(); List<PaletteContainer> categories = new ArrayList<PaletteContainer>(); int open = 0; for( ModalToolCategory category : toolManager.getModalToolCategories() ) { open++; String name = category.getName(); name = fixLabel(name); final int NOT_USED = -1; PaletteContainer container; if (open == NOT_USED ) { PaletteToolbar toolbar = new PaletteToolbar(name); toolbar.setUserModificationPermission(PaletteToolbar.PERMISSION_NO_MODIFICATION); container = toolbar; } else if (open == NOT_USED ){ PaletteGroup group = new PaletteGroup( name ); container = group; } else if( open == 1 || open == 2){ PaletteDrawer drawer = new PaletteDrawer(name); drawer.setInitialState(PaletteDrawer.INITIAL_STATE_OPEN); drawer.setDrawerType(ToolEntry.PALETTE_TYPE_TOOL); drawer.setShowDefaultIcon(false); container = drawer; } else { PaletteDrawer drawer = new PaletteDrawer(name); drawer.setInitialState(PaletteDrawer.INITIAL_STATE_CLOSED); drawer.setDrawerType(ToolEntry.PALETTE_TYPE_TOOL); drawer.setShowDefaultIcon(false); container = drawer; } category.container( container ); for( ModalItem modalItem : category ) { String label = fixLabel(modalItem.getName()); ToolEntry tool = new MapToolEntry(label, modalItem, category.getId()); if(modalItem.getId().equals(DEFAULT_ID)){ root.setDefaultEntry(tool); } container.add(tool); } categories.add(container); } root.addAll(categories); return root; }

Target:
public static PaletteRoot createPalette() { PaletteRoot root = new PaletteRoot(); IToolManager toolManager = ApplicationGIS.getToolManager(); List<PaletteContainer> categories = new ArrayList<PaletteContainer>(); int open = 0; for( ModalToolCategory category : toolManager.getModalToolCategories() ) { open++; String name = category.getName(); name = fixLabel(name); PaletteContainer container; PaletteDrawer drawer = new PaletteDrawer(name); if( category == toolManager.getActiveCategory()){ drawer.setInitialState(PaletteDrawer.INITIAL_STATE_OPEN); } else { drawer.setInitialState(PaletteDrawer.INITIAL_STATE_CLOSED); } drawer.setDrawerType(ToolEntry.PALETTE_TYPE_TOOL); drawer.setUserModificationPermission(PaletteContainer.PERMISSION_NO_MODIFICATION); drawer.setShowDefaultIcon(false); container = drawer; category.container( container ); for( ModalItem modalItem : category ) { String label = fixLabel(modalItem.getName()); ToolEntry tool = new MapToolEntry(label, modalItem, category.getId()); if(modalItem.getId().equals(DEFAULT_ID)){ root.setDefaultEntry(tool); } container.add(tool); } categories.add(container); } root.addAll(categories); return root; }
Source:
public static void unloadWorlds(Hashtable<Integer, long[]> worldTickTimes) { ArrayList<Integer> toRemove = new ArrayList<Integer>(); for (int id : unloadQueue) { Dimension dimension = dimensions.get(id); if (dimension.ticksWaited != dimension.delayToUnload) { dimension.ticksWaited++; continue; } WorldServer w = worlds.get(id); toRemove.add(id); dimension.ticksWaited = 0; if (w != null && (!ForgeChunkManager.getPersistentChunksFor(w).isEmpty() || !w.playerEntities.isEmpty()) || dimension.type.shouldLoadSpawn()) { FMLLog.fine("Aborting unload for dimension %s as status changed", id); continue; } try { if (w != null) { w.saveAllChunks(true, null); } else { FMLLog.warning("Unexpected world unload - world %d is already unloaded", id); } } catch (MinecraftException e) { e.printStackTrace(); } finally { if (w != null) { MinecraftForge.EVENT_BUS.post(new WorldEvent.Unload(w)); w.flush(); setWorld(id, null, w.getMinecraftServer()); } } } unloadQueue.removeAll(toRemove); }

Target:
public static void unloadWorlds(Hashtable<Integer, long[]> worldTickTimes) { IntListIterator queueIterator = unloadQueue.iterator(); while (queueIterator.hasNext()) { int id = queueIterator.next(); Dimension dimension = dimensions.get(id); if (dimension.ticksWaited < ForgeModContainer.dimensionUnloadQueueDelay) { dimension.ticksWaited++; continue; } WorldServer w = worlds.get(id); queueIterator.remove(); dimension.ticksWaited = 0; if (w == null || !ForgeChunkManager.getPersistentChunksFor(w).isEmpty() || !w.playerEntities.isEmpty() || dimension.type.shouldLoadSpawn()) { FMLLog.fine("Aborting unload for dimension %s as status changed", id); continue; } try { w.saveAllChunks(true, null); } catch (MinecraftException e) { e.printStackTrace(); } finally { MinecraftForge.EVENT_BUS.post(new WorldEvent.Unload(w)); w.flush(); setWorld(id, null, w.getMinecraftServer()); } } }
Source:
public GoodDataHttpClient(final HttpClient httpClient, final SSTRetrievalStrategy sstStrategy) { notNull(httpClient); this.httpClient = httpClient; if (sstStrategy instanceof LoginSSTRetrievalStrategy) { this.sstStrategy = sstStrategy; this.authHost = ((LoginSSTRetrievalStrategy) sstStrategy).getHttpHost(); } else { throw new IllegalArgumentException("This constructor is deprecated and works with LoginSSTRetrievalStrategy argument only!"); } }

Target:
public GoodDataHttpClient(final HttpClient httpClient, final SSTRetrievalStrategy sstStrategy) { notNull(httpClient); this.httpClient = httpClient; if (sstStrategy instanceof LoginSSTRetrievalStrategy) { this.sstStrategy = sstStrategy; this.authHost = ((LoginSSTRetrievalStrategy) sstStrategy).getHttpHost(); notNull(authHost, "HTTP host cannot be null"); } else { throw new IllegalArgumentException("This constructor is deprecated and works with LoginSSTRetrievalStrategy argument only!"); } }
Source:
public ApiFuture<List<KeyOffset>> sampleRowKeysAsync(String tableId) { String fullTableName = NameUtil.formatTableName( requestContext.getProjectId(), requestContext.getInstanceId(), tableId); SampleRowKeysRequest requestProto = SampleRowKeysRequest.newBuilder().setTableName(fullTableName).build(); ListenableFuture<List<SampleRowKeysResponse>> responseProto = delegate.sampleRowKeysAsync(requestProto); return ApiFutureUtil.transformAndAdapt( responseProto, new Function<List<SampleRowKeysResponse>, List<KeyOffset>>() { @Override public List<KeyOffset> apply(List<SampleRowKeysResponse> rowKeysList) { if (rowKeysList == null || rowKeysList.isEmpty()) { return Collections.emptyList(); } ImmutableList.Builder<KeyOffset> keyOffsetBuilder = ImmutableList.builder(); for (SampleRowKeysResponse rowKeys : rowKeysList) { keyOffsetBuilder.add(KeyOffset.create(rowKeys.getRowKey(), rowKeys.getOffsetBytes())); } return keyOffsetBuilder.build(); } }); }

Target:
public ApiFuture<List<KeyOffset>> sampleRowKeysAsync(String tableId) { String fullTableName = NameUtil.formatTableName( requestContext.getProjectId(), requestContext.getInstanceId(), tableId); SampleRowKeysRequest requestProto = SampleRowKeysRequest.newBuilder().setTableName(fullTableName).build(); ListenableFuture<List<SampleRowKeysResponse>> responseProto = delegate.sampleRowKeysAsync(requestProto); return ApiFutureUtil.transformAndAdapt( responseProto, new Function<List<SampleRowKeysResponse>, List<KeyOffset>>() { @Override public List<KeyOffset> apply(List<SampleRowKeysResponse> rowKeysList) { ImmutableList.Builder<KeyOffset> keyOffsetBuilder = ImmutableList.builder(); for (SampleRowKeysResponse rowKeys : rowKeysList) { keyOffsetBuilder.add(KeyOffset.create(rowKeys.getRowKey(), rowKeys.getOffsetBytes())); } return keyOffsetBuilder.build(); } }); }
Source:
public StreamingRestClient streamingSearch() { URLConnection urlConnection = null; try { final WebTarget webTarget = client.target(baseUrl).path("search"); urlConnection = setParams(webTarget).getUri().toURL().openConnection(); setHeaders(urlConnection); setCookies(urlConnection); urlConnection.setReadTimeout(60 * 1000); return new StreamingRestClient(urlConnection.getInputStream()); } catch (ConnectException ce) { LOGGER.info("search failed: {}/search?{}", baseUrl, printParams()); LOGGER.error("Caught exception while connecting", ce); throw new RestClientException(503, ce); } catch (IOException e) { try (InputStream errorStream = ((HttpURLConnection) urlConnection).getErrorStream()) { final WhoisResources whoisResources = StreamingRestClient.unMarshalError(errorStream); throw new RestClientException(((HttpURLConnection) urlConnection).getResponseCode(), whoisResources.getErrorMessages()); } catch (IllegalArgumentException | StreamingException | IOException | NullPointerException e1) { LOGGER.info("search failed: {}/search?{}", baseUrl, printParams()); LOGGER.error("Initial IOException: ", e); LOGGER.error("Caught exception while unmarshalling error", e1); throw new RestClientException(500, e1); } } }

Target:
public StreamingRestClient streamingSearch() { URLConnection urlConnection = null; try { final WebTarget webTarget = client.target(baseUrl).path("search"); urlConnection = setParams(webTarget).getUri().toURL().openConnection(); setHeaders(urlConnection); setCookies(urlConnection); urlConnection.setReadTimeout(60 * 1000); return new StreamingRestClient(urlConnection.getInputStream()); } catch (ConnectException ce) { LOGGER.info("search failed: {}/search?{}", baseUrl, printParams()); LOGGER.error("Caught exception while connecting", ce); throw new RestClientException(Response.Status.SERVICE_UNAVAILABLE, ce); } catch (IOException e) { try (InputStream errorStream = ((HttpURLConnection) urlConnection).getErrorStream()) { final WhoisResources whoisResources = StreamingRestClient.unMarshalError(errorStream); throw new RestClientException(((HttpURLConnection) urlConnection).getResponseCode(), whoisResources.getErrorMessages()); } catch (IllegalArgumentException | StreamingException | IOException | NullPointerException e1) { LOGGER.info("search failed: {}/search?{}", baseUrl, printParams()); LOGGER.error("Initial IOException: ", e); LOGGER.error("Caught exception while unmarshalling error", e1); throw new RestClientException(Response.Status.INTERNAL_SERVER_ERROR, e1); } } }
Source:
public ComputableCacheNode duplicate() { if (cacheEvals && cachedValue != null && !cachedValue.isNull()) { return new ComputableCacheNode(getKey(), getTags(), getParents(), func, true, cachedValue.deepCopy(), isCacheCurrent); } else { return new ComputableCacheNode(getKey(), getTags(), getParents(), func, cacheEvals, null, isCacheCurrent); } }

Target:
public ComputableCacheNode duplicate() { if (isStoredValueAvailable()) { return new ComputableCacheNode(getKey(), getTags(), getParents(), func, true, cachedValue.duplicate(), isCacheCurrent); } else { return new ComputableCacheNode(getKey(), getTags(), getParents(), func, cacheEvals, null, isCacheCurrent); } }
Source:
public void bridge$placeEntity(net.minecraft.world.World world, Entity entity, float yaw) { boolean didPort; if (entity instanceof EntityPlayerMP) { this.placeInPortal(entity, yaw); didPort = true; } else { if (((WorldServerBridge) this.world).bridge$getDimensionId() == 1) { didPort = true; } else { didPort = this.placeInExistingPortal(entity, yaw); } } if (PhaseTracker.getInstance().getCurrentContext() instanceof InvokingTeleporterContext) { if (!((InvokingTeleporterContext) PhaseTracker.getInstance().getCurrentContext()).getDidPort()) { ((InvokingTeleporterContext) PhaseTracker.getInstance().getCurrentContext()).setDidPort(didPort); } } }

Target:
public void bridge$placeEntity(net.minecraft.world.World world, Entity entity, float yaw) { boolean didPort; if (entity instanceof EntityPlayerMP) { this.placeInPortal(entity, yaw); didPort = true; } else { if (((WorldServerBridge) this.world).bridge$getDimensionId() == Constants.World.END_DIMENSION_ID) { didPort = true; } else { didPort = this.placeInExistingPortal(entity, yaw); } } if (didPort) { ((IPhaseState) PhaseTracker.getInstance().getCurrentState()).markTeleported(PhaseTracker.getInstance().getCurrentContext()); } }
Source:
public void testParameterCollectionAndPositional() { final Item item = new Item( "Mouse", "Micro$oft mouse" ); final Item item2 = new Item( "Computer", "Dell computer" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); try { em.persist( item ); em.persist( item2 ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.getTransaction().begin(); Query q = em.createQuery( "select item from Item item where item.name in ?1 and item.descr = ?2" ); q.setHint( "org.hibernate.fetchSize", 10 ); q.setHint( "org.hibernate.fetchSize", "10" ); List params = new ArrayList(); params.add( item.getName() ); params.add( item2.getName() ); q.setParameter( 1, params ); q.setParameter( 2, item2.getDescr() ); List result = q.getResultList(); assertNotNull( result ); assertEquals( 1, result.size() ); } catch (Exception e){ if ( em.getTransaction() != null && em.getTransaction().isActive() ) { em.getTransaction().rollback(); } throw e; } finally { em.close(); } }

Target:
public void testParameterCollectionAndPositional() { final Item item = new Item( "Mouse", "Microsoft mouse" ); final Item item2 = new Item( "Computer", "Dell computer" ); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); try { em.persist( item ); em.persist( item2 ); assertTrue( em.contains( item ) ); em.getTransaction().commit(); em.getTransaction().begin(); Query q = em.createQuery( "select item from Item item where item.name in ?1 and item.descr = ?2" ); List params = new ArrayList(); params.add( item.getName() ); params.add( item2.getName() ); q.setParameter( 1, params ); q.setParameter( 2, item2.getDescr() ); List result = q.getResultList(); assertNotNull( result ); assertEquals( 1, result.size() ); } catch (Exception e){ if ( em.getTransaction() != null && em.getTransaction().isActive() ) { em.getTransaction().rollback(); } throw e; } finally { em.close(); } }
Source:
public void testNoUpdatesIfHidden() throws Exception { openProgressView(); IWorkbenchPage activePage = window.getActivePage(); activePage.setPartState(activePage.getActivePartReference(), IWorkbenchPage.STATE_MINIMIZED); assertFalse("Progress view still visible.", activePage.isPartVisible(progressView)); Job job1 = runDummyJob(); Job job2 = runDummyJob(); processEventsUntil(() -> false, 1000); int count1 = countJobs(job1); assertEquals(0, count1); int count2 = countJobs(job2); assertEquals(0, count2); openProgressView(); count1 = countJobs(job1); assertEquals(1, count1); count2 = countJobs(job2); assertEquals(1, count2); FinishedJobs.getInstance().clearAll(); processEventsUntil(() -> false, 1000); count1 = countJobs(job1); assertEquals(0, count1); count2 = countJobs(job2); assertEquals(0, count2); }

Target:
public void testNoUpdatesIfHidden() throws Exception { openProgressView(); IWorkbenchPage activePage = window.getActivePage(); activePage.setPartState(activePage.getActivePartReference(), IWorkbenchPage.STATE_MINIMIZED); processEvents(); assertFalse("Progress view still visible.", activePage.isPartVisible(progressView)); Job job1 = runDummyJob(); Job job2 = runDummyJob(); processEventsUntil(() -> false, 1000); int count1 = countJobs(job1); assertEquals(0, count1); int count2 = countJobs(job2); assertEquals(0, count2); openProgressView(); count1 = countJobs(job1); assertEquals(1, count1); count2 = countJobs(job2); assertEquals(1, count2); FinishedJobs.getInstance().clearAll(); processEventsUntil(() -> false, 1000); count1 = countJobs(job1); assertEquals(0, count1); count2 = countJobs(job2); assertEquals(0, count2); }
Source:
public Context startScopedSpan(String spanName, Context context) { Span span; if (context.getData(SPAN_CONTEXT).isPresent()) { span = startSpanWithRemoteParent(spanName, context); } else { SpanBuilder spanBuilder = startSpanWithExplicitParent(spanName, context); span = spanBuilder.setSpanKind(Span.Kind.SERVER).startSpan(); } return context.addData(OPENTELEMETRY_SPAN_KEY, span).addData("scope", TRACER.withSpan(span)); }

Target:
private Context startScopedSpan(String spanName, Context context) { Span span; Optional<Object> optionalSpanContext = context.getData(SPAN_CONTEXT); if (optionalSpanContext.isPresent() && optionalSpanContext.get() instanceof SpanContext) { span = startSpanWithRemoteParent(spanName, (SpanContext) optionalSpanContext.get()); } else { SpanBuilder spanBuilder = startSpanWithExplicitParent(spanName, context); span = spanBuilder.setSpanKind(Span.Kind.SERVER).startSpan(); } return context.addData(OPENTELEMETRY_SPAN_KEY, span).addData("scope", TRACER.withSpan(span)); }