auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void updateImpactCache(Pattern pattern) { impactCache.keySet().forEach(uri -> impactCache.remove(uri, pattern)); Set<URI> referredUris = PatternLanguageHelper.getReferencedPatternsTransitive(pattern).stream().map(p -> p.eResource().getURI()).collect(Collectors.toSet()); <START> referredUris.forEach(u -> impactCache.put(u, pattern)); <END> }</code><technical_language>I limited reason instantiate referredUris set</technical_language>

Target:
private void updateImpactCache(Pattern pattern) { dependencyCache.keySet().forEach(uri -> dependencyCache.remove(uri, pattern)); Set<URI> referredUris = PatternLanguageHelper.getReferencedPatternsTransitive(pattern).stream() .map(p -> p.eResource().getURI()).collect(Collectors.toSet()); referredUris.forEach(u -> dependencyCache.put(u, pattern)); }
Source:
<code>public static void checkPermissionsAndPerformAction(Activity activity, String permission, Runnable onPermissionGranted, Runnable onPermissionDenied, @StringRes int rationaleTitle, @StringRes int rationaleMessage) { Dexter.withActivity(activity) .withPermission(permission) .withListener(new BasePermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse response) { onPermissionGranted.run(); } @Override public void onPermissionDenied(PermissionDeniedResponse response) { if (response.isPermanentlyDenied()) { DialogUtil.showAlertDialog(activity, activity.getString(rationaleTitle), activity.getString(rationaleMessage), activity.getString(R.string.navigation_item_settings), null, () -> askUserToManuallyEnablePermissionFromSettings(activity), null); } else { <START> onPermissionDenied.run(); <END> } } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { DialogUtil.showAlertDialog(activity, activity.getString(rationaleTitle), activity.getString(rationaleMessage), activity.getString(android.R.string.ok), activity.getString(android.R.string.cancel), token::continuePermissionRequest, token::cancelPermissionRequest); } }) .check(); }</code><technical_language>Discussed offline. @ashishkumar468 is making some changes this</technical_language>

Target:
public static void checkPermissionsAndPerformAction(Activity activity, String permission, Runnable onPermissionGranted, Runnable onPermissionDenied, @StringRes int rationaleTitle, @StringRes int rationaleMessage) { Dexter.withActivity(activity) .withPermission(permission) .withListener(new BasePermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse response) { onPermissionGranted.run(); } @Override public void onPermissionDenied(PermissionDeniedResponse response) { if (response.isPermanentlyDenied()) { DialogUtil.showAlertDialog(activity, activity.getString(rationaleTitle), activity.getString(rationaleMessage), activity.getString(R.string.navigation_item_settings), null, () -> askUserToManuallyEnablePermissionFromSettings(activity), null); } else { if (null != onPermissionDenied) { onPermissionDenied.run(); } } } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { DialogUtil.showAlertDialog(activity, activity.getString(rationaleTitle), activity.getString(rationaleMessage), activity.getString(android.R.string.ok), activity.getString(android.R.string.cancel), token::continuePermissionRequest, token::cancelPermissionRequest); } }) .check(); }
Source:
<code>public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException { super.validateParameter(parameterName, value); if (value.isDefined()) { List<ModelNode> list = value.asList(); int size = list.size(); if (size < min) { throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.invalidMinSize(size, parameterName, min)); } else if (size > max) { throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.invalidMaxSize(size, parameterName, max)); } else { if (!allowDuplicates){ HashSet<ModelNode> dups = new HashSet<>(); for (ModelNode element : list) { <START> if (dups.contains(element)){ <END> throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.duplicateElementsInList(parameterName)); } dups.add(element); } dups.clear(); } for (ModelNode element : list) { elementValidator.validateParameter(parameterName, element); } } } }</code><technical_language>More efficient is if (!dups.add(element))</technical_language>

Target:
public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException { super.validateParameter(parameterName, value); if (value.isDefined()) { List<ModelNode> list = value.asList(); int size = list.size(); if (size < min) { throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.invalidMinSize(size, parameterName, min)); } else if (size > max) { throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.invalidMaxSize(size, parameterName, max)); } else { if (!allowDuplicates){ HashSet<ModelNode> dups = new HashSet<>(); for (ModelNode element : list) { if (!dups.add(element)){ throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.duplicateElementsInList(parameterName)); } } dups.clear(); } for (ModelNode element : list) { elementValidator.validateParameter(parameterName, element); } } } }
Source:
<code>public AsyncFuture<FindTags> findTags(FindTags.Request request) { <START> return delegateGroup.findTags(request).catchFailed(wrapExceptionTransform()); <END> }</code><technical_language>This done (in ClusterShard) if give TracingClusterNode a good toString() implementation</technical_language>

Target:
public AsyncFuture<FindTags> findTags(FindTags.Request request) { return delegateGroup.findTags(request); }
Source:
<code>protected void configureOAuth20Client(final Collection<IndirectClient> properties) { val pac4jProperties = casProperties.getAuthn().getPac4j(); val index = new AtomicInteger(); pac4jProperties.getOauth2() .stream() .filter(oauth -> oauth.isEnabled() && StringUtils.isNotBlank(oauth.getId()) && StringUtils.isNotBlank(oauth.getSecret())) .forEach(oauth -> { val client = new GenericOAuth20Client(); client.setProfileId(StringUtils.defaultIfBlank(oauth.getPrincipalAttributeId(), pac4jProperties.getPrincipalAttributeId())); client.setKey(oauth.getId()); client.setSecret(oauth.getSecret()); client.setProfileAttrs(oauth.getProfileAttrs()); client.setProfileNodePath(oauth.getProfilePath()); client.setProfileUrl(oauth.getProfileUrl()); client.setProfileVerb(Verb.valueOf(oauth.getProfileVerb().toUpperCase())); client.setTokenUrl(oauth.getTokenUrl()); client.setAuthUrl(oauth.getAuthUrl()); client.setScope(oauth.getScope()); client.setCustomParams(oauth.getCustomParams()); client.getConfiguration().setResponseType(oauth.getResponseType()) <START> System.out.println(oauth.getResponseType()); <END> if (StringUtils.isBlank(oauth.getClientName())) { val count = index.intValue(); client.setName(client.getClass().getSimpleName() + count); } configureClient(client, oauth); index.incrementAndGet(); LOGGER.debug("Created client [{}]", client); properties.add(client); }); }</code><technical_language>Remove</technical_language>

