auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static WsMeasures.Component.Builder toWsComponent(ComponentDto component, Map<MetricDto, ComponentTreeData.Measure> measures, Map<String, ComponentDto> referenceComponentsByUuid) { WsMeasures.Component.Builder wsComponent = componentDtoToWsComponent(component); ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyResourceUuid()); if (referenceComponent != null) { wsComponent.setRefId(referenceComponent.uuid()); wsComponent.setRefKey(referenceComponent.key()); } for (Map.Entry<MetricDto, ComponentTreeData.Measure> entry : measures.entrySet()) { <START> ComponentTreeData.Measure measure = entry.getValue(); <END> Double value = measure.isValueSet() ? measure.getValue() : null; Double variation = measure.isVariationSet() ? measure.getVariation() : null; WsMeasures.Measure.Builder wsMeasureBuilder = createWsMeasureBuilder(entry.getKey(), value, measure.getData(), variation); wsComponent.addMeasures(wsMeasureBuilder); } return wsComponent; }</code><technical_language>This loop optimized reusing instances of protobuf Measure.Builder PeriodValue.Builder (by calling clear() call). variation autoboxed Double</technical_language>

Target:
private static WsMeasures.Component.Builder toWsComponent(ComponentDto component, Map<MetricDto, ComponentTreeData.Measure> measures, Map<String, ComponentDto> referenceComponentsByUuid) { WsMeasures.Component.Builder wsComponent = componentDtoToWsComponent(component); ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyResourceUuid()); if (referenceComponent != null) { wsComponent.setRefId(referenceComponent.uuid()); wsComponent.setRefKey(referenceComponent.key()); } WsMeasures.Measure.Builder measureBuilder = WsMeasures.Measure.newBuilder(); for (Map.Entry<MetricDto, ComponentTreeData.Measure> entry : measures.entrySet()) { ComponentTreeData.Measure measure = entry.getValue(); updateMeasureBuilder(measureBuilder, entry.getKey(), measure.getValue(), measure.getData(), measure.getVariation()); wsComponent.addMeasures(measureBuilder); measureBuilder.clear(); } return wsComponent; }
Source:
<code>public boolean isTablet(){ int size = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; boolean large = Configuration.SCREENLAYOUT_SIZE_LARGE == size; <START> boolean xlarge = Configuration.SCREENLAYOUT_SIZE_XLARGE == size; <END> return (xlarge || large); }</code><technical_language>I want >= instead of equality screen densities match standard bucket sizes i.e. SCREENLAYOUT_SIZE_LARGE, SCREENLAYOUT_SIZE_XLARGE</technical_language>

Target:
private boolean isTablet() { return isTablet(this); }
Source:
<code>public void actionPerformed(ActionEvent evt) { Node[] selected = ExplorerTopComponent.findInstance().getExplorerManager().getSelectedNodes(); if (selected.length != 1 || !(selected[0] instanceof MarkersNode)) { return; } MarkersNode markersNode = (MarkersNode) selected[0]; Model model = markersNode.getModelForNode(); Vec3 offset = new Vec3(0.11, 0.22, 0.33); MarkerSet markerset = model.getMarkerSet(); PhysicalFrame frameToUse; if ( model.getBodySet().getSize()==0) frameToUse = model.get_ground(); else <START> frameToUse = model.getBodyList().begin().__deref__(); <END> String newMarkerName = makeUniqueMarkerName(markerset); Marker newMarker = new Marker(); newMarker.setName(newMarkerName); newMarker.set_location(offset); newMarker.setParentFrame(frameToUse); OpenSimContext context = OpenSimDB.getInstance().getContext(model); context.cacheModelAndState(); model.addMarker(newMarker); try { context.restoreStateFromCachedModel(); } catch (IOException ex) { ErrorDialog.displayExceptionDialog(ex); } Vector<OpenSimObject> markers = new Vector<OpenSimObject>(); markers.add(newMarker); addMarkers(markers, true); }</code><technical_language>ground</technical_language>

Target:
public void actionPerformed(ActionEvent evt) { Node[] selected = ExplorerTopComponent.findInstance().getExplorerManager().getSelectedNodes(); if (selected.length != 1 || !(selected[0] instanceof MarkersNode)) { return; } MarkersNode markersNode = (MarkersNode) selected[0]; Model model = markersNode.getModelForNode(); Vec3 offset = new Vec3(0.11, 0.22, 0.33); MarkerSet markerset = model.getMarkerSet(); PhysicalFrame frameToUse = model.get_ground(); String newMarkerName = makeUniqueMarkerName(markerset); Marker newMarker = new Marker(); newMarker.setName(newMarkerName); newMarker.set_location(offset); newMarker.setParentFrame(frameToUse); OpenSimContext context = OpenSimDB.getInstance().getContext(model); context.cacheModelAndState(); model.addMarker(newMarker); try { context.restoreStateFromCachedModel(); } catch (IOException ex) { ErrorDialog.displayExceptionDialog(ex); } Vector<OpenSimObject> markers = new Vector<OpenSimObject>(); markers.add(newMarker); addMarkers(markers, true); }
Source:
<code>public void onProcessFailed(ExecuteException e) { this.commandStatus.setExitStatus(new LinuxExitValue(e.getExitValue())); <START> if (e.getExitValue() == 124) { <END> this.commandStatus.setTimedout(true); } this.callback.accept(this.commandStatus); }</code><technical_language>124 a constant</technical_language>

Target:
public void onProcessFailed(ExecuteException e) { this.commandStatus.setExitStatus(new LinuxExitValue(e.getExitValue())); if (e.getExitValue() == TIMEOUT_EXIT_VALUE || e.getExitValue() == SIGTERM_EXIT_VALUE) { this.commandStatus.setTimedout(true); } this.callback.accept(this.commandStatus); }
Source:
<code>URL getURLForQuery(String query) throws URISyntaxException, MalformedURLException, FetcherException; Parser getParser(); @Override default List<BibEntry> performSearch(String query) throws FetcherException { if (StringUtil.isBlank(query)) { return Collections.emptyList(); } URL urlForQuery; try { urlForQuery = getURLForQuery(query); } catch (URISyntaxException | MalformedURLException e) { LoggerFactory.getLogger(this.getClass()).info("Search URL is malformed", query); throw new FetcherException("Search URI is malformed", e); } try (InputStream stream = getUrlDownload(urlForQuery).asInputStream()) { List<BibEntry> fetchedEntries = getParser().parseEntries(stream); fetchedEntries.forEach(this::doPostCleanup); return fetchedEntries; } catch (IOException e) { <START> LoggerFactory.getLogger(this.getClass()).info("IOException at URL {}", urlForQuery.toString()); <END> throw new FetcherException("A network error occurred", e); } catch (ParseException e) { throw new FetcherException("An internal parser error occurred", e); } }</code><technical_language>Extract constant consistent other code: private static final Logger LOGGER = LoggerFactory.getLogger(SearchBasedParserFetcher.java .class);</technical_language>

