auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onInfoWindowClick(Marker marker) { // Stop any callbacks to refresh the vehicle marker popup balloons mCustomInfoWindowAdapter.cancelUpdates(); // Show trip details screen for the vehicle associated with this marker ObaTripStatus status = mMarkerData.getStatusFromMarker(marker); String focusedStopId = mController.getFocusedStopId(); if (mController != null && mController.getFocusedStopId != null) { TripDetailsActivity.start(mActivity, status.getActiveTripId(), focusedStopId); } else { TripDetailsActivity.start(mActivity, status.getActiveTripId()); } }

Target:
public void onInfoWindowClick(Marker marker) { // Stop any callbacks to refresh the vehicle marker popup balloons mCustomInfoWindowAdapter.cancelUpdates(); // Show trip details screen for the vehicle associated with this marker ObaTripStatus status = mMarkerData.getStatusFromMarker(marker); if (mController != null && mController.getFocusedStopId() != null) { TripDetailsActivity.start(mActivity, status.getActiveTripId(), mController.getFocusedStopId()); } else { TripDetailsActivity.start(mActivity, status.getActiveTripId()); } }
Source:
public StatementsMatcher(List<Statement> statements) { Collections.copy(statements, unmatched); }

Target:
public StatementsMatcher(List<Statement> statements) { unmatched = new ArrayList<>(); // Make a local copy of statements, because it's probably mutable // and we don't want to change it upon a later removeAll call. Collections.copy(statements, unmatched); }
Source:
public void notifySurfaceDetached() { // Release active image reader in detached listener super.notifySurfaceDetached(); // Release inactive image readers if (mImageReaderToReleaseList.size() > 0) { for (ImageReaderProxy imageReader : mImageReaderToReleaseList) { Surface surface = imageReader.getSurface(); if (surface != null) { surface.release(); } imageReader.close(); } mImageReaderToReleaseList.clear(); } }

Target:
public void notifySurfaceDetached() { // Release active image reader in detached listener super.notifySurfaceDetached(); // Release inactive image readers if (!mImageReaderToReleaseList.isEmpty()) { for (ImageReaderProxy imageReader : mImageReaderToReleaseList) { // There will be the stric mode erro under API Level 23. Add surface // release to dereference. Surface surface = imageReader.getSurface(); if (surface != null) { surface.release(); } imageReader.close(); } mImageReaderToReleaseList.clear(); } }
Source:
public Optional<U> generate(final WebContext context, final U profile) { init(); final U linkedProfile = profileService.findByLinkedId(profile.getId()); if (linkedProfile != null) { return Optional.of(linkedProfile); } else { if (failIfLinkedUserNotFound) { throw new TechnicalException("No linked account found for: " + profile); } else { // fallback to the original account return Optional.ofNullable(profile); } } }

Target:
public U generate(final WebContext context, final U profile) { init(); final U linkedProfile = profileService.findByLinkedId(profile.getId()); if (linkedProfile != null) { return linkedProfile; } else { if (failIfLinkedUserNotFound) { throw new TechnicalException("No linked account found for: " + profile); } else { // fallback to the original account return profile; } } }
Source:
/* package */void openFirstTimeWindow() { final boolean showProgress = PrefUtil.getAPIPreferenceStore().getBoolean( IWorkbenchPreferenceConstants.SHOW_PROGRESS_ON_STARTUP); if (!showProgress) { doOpenFirstTimeWindow(); } else { // We don't know how many plug-ins will be loaded, // assume we are loading a tenth of the installed plug-ins. // (The Eclipse SDK loads 7 of 86 plug-ins at startup as of // 2005-5-20) final int expectedProgressCount = Math.max(1, WorkbenchPlugin.getDefault().getBundleCount()); runStartupWithProgress(expectedProgressCount, () -> doOpenFirstTimeWindow()); } }

Target:
/* package */void openFirstTimeWindow() { final boolean showProgress = PrefUtil.getAPIPreferenceStore().getBoolean( IWorkbenchPreferenceConstants.SHOW_PROGRESS_ON_STARTUP); if (!showProgress) { doOpenFirstTimeWindow(); } else { // We don't know how many plug-ins will be loaded, // assume we are loading a tenth of the installed plug-ins. // (The Eclipse SDK loads 7 of 86 plug-ins at startup as of // 2005-5-20) runStartupWithProgress(() -> doOpenFirstTimeWindow()); } }
Source:
public String getY() { return y; }

Target:
String getY() { return y; }
Source:
public boolean matches(String type, URI uri, String realm) { //Realm is not used as for now boolean match = true; match &= AuthScheme.NEGOTIATE.toString().equalsIgnoreCase(type); match &= getServiceUri().getScheme().equalsIgnoreCase(uri.getScheme()); match &= getServiceUri().getHost().equalsIgnoreCase(uri.getHost()); return match; }

Target:
public boolean matches(String type, URI uri, String realm) { // The class matches all requests for Negotiate scheme.Realm is not used as for now return NEGOTIATE.equalsIgnoreCase(type); }
Source:
public final Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable { if (!passivation) { //if we don't have passivation then it is a simple remove from DataContainer. The CDL already locks the key in //commit entries (EntryWrappingInterceptor) return invokeNextInterceptor(ctx, command); } final Object key = command.getKey(); try { cdl.lock(key, true); return invokeNextInterceptor(ctx, command); } finally { cdl.unlock(key); } }

Target:
public final Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable { if (!passivation) { //if we don't have passivation then it is a simple remove from DataContainer. The CDL already locks the key in //commit entries (EntryWrappingInterceptor) return invokeNextInterceptor(ctx, command); } final Object key = command.getKey(); if (!cdl.lock(key, true)) { return null; //no-op } try { return invokeNextInterceptor(ctx, command); } finally { cdl.unlock(key); } }
Source:
ViewerSorter createSorterInstance() throws CoreException { Object contributed = element.createExecutableExtension(ATT_CLASS); if (contributed instanceof ViewerSorter) { return (ViewerSorter) contributed; } if (contributed instanceof ViewerComparator) { return new WrappedViewerComparator((ViewerComparator) contributed); } throw new ClassCastException("Class contributed by " + element.getNamespaceIdentifier() + //$NON-NLS-1$ " to " + INavigatorContentExtPtConstants.TAG_NAVIGATOR_CONTENT + //$NON-NLS-1$ "/" + INavigatorContentExtPtConstants.TAG_COMMON_SORTER //$NON-NLS-1$ + " is not an instance of " + ViewerComparator.class.getName() + ": " + contributed.getClass().getName() //$NON-NLS-1$ //$NON-NLS-2$ ); }

Target:
private ViewerSorter createSorterInstance() throws CoreException { Object contributed = element.createExecutableExtension(ATT_CLASS); if (contributed instanceof ViewerSorter) { return (ViewerSorter) contributed; } if (contributed instanceof ViewerComparator) { return new WrappedViewerComparator((ViewerComparator) contributed); } throw new ClassCastException("Class contributed by " + element.getNamespaceIdentifier() + //$NON-NLS-1$ " to " + INavigatorContentExtPtConstants.TAG_NAVIGATOR_CONTENT + //$NON-NLS-1$ "/" + INavigatorContentExtPtConstants.TAG_COMMON_SORTER //$NON-NLS-1$ + " is not an instance of " + ViewerComparator.class.getName() + ": " + contributed.getClass().getName() //$NON-NLS-1$ //$NON-NLS-2$ ); }
Source:
public static void main(String[] args) { int status = getConf(args); System.exit(status); }

Target:
public static void main(String[] args) { System.exit(getConf(args)); }
Source:
public void processBean(CRResolvableBean bean, IndexWriter writer) throws CRException { System.out.println(writer.numDocs()); }

Target:
public void processBean(CRResolvableBean bean, IndexWriter writer) throws CRException { }
Source:
public XWikiAttachment setAttachment(XWikiAttachment attachment) { attachment.setDoc(this); XWikiAttachmentList list = this.attachmentList; XWikiAttachment currentAttachment = list.getByFilename(attachment.getFilename()); list.set(attachment); return currentAttachment; }

Target:
public XWikiAttachment setAttachment(XWikiAttachment attachment) { return this.attachmentList.set(attachment); }
Source:
public static AbstractTaskContextStore loadTaskContextStore() { ExtensionPointReader<AbstractTaskContextStore> reader = new ExtensionPointReader<AbstractTaskContextStore>( ITasksCoreConstants.ID_PLUGIN, "contextStore", "contextStore", AbstractTaskContextStore.class); //$NON-NLS-1$ //$NON-NLS-2$ IStatus status = reader.read(); if (!status.isOK()) { StatusHandler.log(status); } AbstractTaskContextStore contextStore = reader.getItem(); if (contextStore != null) { return contextStore; } return new DefaultTaskContextStore(); }

Target:
public static AbstractTaskContextStore loadTaskContextStore() { ExtensionPointReader<AbstractTaskContextStore> reader = new ExtensionPointReader<AbstractTaskContextStore>( ITasksCoreConstants.ID_PLUGIN, "contextStore", "contextStore", AbstractTaskContextStore.class); //$NON-NLS-1$ //$NON-NLS-2$ reader.read(); AbstractTaskContextStore contextStore = reader.getItem(); if (contextStore != null) { return contextStore; } return new DefaultTaskContextStore(); }
Source:
public void sendMessage(String message) { buffer.append(message + "\n"); }

Target:
public void sendMessage(String message) { buffer.append(message).append("\n"); }
Source:
public void createActions() { setGoalOrderAction = new SetGoalOrderAction((GoalArtifact) editor.getAwa(), this); RemovedFromGoalHandler handler = new RemovedFromGoalHandler() { @Override public void removedFromGoal(Collection<? extends Artifact> removed) { worldComposite.removeItems(removed); worldComposite.getXViewer().remove(removed); worldComposite.getXViewer().refresh(goalArtifact); } }; removeFromGoalAction = new RemoveFromGoalAction((GoalArtifact) editor.getAwa(), this, handler); }

Target:
private void createActions() { setGoalOrderAction = new SetGoalOrderAction((GoalArtifact) editor.getAwa(), this); RemovedFromGoalHandler handler = new RemovedFromGoalHandler() { @Override public void removedFromGoal(Collection<? extends Artifact> removed) { worldComposite.removeItems(removed); worldComposite.getXViewer().remove(removed); worldComposite.getXViewer().refresh(goalArtifact); } }; removeFromGoalAction = new RemoveFromGoalAction((GoalArtifact) editor.getAwa(), this, handler); }
Source:
@After public void tearDown() throws Exception { if (socksProxy != null) { socksProxy.shutdown(); } if (cache != null) { cache.delete(); } client.connectionPool().evictAll(); if (client.connectionPool().connectionCount() > 0) { // Minimise test flakiness due to possible race conditions with connections closing. // Some number of tests will report here, but not fail due to this delay. System.out.println("Delaying to avoid flakes"); Thread.sleep(500L); System.out.println("After delay: " + client.connectionPool().connectionCount()); } }

Target:
@After public void tearDown() throws Exception { if (socksProxy != null) { socksProxy.shutdown(); } if (cache != null) { cache.delete(); } }
Source:
protected void buildScript(int age) { // hard-coded list of card types to load when continuing the feed if (age == 0) { init(); } addPendingClient(new BecauseYouReadClient()); addPendingClient(new ContinueReadingClient()); addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new IntegerListClient()); addPendingClient(new MostReadClient()); addPendingClient(new RandomClient(new RandomCard(getContext(), getSite()))); }

Target:
protected void buildScript(int age) { // hard-coded list of card types to load when continuing the feed if (age == 0) { init(); } addPendingClient(new BecauseYouReadClient()); addPendingClient(new ContinueReadingClient()); addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new IntegerListClient()); addPendingClient(new MostReadClient()); addPendingClient(new RandomClient()); }
Source:
public void addLocation(long blockId, BlockLocation location) { mBlockLocations.computeIfAbsent(blockId, x -> new HashMap<>()); mBlockLocations.get(blockId).put(location.getWorkerId(), location); }

Target:
public void addLocation(long blockId, BlockLocation location) { mBlockLocations.computeIfAbsent(blockId, x -> new HashMap<>(4)); mBlockLocations.get(blockId).put(location.getWorkerId(), location); }
Source:
protected void onPostExecute(OEmbed embed) { if (embed != null) { // TODO: decide if this is ok. Most likely because the setStep // function isnt intensive if(!isCancelled()) { mMainWebView.loadUrl(mStep.getEmded().getOembed().getURL()); mMainWebView.setTag(mStep.getEmded().getOembed().getURL()); } } }

Target:
protected void onPostExecute(OEmbed embed) { if (embed != null) { // TODO: decide if this is ok. Most likely because the setStep // function isnt intensive if(!isCancelled()) { String url = mStep.getEmded().getOembed().getURL(); mMainWebView.loadUrl(url); mMainWebView.setTag(url); } } }
Source:
public void tearDown(final ManagementClient managementClient, final String containerId) { // TODO: add {"allow-resource-service-restart" => true} to ejbRemoteAddress write-attribute operation once WFLY-8793 / JBEAP-10955 is fixed // and remove this reload try { ServerReload.reloadIfRequired(managementClient.getControllerClient()); } catch (Exception e) { throw new RuntimeException(e); } // TODO: remove this reload once WFLY-8821 / JBEAP-11074 is fixed try { ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); } catch (Exception e) { throw new RuntimeException(e); } applyRemoveAllowReload(managementClient.getControllerClient(), domainAddress, false); applyRemoveAllowReload(managementClient.getControllerClient(), realmAddress, false); }

Target:
public void tearDown(final ManagementClient managementClient, final String containerId) { applyRemoveAllowReload(managementClient.getControllerClient(), domainAddress, false); applyRemoveAllowReload(managementClient.getControllerClient(), realmAddress, false); }
Source:
public GroupScan clone(List<SchemaPath> columns) { logger.debug("HttpGroupScan clone {}", columns); HttpGroupScan newScan = new HttpGroupScan(this); newScan.columns = columns; return newScan; }

Target:
public GroupScan clone(List<SchemaPath> columns) { return new HttpGroupScan(this, columns); }
Source:
private void executeUpdate(String sql) { try { Statement statement = this.connection.createStatement(); statement.executeUpdate(sql); statement.close(); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
private void executeUpdate(String sql) { try (Statement statement = this.connection.createStatement()) { statement.executeUpdate(sql); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public static String toString(int oid) { try { Field[] fields = Oid.class.getFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (field.getInt(null) == oid) { return field.getName(); } } } catch (IllegalAccessException e) { // never happens } return "<unknown:" + oid + ">"; }

Target:
public static String toString(int oid) { try { Field[] fields = Oid.class.getFields(); for (Field field : fields) { if (field.getInt(null) == oid) { return field.getName(); } } } catch (IllegalAccessException e) { // never happens } return "<unknown:" + oid + ">"; }
Source:
public void testPasswordResetWithNoExistingUser_shouldThrow() { String username= "anyUser"; //mocks when(userRepository.findUser(anyString())).thenReturn(null); //Test passwordResetService.resetUserPassword(username); Assert.assertNotNull(userRepository.findUser(username)); verify(userRepository).findUser(username); verify(passwordResetService).resetUserPassword(username); }

Target:
public void testPasswordResetWithNoExistingUser_shouldThrow() { String username = "anyUser"; // mocks when(userRepository.findUser(anyString())).thenReturn(null); // Test passwordResetService.resetUserPassword(username); }
Source:
public DelegatingTemplateEngine(final CompositeConfiguration config, final ContentStore db, final File destination, final File templatesPath) { super(config, db, destination, templatesPath); this.renderers = new TemplateEngines(config, db, destination, templatesPath); this.registerExtractorsForCustomTypes(); }

Target:
public DelegatingTemplateEngine(final CompositeConfiguration config, final ContentStore db, final File destination, final File templatesPath) { super(config, db, destination, templatesPath); this.renderers = new TemplateEngines(config, db, destination, templatesPath); }
Source:
NavigableSet<Clustering> makeClusterings(boolean reversed) { int pos = 0; NavigableSet<Clustering> clusterings = new TreeSet<>(reversed ? metadata.comparator.reversed() : metadata.comparator); while (pos <= KEY_RANGE) { int skip = rand.nextInt(KEY_RANGE / 10) * (rand.nextInt(3) + 2 / 3); // increased chance of getting 0 pos += skip; clusterings.add(clustering(pos)); } return clusterings; }

Target:
private NavigableSet<Clustering> makeClusterings(boolean reversed) { int pos = 0; NavigableSet<Clustering> clusterings = new TreeSet<>(reversed ? metadata.comparator.reversed() : metadata.comparator); while (pos <= KEY_RANGE) { int skip = rand.nextInt(KEY_RANGE / 10) * (rand.nextInt(3) + 2 / 3); // increased chance of getting 0 pos += skip; clusterings.add(clustering(pos)); } return clusterings; }
Source:
public boolean visitEnter(FunctionParseNode node) throws SQLException { // TODO: Oracle supports nested aggregate function while other DBs don't. Should we? if (node.isAggregate()) { if (aggregateFunction != null) { throw new SQLFeatureNotSupportedException("Nested aggregate functions are not supported"); } this.aggregateFunction = node; this.isAggregate = true; } else if(node.getClass().isAssignableFrom(ArrayIndexFunction.class)) { this.isAggregate = true; } return true; }

Target:
public boolean visitEnter(FunctionParseNode node) throws SQLException { // TODO: Oracle supports nested aggregate function while other DBs don't. Should we? if (node.isAggregate()) { if (aggregateFunction != null) { throw new SQLFeatureNotSupportedException("Nested aggregate functions are not supported"); } this.aggregateFunction = node; this.isAggregate = true; } return true; }
Source:
public int hashCode() { return Objects.hash(baseDataSource + dimensions + metrics); }

Target:
public int hashCode() { return Objects.hash(baseDataSource, dimensions, metrics); }
Source:
public GeographyPointValue(double longitude, double latitude) { // Add 0.0 to avoid -0.0. m_latitude = latitude + 0.0; m_longitude = longitude + 0.0; if (m_latitude < -90.0 || m_latitude > 90.0) { throw new IllegalArgumentException("Latitude out of range in GeographyPointValue constructor"); } if (m_longitude < -180.0 || m_longitude > 180.0) { throw new IllegalArgumentException("Longitude out of range in GeographyPointValue constructor"); } }

Target:
public GeographyPointValue(double longitude, double latitude) { m_latitude = latitude; m_longitude = longitude; if (m_latitude < -90.0 || m_latitude > 90.0) { throw new IllegalArgumentException("Latitude out of range in GeographyPointValue constructor"); } if (m_longitude < -180.0 || m_longitude > 180.0) { throw new IllegalArgumentException("Longitude out of range in GeographyPointValue constructor"); } }
Source:
public static IRemoteConnection createConnection(URI hostUri, String hostName) throws RemoteConnectionException { IRemoteConnection connection = null; IRemoteConnectionType connectionType = getConnectionType(hostUri); IConnectionFactory connectionFactory = CONNECTION_FACTORIES.get(connectionType.getId()); // Create a new connection if (connectionFactory != null) { connection = connectionFactory.createConnection(hostUri, hostName); } else { connection = DEFAULT_CONNECTION_FACTORY.createConnection(hostUri, hostName); } return connection; }

Target:
public static IRemoteConnection createConnection(URI hostUri, String hostName) throws RemoteConnectionException { IRemoteConnectionType connectionType = getConnectionType(hostUri); IConnectionFactory connectionFactory = CONNECTION_FACTORIES.get(connectionType.getId()); if (connectionFactory == null) { connectionFactory = DEFAULT_CONNECTION_FACTORY; } // Create and return a new connection return connectionFactory.createConnection(hostUri, hostName); }
Source:
public InodeLockList() { mInodes = new ArrayList<>(); mLockModes = new ArrayList<>(); }

Target:
InodeLockList() { mInodes = new ArrayList<>(); mLockModes = new ArrayList<>(); }
Source:
public void testBuildBlobId() throws Exception { for (Short version : versions) { buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId); } }

Target:
public void testBuildBlobId() throws Exception { buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId); }
Source:
protected void unregisterSender() { if (sender != null) sender.unregister(context, parent.getPriorityClass()); }

Target:
protected void unregisterSender() { sender.unregister(context, parent.getPriorityClass()); }
Source:
private void invokeClassLoadTestingHookIfNeeded() throws InterruptedException { // Testing support only. if (TESTING_CLASS_LOAD != null) { TESTING_CLASS_LOAD.run(); if (Thread.currentThread().isInterrupted()) { // Otherwise the interrupt isn't recognized and the test doesn't work. throw new InterruptedException("loading was interrupted."); } } }

Target:
private void invokeClassLoadTestingHookIfNeeded() throws InterruptedException { // Testing support only. if (TESTING_CLASS_LOAD != null) { TESTING_CLASS_LOAD.run(); } }
Source:
protected void loadProperties(Properties props) throws IOException { try { super.loadProperties(props); } catch(FileNotFoundException e) { //location was not found, create if (configFile != null && copyOutTemplate) { OutputStream fout = configFile.out(); props.store(fout, comments); fout.flush(); fout.close(); } } }

Target:
protected void loadProperties(Properties props) throws IOException { try { super.loadProperties(props); } catch(FileNotFoundException e) { //location was not found, create if (configFile != null && copyOutTemplate) { try (OutputStream fout = configFile.out()) { props.store(fout, comments); fout.flush(); } } } }
Source:
public RegisteredService findServiceBy(final long id) { var result = this.services.get(id, k -> this.serviceRegistry.findServiceById(id)); return validateRegisteredService(result); }

Target:
public RegisteredService findServiceBy(final long id) { val result = this.services.get(id, k -> this.serviceRegistry.findServiceById(id)); return validateRegisteredService(result); }
Source:
private int addFieldToDescriptionMap(Map<String, Object> descriptionMap, String diskAlias, String fieldName, String fieldValue, int descriptionAvailableLength) { if ((descriptionAvailableLength -= getJsonFieldPotentialOverhead(fieldName, descriptionMap)) > 0) { // There's enough space for the field's overhead in the metadata + at least one character from its value. if (fieldValue.length() > descriptionAvailableLength) { fieldValue = fieldValue.substring(0, descriptionAvailableLength); auditLogNoSpaceToStoreEntireDiskField(diskAlias, fieldName, fieldValue); } descriptionMap.put(fieldName, fieldValue); return descriptionAvailableLength - fieldValue.length(); } return 0; }

Target:
private int addFieldToDescriptionMap(Map<String, Object> descriptionMap, String diskAlias, String fieldName, String fieldValue, int descriptionAvailableLength) { if ((descriptionAvailableLength -= getJsonFieldPotentialOverhead(fieldName, descriptionMap)) > 0) { // There's enough space for the field's overhead in the metadata + at least one character from its value. if (fieldValue.length() > descriptionAvailableLength) { fieldValue = fieldValue.substring(0, descriptionAvailableLength); } descriptionMap.put(fieldName, fieldValue); return descriptionAvailableLength - fieldValue.length(); } return descriptionAvailableLength; }
Source:
private void startDiscovery() { discoveryService.scheduleWithFixedDelay(() -> { try { // jitter to avoid overloading database and overloading the backup store SECONDS.sleep(ThreadLocalRandom.current().nextLong(1, organizationDiscoveryIntervalMillis / 1000)); log.info("Running shard organizer..."); submitJobs(discoverAndInitializeTablesToOrganize()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { log.error(t, "Error running shard organizer"); } }, 0, organizationDiscoveryIntervalMillis, TimeUnit.MILLISECONDS); }

Target:
private void startDiscovery() { discoveryService.scheduleWithFixedDelay(() -> { try { // jitter to avoid overloading database and overloading the backup store MILLISECONDS.sleep(ThreadLocalRandom.current().nextLong(1, organizationDiscoveryIntervalMillis)); log.info("Running shard organizer..."); submitJobs(discoverAndInitializeTablesToOrganize()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { log.error(t, "Error running shard organizer"); } }, 0, organizationDiscoveryIntervalMillis, TimeUnit.MILLISECONDS); }
Source:
private CacheBuilder<CacheKey, TypeCodec<?>> defaultCacheBuilder() { CacheBuilder<CacheKey, TypeCodec<?>> builder = CacheBuilder.newBuilder() // 19 primitive codecs + collections thereof = 19*3 + 19*19 = 418 codecs, // so let's start with roughly 1/4 of that .initialCapacity(100) .weigher(new TypeCodecWeigher()) .maximumWeight(1000); if (logger.isTraceEnabled()) // do not bother adding a listener if it will be ineffective builder = builder.removalListener(new TypeCodecRemovalListener()); return builder; }

Target:
private CacheBuilder<CacheKey, TypeCodec<?>> defaultCacheBuilder() { CacheBuilder<CacheKey, TypeCodec<?>> builder = CacheBuilder.newBuilder() // 19 primitive codecs + collections thereof = 19*3 + 19*19 = 418 codecs, // so let's start with roughly 1/4 of that .initialCapacity(100) .maximumWeight(1000) .weigher(new TypeCodecWeigher()); if (logger.isTraceEnabled()) // do not bother adding a listener if it will be ineffective builder = builder.removalListener(new TypeCodecRemovalListener()); return builder; }
Source:
public static Project getByName(String name) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); if (env.hasProjects()) { Project search = new Project(name); Project proj; if ((proj = env.getProjects().get(name)) != null) { return (proj); } } return null; }

Target:
public static Project getByName(String name) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); if (env.hasProjects()) { Project proj; if ((proj = env.getProjects().get(name)) != null) { return (proj); } } return null; }
Source:
private void usingIsEmpty() { Optional<Object> op = Optional.emtpy(); if (!op.isEmpty()) { op.get(); // Compliant - dead code } }

Target:
private void usingIsEmpty() { Optional<Object> op = Optional.empty(); if (!op.isEmpty()) { op.get(); // Compliant - dead code } }
Source:
private void synchCTFState(MArea areaModel) { List<MPartStack> stacks = findDirectStacks(areaModel); int count = 0; for (MPartStack stack : stacks) { if (stack.isToBeRendered()) count++; } // If there's more than one stack visible we use a CTF if (count > 1) ensureCTF(areaModel); else ensureComposite(areaModel); }

Target:
private void synchCTFState(MArea areaModel) { List<MPartStack> stacks = findDirectStacks(areaModel); int count = 0; for (MPartStack stack : stacks) { if (stack.isToBeRendered()) count++; } // If there's more than one stack visible we use a CTF if (count > 1) ensureCTF(areaModel, stacks); else ensureComposite(areaModel, stacks); }
Source:
public void reset() { // Clear the entire usedFlagBuffer final int usedFlagBufferCapacity = usedFlagBuffer.capacity(); // putLong() instead of put() can boost the performance of clearing the buffer final int n = usedFlagBufferCapacity / Long.BYTES; for (int i = 0; i < n; i += Long.BYTES) { usedFlagBuffer.putLong(i, 0L); } for (int i = n; i < usedFlagBufferCapacity; i++) { usedFlagBuffer.put(i, (byte) 0); } }

Target:
public void reset() { // Clear the entire usedFlagBuffer final int usedFlagBufferCapacity = usedFlagBuffer.capacity(); // putLong() instead of put() can boost the performance of clearing the buffer final int n = (usedFlagBufferCapacity / Long.BYTES) * Long.BYTES; for (int i = 0; i < n; i += Long.BYTES) { usedFlagBuffer.putLong(i, 0L); } for (int i = n; i < usedFlagBufferCapacity; i++) { usedFlagBuffer.put(i, (byte) 0); } }
Source:
private void updateBrickSize() { long totalSize = 0; // Calculate and show the total size of all selected device so that user can get an idea of what will be his // brick // capacity. if (getStorageDevices().getSelectedItems() != null) { for (StorageDevice storageDevice : getStorageDevices().getSelectedItems()) { if (storageDevice.getCanCreateBrick()) { totalSize += storageDevice.getSize(); } } } Pair<SizeUnit, Double> convertedSize = SizeConverter.autoConvert(totalSize, SizeUnit.MB); setBrickSize(convertedSize); }

Target:
private void updateBrickSize() { long totalSize = 0; // Calculate and show the total size of all selected device so that user can get an idea of what will be his // brick // capacity. if (getStorageDevices().getSelectedItems() != null) { for (StorageDevice storageDevice : getStorageDevices().getSelectedItems()) { totalSize += storageDevice.getSize(); } } Pair<SizeUnit, Double> convertedSize = SizeConverter.autoConvert(totalSize, SizeUnit.MB); setBrickSize(convertedSize); }
Source:
public void start() throws Exception { logger.info("Starting Gerrit-Trigger Plugin"); doXStreamRegistrations(); logger.trace("Loading configs"); load(); if (servers == null) { servers = new ArrayList<GerritServer>(); if (config != null) { //have loaded data in old format, so add a new server with the old config to the list. GerritServer defaultServer = new GerritServer(DEFAULT_SERVER_NAME); defaultServer.setConfig(config); servers.add(defaultServer); } } for (GerritServer s : servers) { s.start(); } }

Target:
public void start() throws Exception { logger.info("Starting Gerrit-Trigger Plugin"); doXStreamRegistrations(); logger.trace("Loading configs"); load(); for (GerritServer s : servers) { s.start(); } }
Source:
public int compareTo(ApplicationInfoEx other) { if (mContext == null) return TextUtils.join(", ", getApplicationName()).compareToIgnoreCase( TextUtils.join(", ", other.getApplicationName())); // Locale respecting sorter Collator collator = Collator.getInstance(Locale.getDefault()); return collator.compare(TextUtils.join(", ", getApplicationName()), TextUtils.join(", ", other.getApplicationName())); }

Target:
public int compareTo(ApplicationInfoEx other) { // Locale respecting sorter Collator collator = Collator.getInstance(Locale.getDefault()); return collator.compare(TextUtils.join(", ", getApplicationName()), TextUtils.join(", ", other.getApplicationName())); }
Source:
public void eval() { // Get the timestamp in milliseconds long timestamp = inputDate.value; // Get the interval in milliseconds long groupByInterval = interval.value; java.time.Instant instant = java.time.Instant.ofEpochMilli(timestamp - (timestamp % groupByInterval)); out.value = instant.toEpochMilli(); }

Target:
public void eval() { // Get the timestamp in milliseconds long timestamp = inputDate.value; // Get the interval in milliseconds long groupByInterval = interval.value; out.value = (timestamp - (timestamp % groupByInterval)); }
Source:
public void finish() { if (state == State.NEEDS_INPUT) { state = State.HAS_OUTPUT; WorkProcessor<Page> resultPages = getSortedPages( new SimplePageWithPositionComparator(sourceTypes, sortChannels, sortOrder)); resultPages.process(); sortedPages = resultPages.iterator(); } }

Target:
public void finish() { if (state == State.NEEDS_INPUT) { state = State.HAS_OUTPUT; WorkProcessor<Page> resultPages = getSortedPages( new SimplePageWithPositionComparator(sourceTypes, sortChannels, sortOrder)); sortedPages = resultPages.iterator(); } }
Source:
protected void completeRemoval(IModule m) { // AS7 requires the .deployed markers to be removed. Other servers require no action try { IPath archiveDestination = getModuleDeployRoot(new IModule[]{m}); IFilesystemController controller = getFilesystemController(); boolean useAS7Behavior = DeploymentMarkerUtils.supportsJBoss7MarkerDeployment(getServer()); if( useAS7Behavior) { DeploymentMarkerUtils.removedDeployedMarker(archiveDestination, controller); DeploymentMarkerUtils.removedDeployFailedMarker(archiveDestination, controller); } } catch(CoreException ce) { JBossServerCorePlugin.log(ce); } }

Target:
protected void completeRemoval(IModule m) { try { IPath archiveDestination = getModuleDeployRoot(new IModule[]{m}); boolean useAS7Behavior = DeploymentMarkerUtils.supportsJBoss7MarkerDeployment(getServer()); // AS7-derived requires the .deployed markers to be removed. Other servers require no action if( useAS7Behavior) { IFilesystemController controller = getFilesystemController(); DeploymentMarkerUtils.removedDeployedMarker(archiveDestination, controller); DeploymentMarkerUtils.removedDeployFailedMarker(archiveDestination, controller); } } catch(CoreException ce) { JBossServerCorePlugin.log(ce); } }
Source:
public void onClick(ClickEvent event) { ExpandableListViewItem eventItem = null; if (event.getSource() instanceof ExpandableListViewItem) { eventItem = (ExpandableListViewItem)event.getSource(); } if (eventItem != null) { boolean active = eventItem.isActive(); // Hide all, then unhide the one clicked. hideAllDetails(); eventItem.toggleExpanded(!active); toggleExpanded(); } else { // Clicked a close icon hideAllDetails(); } event.preventDefault(); event.stopPropagation(); }

Target:
public void onClick(ClickEvent event) { event.preventDefault(); event.stopPropagation(); ExpandableListViewItem eventItem = null; if (event.getSource() instanceof ExpandableListViewItem) { eventItem = (ExpandableListViewItem)event.getSource(); } if (eventItem != null) { boolean active = eventItem.isActive(); // Hide all, then unhide the one clicked. hideAllDetails(); eventItem.toggleExpanded(!active); toggleExpanded(); } else { // Clicked a close icon hideAllDetails(); } }
Source:
public String getPropertyString() { return ((Creeper) entity.getBukkitEntity()).getMaxFuseTicks() + ""; }

Target:
public String getPropertyString() { return String.valueOf(((Creeper) entity.getBukkitEntity()).getMaxFuseTicks()); }
Source:
protected CaseInsensitiveMap(final Map<String, VALUE> underlyingMap) { this.underlyingMap = underlyingMap; }

Target:
private CaseInsensitiveMap(final Map<String, VALUE> underlyingMap) { this.underlyingMap = underlyingMap; }
Source:
public final boolean continueReading(UncheckedBooleanSupplier maybeMoreDataSupplier) { return (readPending && maybeMoreDataToRead()) || delegate.continueReading(maybeMoreDataSupplier); }

Target:
public final boolean continueReading(UncheckedBooleanSupplier maybeMoreDataSupplier) { return delegate.continueReading(maybeMoreDataSupplier); }
Source:
private void saveZeroValueForResource(org.sonar.api.resources.File resource, SensorContext context) { // use non comment lines of code for coverage calculation Measure<Integer> nclocMeasure = context.getMeasure(resource, CoreMetrics.NCLOC); if (nclocMeasure != null) { double ncloc = context.getMeasure(resource, CoreMetrics.NCLOC).getValue(); context.saveMeasure(resource, getZeroCoverageLineHitsDataMetric(resource, context)); context.saveMeasure(resource, linesToCoverMetric, ncloc); context.saveMeasure(resource, uncoveredLinesMetric, ncloc); } }

Target:
private void saveZeroValueForResource(org.sonar.api.resources.File resource, SensorContext context) { // use non comment lines of code for coverage calculation Measure<Integer> nclocMeasure = context.getMeasure(resource, CoreMetrics.NCLOC); if (nclocMeasure != null) { double ncloc = nclocMeasure.getValue(); context.saveMeasure(resource, getZeroCoverageLineHitsDataMetric(resource, context)); context.saveMeasure(resource, linesToCoverMetric, ncloc); context.saveMeasure(resource, uncoveredLinesMetric, ncloc); } }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; throw new RuntimeException("Only one PropertiesModule may be installed"); }

Target:
public boolean equals(Object obj) { // equals() is used by Guice to dedup multiple installs. This is module has state so we only // allow one instance of it to ever be installed. This equals() implementation // forces guice to dedup as long as it is the same exact object. Installing multiple // PropertiesPropertySource instances will result in duplicate binding errors for PropertySource // where the errors will provide details about where the multiple installs came from. return this == obj; }
Source:
public void send(Message<?> message, ScopeDescriptor scopeDescription) throws Exception { if (canResolve(scopeDescription)) { String aggregateIdentifier = ((AggregateScopeDescriptor) scopeDescription).getIdentifier().toString(); Aggregate<T> aggregate = load(aggregateIdentifier); if (aggregate != null) { aggregate.handle(message); } else { logger.debug("Aggregate (with id: [{}]) cannot be loaded. Hence, message '[{}]' cannot be handled.", aggregateIdentifier, message); } } }

Target:
public void send(Message<?> message, ScopeDescriptor scopeDescription) throws Exception { if (canResolve(scopeDescription)) { String aggregateIdentifier = ((AggregateScopeDescriptor) scopeDescription).getIdentifier().toString(); load(aggregateIdentifier).handle(message); } }
Source:
public void updateReviewItem(ChangeInfo task) { fReviewList.put(task.getChange_id(), task); //Here we keep the change_id because it is shown to the user }

Target:
public void updateReviewItem(ChangeInfo task) { fReviewList.put(task.getId(), task); }
Source:
public static Protocol fromValue(String value) { Protocol[] items = Protocol.values(); for (Protocol item : items) { if (item.toString().equalsIgnoreCase(value)) { return item; } } return (Protocol) GetEnumValue.fromValueOrDefault(value, UNRECOGNIZED); }

Target:
public static Protocol fromValue(String value) { return (Protocol) GetEnumValue.fromValueOrDefault(value, Protocol.UNRECOGNIZED); }
Source:
private String GetLocalStoragesFormattedString() { StringBuilder localStorages = new StringBuilder(""); //$NON-NLS-1$ for (StorageDomain a : Linq.<StorageDomain> cast(getSelectedItems())) { if (a.getStorageType() == StorageType.LOCALFS) { localStorages.append(a.getStorageName()).append(", "); //$NON-NLS-1$ } } return localStorages.substring(0, localStorages.length() - 2); }

Target:
private String GetLocalStoragesFormattedString() { StringBuilder localStorages = new StringBuilder(); for (StorageDomain a : Linq.<StorageDomain> cast(getSelectedItems())) { if (a.getStorageType() == StorageType.LOCALFS) { localStorages.append(a.getStorageName()).append(", "); //$NON-NLS-1$ } } return localStorages.substring(0, localStorages.length() - 2); }
Source:
public String getFingerprint(Schema schema) { if (theClient == null) { theClient = initializeClient(); } String subject = schema.getName(); final int guid; try { guid = theClient.register(subject, schema); System.out.println("GUID: [" + guid + "]"); } catch (IOException | RestClientException e) { throw new RuntimeException(e); } return Integer.toString(guid); }

Target:
public String getFingerprint(Schema schema) { final String subject = schema.getName(); final int guid; try { guid = theClient.register(subject, schema); } catch (IOException | RestClientException e) { throw new RuntimeException(e); } return Integer.toString(guid); }
Source:
private boolean declaringTypeIsLocalOrImported(CtTypeReference declaringType) { if (declaringType != null) { if (!isTypeInCollision(declaringType, false) && (isImportedInClassImports(declaringType) || classNamePresentInJavaLang(declaringType))) { return true; } if (!isTypeInCollision(declaringType, false) && addClassImport(declaringType)) { return true; } while (declaringType != null) { if (declaringType.equals(targetType)) { return true; } declaringType = declaringType.getDeclaringType(); } } return false; }

Target:
private boolean declaringTypeIsLocalOrImported(CtTypeReference declaringType) { if (declaringType != null) { if (!isTypeInCollision(declaringType, false) && addClassImport(declaringType)) { return true; } if (isImportedInClassImports(declaringType) || classNamePresentInJavaLang(declaringType)) { return true; } while (declaringType != null) { if (declaringType.equals(targetType)) { return true; } declaringType = declaringType.getDeclaringType(); } } return false; }
Source:
MkNotifications(final int quantity) { this.notifications = new ArrayList<Notification>(quantity); for (int index = 0; index < quantity; index += 1) { this.notifications.add(index, new MkNotification(index)); } }

Target:
MkNotifications(final int quantity) { this.notifications = new ArrayList<Notification>(quantity); for (int index = 0; index < quantity; ++index) { this.notifications.add(index, new MkNotification(index)); } }
Source:
@Override public void testSiteBuildWithForkedMojo() throws Exception { // TODO currently failing, apparently from NPE in DefaultDependencyGraphBuilder.canFindCoreClass after failing to resolve an artifact from the test project }

Target:
public void testSiteBuildWithForkedMojo() throws Exception { // TODO currently failing, apparently from NPE in DefaultDependencyGraphBuilder.canFindCoreClass after failing to resolve an artifact from the test project }
Source:
public boolean isFinished() { checkState(initialized.get(), "Driver is not initialized"); checkLockNotHeld("Can not check finished status while holding the driver lock"); // if we can get the lock, attempt a clean shutdown; otherwise someone else will shutdown Optional<Boolean> result = tryWithLock(this::isFinishedInternal); return result.orElseGet(() -> state.get() != State.ALIVE || driverContext.isDone()); }

Target:
public boolean isFinished() { checkLockNotHeld("Can not check finished status while holding the driver lock"); // if we can get the lock, attempt a clean shutdown; otherwise someone else will shutdown Optional<Boolean> result = tryWithLock(this::isFinishedInternal); return result.orElseGet(() -> state.get() != State.ALIVE || driverContext.isDone()); }
Source:
public Node(String address, String logPath) { this.address = address; this.logPath = logPath; this.shutdown = new ShutdownAction(this); this.start = new StartAction(this); }

Target:
public Node(String address, String logPath) { this(address, null, logPath); }
Source:
protected UserException typeConversionError(ColumnMetadata schema, ValueDef valueDef) { String type = valueDef.type().name().toLowerCase(); if (valueDef.isArray()) { for (int i = 0; i < valueDef.dimensions(); i++) { type += "[]"; } } return typeConversionError(schema, type); }

Target:
protected UserException typeConversionError(ColumnMetadata schema, ValueDef valueDef) { StringBuilder buf = new StringBuilder() .append(valueDef.type().name().toLowerCase()); if (valueDef.isArray()) { for (int i = 0; i < valueDef.dimensions(); i++) { buf.append("[]"); } } return typeConversionError(schema, buf.toString()); }
Source:
public void testStructWithNull() throws Exception { runTest( "test_flat_map/flat_map_struct_with_null.dwrf", INTEGER, STRUCT_TYPE, ExpectedValuesBuilder.get(Function.identity(), TestMapFlatSelectiveStreamReader::intToList).setNullValuesFrequency(TestMapFlatSelectiveStreamReader.ExpectedValuesBuilder.Frequency.SOME)); }

Target:
public void testStructWithNull() throws Exception { runTest( "test_flat_map/flat_map_struct_with_null.dwrf", INTEGER, STRUCT_TYPE, ExpectedValuesBuilder.get(Function.identity(), TestMapFlatSelectiveStreamReader::intToList).setNullValuesFrequency(SOME)); }
Source:
protected void refreshVisuals() { Connector connector = (Connector) getNotationView(); NamedStyle namedStyle = connector.getNamedStyle(NotationPackage.Literals.INT_VALUE_STYLE, "delta"); if (namedStyle instanceof IntValueStyle) { refreshArrowDelta((IntValueStyle) namedStyle); } else { // no style - reset value ((DurationLinkFigure) getFigure()).setArrowPositionDelta(0); } super.refreshVisuals(); }

Target:
protected void refreshVisuals() { refreshArrowDelta(); super.refreshVisuals(); }
Source:
void setTo( String to ) { if ( to != null && !"".equals( to ) ) { to = to.replaceAll( ";", "," ); props.put( "to", to ); } }

Target:
public void setTo( String to ) { if ( to != null && !"".equals( to ) ) { to = to.replaceAll( ";", "," ); props.put( "to", to ); } }
Source:
public IStatus validate(Object[] selection) { String errorMessage = ""; //$NON-NLS-1$ if (selection.length == 0) { errorMessage = NO_SELECTION; } else { final Object firstSelection = selection[0]; if (selection.length != 1 || false == firstSelection instanceof Property || (firstSelection instanceof Property && false == ((Property) firstSelection).getType() instanceof PrimitiveType)) { errorMessage = Messages.SinglePropertyAttributeValidator_errorMessage; } } return buildIStatus(errorMessage); }

Target:
public IStatus validate(Object[] selection) { String errorMessage = ""; //$NON-NLS-1$ if (selection.length <= 0) { errorMessage = NO_SELECTION; } else { final Object firstSelection = selection[0]; if (selection.length != 1 || false == firstSelection instanceof Property || (firstSelection instanceof Property && false == ((Property) firstSelection).getType() instanceof PrimitiveType)) { errorMessage = Messages.SinglePropertyAttributeValidator_errorMessage; } } return buildIStatus(errorMessage); }
Source:
public MigratableTableTranslation<DBOColumnModel, DBOColumnModel> getTranslator() { return new BasicMigratableTableTranslation<DBOColumnModel>(){ @TemporaryCode(author="ziming", comment = "one-time migration change. remove after stack 309") @Override public DBOColumnModel createDatabaseObjectFromBackup(DBOColumnModel backup) { //doing this round trip will assign default value to maxListLength ColumnModel columnModel = ColumnModelUtils.createDTOFromDBO(backup); if(ColumnTypeListMappings.isList(columnModel.getColumnType())){ columnModel.setMaximumListLength(ColumnConstants.MAX_ALLOWED_LIST_LENGTH); } DBOColumnModel modifiedDBO = ColumnModelUtils.createDBOFromDTO(columnModel, StackConfigurationSingleton.singleton().getTableMaxEnumValues()); return modifiedDBO; } }; }

Target:
public MigratableTableTranslation<DBOColumnModel, DBOColumnModel> getTranslator() { return new BasicMigratableTableTranslation<DBOColumnModel>(){ @TemporaryCode(author="ziming", comment = "one-time migration change. remove after stack 309") @Override public DBOColumnModel createDatabaseObjectFromBackup(DBOColumnModel backup) { //doing this round trip will assign default value to maxListLength ColumnModel columnModel = ColumnModelUtils.createDTOFromDBO(backup); DBOColumnModel modifiedDBO = ColumnModelUtils.createDBOFromDTO(columnModel, StackConfigurationSingleton.singleton().getTableMaxEnumValues()); return modifiedDBO; } }; }
Source:
protected void revertTask() { getEnclosingCommand().getParameters().getDiskImage().setImageStatus(ImageStatus.ILLEGAL); ImagesHandler.updateImageStatus( getEnclosingCommand().getParameters().getDestinationImageId(), ImageStatus.ILLEGAL); }

Target:
protected void revertTask() { // nothing to do }
Source:
public State advance() throws IOException { mCheckpointStream = null; mNextEntry = null; while (true) { updateInputStream(); if (mCheckpointStream != null) { return State.CHECKPOINT; } advanceEntry(); if (mNextEntry != null) { return State.LOG; } if (mInputStream == null || mInputStream.isDone() || mInputStream.mFile.isIncompleteLog()) { return State.DONE; } } }

Target:
public State advance() throws IOException { mCheckpointStream = null; mNextEntry = null; updateInputStream(); if (mCheckpointStream != null) { return State.CHECKPOINT; } advanceEntry(); if (mNextEntry != null) { return State.LOG; } return State.DONE; }
Source:
public void process(IProgressMonitor monitor) throws CoreException { if (monitor == null) monitor = new NullProgressMonitor(); SubMonitor subMonitor = SubMonitor.convert(monitor, "Searching unused members", this.units.length); //$NON-NLS-1$ for (ICompilationUnit unit : this.units) { doSearchCU(unit, subMonitor.newChild(1)); } }

Target:
public void process(IProgressMonitor monitor) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor, "Searching unused members", this.units.length); //$NON-NLS-1$ for (ICompilationUnit unit : this.units) { doSearchCU(unit, subMonitor.split(1)); } }