Target:
protected void configureOAuth20Client(final Collection<IndirectClient> properties) { val pac4jProperties = casProperties.getAuthn().getPac4j(); val index = new AtomicInteger(); pac4jProperties.getOauth2() .stream() .filter(oauth -> oauth.isEnabled() && StringUtils.isNotBlank(oauth.getId()) && StringUtils.isNotBlank(oauth.getSecret())) .forEach(oauth -> { val client = new GenericOAuth20Client(); client.setProfileId(StringUtils.defaultIfBlank(oauth.getPrincipalAttributeId(), pac4jProperties.getPrincipalAttributeId())); client.setKey(oauth.getId()); client.setSecret(oauth.getSecret()); client.setProfileAttrs(oauth.getProfileAttrs()); client.setProfileNodePath(oauth.getProfilePath()); client.setProfileUrl(oauth.getProfileUrl()); client.setProfileVerb(Verb.valueOf(oauth.getProfileVerb().toUpperCase())); client.setTokenUrl(oauth.getTokenUrl()); client.setAuthUrl(oauth.getAuthUrl()); client.setScope(oauth.getScope()); client.setCustomParams(oauth.getCustomParams()); client.getConfiguration().setResponseType(oauth.getResponseType()); if (StringUtils.isBlank(oauth.getClientName())) { val count = index.intValue(); client.setName(client.getClass().getSimpleName() + count); } configureClient(client, oauth); index.incrementAndGet(); LOGGER.debug("Created client [{}]", client); properties.add(client); }); }
Source:
<code>private <T> void registerHandler(String address, HandlerRegistration<T> registration, boolean replyHandler, boolean localOnly, long timeoutID) { checkStarted(); Objects.requireNonNull(address, "address"); Objects.requireNonNull(registration.handler, "handler"); ContextImpl context = vertx.getContext(); boolean hasContext = context != null; if (!hasContext) { context = vertx.createEventLoopContext(null, new JsonObject(), Thread.currentThread().getContextClassLoader()); } HandlerHolder holder = new HandlerHolder<T>(registration, replyHandler, localOnly, context, timeoutID); Handlers handlers = handlerMap.get(address); if (handlers == null) { handlers = new Handlers(); Handlers prevHandlers = handlerMap.putIfAbsent(address, handlers); if (prevHandlers != null) { handlers = prevHandlers; } if (subs != null && !replyHandler && !localOnly) { subs.add(address, serverID, ar -> { holder.context.runOnContext(v -> { registration.setResult(ar); }); }); } else { <START> holder.context.runOnContext(v -> { <END> registration.setResult(Future.succeededFuture()); }); } } else { holder.context.runOnContext(v -> { registration.setResult(Future.succeededFuture()); }); } handlers.list.add(holder); if (hasContext) { HandlerEntry entry = new HandlerEntry<T>(address, registration); context.addCloseHook(entry); } }</code><technical_language>running a context (registration.setrestult call context.runOnContext)</technical_language>

Target:
private <T> void registerHandler(String address, HandlerRegistration<T> registration, boolean replyHandler, boolean localOnly, long timeoutID) { checkStarted(); Objects.requireNonNull(address, "address"); Objects.requireNonNull(registration.handler, "handler"); ContextImpl context = vertx.getContext(); boolean hasContext = context != null; Handler<AsyncResult<Void>> register; if (!hasContext) { Context newContext = context = vertx.createEventLoopContext(null, new JsonObject(), Thread.currentThread().getContextClassLoader()); register = fut -> { newContext.runOnContext(v -> registration.setResult(fut)); }; } else { register = registration::setResult; } HandlerHolder holder = new HandlerHolder<T>(registration, replyHandler, localOnly, context, timeoutID); Handlers handlers = handlerMap.get(address); if (handlers == null) { handlers = new Handlers(); Handlers prevHandlers = handlerMap.putIfAbsent(address, handlers); if (prevHandlers != null) { handlers = prevHandlers; } if (subs != null && !replyHandler && !localOnly) { subs.add(address, serverID, ar -> { register.handle(ar); }); } else { register.handle(Future.succeededFuture()); } } else { register.handle(Future.succeededFuture()); } handlers.list.add(holder); if (hasContext) { HandlerEntry entry = new HandlerEntry<T>(address, registration); context.addCloseHook(entry); } }
Source:
<code>protected void onLoad() throws IOException, ConfigInvalidException { ObjectId rev = getRevision(); if (rev == null) { loadDefaults(); return; } RevWalk walk = new RevWalk(reader); try (ChangeNotesParser parser = new ChangeNotesParser(change, rev, walk, repoManager)) { parser.parseAll(); if (parser.status != null) { change.setStatus(parser.status); } approvals = parser.buildApprovals(); changeMessages = parser.buildMessages(); commentsForBase = ImmutableListMultimap.copyOf(parser.commentsForBase); commentsForPS = ImmutableListMultimap.copyOf(parser.commentsForPs); noteMap = parser.commentNoteMap; if (parser.hashtags != null) { hashtags = ImmutableSet.copyOf(parser.hashtags); <START> } <END> ImmutableSetMultimap.Builder<ReviewerState, Account.Id> reviewers = ImmutableSetMultimap.builder(); for (Map.Entry<Account.Id, ReviewerState> e : parser.reviewers.entrySet()) { reviewers.put(e.getValue(), e.getKey()); } this.reviewers = reviewers.build(); this.allPastReviewers = ImmutableList.copyOf(parser.allPastReviewers); submitRecords = ImmutableList.copyOf(parser.submitRecords); } catch (ParseException e1) { throw new IOException(e1); } finally { walk.release(); } }</code><technical_language>If set empty otherwise, logic easier in other places else { hashtags = ImmutableSet.of(); }</technical_language>