Target:
URL getURLForQuery(String query) throws URISyntaxException, MalformedURLException, FetcherException; Parser getParser(); @Override default List<BibEntry> performSearch(String query) throws FetcherException { if (StringUtil.isBlank(query)) { return Collections.emptyList(); } URL urlForQuery; try { urlForQuery = getURLForQuery(query); } catch (URISyntaxException | MalformedURLException | FetcherException e) { throw new FetcherException(String.format("Search URI crafted from query %s is malformed", query), e); } return getBibEntries(urlForQuery); }
Source:
<code>public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { <START> if (orderParams instanceof CancelOrderByIdParams) { <END> return cancelOrder(((CancelOrderByIdParams) orderParams).getOrderId()); } return false; }</code><technical_language>exception thrown if required param is missing</technical_language>

Target:
public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { if (!(orderParams instanceof CancelOrderByIdParams)) { return false; } CancelOrderByIdParams cancelParams = (CancelOrderByIdParams) orderParams; return cancelOrder(cancelParams.getOrderId()); }
Source:
<code>public TextBlock getJavadocBefore(int lineNoBefore) { int lineNo = lineNoBefore - 2; <START> while (lineNo > 0 && shouldSkip(lineNo)) { <END> lineNo--; } return javadocComments.get(lineNo); }</code><technical_language>uhh, need do regression affected Checks - <LINK_0> provide investigation code added, git history</technical_language>

Target:
public TextBlock getJavadocBefore(int lineNoBefore) { int lineNo = lineNoBefore - 2; while (lineNo > 0 && (lineIsBlank(lineNo) || lineIsComment(lineNo))) { lineNo--; } return javadocComments.get(lineNo); }
Source:
<code>public boolean testSourceType(CommandSource source) { Class<? extends CommandSource> clazz = source.getClass(); <START> return sourceTypeDeep ? sourceType.isAssignableFrom(clazz) : sourceType.equals(clazz); <END> }</code><technical_language>this.sourceType this.sourceTypeDeep</technical_language>

Target:
public boolean testSourceType(CommandSource source) { Class<? extends CommandSource> clazz = source.getClass(); return this.sourceTypeDeep ? this.sourceType.isAssignableFrom(clazz) : this.sourceType.equals(clazz); }
Source:
<code>public LocalFirehoseFactory( @JsonProperty("baseDir") File baseDir, @JsonProperty("filter") String filter, @JsonProperty("parser") StringInputRowParser parser ) { super( <START> FileUtils.listFiles( <END> Preconditions.checkNotNull(baseDir).getAbsoluteFile(), new WildcardFileFilter(filter), TrueFileFilter.INSTANCE ) ); this.baseDir = baseDir; this.filter = filter; this.parser = parser; log.info("Initialized with " + getObjects() + " files"); }</code><technical_language>This happen in construction. Firehose factories get constructed semi-frequently (anytime Task objects deserialized) necessarily used. hits disk network deferred firehose is connected</technical_language>

Target:
public LocalFirehoseFactory( @JsonProperty("baseDir") File baseDir, @JsonProperty("filter") String filter, @JsonProperty("parser") StringInputRowParser parser ) { this.baseDir = baseDir; this.filter = filter; this.parser = parser; }
Source:
<code>private void handlePushNotificationResponsePerToken(final PushNotificationResponse<AeroGearApnsPushNotification> pushNotificationResponse ) { final String deviceToken = pushNotificationResponse.getPushNotification().getToken(); if (pushNotificationResponse.isAccepted()) { logger.trace(String.format("Push notification for '%s' (payload=%s)", deviceToken, pushNotificationResponse.getPushNotification().getPayload())); } else { final String rejectReason = pushNotificationResponse.getRejectionReason(); if ((pushNotificationResponse.getTokenInvalidationTimestamp() != null) || ("BadDeviceToken".equals(rejectReason))) { <START> logger.warn(rejectReason + ", removing token: " + deviceToken); <END> invalidTokens.add(deviceToken); } } }</code><technical_language>this INFO</technical_language>

Target:
private void handlePushNotificationResponsePerToken(final PushNotificationResponse<AeroGearApnsPushNotification> pushNotificationResponse ) { final String deviceToken = pushNotificationResponse.getPushNotification().getToken(); if (pushNotificationResponse.isAccepted()) { logger.trace(String.format("Push notification for '%s' (payload=%s)", deviceToken, pushNotificationResponse.getPushNotification().getPayload())); } else { final String rejectReason = pushNotificationResponse.getRejectionReason(); if ((pushNotificationResponse.getTokenInvalidationTimestamp() != null) || ("BadDeviceToken".equals(rejectReason))) { logger.info(rejectReason + ", removing token: " + deviceToken); invalidTokens.add(deviceToken); } } }
Source:
<code><START> private static AsyncRequestResponseHandler getInstance(RestServerMetrics restServerMetrics) { <END> if (instantiated.compareAndSet(false, true)) { AsyncRequestResponseHandlerFactory.restServerMetrics = restServerMetrics; instance = new AsyncRequestResponseHandler(restServerMetrics); } if (AsyncRequestResponseHandlerFactory.restServerMetrics != restServerMetrics) { throw new IllegalStateException("RestServerMetrics instance provided during construction of " + "AsyncRequestResponseHandler differs from the one currently received"); } return instance; }</code><technical_language>this is thread safe right? if threads call this method simultaneously</technical_language>