Target:
protected void onLoad() throws IOException, ConfigInvalidException { ObjectId rev = getRevision(); if (rev == null) { loadDefaults(); return; } RevWalk walk = new RevWalk(reader); try (ChangeNotesParser parser = new ChangeNotesParser(change, rev, walk, repoManager)) { parser.parseAll(); if (parser.status != null) { change.setStatus(parser.status); } approvals = parser.buildApprovals(); changeMessages = parser.buildMessages(); commentsForBase = ImmutableListMultimap.copyOf(parser.commentsForBase); commentsForPS = ImmutableListMultimap.copyOf(parser.commentsForPs); noteMap = parser.commentNoteMap; if (parser.hashtags != null) { hashtags = ImmutableSet.copyOf(parser.hashtags); } else { hashtags = ImmutableSet.of(); } ImmutableSetMultimap.Builder<ReviewerState, Account.Id> reviewers = ImmutableSetMultimap.builder(); for (Map.Entry<Account.Id, ReviewerState> e : parser.reviewers.entrySet()) { reviewers.put(e.getValue(), e.getKey()); } this.reviewers = reviewers.build(); this.allPastReviewers = ImmutableList.copyOf(parser.allPastReviewers); submitRecords = ImmutableList.copyOf(parser.submitRecords); } catch (ParseException e1) { throw new IOException(e1); } finally { walk.release(); } }
Source:
<code>public Tuple next() { <START> Tuple current = createTuple( entityCache.get( this.next ) ); <END> this.next = next( this.iterator ); return current; }</code><technical_language>In another case, tested hasNext. I if do throw a NoSuchElementException passing null</technical_language>

Target:
public Tuple next() { if ( hasNext ) { Tuple current = createTuple( entityCache.get( this.next ) ); this.next = next( this.iterator ); return current; } throw new NoSuchElementException(); }
Source:
<code>public void init(AdaptorContext context) throws Exception { this.context = context; this.params = new Params(context.getConfig()); try (Connection connection = getConnection()) { logger.log(Level.INFO, "Connecting to object store {0}", <START> params.getObjectStore()); <END> factory.getObjectStore(connection, params.getObjectStore()); } catch (EngineRuntimeException e) { throw new StartupException( "Failed to access content engine's object store", e); } documentTraverser = new MockTraverser(params); }</code><technical_language>I Params get factory class name, hold actual ObjectFactory possibly getters for some of created objects. FileSession in v3 a getter for ObjectFactory created passed ObjectStore traversers. I want getConnection this clas move Params well. Some fuzziness abounds wiring, ObjectFactory Connection Params, rest Params ObjectFactory (maybe depending constructing requires values Params?)</technical_language>

Target:
public void init(AdaptorContext context) throws Exception { this.context = context; this.configOptions = new ConfigOptions(context); try (Connection connection = configOptions.getConnection()) { configOptions.getObjectStore(connection); } catch (EngineRuntimeException e) { throw new StartupException( "Failed to access content engine's object store", e); } documentTraverser = new MockTraverser(configOptions); }
Source:
<code>public void initialize() throws SchedulerConfigException { <START> if (threadCount < 0) { <END> throw new SchedulerConfigException("Thread count must be > 0"); } }</code><technical_language>threadCount <= 0</technical_language>

Target:
public void initialize() throws SchedulerConfigException { if (threadCount <= 0) { throw new SchedulerConfigException("Thread count must be > 0"); } }
Source:
<code>public void notFound() { String newUrl = GWT.getHostPageBaseURL() + "?standalone&" + <START> "perspective=" + NotFoundPerspective.ID + "&" + <END> DASHBOARD_PARAM + "=" + dashboard; DomGlobal.window.history.pushState(null, "Dashbuilder Runtime | Not Found", newUrl); this.hideLoading(); }</code><technical_language>stop PERSPECTIVE_PARAM here</technical_language>

Target:
public void notFound() { String newUrl = GWT.getHostPageBaseURL() + "?standalone&" + PERSPECTIVE_PARAM + "=" + NotFoundPerspective.ID + "&" + DASHBOARD_PARAM + "=" + dashboard; DomGlobal.window.history.pushState(null, "Dashbuilder Runtime | Not Found", newUrl); this.hideLoading(); }
Source:
<code>void addConstrainingMembersToMap( Exp arg, Map<Dimension, List<RolapMember>> memberLists) <START> { <END> if (arg instanceof ResolvedFunCall) { ResolvedFunCall call = (ResolvedFunCall) arg; for (Exp callArg : call.getArgs()) { addConstrainingMembersToMap(callArg, memberLists); } } Exp[] tupleArgs = getCalculatedTupleArgs(arg); for (Exp tupleArg : tupleArgs) { Dimension dimension = tupleArg.getType().getDimension(); if (tupleArg instanceof ResolvedFunCall) { addConstrainingMembersToMap(tupleArg, memberLists); } else if (dimension != null && !dimension.isMeasures()) { List<RolapMember> members; if (memberLists.containsKey(dimension)) { members = memberLists.get(dimension); } else { members = new ArrayList<RolapMember>(); } members .add((RolapMember) ((MemberExpr) tupleArg).getMember()); memberLists.put(dimension, members); } else if (isConstrainedMeasure(tupleArg)) { addConstrainingMembersToMap(tupleArg, memberLists); } } }</code><technical_language>Please revert change in indentation</technical_language>