Target:
private static AsyncRequestResponseHandler getInstance(RestServerMetrics restServerMetrics) { lock.lock(); try { if (instance == null) { AsyncRequestResponseHandlerFactory.restServerMetrics = restServerMetrics; instance = new AsyncRequestResponseHandler(restServerMetrics); } if (AsyncRequestResponseHandlerFactory.restServerMetrics != restServerMetrics) { throw new IllegalStateException("RestServerMetrics instance provided during construction of " + "AsyncRequestResponseHandler differs from the one currently received"); } } finally { lock.unlock(); } return instance; }
Source:
<code>public void run() { try { while (true) { long currentTime = System.currentTimeMillis(); <START> long remainingTime = _lastInvokeTime + _periodicTriggerInterval - currentTime; <END> if (remainingTime <= 0) { if (_batchCallbackProcessor == null || _batchCallbackProcessor.queueIsEmpty()) { NotificationContext changeContext = new NotificationContext(_manager); changeContext.setType(Type.CALLBACK); changeContext.setChangeType(_changeType); enqueueTask(changeContext); } break; } else { wait(remainingTime); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e1) { logger.warn("Exception during execute refresh task. Error: ", e1); } }</code><technical_language>reduce usage of _periodicTriggerInterval in callback class, please pass interval a constructor parameter? a cleaner design</technical_language>

Target:
public void run() { if (!isReady()) { return; } long currentTime = System.currentTimeMillis(); long remainingTime = _lastInvokeTime + _triggerInterval - currentTime; if (remainingTime <= 0) { if (_batchCallbackProcessor == null || _batchCallbackProcessor.queueIsEmpty()) { NotificationContext changeContext = new NotificationContext(_manager); changeContext.setType(Type.CALLBACK); changeContext.setChangeType(_changeType); try { enqueueTask(changeContext); } catch (Exception e) { logger.warn("An exception was thrown during periodic triggered task.", e); } } scheduleNewTask(_triggerInterval); } else { scheduleNewTask(remainingTime); } }
Source:
<code>public void setUp() { bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout)); <START> standardOutOrig = System.out; <END> }</code><technical_language>need this, if do in needs set standardOutOrig call System.setOut - a reference set</technical_language>

Target:
public void setUp() { bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout)); }
Source:
<code><START> public static List<OpenMode> getOperationSupportedFileSystem() { <END> ArrayList<OpenMode> arrayList = new ArrayList<>(); arrayList.add(OpenMode.SMB); arrayList.add(OpenMode.FILE); arrayList.add(OpenMode.DROPBOX); arrayList.add(OpenMode.BOX); arrayList.add(OpenMode.GDRIVE); arrayList.add(OpenMode.ONEDRIVE); return arrayList; }</code><technical_language>Please a HashSet, faster contains() operations</technical_language>

Target:
public static HashSet<OpenMode> getOperationSupportedFileSystem() { HashSet<OpenMode> hashSet = new HashSet<>(); hashSet.add(OpenMode.SMB); hashSet.add(OpenMode.FILE); hashSet.add(OpenMode.DROPBOX); hashSet.add(OpenMode.BOX); hashSet.add(OpenMode.GDRIVE); hashSet.add(OpenMode.ONEDRIVE); return hashSet; }
Source:
<code>@Override public void onAuthenticationFailed() { runOnUiThread(new Runnable() { @Override public void run() { <START> Toast.makeText(getBaseContext(), "Wrong password.", Toast.LENGTH_LONG).show(); <END> } }); }</code><technical_language>String constants in strings.xml</technical_language>

Target:
@Override public void onAuthenticationFailed() { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getBaseContext(), getString(R.string.notification_wrong_password), Toast.LENGTH_LONG).show(); } }); }
Source:
<code>private PhoneAccountHandle getAccountHandleFromNumber(String dialNumber) { Cursor cursor = mContentResolver.query(Calls.CONTENT_URI, new String[] {Calls.PHONE_ACCOUNT_ID, Calls.PHONE_ACCOUNT_COMPONENT_NAME}, Calls.TYPE + "=" + Calls.OUTGOING_TYPE + " AND " + Calls.NUMBER + "=\"" + PhoneNumberUtils.normalizeNumber(dialNumber) + "\"", null, Calls.DEFAULT_SORT_ORDER + " LIMIT 1"); if (cursor == null) { return null; } <START> if (cursor.getCount() > 0) { <END> cursor.moveToNext(); String componentName = cursor.getString( cursor.getColumnIndex(Calls.PHONE_ACCOUNT_COMPONENT_NAME)); String accountId = cursor.getString(cursor.getColumnIndex(Calls.PHONE_ACCOUNT_ID)); cursor.close(); if (!TextUtils.isEmpty(componentName) && !TextUtils.isEmpty(accountId)) { return new PhoneAccountHandle( ComponentName.unflattenFromString(componentName), accountId); } } return null; }</code><technical_language>prefer returning early error conditions. In this case if (cursor.getCount() == 0) { cursor.close(); return null; }</technical_language>

Target:
private PhoneAccountHandle getAccountHandleFromNumber(String dialNumber) { Cursor cursor = mContentResolver.query(Calls.CONTENT_URI, PHONE_ACCOUNT_STRING, Calls.TYPE + "=" + Calls.OUTGOING_TYPE + " AND " + Calls.NUMBER + "=\"" + PhoneNumberUtils.normalizeNumber(dialNumber) + "\"", null, Calls.DEFAULT_SORT_ORDER + " LIMIT 1"); if (cursor == null) { return null; } if (cursor.getCount() < 1) { cursor.close(); retrun null; } cursor.moveToNext(); String componentName = cursor.getString( cursor.getColumnIndex(Calls.PHONE_ACCOUNT_COMPONENT_NAME)); String accountId = cursor.getString(cursor.getColumnIndex(Calls.PHONE_ACCOUNT_ID)); cursor.close(); if (TextUtils.isEmpty(componentName) || TextUtils.isEmpty(accountId)) { return null; } return new PhoneAccountHandle( ComponentName.unflattenFromString(componentName), accountId); }
Source:
<code>public void testGetKwh() { final String result = DlmsUnitTypeDto.getUnit(30); <START> Assert.assertTrue("KWH".equals(result)); <END> }</code><technical_language>assertEquals</technical_language>

Target:
public void testGetKwh() { final String result = DlmsUnitTypeDto.getUnit(30); assertEquals("KWH", result); }
Source:
<code>public Builder setRating(int rating) { <START> if (rating <= 10 && rating >= 0) { <END> this.rating = rating; } else { throw new IllegalArgumentException("Rating tried to set was out of bounds"); } return this; }</code><technical_language>This allows for rating 0, is invalid I XEP-0118. simplified to: if (rating < 1 || rating > 10) { throw new IllegalArgumentException("Meaningful exception message"); } this.rating = rating; return this;</technical_language>

Target:
public Builder setRating(int rating) { this.rating = rating; return this; }
Source:
<code>public void topologicalSort() { ppp("================ SORTING"); m_strictlySortedNodes = Lists.newArrayList(); initializeIndependentNodes(); List<Node<T>> nodes2 = Lists.newArrayList(); for (Node<T> n : getNodes()) { if (! isIndependent(n.getObject())) { ppp("ADDING FOR SORT: " + n.getObject()); nodes2.add(n.clone()); } else { ppp("SKIPPING INDEPENDENT NODE " + n); } } <START> Comparator<Node> comparator = Systematiser.getComparator(); <END> if (comparator != null) { Collections.sort(nodes2, comparator); } while (! nodes2.isEmpty()) { Node<T> node = findNodeWithNoPredecessors(nodes2); if (null == node) { List<T> cycle = new Tarjan<>(this, nodes2.get(0).getObject()).getCycle(); StringBuilder sb = new StringBuilder(); sb.append("The following methods have cyclic dependencies:\n"); for (T m : cycle) { sb.append(m).append("\n"); } throw new TestNGException(sb.toString()); } else { m_strictlySortedNodes.add(node.getObject()); removeFromNodes(nodes2, node); } } ppp("=============== DONE SORTING"); if (m_verbose) { dumpSortedNodes(); } }</code><technical_language>add Comparator<Node<T>> constructor param</technical_language>

Target:
public void topologicalSort() { ppp("================ SORTING"); m_strictlySortedNodes = Lists.newArrayList(); initializeIndependentNodes(); List<Node<T>> nodes2 = Lists.newArrayList(); for (Node<T> n : getNodes()) { if (! isIndependent(n.getObject())) { ppp("ADDING FOR SORT: " + n.getObject()); nodes2.add(n.clone()); } else { ppp("SKIPPING INDEPENDENT NODE " + n); } } Collections.sort(nodes2, comparator); while (! nodes2.isEmpty()) { Node<T> node = findNodeWithNoPredecessors(nodes2); if (null == node) { List<T> cycle = new Tarjan<>(this, nodes2.get(0).getObject()).getCycle(); StringBuilder sb = new StringBuilder(); sb.append("The following methods have cyclic dependencies:\n"); for (T m : cycle) { sb.append(m).append("\n"); } throw new TestNGException(sb.toString()); } else { m_strictlySortedNodes.add(node.getObject()); removeFromNodes(nodes2, node); } } ppp("=============== DONE SORTING"); if (m_verbose) { dumpSortedNodes(); } }
Source:
<code>public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); <START> final String type = request.param(PARAM_TYPE); <END> final String value = request.param(PARAM_VALUE); if (PROJECT.toString().equals(type) && isBlank(value)) { throw new IllegalArgumentException("type PROJECT requires a mandatory project key"); } if (ORGANIZATION.toString().equals(type) && isBlank(value)) { throw new IllegalArgumentException("type ORGANIZATION requires a mandatory project key"); } String userLogin = userSession.getLogin(); String uuid = ""; try (DbSession dbSession = dbClient.openSession(false)) { if (PROJECT.toString().equals(type)) { com.google.common.base.Optional<ComponentDto> dto = dbClient.componentDao().selectByKey(dbSession, value); if (dto.isPresent()) { uuid = dto.get().uuid(); } else { throw new IllegalStateException("No Project found for homepage key " + uuid); } } if (ORGANIZATION.toString().equals(type)) { Optional<OrganizationDto> dto = dbClient.organizationDao().selectByKey(dbSession, value); if (dto.isPresent()) { uuid = dto.get().getUuid(); } else { throw new IllegalStateException("No Organization found for homepage key " + uuid); } } UserDto userDto = dbClient.userDao().selectActiveUserByLogin(dbSession, userLogin); checkState(userDto != null, "User login '%s' cannot be found", userLogin); userDto.setHomepageType(type); userDto.setHomepageValue(uuid); dbClient.userDao().update(dbSession, userDto); dbSession.commit(); } response.noContent(); }</code><technical_language>need for final call request.mandatoryParam avoid null check</technical_language>

Target:
public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String type = request.mandatoryParam(PARAM_TYPE); String value = request.param(PARAM_PARAMETER); checkRequest(type, value); String login = userSession.getLogin(); try (DbSession dbSession = dbClient.openSession(false)) { UserDto user = dbClient.userDao().selectActiveUserByLogin(dbSession, login); checkState(user != null, "User login '%s' cannot be found", login); user.setHomepageType(type); user.setHomepageValue(findHomepageValue(dbSession, type, value)); dbClient.userDao().update(dbSession, user); dbSession.commit(); } response.noContent(); }
Source:
<code>private PeriodicMetrics providePeriodicMetrics(final MetricsFactory metricsFactory, final ActorSystem actorSystem) { final TsdPeriodicMetrics periodicMetrics = new TsdPeriodicMetrics.Builder() .setMetricsFactory(metricsFactory) .setPollingExecutor(actorSystem.dispatcher()) .build(); <START> final FiniteDuration delay = FiniteDuration.apply(500, TimeUnit.MILLISECONDS); <END> actorSystem.scheduler().schedule(delay, delay, periodicMetrics, actorSystem.dispatcher()); return periodicMetrics; }</code><technical_language>I prefer 1 second</technical_language>

Target:
private PeriodicMetrics providePeriodicMetrics(final MetricsFactory metricsFactory, final ActorSystem actorSystem) { final TsdPeriodicMetrics periodicMetrics = new TsdPeriodicMetrics.Builder() .setMetricsFactory(metricsFactory) .setPollingExecutor(actorSystem.dispatcher()) .build(); final FiniteDuration delay = FiniteDuration.apply(1, TimeUnit.SECONDS); actorSystem.scheduler().schedule(delay, delay, periodicMetrics, actorSystem.dispatcher()); return periodicMetrics; }
Source:
<code>public AssetRequestHandler(Context context) { <START> this.context = context; <END> assetManager = context.getAssets(); }</code><technical_language>safe please context.getApplicationContext()</technical_language>

Target:
public AssetRequestHandler(Context context) { this.context = context.getApplicationContext(); assetManager = context.getAssets(); }
Source:
<code>public static String argTypeList(final ImmutableList<Arguments> arguments) { if (arguments.isEmpty()) { return ""; } final StringBuilder stringBuilder = new StringBuilder(); <START> for (int i = 0; i < arguments.size(); i++) { <END> stringBuilder.append(arguments.get(i).getType()); if (i < arguments.size() - 1) { stringBuilder.append(", "); } } return stringBuilder.toString(); }</code><technical_language>a String.join in java 8</technical_language>