Target:
private void addConstrainingMembersToMap( Exp arg, Map<Dimension, List<RolapMember>> memberLists) { if (arg instanceof ResolvedFunCall) { ResolvedFunCall call = (ResolvedFunCall) arg; for (Exp callArg : call.getArgs()) { addConstrainingMembersToMap(callArg, memberLists); } } Exp[] tupleArgs = getCalculatedTupleArgs(arg); for (Exp tupleArg : tupleArgs) { Dimension dimension = tupleArg.getType().getDimension(); if (tupleArg instanceof ResolvedFunCall) { addConstrainingMembersToMap(tupleArg, memberLists); } else if (dimension != null && !dimension.isMeasures()) { List<RolapMember> members; if (memberLists.containsKey(dimension)) { members = memberLists.get(dimension); } else { members = new ArrayList<RolapMember>(); } members.add((RolapMember) ((MemberExpr) tupleArg).getMember()); memberLists.put(dimension, members); } else if (isConstrainedMeasure(tupleArg)) { addConstrainingMembersToMap(tupleArg, memberLists); } } }
Source:
<code>public void errorHandler_manualExecuteClientReset() { SyncUser user = createTestUser(); String url = "realm://objectserver.realm.io/default"; final SyncConfiguration config = configFactory.createSyncConfigurationBuilder(user , url) .errorHandler(new SyncSession.ErrorHandler() { @Override public void onError(SyncSession session, ObjectServerError error) { fail("Wrong error " + error.toString()); } @Override public void onClientReset(SyncSession session, ClientResetRequiredError error) { try { <START> error.executeClientReset(); <END> fail("All Realms should be closed before executing Client Reset can be allowed"); } catch(IllegalStateException ignored) { } looperThread.testRealms.get(0).close(); error.executeClientReset(); assertFalse(error.getOriginalFile().exists()); assertTrue(error.getBackupFile().exists()); looperThread.testComplete(); } }) .build(); Realm realm = Realm.getInstance(config); looperThread.testRealms.add(realm); SyncManager.simulateClientReset(SyncManager.getSession(config)); }</code><technical_language>I understand this test. Do a client reset onClientReset</technical_language>

Target:
public void errorHandler_manualExecuteClientReset() { SyncUser user = createTestUser(); String url = "realm://objectserver.realm.io/default"; final SyncConfiguration config = configFactory.createSyncConfigurationBuilder(user , url) .errorHandler(new SyncSession.ErrorHandler() { @Override public void onError(SyncSession session, ObjectServerError error) { fail("Wrong error " + error.toString()); } @Override public void onClientResetRequired(SyncSession session, ClientResetHandler handler) { try { handler.executeClientReset(); fail("All Realms should be closed before executing Client Reset can be allowed"); } catch(IllegalStateException ignored) { } looperThread.testRealms.get(0).close(); handler.executeClientReset(); assertFalse(handler.getOriginalFile().exists()); assertTrue(handler.getBackupFile().exists()); looperThread.testComplete(); } }) .build(); Realm realm = Realm.getInstance(config); looperThread.testRealms.add(realm); SyncManager.simulateClientReset(SyncManager.getSession(config)); }
Source:
<code>public void onExit() { try { freePartitions(new HashSet<>(listeners.keySet())); } catch (final NakadiRuntimeException | NakadiBaseException ex) { getLog().error("Failed to transfer partitions when leaving ClosingState", ex); <START> TracingService.logErrorInSpan(getContext().getCurrentSpan(), <END> "Failed to transfer partitions when leaving ClosingState " + ex.getMessage()); } finally { if (null != topologyListener) { try { topologyListener.close(); } finally { topologyListener = null; } } } }</code><technical_language>user need it, is internal exception, track in logs</technical_language>

Target:
public void onExit() { try { freePartitions(new HashSet<>(listeners.keySet())); } catch (final NakadiRuntimeException | NakadiBaseException ex) { getLog().error("Failed to transfer partitions when leaving ClosingState", ex); } finally { if (null != topologyListener) { try { topologyListener.close(); } finally { topologyListener = null; } } } }
Source:
<code>public static MainPlayer.PlayerType getType() { if (player == null) { return null; } <START> return player.videoPlayerSelected() ? MainPlayer.PlayerType.VIDEO : player.popupPlayerSelected() ? MainPlayer.PlayerType.POPUP : player.audioPlayerSelected() ? MainPlayer.PlayerType.AUDIO : null; <END> }</code><technical_language>Add a method VideoPlayerImpl returns playerType field</technical_language>

Target:
public static MainPlayer.PlayerType getType() { if (player == null) { return null; } return player.getPlayerType(); }
Source:
<code>private boolean isKnoxSSOEnabled() { Collection realmsList = SecurityUtils.getRealmsList(); if (realmsList != null) { for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) { Realm realm = iterator.next(); String name = realm.getClass().getName(); if (LOG.isDebugEnabled()) { <START> LOG.debug("RealmClass.getName: " + name); <END> } if (name.equals("org.apache.zeppelin.realm.jwt.KnoxJwtRealm")) { return true; } } } return false; }</code><technical_language>LOG.debug()? sensitive</technical_language>

Target:
private boolean isKnoxSSOEnabled() { Collection realmsList = SecurityUtils.getRealmsList(); if (realmsList != null) { for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) { Realm realm = iterator.next(); String name = realm.getClass().getName(); LOG.debug("RealmClass.getName: " + name); if (name.equals("org.apache.zeppelin.realm.jwt.KnoxJwtRealm")) { return true; } } } return false; }
Source:
<code>private String login(String host, String username, String password) throws APIManagementException { AuthenticatorClient authenticatorClient = null; try { authenticatorClient = new AuthenticatorClient(host); <START> URL url = new URL(host); <END> String sessionCookie = authenticatorClient.login(username, password, "localhost"); return sessionCookie; } catch (Exception e) { throw new APIManagementException("Unable login to Host: " + host, e); } }</code><technical_language>url object longer usages suggestion</technical_language>

Target:
private String login(String host, String username, String password) throws APIManagementException { AuthenticatorClient authenticatorClient = null; try { authenticatorClient = new AuthenticatorClient(host); String sessionCookie = authenticatorClient.login(username, password, "localhost"); return sessionCookie; } catch (Exception e) { throw new APIManagementException("Unable login to Host: " + host, e); } }
Source:
<code>public static String trimFieldName(String fieldName) { IPreferencesService preferences = Platform.getPreferencesService(); String prefix = preferences.getString(CUIPlugin.PLUGIN_ID, PreferenceConstants.NAME_STYLE_FIELD_PREFIX, "", null); if (fieldName.startsWith(prefix)) fieldName = fieldName.substring(prefix.length()); <START> CBreakIterator iterator = new CBreakIterator(); <END> iterator.setText(fieldName); int firstWordStart = -1; int secondWordStart = -1; int lastWordEnd = -1; int end; for (int start = iterator.first(); (end = iterator.next()) != BreakIterator.DONE; start = end) { if (Character.isLetterOrDigit(fieldName.charAt(start))) { int pos = end; while (--pos >= start && !Character.isLetterOrDigit(fieldName.charAt(pos))) { } lastWordEnd = pos + 1; if (firstWordStart < 0) { firstWordStart = start; } else if (secondWordStart < 0) { secondWordStart = start; } } } if (firstWordStart < 0) { return fieldName; } else { return fieldName.substring(firstWordStart, lastWordEnd); } }</code><technical_language>CBreakIterator overkill NAME_STYLE_FIELD_PREFIX is used. this block changed simpler</technical_language>

Target:
public static String trimFieldName(String fieldName) { IPreferencesService preferences = Platform.getPreferencesService(); String prefix = preferences.getString(CUIPlugin.PLUGIN_ID, PreferenceConstants.NAME_STYLE_FIELD_PREFIX, "", null); if (fieldName.startsWith(prefix)) fieldName = fieldName.substring(prefix.length()); int firstWordStart = -1; int lastWordEnd = -1; for (int i = 0; i < fieldName.length(); ++i) { if (Character.isLetterOrDigit(fieldName.charAt(i))) { int pos = i + 1; while (--pos >= i && !Character.isLetterOrDigit(fieldName.charAt(pos))) { } lastWordEnd = pos + 1; if (firstWordStart < 0) { firstWordStart = i; } } } if (firstWordStart < 0) { return fieldName; } else { return fieldName.substring(firstWordStart, lastWordEnd); } }
Source:
<code>public void setup() { <START> Robolectric.getBackgroundThreadScheduler().pause(); <END> Robolectric.getForegroundThreadScheduler().pause(); ReferenceManager._().addReferenceFactory(new ResourceReferenceFactory()); setupPrototypeFactory(); TestAppInstaller appTestInstaller = new TestAppInstaller("jr://resource/commcare-apps/flipper/profile.ccpr", "fp", "123"); appTestInstaller.installAppAndLogin(); }</code><technical_language>dd test thse</technical_language>

Target:
public void setup() { ReferenceManager._().addReferenceFactory(new ResourceReferenceFactory()); setupPrototypeFactory(); TestAppInstaller appTestInstaller = new TestAppInstaller("jr://resource/commcare-apps/flipper/profile.ccpr", "fp", "123"); appTestInstaller.installAppAndLogin(); }
Source:
<code>public void testNotFoundGetTTL() throws IOException { <START> TestUtils.verifyException(HttpFailureException.class, new Callable<Void>() { <END> @Override public Void call() throws Exception { streamClient.getTTL(TestUtils.NOT_FOUND_STREAM_NAME); return null; } }); }</code><technical_language>for picky - this in a status code (404 in this case is NOT_FOUND) instead of HttpFailureException.class, right? This tests more accurate</technical_language>

Target:
public void testNotFoundGetTTL() throws IOException { try { streamClient.getTTL(TestUtils.NOT_FOUND_STREAM_NAME); Assert.fail("Expected HttpFailureException"); } catch (HttpFailureException e) { Assert.assertEquals(HttpURLConnection.HTTP_NOT_FOUND, e.getStatusCode()); } }
Source:
<code>public PopulationProgress indexGetPopulationProgress( LabelSchemaDescriptor descriptor ) throws IndexNotFoundKernelException { <START> return indexService.getIndexProxy( NewIndexDescriptorFactory.forSchema( descriptor ) ).getIndexPopulationProgress(); <END> }</code><technical_language>This is called for general indexes, unique index population is synchronous</technical_language>

Target:
public PopulationProgress indexGetPopulationProgress( LabelSchemaDescriptor descriptor ) throws IndexNotFoundKernelException { return indexService.getIndexProxy( descriptor ).getIndexPopulationProgress(); }
Source:
<code>public void addStateTo(StateDumpCollector dump) { ClusterTierManagerDump.dump(dump, clusterTierManagerConfig); { Map<ClientDescriptor, ClientState> clients = new HashMap<>(clientStateMap); dump.addState("clientCount", String.valueOf(clients.size())); List<Map> allClients = new ArrayList<>(); for (Map.Entry<ClientDescriptor, ClientState> entry : clients.entrySet()) { Map<String,String> clientMap = new HashMap<>(); clientMap.put("clientDescriptor", entry.getKey().toString()); clientMap.put("clientIdentifier", String.valueOf(entry.getValue().getClientIdentifier())); clientMap.put("attached", String.valueOf(entry.getValue().isAttached())); <START> allClients.add(clientMap); <END> } dump.addState("clients", allClients); } }</code><technical_language>give ArrayList clients.size() a size</technical_language>