Target:
public static String argTypeList(final ImmutableList<Arguments> arguments) { return arguments.stream().map(i -> i.getType()).collect(Collectors.joining(", ")); }
Source:
<code>private void assertNotInitializedExceptionIsThrownAndMappedCorrectly() { try { addTodo(); <START> } catch (Exception e) { <END> assertTrue(exceptionIsRetryableAndContainsMessage(e, "CassandraKeyValueService is not initialized yet")); } }</code><technical_language>fail() if addTodo() lead exception, cover IsThrown part of method name</technical_language>

Target:
private void assertNotInitializedExceptionIsThrownAndMappedCorrectly() { try { addTodo(); fail("Expected to throw an exception"); } catch (Exception e) { assertTrue(exceptionIsRetryableAndContainsMessage(e, "CassandraKeyValueService is not initialized yet")); } }
Source:
<code>public void testDeleteBaseTableRows() throws Exception { String baseTableName = generateUniqueName(); String baseTableFullName = SchemaUtil.getTableName(SCHEMA1, baseTableName); try (Connection connection = DriverManager.getConnection(getUrl()); Connection viewConnection = isMultiTenant ? DriverManager.getConnection(TENANT_SPECIFIC_URL) : connection) { createBaseTableAndViews(connection, baseTableFullName, viewConnection, SCHEMA2, SCHEMA2, SCHEMA2); <START> String deleteTableRows = "DELETE FROM " + SYSTEM_CATALOG_NAME + <END> " WHERE " + TABLE_SCHEM + " = '" + SCHEMA1 + "' AND " + TABLE_NAME + " = '" + baseTableName + "' AND " + TABLE_TYPE + " = '" + PTableType.TABLE.getSerializedValue() + "'"; connection.createStatement().execute(deleteTableRows); connection.commit(); String viewQuery = "SELECT COUNT(*) FROM " + SYSTEM_CATALOG_NAME + " WHERE " + TABLE_TYPE + " = '" + PTableType.VIEW.getSerializedValue() + "'"; ResultSet rs = connection.createStatement().executeQuery(viewQuery); assertTrue(rs.next()); long count = rs.getLong(1); assertTrue(rs.getLong(1) == fanout + fanout * fanout + fanout * fanout * fanout); runOrphanViewTool(false, true, true, false); assertTrue(getLineCount() == fanout + fanout * fanout + fanout * fanout * fanout); rs = connection.createStatement().executeQuery(viewQuery); assertTrue(rs.next()); assertTrue(rs.getLong(1) == fanout + fanout * fanout + fanout * fanout * fanout); runOrphanViewTool(true, false, false, true); verifyNoViewNoLink(connection, SCHEMA2); verifyNoChildLink(connection, SCHEMA1); deleteAllRows(connection, SCHEMA1, SCHEMA2, SCHEMA3, SCHEMA4); } }</code><technical_language>A lot of String queries extracted out static final Strings String.format required. reduce duplication unit tests easier helper queries in spot</technical_language>

Target:
public void testDeleteBaseTableRows() throws Exception { String baseTableName = generateUniqueName(); String baseTableFullName = SchemaUtil.getTableName(SCHEMA1, baseTableName); try (Connection connection = DriverManager.getConnection(getUrl()); Connection viewConnection = isMultiTenant ? DriverManager.getConnection(TENANT_SPECIFIC_URL) : connection) { createBaseTableAndViews(connection, baseTableFullName, viewConnection, SCHEMA2, SCHEMA2, SCHEMA2); executeDeleteQuery(connection, deleteTableRows, SCHEMA1); ResultSet rs = connection.createStatement().executeQuery(countAllViewsQuery); assertTrue(rs.next()); assertTrue(rs.getLong(1) == childCount + grandChildCount + grandGrandChildCount); runOrphanViewTool(false, true, true, false); verifyOrphanFileLineCounts(childCount + grandChildCount + grandGrandChildCount, 0, childCount + grandChildCount + grandGrandChildCount, childCount); rs = connection.createStatement().executeQuery(countAllViewsQuery); assertTrue(rs.next()); assertTrue(rs.getLong(1) == childCount + grandChildCount + grandGrandChildCount); runOrphanViewTool(true, false, false, true); verifyNoViewNoLinkInSystemCatalog(connection, SCHEMA2); verifyNoChildLink(connection, SCHEMA1); deleteAllRows(connection, SCHEMA1, SCHEMA2, SCHEMA3, SCHEMA4); } }
Source:
<code>public Mono<String> vote(ServerWebExchange serverWebExchange) { return serverWebExchange.getFormData() <START> .flatMap(formData -> <END> voteRepository.save(new Vote(formData.getFirst("team"))) .map(vote -> String.format("Vote successfully cast for '%s' at time %s!%n", vote.candidate, vote.timeCast))); }</code><technical_language>I simpler if left .map unnested .flatmap, this: return serverWebExchange.getFormData() .flatMap(formData -> voteRepository.save(new Vote(formData.getFirst("team")))) .map(vote -> String.format( "Vote successfully cast for '%s' time %s!%n", vote.candidate, vote.timeCast));</technical_language>

Target:
public Mono<String> vote(ServerWebExchange serverWebExchange) { return serverWebExchange.getFormData() .flatMap(formData -> voteRepository.save(new Vote(formData.getFirst("team")))) .map(vote -> String.format("Vote successfully cast for '%s' at time %s!%n", vote.getCandidate(), vote.getTimeCast())); }
Source:
<code>public void performWork(LuceneWork work, IndexWriter writer, IndexingMonitor monitor) { DeleteByQueryLuceneWork deleteWork = (DeleteByQueryLuceneWork) work; final Class<?> entityType = work.getEntityClass(); final DeletionQuery query = deleteWork.getDeletionQuery(); <START> log.tracef( "Removing all %s matching Query: %s", entityType.toString(), query.toString() ); <END> BooleanQuery entityDeletionQuery = new BooleanQuery(); { DeleteByQuerySupport.ToLuceneQuery converter = DeleteByQuerySupport.TO_LUCENE_QUERY_CONVERTER.get( query.getQueryKey() ); ScopedAnalyzer analyzer = this.workspace.getDocumentBuilder( entityType ).getAnalyzer(); Query queryToDelete = converter.build( query, analyzer ); entityDeletionQuery.add( queryToDelete, BooleanClause.Occur.MUST ); } Term classNameQueryTerm = new Term( ProjectionConstants.OBJECT_CLASS, entityType.getName() ); TermQuery classNameQuery = new TermQuery( classNameQueryTerm ); entityDeletionQuery.add( classNameQuery, BooleanClause.Occur.MUST ); try { writer.deleteDocuments( entityDeletionQuery ); } catch (Exception e) { String message = String.format( "unable to remove all %s matching Query: %s", entityType.toString(), query.toString() ); throw new SearchException( message, e ); } this.workspace.notifyWorkApplied( work ); }</code><technical_language>guard this tracef method "if (log.isTraceEnabled()) " toString() methods get invoked in vain</technical_language>