Target:
public void addStateTo(StateDumpCollector dump) { ClusterTierManagerDump.dump(dump, clusterTierManagerConfig); { Map<ClientDescriptor, ClientState> clients = new HashMap<>(clientStateMap); List<Map> allClients = new ArrayList<>(); for (Map.Entry<ClientDescriptor, ClientState> entry : clients.entrySet()) { Map<String,String> clientMap = new HashMap<>(3); clientMap.put("clientDescriptor", entry.getKey().toString()); clientMap.put("clientIdentifier", String.valueOf(entry.getValue().getClientIdentifier())); clientMap.put("attached", String.valueOf(entry.getValue().isAttached())); allClients.add(clientMap); } dump.addState("clientCount", String.valueOf(allClients.size())); dump.addState("clients", allClients); } }
Source:
<code>private List<IRecord> create(BrowserAction action) { <START> List<IRecord> records = new LinkedList<IRecord>(); <END> ElementRecord parent = sxe.getDocumentRecord().getRoot(); ElementRecord newElement = parent.createNewElementRecord(null, action.getElementType()); newElement.setRid(action.getID()); records.add(newElement); records.addAll(setAttributes(newElement, action.getAttributes())); return records; }</code><technical_language>ArrayList sufficient, this applies appearances in this patch set</technical_language>

Target:
private List<IRecord> create(BrowserAction action) { List<IRecord> records = new ArrayList<IRecord>(); ElementRecord parent = sxe.getDocumentRecord().getRoot(); ElementRecord newElement = parent.createNewElementRecord(null, action.getElementType()); newElement.setRid(action.getID()); records.add(newElement); records.addAll(setAttributes(newElement, action.getAttributes())); return records; }
Source:
<code>private KijiFuture<Object> deleteGroupFamily( final EntityId entityId, final FamilyLayout familyLayout, final long upToTimestamp ) throws IOException { <START> final String familyName = Preconditions.checkNotNull(familyLayout.getName()); <END> final HBaseColumnNameTranslator colNameTranslator = mWriterLayoutCapsule.getColumnNameTranslator(); int i = 0; final int numColumnLayouts = familyLayout.getColumnMap().size(); byte[][] qualifiers = new byte[numColumnLayouts][]; for (ColumnLayout columnLayout : familyLayout.getColumnMap().values()) { final String qualifier = columnLayout.getName(); final KijiColumnName column = KijiColumnName.create(familyName, qualifier); final HBaseColumnName hbaseColumnName = colNameTranslator.toHBaseColumnName(column); qualifiers[i] = hbaseColumnName.getQualifier(); i ++; } final byte[] hbaseFamilyName = mWriterLayoutCapsule.getColumnNameTranslator(). toHBaseFamilyName(familyLayout.getLocalityGroup()); final DeleteRequest delete = new DeleteRequest( mTableName, entityId.getHBaseRowKey(), hbaseFamilyName, qualifiers, upToTimestamp); Deferred<Object> deferred = mHBClient.delete(delete); return AsyncHBaseKijiFuture.create(deferred); }</code><technical_language>family name is allowed null</technical_language>

Target:
private KijiFuture<Object> deleteGroupFamily( final EntityId entityId, final FamilyLayout familyLayout, final long upToTimestamp ) throws IOException { final String familyName = familyLayout.getName(); final HBaseColumnNameTranslator colNameTranslator = mWriterLayoutCapsule.getColumnNameTranslator(); int i = 0; final int numColumnLayouts = familyLayout.getColumnMap().size(); byte[][] qualifiers = new byte[numColumnLayouts][]; for (ColumnLayout columnLayout : familyLayout.getColumnMap().values()) { final String qualifier = columnLayout.getName(); final KijiColumnName column = KijiColumnName.create(familyName, qualifier); final HBaseColumnName hbaseColumnName = colNameTranslator.toHBaseColumnName(column); qualifiers[i] = hbaseColumnName.getQualifier(); i++; } final byte[] hbaseFamilyName = mWriterLayoutCapsule.getColumnNameTranslator(). toHBaseFamilyName(familyLayout.getLocalityGroup()); final DeleteRequest delete = new DeleteRequest( mTableName, entityId.getHBaseRowKey(), hbaseFamilyName, qualifiers, upToTimestamp); Deferred<Object> deferred = mHBClient.delete(delete); return AsyncHBaseKijiFuture.create(deferred); }
Source:
<code>default CacheContainerAdmin administration() { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>lose typing CacheContainerAdmin, define this method a generic CacheContainer least</technical_language>

Target:
default CacheContainerAdmin<?> administration() { throw new UnsupportedOperationException(); }
Source:
<code>public List<ResponseInfo> sendAndPoll(List<RequestInfo> requestInfos, Set<Integer> requestsToDrop, int pollTimeoutMs) { if (closed) { throw new IllegalStateException("The client is closed."); } <START> if (processorId < 0) { <END> throw new IllegalStateException("The processorId has not been set."); } long startTime = time.milliseconds(); try { for (RequestInfo requestInfo : requestInfos) { ByteBuffer buffer = LocalRequestResponseChannel.byteBufferFromPayload(requestInfo.getRequest()); channel.sendRequest(new LocalChannelRequest(requestInfo, processorId, new ByteBufferInputStream(buffer))); } } catch (Exception e) { logger.error("Received an unexpected error during sendAndPoll(): ", e); networkMetrics.networkClientException.inc(); } List<ResponseInfo> responses = channel.receiveResponses(processorId); networkMetrics.networkClientSendAndPollTime.update(time.milliseconds() - startTime, TimeUnit.MILLISECONDS); return responses; }</code><technical_language>this condition? set <0 somewhere</technical_language>

Target:
public List<ResponseInfo> sendAndPoll(List<RequestInfo> requestInfos, Set<Integer> requestsToDrop, int pollTimeoutMs) { if (closed) { throw new IllegalStateException("The client is closed."); } long startTime = time.milliseconds(); try { for (RequestInfo requestInfo : requestInfos) { ByteBuffer buffer = LocalRequestResponseChannel.byteBufferFromPayload(requestInfo.getRequest()); channel.sendRequest(new LocalChannelRequest(requestInfo, processorId, new ByteBufferInputStream(buffer))); } } catch (Exception e) { logger.error("Received an unexpected error during sendAndPoll(): ", e); networkMetrics.networkClientException.inc(); } List<ResponseInfo> responses = channel.receiveResponses(processorId, pollTimeoutMs); networkMetrics.networkClientSendAndPollTime.update(time.milliseconds() - startTime, TimeUnit.MILLISECONDS); return responses; }
Source:
<code>public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException { Function<SecurityDomain, IdentityCache> cacheFunction = createIdentityCacheFunction(request); if (cacheFunction!= null && attemptReAuthentication(request, cacheFunction)) { <START> httpClientCert.trace("ClientCertAuthenticationMechanism: re-authentication succeed"); <END> return; } if (attemptAuthentication(request, cacheFunction)) { return; } httpClientCert.trace("ClientCertAuthenticationMechanism: both, re-authentication and authentication, failed"); fail(request); }</code><technical_language>please remove "ClientCertAuthenticationMechanism" message defined logger</technical_language>

Target:
public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException { Function<SecurityDomain, IdentityCache> cacheFunction = createIdentityCacheFunction(request); if (cacheFunction!= null && attemptReAuthentication(request, cacheFunction)) { httpClientCert.trace("Re-authentication succeed"); return; } if (attemptAuthentication(request, cacheFunction)) { return; } httpClientCert.trace("Both, re-authentication and authentication, failed"); fail(request); }
Source:
<code>public SampleClass inferStockFromAliquot(SampleClass sampleClass) { SampleClass aliquotClass = sampleClassDao.getSampleClass(sampleClass.getId()); if (aliquotClass == null || !aliquotClass.getSampleCategory().equals(SampleAliquot.CATEGORY_NAME)) { throw new IllegalArgumentException("Sample class " + sampleClass.getId() + " is not a valid aliquot class."); } SampleClass stockClass = null; for (SampleValidRelationship relationship : sampleValidRelationshipDao.getSampleValidRelationship()) { if (relationship.getChild().getId() == aliquotClass.getId() <START> && relationship.getParent().getSampleCategory().equals(SampleStock.CATEGORY_NAME)) { <END> if (stockClass == null) { stockClass = relationship.getParent(); } else { throw new IllegalStateException("Aliquot class " + sampleClass.getId() + " has multiple stock class parents."); } } } if (stockClass == null) throw new IllegalStateException("Aliquot class " + sampleClass.getId() + " has no stock class."); return stockClass; }</code><technical_language>archived. cDNA (aliquot) parented cDNA (stock) RNA (stock), of is archived relationship</technical_language>

Target:
public SampleClass inferStockFromAliquot(SampleClass sampleClass) { SampleClass aliquotClass = sampleClassDao.getSampleClass(sampleClass.getId()); if (aliquotClass == null || !aliquotClass.getSampleCategory().equals(SampleAliquot.CATEGORY_NAME)) { throw new IllegalArgumentException("Sample class " + sampleClass.getId() + " is not a valid aliquot class."); } SampleClass stockClass = null; for (SampleValidRelationship relationship : sampleValidRelationshipDao.getSampleValidRelationship()) { if (!relationship.getArchived() && relationship.getChild().getId() == aliquotClass.getId() && relationship.getParent().getSampleCategory().equals(SampleStock.CATEGORY_NAME)) { if (stockClass == null) { stockClass = relationship.getParent(); } else { throw new IllegalStateException("Aliquot class " + sampleClass.getId() + " has multiple stock class parents."); } } } if (stockClass == null) throw new IllegalStateException("Aliquot class " + sampleClass.getId() + " has no stock class."); return stockClass; }
Source:
<code>public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", <START> key, customFormModelField.getName(), customFormModelField.getAccuracy()))); <END> }); END: com.azure.ai.formrecognizer.FormTrainingAsyncClient.getCustomModel#string }</code><technical_language>"Model Type Id: --> Form type:</technical_language>

Target:
public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); END: com.azure.ai.formrecognizer.FormTrainingAsyncClient.getCustomModel#string }
Source:
<code>public synchronized int getLoadBalanceFactor(Engine engine) { boolean nodeUnavailable = false; int totalWeight = 0; double totalWeightedLoad = 0; for (Map.Entry<LoadMetric, List<Double>> entry : this.loadHistory.entrySet()) { LoadMetric metric = entry.getKey(); int weight = metric.getWeight(); if (weight > 0) { List<Double> metricLoadHistory = entry.getValue(); try { this.recordLoad(metricLoadHistory, metric.getLoad(engine) / metric.getCapacity()); totalWeight += weight; totalWeightedLoad += this.average(metricLoadHistory) * weight; } catch (NodeUnavailableException e) { nodeUnavailable = true; } catch (Exception e) { this.log.error(e.getLocalizedMessage(), e); } } } if (nodeUnavailable) { return -1; <START> } else { <END> int load = (int) Math.round(100 * totalWeightedLoad / totalWeight); return 100 - Math.max(0, Math.min(load, 99)); } }</code><technical_language>else clause is redundant here</technical_language>

Target:
public synchronized int getLoadBalanceFactor(Engine engine) { boolean nodeUnavailable = false; int totalWeight = 0; double totalWeightedLoad = 0; for (Map.Entry<LoadMetric, List<Double>> entry : this.loadHistory.entrySet()) { LoadMetric metric = entry.getKey(); int weight = metric.getWeight(); if (weight > 0) { List<Double> metricLoadHistory = entry.getValue(); try { this.recordLoad(metricLoadHistory, metric.getLoad(engine) / metric.getCapacity()); totalWeight += weight; totalWeightedLoad += this.average(metricLoadHistory) * weight; } catch (NodeUnavailableException e) { nodeUnavailable = true; } catch (Exception e) { this.log.error(e.getLocalizedMessage(), e); } } } if (nodeUnavailable) { return -1; } int load = (int) Math.round(100 * totalWeightedLoad / totalWeight); return 100 - Math.max(0, Math.min(load, 99)); }
Source:
<code>public static void main(String[] args) throws Exception { BriefLogFormatter.init(); <START> System.out.println("USAGE: [--net={MAIN/TEST/REGTEST}] host"); <END> final String net = args.length > 1 ? args[0] : ""; NetworkParameters params; switch(net) { case "--net=REGTEST": default: params = RegTestParams.get(); break; case "--net=TEST": params = TestNet3Params.get(); break; case "--net=MAIN": params = MainNetParams.get(); break; } new ExamplePaymentChannelClient().run(args.length > 1 ? args[1] : args[0], params); }</code><technical_language>In tools, "jopt" for argument parsing. want introduce well</technical_language>