Target:
public void performWork(LuceneWork work, IndexWriter writer, IndexingMonitor monitor) { DeleteByQueryLuceneWork deleteWork = (DeleteByQueryLuceneWork) work; final Class<?> entityType = work.getEntityClass(); final DeletionQuery query = deleteWork.getDeletionQuery(); if ( log.isTraceEnabled() ) { log.tracef( "Removing all %s matching Query: %s", entityType.toString(), query.toString() ); } BooleanQuery entityDeletionQuery = new BooleanQuery(); { DeleteByQuerySupport.ToLuceneQuery converter = DeleteByQuerySupport.TO_LUCENE_QUERY_CONVERTER.get( query.getQueryKey() ); ScopedAnalyzer analyzer = this.workspace.getDocumentBuilder( entityType ).getAnalyzer(); Query queryToDelete = converter.build( query, analyzer ); entityDeletionQuery.add( queryToDelete, BooleanClause.Occur.MUST ); } Term classNameQueryTerm = new Term( ProjectionConstants.OBJECT_CLASS, entityType.getName() ); TermQuery classNameQuery = new TermQuery( classNameQueryTerm ); entityDeletionQuery.add( classNameQuery, BooleanClause.Occur.MUST ); try { writer.deleteDocuments( entityDeletionQuery ); } catch (IOException e) { String message = String.format( "unable to remove all %s matching Query: %s", entityType.toString(), query.toString() ); throw new SearchException( message, e ); } this.workspace.notifyWorkApplied( work ); }
Source:
<code><START> public boolean equals(Object o) { <END> if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CacheKey cacheKey = (CacheKey) o; return joinedPath.equals(cacheKey.joinedPath) && loader.equals(cacheKey.loader); }</code><technical_language>consider Apache Commons Lang build equals hashCode. <LINK_0> <LINK_1></technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CacheKey cacheKey = (CacheKey) o; return new EqualsBuilder().append(joinedPath, cacheKey.joinedPath) .append(loader, cacheKey.loader).isEquals(); }
Source:
<code>public static BlockData getLavaData(final int level) { <START> return Material.LAVA.createBlockData(d -> ((Levelled) d).setLevel((level < 0 || level > 15) ? 0 : level)); <END> }</code><technical_language>I expect this change anytime soon, prevent of magic values in checks good Levelled::getMaximumLevel()</technical_language>

Target:
public static BlockData getLavaData(final int level) { return Material.LAVA.createBlockData(d -> ((Levelled) d).setLevel((level < 0 || level > ((Levelled) d).getMaximumLevel()) ? 0 : level)); }
Source:
<code>public String toString() { switch (this) { case TRAITS: return "Ink"; case TYPE: return "Material"; case COMBO: return "Combo"; case NONE: <START> return "None"; <END> } return "Unkown"; }</code><technical_language>This a field enum</technical_language>

Target:
public String toString() { switch (this) { case TRAITS: return "Ink"; case TYPE: return "Material"; case COMBO: return "Combo"; case NONE: return "None"; } return "Unknown"; }
Source:
<code>public UserData getUserDataFromSessionId(@PathParam("sessionId") String sessionId) { if (sessionId != null && sessionStore.exists(sessionId)) { try { renewSession(sessionId); Scheduler scheduler = sessionStore.get(sessionId).getScheduler(); UserData userData = scheduler.getCurrentUserData(); return userData; } catch (Exception e) { return null; } } else { <START> return null; <END> } }</code><technical_language>If catch exception log hard find issue if is a bug</technical_language>

Target:
public UserData getUserDataFromSessionId(@PathParam("sessionId") String sessionId) { if (sessionId != null && sessionStore.exists(sessionId)) { try { renewSession(sessionId); Scheduler scheduler = sessionStore.get(sessionId).getScheduler(); UserData userData = scheduler.getCurrentUserData(); return userData; } catch (NotConnectedRestException | NotConnectedException e) { logger.trace(e); } catch (Exception e) { logger.warn(e); } } return null; }
Source:
<code>public void auditLoggingOffForOutboundDR() { RetrieveDocumentSetRequestType request = new RetrieveDocumentSetRequestType(); AssertionType assertion = new AssertionType(); <START> NhinTargetCommunitiesType targets = new NhinTargetCommunitiesType(); <END> targets.setUseSpecVersion("2.0"); RetrieveDocumentSetResponseType expectedResponse = new RetrieveDocumentSetResponseType(); CONNECTOutboundOrchestrator orchestrator = mock(CONNECTOutboundOrchestrator.class); OutboundDocRetrieveOrchestratable orchResponse = mock(OutboundDocRetrieveOrchestratable.class); when(orchestrator.process(any(OutboundDocRetrieveOrchestratable.class))).thenReturn(orchResponse); when(orchResponse.getResponse()).thenReturn(expectedResponse); PassthroughOutboundDocRetrieve outboundDocRetrieve = (PassthroughOutboundDocRetrieve) getOutboundDocRetrieve( orchestrator, false); RetrieveDocumentSetResponseType actualResponse = outboundDocRetrieve.respondingGatewayCrossGatewayRetrieve( request, assertion, targets, ADAPTER_API_LEVEL.LEVEL_a0); assertSame(expectedResponse, actualResponse); verify(mockEJBLogger, never()).auditRequestMessage(eq(request), eq(assertion), any(NhinTargetSystemType.class), eq(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_NHIN_INTERFACE), eq(Boolean.TRUE), isNull(Properties.class), eq(NhincConstants.DOC_RETRIEVE_SERVICE_NAME), any(DocRetrieveAuditTransforms.class)); }</code><technical_language>move variables common in places class level</technical_language>