Target:
public static void main(String[] args) throws Exception { BriefLogFormatter.init(); OptionParser parser = new OptionParser(); OptionSpec<NetworkEnum> net = parser.accepts("net", "The network to run the examples on").withRequiredArg().ofType(NetworkEnum.class).defaultsTo(NetworkEnum.TEST); OptionSpec<Integer> version = parser.accepts("version", "The payment channel protocol to use").withRequiredArg().ofType(Integer.class); parser.accepts("help", "Displays program options"); OptionSet opts = parser.parse(args); if (opts.has("help") || !opts.has(net) || opts.nonOptionArguments().size() != 1) { System.err.println("usage: ExamplePaymentChannelClient --net=MAIN/TEST/REGTEST --version=1/2 host"); parser.printHelpOn(System.err); return; } PaymentChannelClient.VersionSelector versionSelector = PaymentChannelClient.VersionSelector.VERSION_1; if (opts.has("version")) { switch (version.value(opts)) { case 1: versionSelector = PaymentChannelClient.VersionSelector.VERSION_1; break; case 2: versionSelector = PaymentChannelClient.VersionSelector.VERSION_2; break; default: System.err.println("Invalid version - valid versions are 1, 2"); return; } } NetworkParameters params = net.value(opts).get(); new ExamplePaymentChannelClient().run(opts.nonOptionArguments().get(0), versionSelector, params); }
Source:
<code>public void testRequestedMappingIsStoredInFS() throws Exception { Ignite srv1 = startGrid(0); Organization org = new Organization(1, "Microsoft", "One Microsoft Way Redmond, WA 98052-6399, USA"); srv1.cache(DEFAULT_CACHE_NAME).put(1, org); <START> clientMode = true; <END> Ignite cl1 = startClientGrid(1); cl1.cache(DEFAULT_CACHE_NAME).get(1); String clsName = Organization.class.getName(); stopGrid(1); File[] files = Paths.get(TMP_DIR, "marshaller").toFile().listFiles(); assertNotNull(TMP_DIR + "/marshaller directory should contain at least one file", files); boolean orgClsMarshalled = false; for (File f : files) { if (clsName.equals(new String(Files.readAllBytes(f.toPath())))) { orgClsMarshalled = true; break; } } assertTrue(clsName + " should be marshalled and stored to disk", orgClsMarshalled); }</code><technical_language>This is redundant</technical_language>

Target:
public void testRequestedMappingIsStoredInFS() throws Exception { Ignite srv1 = startGrid(0); Organization org = new Organization(1, "Microsoft", "One Microsoft Way Redmond, WA 98052-6399, USA"); srv1.cache(DEFAULT_CACHE_NAME).put(1, org); Ignite cl1 = startClientGrid(1); cl1.cache(DEFAULT_CACHE_NAME).get(1); String clsName = Organization.class.getName(); stopGrid(1); File[] files = Paths.get(TMP_DIR, "marshaller").toFile().listFiles(); assertNotNull(TMP_DIR + "/marshaller directory should contain at least one file", files); boolean orgClsMarshalled = false; for (File f : files) { if (clsName.equals(new String(Files.readAllBytes(f.toPath())))) { orgClsMarshalled = true; break; } } assertTrue(clsName + " should be marshalled and stored to disk", orgClsMarshalled); }
Source:
<code>public Set<ConnectorPlanOptimizer> getConnectorPlanOptimizers() { <START> return new HashSet<>(); <END> }</code><technical_language>return ImmutableSet.of();</technical_language>

Target:
public Set<ConnectorPlanOptimizer> getConnectorPlanOptimizers() { return ImmutableSet.of(); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); <START> ImageButton one = (ImageButton) findViewById(R.id.facebookButton); <END> one.setOnClickListener(this); ImageButton two = (ImageButton) findViewById(R.id.twitterButton); two.setOnClickListener(this); ImageButton three = (ImageButton) findViewById(R.id.youtubeButton); three.setOnClickListener(this); Button website = (Button) findViewById(R.id.websiteButton); website.setOnClickListener(this); }</code><technical_language>findViewByIds written in a seperate initViews method. Check out other activities for reference</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); initialize(); }
Source:
<code>public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("provisioned"); action .setDescription( "Get the list of provisioned projects.<br /> " + "Require 'Create Projects' permission.") .setSince("5.2") .setResponseExample(Resources.getResource(getClass(), "projects-example-provisioned.json")) .setHandler(this) .addPagingParams(100, MAX_LIMIT) .addSearchQuery("sonar", "names", "keys") .addFieldsParam(POSSIBLE_FIELDS); action.setChangelog( new Change("6.4", "The 'uuid' field is deprecated in the response"), new Change("6.4", "The fields 'total', 'p' and 'ps' are now named 'total', 'pageIndex' and 'pageSize' in the response " + <START> "and are nested inside an attribute 'paging'")); <END> support.addOrganizationParam(action); }</code><technical_language>a simpler sentence "Paging response fields is in a Paging object"</technical_language>

Target:
public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("provisioned"); action .setDescription( "Get the list of provisioned projects.<br /> " + "Require 'Create Projects' permission.") .setSince("5.2") .setResponseExample(Resources.getResource(getClass(), "projects-example-provisioned.json")) .setHandler(this) .addPagingParams(100, MAX_LIMIT) .addSearchQuery("sonar", "names", "keys") .addFieldsParam(POSSIBLE_FIELDS); action.setChangelog( new Change("6.4", "The 'uuid' field is deprecated in the response"), new Change("6.4", "Paging response fields is now in a Paging object")); support.addOrganizationParam(action); }