Target:
public void auditLoggingOffForOutboundDR() { targets.setUseSpecVersion("2.0"); RetrieveDocumentSetResponseType expectedResponse = new RetrieveDocumentSetResponseType(); when(orchestrator.process(any(OutboundDocRetrieveOrchestratable.class))).thenReturn(orchResponse); when(orchResponse.getResponse()).thenReturn(expectedResponse); PassthroughOutboundDocRetrieve outboundDocRetrieve = (PassthroughOutboundDocRetrieve) getOutboundDocRetrieve( orchestrator, false); RetrieveDocumentSetResponseType actualResponse = outboundDocRetrieve.respondingGatewayCrossGatewayRetrieve( request, assertion, targets, ADAPTER_API_LEVEL.LEVEL_a0); assertSame(expectedResponse, actualResponse); verify(mockEJBLogger, never()).auditRequestMessage(eq(request), eq(assertion), any(NhinTargetSystemType.class), eq(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_NHIN_INTERFACE), eq(Boolean.TRUE), isNull(Properties.class), eq(NhincConstants.DOC_RETRIEVE_SERVICE_NAME), any(DocRetrieveAuditTransforms.class)); }
Source:
<code><START> private EClass getSubclass(Shell shell, EObject object, EReference reference) { <END> EClass eclass = reference.getEReferenceType(); final EditingDomain editingDomain = AdapterFactoryEditingDomain.getEditingDomainFor(object); final Collection<EClass> subClasses = EMFUtils.getSubClasses(eclass, true, editingDomain); final ComposedAdapterFactory adapterFactory = new ComposedAdapterFactory(new AdapterFactory[] { new ReflectiveItemProviderAdapterFactory(), new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE) }); final AdapterFactoryLabelProvider labelProvider = new AdapterFactoryLabelProvider( adapterFactory); final ElementListSelectionDialog dialog = new ElementListSelectionDialog(shell, labelProvider); dialog.setTitle("Select EClass"); dialog.setMessage("Select a subclass to generate columns for all attributes from this EClass."); dialog.setMultipleSelection(false); dialog.setElements(subClasses.toArray(new EClass[subClasses.size()])); if (dialog.open() == Window.OK) { final Object firstResult = dialog.getFirstResult(); if (firstResult != null) { eclass = (EClass) firstResult; } } else { eclass = null; } labelProvider.dispose(); adapterFactory.dispose(); return eclass; }</code><technical_language>refactoring do current problem</technical_language>

Target:
private EClass getSubclass(Shell shell, EObject object, EReference reference) { EClass eclass = reference.getEReferenceType(); final Collection<EClass> subClasses = EMFUtils.getSubClasses(eclass, true, null); final ComposedAdapterFactory adapterFactory = new ComposedAdapterFactory(new AdapterFactory[] { new ReflectiveItemProviderAdapterFactory(), new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE) }); final AdapterFactoryLabelProvider labelProvider = new AdapterFactoryLabelProvider( adapterFactory); final ElementListSelectionDialog dialog = new ElementListSelectionDialog(shell, labelProvider); dialog.setTitle("Select EClass"); dialog.setMessage("Select a subclass to generate columns for all attributes from this EClass."); dialog.setMultipleSelection(false); dialog.setElements(subClasses.toArray(new EClass[subClasses.size()])); if (dialog.open() == Window.OK) { final Object firstResult = dialog.getFirstResult(); if (firstResult != null) { eclass = (EClass) firstResult; } } else { eclass = null; } labelProvider.dispose(); adapterFactory.dispose(); return eclass; }
Source:
<code>private static Req pack(final Comment.Smart comment, final Pull pull) throws IOException { final PullRef head = pull.head(); final PullRef base = pull.base(); final Req req; final String repo = "repo"; if (head.json().isNull(repo)) { new Answer(comment).post( false, QnMerge.PHRASES.getString("QnMerge.head-is-gone") ); req = Req.EMPTY; } else if (base.json().isNull(repo)) { new Answer(comment).post( false, QnMerge.PHRASES.getString("QnMerge.base-is-gone") ); req = Req.EMPTY; } else { req = new Req.Simple( "merge", <START> new MapOf<String, String>( <END> new MapEntry<String, String>( "pull_id", Integer.toString(pull.number()) ), new MapEntry<String, String>( "pull_title", new Issue.Smart(comment.issue()).title() ), new MapEntry<String, String>( "fork_branch", head.ref() ), new MapEntry<String, String>( "head_branch", base.ref() ), new MapEntry<String, String>( "head", String.format( "git@github.com:%s.git", base.repo().coordinates().toString() ) ), new MapEntry<String, String>( "fork", String.format( "git@github.com:%s.git", head.repo().coordinates().toString() ) ) ) ); } return req; }</code><technical_language>@filfreire SolidMap</technical_language>

Target:
private static Req pack(final Comment.Smart comment, final Pull pull) throws IOException { final PullRef head = pull.head(); final PullRef base = pull.base(); final Req req; final String repo = "repo"; if (head.json().isNull(repo)) { new Answer(comment).post( false, QnMerge.PHRASES.getString("QnMerge.head-is-gone") ); req = Req.EMPTY; } else if (base.json().isNull(repo)) { new Answer(comment).post( false, QnMerge.PHRASES.getString("QnMerge.base-is-gone") ); req = Req.EMPTY; } else { req = new Req.Simple( "merge", new SolidMap<String, String>( new MapEntry<String, String>( "pull_id", Integer.toString(pull.number()) ), new MapEntry<String, String>( "pull_title", new Issue.Smart(comment.issue()).title() ), new MapEntry<String, String>( "fork_branch", head.ref() ), new MapEntry<String, String>( "head_branch", base.ref() ), new MapEntry<String, String>( "head", String.format( "git@github.com:%s.git", base.repo().coordinates().toString() ) ), new MapEntry<String, String>( "fork", String.format( "git@github.com:%s.git", head.repo().coordinates().toString() ) ) ) ); } return req; }
Source:
<code>boolean validateVdsGroup() { if (getVdsGroup() == null) { addCanDoActionMessage(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); <START> return false; <END> } return true; }</code><technical_language>return failCanDoAction</technical_language>

Target:
boolean validateVdsGroup() { if (getVdsGroup() == null) { return failCanDoAction(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); } return true; }
Source:
<code>public void canGetAliases() { <START> assertTrue(scv.getAliases().containsAll(aliases)); <END> }</code><technical_language>suggestion assertThat(scv.getAliases(), contains(aliases));</technical_language>

Target:
public void canGetAliases() { assertThat(scv.getAliases(), contains(aliases.toArray())); }
Source:
<code>private boolean auditDomainsOnVsp(HostVO host, boolean add, boolean remove) { List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listByHost(host.getId()); if (!CollectionUtils.isEmpty(nuageVspDevices)) { _hostDao.loadDetails(host); List<DomainVO> allDomains = _domainDao.listAll(); for (DomainVO domain : allDomains) { try { SyncDomainCommand cmd = new SyncDomainCommand(domain.getUuid(), domain.getName(), domain.getPath(), add, remove); SyncDomainAnswer answer = (SyncDomainAnswer) _agentMgr.easySend(host.getId(), cmd); return answer.getSuccess(); <START> } catch (Exception e) { <END> s_logger.warn(e.getMessage()); return false; } } } return true; }</code><technical_language>checked unchecked exceptions caught</technical_language>

Target:
private boolean auditDomainsOnVsp(HostVO host, boolean add, boolean remove) { List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listByHost(host.getId()); if (CollectionUtils.isEmpty(nuageVspDevices)) { return true; } _hostDao.loadDetails(host); List<DomainVO> allDomains = _domainDao.listAll(); for (DomainVO domain : allDomains) { SyncDomainCommand cmd = new SyncDomainCommand(domain.getUuid(), domain.getName(), domain.getPath(), add, remove); SyncDomainAnswer answer = (SyncDomainAnswer) _agentMgr.easySend(host.getId(), cmd); return answer.getSuccess(); } return true; }
Source:
<code>public void send_shouldFillInIntentData() throws Exception { Intent intent = new Intent(); <START> Context context = new Activity(); <END> PendingIntent pendingIntent = PendingIntent.getActivity(context, 99, intent, 100); Activity otherContext = new Activity(); Intent fillIntent = new Intent().putExtra("TEST", 23); pendingIntent.send(otherContext, 0, fillIntent); Intent i = shadowOf(otherContext).getNextStartedActivity(); assertThat(i).isNotNull(); assertThat(i).isSameAs(intent); assertThat(i.getIntExtra("TEST", -1)).isEqualTo(23); }</code><technical_language>Create Activities Robolectric.setupActivity()</technical_language>

Target:
public void send_shouldFillInIntentData() throws Exception { Intent intent = new Intent(); Context context = Robolectric.setupActivity(Activity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 99, intent, 100); Activity otherContext = Robolectric.setupActivity(Activity.class); Intent fillIntent = new Intent().putExtra("TEST", 23); pendingIntent.send(otherContext, 0, fillIntent); Intent i = shadowOf(otherContext).getNextStartedActivity(); assertThat(i).isNotNull(); assertThat(i).isSameAs(intent); assertThat(i.getIntExtra("TEST", -1)).isEqualTo(23); }
Source:
<code>private void showDetachedHeadWarning() { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { IPreferenceStore store = Activator.getDefault() .getPreferenceStore(); if (store.getBoolean(UIPreferences.SHOW_DETACHED_HEAD_WARNING)) { String toggleMessage = UIText.BranchResultDialog_DetachedHeadWarningDontShowAgain; MessageDialogWithToggle dialog = new MessageDialogWithToggle( PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell(), UIText.BranchOperationUI_DetachedHeadTitle, null, UIText.BranchOperationUI_DetachedHeadMessage, MessageDialog.INFORMATION, new String[] { IDialogConstants.CLOSE_LABEL }, 0, toggleMessage, false); int result = dialog.open(); if (result == IDialogConstants.CLOSE_ID <START> && dialog.getToggleState()) { <END> store.setValue(UIPreferences.SHOW_DETACHED_HEAD_WARNING, false); } } } }); }</code><technical_language>button labeled "Close" I matter I close dialog setting updated. Currently is updates if I do close dialog button. If I close dialog closing window hitting ESC, setting is updated if I toggle checkbox before. ignoring result a possibility. do think</technical_language>

Target:
private void showDetachedHeadWarning() { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { IPreferenceStore store = Activator.getDefault() .getPreferenceStore(); if (store.getBoolean(UIPreferences.SHOW_DETACHED_HEAD_WARNING)) { String toggleMessage = UIText.BranchResultDialog_DetachedHeadWarningDontShowAgain; MessageDialogWithToggle dialog = new MessageDialogWithToggle( PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell(), UIText.BranchOperationUI_DetachedHeadTitle, null, UIText.BranchOperationUI_DetachedHeadMessage, MessageDialog.INFORMATION, new String[] { IDialogConstants.CLOSE_LABEL }, 0, toggleMessage, false); dialog.open(); if (dialog.getToggleState()) { store.setValue(UIPreferences.SHOW_DETACHED_HEAD_WARNING, false); } } } }); }
Source:
<code>public void testVersionNumber() { Pattern versionPattern = <START> Pattern.compile("^(([1]\\.([1][4-9]|[2-9]\\d))|([2-9]\\.\\d{1,2}))\\."); <END> assertTrue(versionPattern.matcher(BigtableHBaseVersion.CLIENT_VERSION).find()); }</code><technical_language>nicer/easier debug if extract numbers this regex: "^(\\d+)\\.(\\d+)\\.(\\d+)" do a comparison separately. java int result = ComparisonChain.start() .compare(1, Integer.parse(matcher.group(1)) .compare(14, Integer.parse(matcher.group(2)) .compare(0, Integer.parse(matcher.group(3)) .result(); assertTrue(result <= 0, "Expected BigtableVersion.getVersion() 1.14.0")</technical_language>

Target:
public void testVersionNumber() { Pattern versionPattern = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)(-\\w+)?"); Matcher versionMatcher = versionPattern.matcher(BigtableHBaseVersion.getVersion()); assertTrue("incorrect version format", versionMatcher.matches()); int result = ComparisonChain.start() .compare(1, Integer.parseInt(versionMatcher.group(1))) .compare(14, Integer.parseInt(versionMatcher.group(2))) .compare(1, Integer.parseInt(versionMatcher.group(3))) .result(); assertTrue("Expected BigtableHBaseVersion.getVersion() to be at least 1.14.1", result <= 0); }