auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String getQName(PsiElement[] fileChildren, final String result, boolean searchInSamePackage) { final HaxeClass classForType = (HaxeClass)Arrays.stream(fileChildren) .filter(child -> child instanceof HaxeClass && result.equals(((HaxeClass)child).getName())) .findFirst() .orElse(null); if (classForType != null) { return classForType.getQualifiedName(); } final HaxeImportStatement importStatement = (HaxeImportStatement)(StreamUtil.reverse(Arrays.stream(fileChildren)) .filter(element -> element instanceof HaxeImportStatement && ((HaxeImportStatement)element).getModel().exposeByName(result) != null) .findFirst() .orElse(null)); final HaxeExpression importStatementExpression = importStatement == null ? null : importStatement.getReferenceExpression(); <START> if (importStatement != null && importStatementExpression != null) { <END> return importStatementExpression.getText(); } if (searchInSamePackage && fileChildren.length > 0) { final HaxeFileModel fileModel = HaxeFileModel.fromElement(fileChildren[0]); if (fileModel != null) { final HaxePackageModel packageModel = fileModel.getPackageModel(); if (packageModel != null) { final HaxeClassModel classModel = packageModel.getClassModel(result); if (classModel != null) { return classModel.haxeClass.getQualifiedName(); } } } } return result; }</code><technical_language>importStatement is null if importStatementExpression is null</technical_language>

Target:
public static String getQName(PsiElement[] fileChildren, final String result, boolean searchInSamePackage) { final HaxeClass classForType = (HaxeClass)Arrays.stream(fileChildren) .filter(child -> child instanceof HaxeClass && result.equals(((HaxeClass)child).getName())) .findFirst() .orElse(null); if (classForType != null) { return classForType.getQualifiedName(); } final HaxeImportStatement importStatement = (HaxeImportStatement)(StreamUtil.reverse(Arrays.stream(fileChildren)) .filter(element -> element instanceof HaxeImportStatement && ((HaxeImportStatement)element).getModel().exposeByName(result) != null) .findFirst() .orElse(null)); final HaxeExpression importStatementExpression = importStatement == null ? null : importStatement.getReferenceExpression(); if (importStatementExpression != null) { return importStatementExpression.getText(); } if (searchInSamePackage && fileChildren.length > 0) { final HaxeFileModel fileModel = HaxeFileModel.fromElement(fileChildren[0]); if (fileModel != null) { final HaxePackageModel packageModel = fileModel.getPackageModel(); if (packageModel != null) { final HaxeClassModel classModel = packageModel.getClassModel(result); if (classModel != null) { return classModel.haxeClass.getQualifiedName(); } } } } return result; }
Source:
<code>public List<String> requiredFields() { <START> return makeFieldNamesFromFields(fields); <END> }</code><technical_language>This right; requiredFields names of fields this aggregator is read, makeFIeldNamesFromFields returns output names. I switching getDimension instead of getOutputName work</technical_language>

Target:
public List<String> requiredFields() { return makeRequiredFieldNamesFromFields(fields); }
Source:
<code>public synchronized static WebDriver getDriver() { if (driver == null) { try { driver = initiateDriver(); <START> driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); <END> } finally { Runtime.getRuntime().addShutdownHook( new Thread(new BrowserCleanup())); } } return driver; }</code><technical_language>This setting in initiateDriver method</technical_language>

Target:
public synchronized static WebDriver getDriver() { if (driver == null) { try { driver = initiateDriver(); } finally { Runtime.getRuntime().addShutdownHook( new Thread(new BrowserCleanup())); } } return driver; }
Source:
<code>public void run() { Object selection = getStructuredSelection().getFirstElement(); if (selection instanceof IBuild) { IBuild build = (IBuild) selection; if (editor != null) { abortBuild(build, editor); } else { <START> abortBuild(build); <END> } } else if (selection instanceof IBuildPlan) { IBuildPlan buildPlan = (IBuildPlan) selection; abortBuild(buildPlan.getLastBuild()); } }</code><technical_language>this calls abortBuild a null editor, delete if call abortBuild(build,editor)</technical_language>

Target:
public void run() { Object selection = getStructuredSelection().getFirstElement(); if (selection instanceof IBuild) { IBuild build = (IBuild) selection; abortBuild(build); } else if (selection instanceof IBuildPlan) { IBuildPlan buildPlan = (IBuildPlan) selection; abortBuild(buildPlan.getLastBuild()); } }
Source:
<code>private SupportedTypeResourceDefinition(SimpleAttributeDefinition... attributes) { super(ModelElement.SUPPORTED_TYPE, new IDMConfigAddStepHandler( <START> getModelValidators(), attributes), null, attributes); <END> }</code><technical_language>remove handler</technical_language>

Target:
private SupportedTypeResourceDefinition(SimpleAttributeDefinition... attributes) { super(ModelElement.SUPPORTED_TYPE, new IDMConfigAddStepHandler( getModelValidators(), attributes), attributes); }
Source:
<code>private static KeyStore getKeyStore(String keyStoreName, String password) throws IOException { KeyStore ks = null; FileInputStream fis = null; try { ks = KeyStore.getInstance("JKS"); char[] passwordArray = password.toCharArray(); fis = new java.io.FileInputStream(keyStoreName); ks.load(fis, passwordArray); fis.close(); } catch (Exception e) { <START> e.printStackTrace(); <END> } finally { if (fis != null) { fis.close(); } } return ks; }</code><technical_language>Do e.printStackTrace(). Log exception. > this.logger.severe( e.getMessage()); > this.logger.finest( Utils.writeException( e ));</technical_language>

Target:
private KeyStore getKeyStore(String keyStoreName, String password) throws IOException { KeyStore ks = null; FileInputStream fis = null; try { ks = KeyStore.getInstance("JKS"); char[] passwordArray = password.toCharArray(); fis = new java.io.FileInputStream(keyStoreName); ks.load(fis, passwordArray); } catch (Exception e) { this.logger.severe( e.getMessage() ); } finally { if (fis != null) { Utils.closeQuietly( fis ); } } return ks; }
Source:
<code>public User createUser(String email, String password, Map<String, ? extends Object> parameters) { ImmutableMap<String, ?extends Object> reqParams = ImmutableMap.of("email", email, "password", password); ImmutableMap<String, Object> allParams = new ImmutableMap.Builder<String, Object>() .putAll(reqParams) .putAll(parameters) .build(); User user = createModel(allParams); <START> return user; <END> }</code><technical_language>Please code concise, replace L86-L88 a single line (return createModel(allParams))</technical_language>

Target:
public User createUser(String email, String password, Map<String, ? extends Object> parameters) { HashMap<String, Object> allParams = new HashMap<String, Object>(); allParams.putAll(parameters); allParams.put("email", email); allParams.put("password", password); User user = createModel(allParams); return user; }
Source:
<code>public void onSuccessPartialConfig(ConfigRepoConfig repoConfig, PartialConfig incoming) { final String fingerprint = repoConfig.getRepo().getFingerprint(); if (this.configWatchList.hasConfigRepoWithFingerprint(fingerprint)) { if (shouldMergePartial(incoming, fingerprint, repoConfig)) { cachedGoPartials.cacheAsLastKnown(fingerprint, incoming); hasRuleViolations(incoming); final boolean isConfigUpdated = updateConfig(incoming, fingerprint, repoConfig); if (isConfigUpdated) { cachedGoPartials.markAsValid(fingerprint, incoming); } else { final PartialConfig previousValidPartial = cachedGoPartials.getValid(repoConfig.getRepo().getFingerprint()); if (previousValidPartial != null) { final boolean isSameRevisionAsOfPreviousValidPartial = ((RepoConfigOrigin) incoming.getOrigin()).getRevision().equals(((RepoConfigOrigin) previousValidPartial.getOrigin()).getRevision()); <START> if (isSameRevisionAsOfPreviousValidPartial) { <END> removeCachedPartialsAndUpdateConfig(fingerprint); } else { ((RepoConfigOrigin) previousValidPartial.getOrigin()).setConfigRepo(((RepoConfigOrigin) incoming.getOrigin()).getConfigRepo()); if (hasRuleViolations(previousValidPartial)) { removeCachedPartialsAndUpdateConfig(fingerprint); } } } } } } }</code><technical_language>if I understand right, assumption is if current version is valid version, config update is failed due rules violation. If is case a wrong assumption adding support for branches/PR. For a revision of config repo material, partials differ based PRs/branches time of parse. if logic sense, if (updateConfig(incoming, fingerprint, repoConfig)) { cachedGoPartials.markAsValid(fingerprint, incoming); } else { final PartialConfig previousValidPartial = cachedGoPartials.getValid(repoConfig.getRepo().getFingerprint()); if (violatesRules && previousValidPartial != null) { // do allow fallback version of partial if current rules do allow cachedGoPartials.removeValidWithoutClearingServerHealthMessage(repoConfig.getRepo().getFingerprint()); goConfigService.updateConfig(cruiseConfig -> { cruiseConfig.getPartials().remove(cachedGoPartials.findPartialByFingerprint(cruiseConfig, fingerprint)); return cruiseConfig; }); } }</technical_language>

Target:
public void onSuccessPartialConfig(ConfigRepoConfig repoConfig, PartialConfig incoming) { final String fingerprint = repoConfig.getRepo().getFingerprint(); if (this.configWatchList.hasConfigRepoWithFingerprint(fingerprint)) { if (shouldMergePartial(incoming, fingerprint, repoConfig)) { cachedGoPartials.cacheAsLastKnown(fingerprint, incoming); hasRuleViolations(incoming); if (updateConfig(incoming, fingerprint, repoConfig)) { cachedGoPartials.markAsValid(fingerprint, incoming); } else { if (hasRuleViolationsOnPreviousValidPartial(repoConfig)) { removeCachedLastValidPartial(fingerprint); } } } } }
Source:
<code>public double firstDerivative(Interpolator1DDataBundle data, double value) { int lowerIndex = data.getLowerBoundIndex(value); if (lowerIndex == data.size() - 1) { <START> if (data.size() == 1) { <END> return 0d; } if (value > data.lastKey()) { throw new MathException("Value of " + value + " after last key. Use extrapolator"); } lowerIndex--; } double x1 = data.getKey(lowerIndex); double y1 = data.getValue(lowerIndex); double x2 = data.getKey(lowerIndex + 1); double y2 = data.getValue(lowerIndex + 1); return (y2 - y1) / (x2 - x1); }</code><technical_language>this if block move other if block? If data a size of 1 index data.size() - 1</technical_language>

Target:
public double firstDerivative(Interpolator1DDataBundle data, double value) { int lowerIndex = data.getLowerBoundIndex(value); if (lowerIndex == data.size() - 1) { if (value > data.lastKey()) { return 0d; } lowerIndex--; } double x1 = data.getKey(lowerIndex); double y1 = data.getValue(lowerIndex); double x2 = data.getKey(lowerIndex + 1); double y2 = data.getValue(lowerIndex + 1); return (y2 - y1) / (x2 - x1); }
Source:
<code>public void call(final Subscriber<? super T> subscriber) { try { final Resource resource = resourceFactory.call(); final DisposeAction<Resource> disposeOnceOnly = new DisposeAction<Resource>(dispose, resource); subscriber.add(disposeOnceOnly); final Observable<? extends T> source; try { source = observableFactory .call(resource); } catch (Throwable e) { Throwable disposeError = dispose(disposeOnceOnly); Exceptions.throwIfFatal(e); Exceptions.throwIfFatal(disposeError); if (disposeError != null) { <START> subscriber.onError(new CompositeException(Arrays.asList(e, disposeError))); <END> } else { subscriber.onError(e); } return; } final Observable<? extends T> observable; if (disposeEagerly) { observable = source .doOnTerminate(disposeOnceOnly); } else { observable = source .doAfterTerminate(disposeOnceOnly) ; } try { observable.unsafeSubscribe(Subscribers.wrap(subscriber)); } catch (Throwable e) { Throwable disposeError = dispose(disposeOnceOnly); Exceptions.throwIfFatal(e); Exceptions.throwIfFatal(disposeError); if (disposeError != null) subscriber.onError(new CompositeException(Arrays.asList(e, disposeError))); else subscriber.onError(e); } } catch (Throwable e) { Exceptions.throwOrReport(e, subscriber); } }</code><technical_language>CompositeException accepts varargs right</technical_language>

Target:
public void call(final Subscriber<? super T> subscriber) { try { final Resource resource = resourceFactory.call(); final DisposeAction<Resource> disposeOnceOnly = new DisposeAction<Resource>(dispose, resource); subscriber.add(disposeOnceOnly); final Observable<? extends T> source; try { source = observableFactory .call(resource); } catch (Throwable e) { Throwable disposeError = dispose(disposeOnceOnly); Exceptions.throwIfFatal(e); Exceptions.throwIfFatal(disposeError); if (disposeError != null) { subscriber.onError(new CompositeException(e, disposeError)); } else { subscriber.onError(e); } return; } final Observable<? extends T> observable; if (disposeEagerly) { observable = source .doOnTerminate(disposeOnceOnly); } else { observable = source .doAfterTerminate(disposeOnceOnly); } try { observable.unsafeSubscribe(Subscribers.wrap(subscriber)); } catch (Throwable e) { Throwable disposeError = dispose(disposeOnceOnly); Exceptions.throwIfFatal(e); Exceptions.throwIfFatal(disposeError); if (disposeError != null) subscriber.onError(new CompositeException(e, disposeError)); else subscriber.onError(e); } } catch (Throwable e) { Exceptions.throwOrReport(e, subscriber); } }
Source:
<code>private void finishedGeotagging(Intent intent) { boolean success = intent.getBooleanExtra(GeoTagImagesService.EXTRA_SUCCESS, false); if (success) { ArrayList<File> files = (ArrayList<File>) intent.getSerializableExtra(GeoTagImagesService.EXTRA_GEOTAGGED_FILES); <START> activity.finishedGeotagging(files); <END> } else { String failure = intent.getStringExtra(GeoTagImagesService.EXTRA_FAILURE_MESSAGE); failedLoading(failure); } }</code><technical_language>@chaviw check for activity null</technical_language>

Target:
private void finishedGeotagging(Intent intent) { boolean success = intent.getBooleanExtra(GeoTagImagesService.EXTRA_SUCCESS, false); if (success) { if (activity != null) { ArrayList<File> files = (ArrayList<File>) intent.getSerializableExtra(GeoTagImagesService.EXTRA_GEOTAGGED_FILES); activity.finishedGeotagging(files); } } else { String failure = intent.getStringExtra(GeoTagImagesService.EXTRA_FAILURE_MESSAGE); failedLoading(failure); } }
Source:
<code>public static MemoryRealm constructRealm(JaxRsApplication application, ConfManager configManager){ MemoryRealm realm = new MemoryRealm(); MapVerifier mapVerifier = new MapVerifier(); String[] users = configManager.get(ConfigResource.DEFAULT).getTrimmedStrings("restapi.auth.users", "admin|admin|admin"); if (users.length <= 1) { throw new IllegalStateException("Check users definition of restapi.auth.users at nutch-site.xml "); } for (String userconf : users) { String[] userDetail = userconf.split("\\|"); if(userDetail.length != 3) { LOG.error("Check user definition of restapi.auth.users at nutch-site.xml"); throw new IllegalStateException("Check user definition of restapi.auth.users at nutch-site.xml "); } User user = new User(userDetail[0], userDetail[1]); mapVerifier.getLocalSecrets().put(user.getIdentifier(), user.getSecret()); realm.getUsers().add(user); realm.map(user, Role.get(application, userDetail[2])); <START> LOG.info("User added: " + userDetail[0]); <END> } realm.setVerifier(mapVerifier); return realm; }</code><technical_language>Parameterized logging please</technical_language>

Target:
public static MemoryRealm constructRealm(JaxRsApplication application, ConfManager configManager){ MemoryRealm realm = new MemoryRealm(); MapVerifier mapVerifier = new MapVerifier(); String[] users = configManager.get(ConfigResource.DEFAULT).getTrimmedStrings("restapi.auth.users", "admin|admin|admin,user|user|user"); if (users.length <= 1) { throw new IllegalStateException("Check users definition of restapi.auth.users at nutch-site.xml "); } for (String userconf : users) { String[] userDetail = userconf.split("\\|"); if(userDetail.length != 3) { LOG.error("Check user definition of restapi.auth.users at nutch-site.xml"); throw new IllegalStateException("Check user definition of restapi.auth.users at nutch-site.xml "); } User user = new User(userDetail[0], userDetail[1]); mapVerifier.getLocalSecrets().put(user.getIdentifier(), user.getSecret()); realm.getUsers().add(user); realm.map(user, Role.get(application, userDetail[2])); LOG.info("User added: {}", userDetail[0]); } realm.setVerifier(mapVerifier); return realm; }
Source:
<code>public int size() { <START> authzManager.checkPermission(CachePermission.ADMIN); <END> return delegate.size(); }</code><technical_language>This more a READ permission</technical_language>

Target:
public int size() { authzManager.checkPermission(AuthorizationPermission.BULK_READ); return delegate.size(); }
Source:
<code>public void canIgnoreInvocationsWithJunit() throws InterruptedException { DelayedExecution delayedExecution = new DelayedExecution(executor, mock, 0); delayedExecution.recordAsyncCall('0'); delayedExecution.recordAsyncCall('1'); delayedExecution.recordAsyncCall('2'); delayedExecution.allAsyncCallsStarted(); <START> verify(mock, timeout(50)).oneArg('0'); <END> verify(mock, timeout(50)).oneArg('1'); verify(mock, timeout(50)).oneArg('2'); }</code><technical_language>@lukasz-szewc This line removed this tested in original test case. For reason call '2' delayed 20ms</technical_language>

Target:
public void canIgnoreInvocationsWithJunit() throws InterruptedException { DelayedExecution delayedExecution = createZeroMillisDelayedExecution(); DelayedExecution twentyMillisDelayedExecution = createTwentyMillisDelayedExecution(); delayedExecution.allAsyncCallsStarted(); verify(mock, timeout(50)).oneArg('1'); twentyMillisDelayedExecution.allAsyncCallsStarted(); verify(mock, timeout(50)).oneArg('2'); }
Source:
<code>private void buildReferences(BundleDescription description, List<Object[]> references) { HostSpecification <START> host = <END> description.getHost(); if (host != null) { if (host.getHosts() != null) { BundleDescription[] hosts = host.getHosts(); for (BundleDescription host1 : hosts) { if (host1 != description) { references.add(new Object[]{description, host1}); } } } GenericDescription[] genericDependencies = description.getResolvedGenericRequires(); for (GenericDescription dependency : genericDependencies) { if (ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE.equals(dependency.getType())) { references.add(new Object[] {description, dependency.getSupplier()}); } } } else { buildReferences(description, ((BundleDescriptionImpl) description).getBundleDependencies(), references); } }</code><technical_language>rename this hostSpecification host foreach var</technical_language>

Target:
private void buildReferences(BundleDescription description, List<Object[]> references) { HostSpecification hostSpecification = description.getHost(); if (hostSpecification != null) { if (hostSpecification.getHosts() != null) { BundleDescription[] hosts = hostSpecification.getHosts(); for (BundleDescription host : hosts) { if (host != description) { references.add(new Object[]{description, host}); } } } GenericDescription[] genericDependencies = description.getResolvedGenericRequires(); for (GenericDescription dependency : genericDependencies) { if (ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE.equals(dependency.getType())) { references.add(new Object[] {description, dependency.getSupplier()}); } } } else { buildReferences(description, ((BundleDescriptionImpl) description).getBundleDependencies(), references); } }
Source:
<code>private boolean passesFilteringByParameter(final AbstractBuild<?, ?> build, final String parameterName, final String parameterValue){ <START> if (parameterName == null){ <END> return true; } Map<String, String> vars = build.getBuildVariables(); if(vars.containsKey(parameterName)){ if (vars.get(parameterName).equals(parameterValue)) { return true; } } return false; }</code><technical_language>please check formatter preferences? Whitespace (WS) ( {. safe select chagnes appy auto-reformat)</technical_language>

Target:
private boolean passesFilteringByParameter(final AbstractBuild<?, ?> build, final String parameterName, final String parameterValue) { if (parameterName == null){ return true; } Map<String, String> vars = build.getBuildVariables(); if (vars == null) { return false; } if(vars.containsKey(parameterName)) { String pv = vars.get(parameterName); if (pv != null && pv.equals(parameterValue)) { return true; } } return false; }
Source:
<code><START> private boolean verifySharingPermissions(String user, Path path) { <END> FileSystem peergosFileSystem = fileSystems.getTestFileSystem(user); FileSystem nativeFileSystem = fileSystems.getReferenceFileSystem(user); boolean isVerified = true; for (FileSystem.Permission permission : FileSystem.Permission.values()) { Set<String> shareesInPeergos = new HashSet<>(peergosFileSystem.getSharees(path, permission)); Set<String> shareesInLocal = new HashSet<>(nativeFileSystem.getSharees(path, permission)); if (! shareesInPeergos.equals(shareesInLocal)) { LOG.info("User " + peergosFileSystem.user() + " path " + path + " has peergos-fs " + permission.name() + "ers " + shareesInPeergos + " and local-fs " + permission.name() + "ers " + shareesInLocal); isVerified = false; } } return isVerified; }</code><technical_language>This verifying sharer's view of permissions, sharee read</technical_language>

Target:
private boolean verifySharingPermissions(String user, Path path) { FileSystem peergosFileSystem = fileSystems.getTestFileSystem(user); FileSystem nativeFileSystem = fileSystems.getReferenceFileSystem(user); boolean isVerified = true; for (FileSystem.Permission permission : FileSystem.Permission.values()) { Set<String> shareesInPeergos = new HashSet<>(peergosFileSystem.getSharees(path, permission)); Set<String> shareesInLocal = new HashSet<>(nativeFileSystem.getSharees(path, permission)); if (! shareesInPeergos.equals(shareesInLocal)) { LOG.info("User " + peergosFileSystem.user() + " path " + path + " has peergos-fs " + permission.name() + "ers " + shareesInPeergos + " and local-fs " + permission.name() + "ers " + shareesInLocal); isVerified = false; } for (String sharee : shareesInPeergos) { byte[] read = null; PeergosFileSystemImpl fs = fileSystems.getTestFileSystem(sharee); switch (permission) { case READ: try { read = fs.read(path); } catch (Exception ex) { LOG.log(Level.WARNING, "User "+ sharee +" could not read shared-path "+ path +"!", ex); isVerified = false; } case WRITE: try { fs.write(path, new byte[]{0}); } catch (Exception ex) { LOG.log(Level.WARNING, "User "+ sharee +" could not write shared-path "+ path +"!", ex); } default: throw new IllegalStateException(); } } } return isVerified; }
Source:
<code>private static void checkFStringLiteral(SubscriptionContext ctx) { StringLiteral literal = (StringLiteral) ctx.syntaxNode(); <START> if (TreeUtils.firstAncestorOfKind(literal, Tree.Kind.PLUS) != null) { <END> return; } List<StringElement> fStrings = literal.stringElements().stream() .filter(stringElement -> stringElement.prefix().toLowerCase(Locale.ENGLISH).contains("f")) .collect(Collectors.toList()); if (!fStrings.isEmpty() && fStrings.stream().allMatch(str -> str.formattedExpressions().isEmpty())) { ctx.addIssue(literal, "Add replacement fields or use a normal string instead of an f-string."); } }</code><technical_language>if this is a common case, more restrictive in case want catch wrongly formatted f-strings of related concatenation of f-strings, foo(f"hello") + bar(f"world")</technical_language>

Target:
private static void checkFStringLiteral(SubscriptionContext ctx) { StringLiteral literal = (StringLiteral) ctx.syntaxNode(); if (literal.parent().is(Tree.Kind.PLUS)) { return; } List<StringElement> fStrings = literal.stringElements().stream() .filter(stringElement -> stringElement.prefix().toLowerCase(Locale.ENGLISH).contains("f")) .collect(Collectors.toList()); if (!fStrings.isEmpty() && fStrings.stream().allMatch(str -> str.formattedExpressions().isEmpty())) { ctx.addIssue(literal, "Add replacement fields or use a normal string instead of an f-string."); } }
Source:
<code><START> public CompletableFuture<StaticResource> getResource(String name) { <END> StaticResource template = templates.get(name); if (template != null) { return CompletableFuture.completedFuture(template); } return delegate .getResource(name) .exceptionally((th) -> { templates.putIfAbsent(name, null); return null; } ) .thenApply( (file) -> { templates.putIfAbsent(name, file); return file; }); }</code><technical_language>Could/should this return a CompletableFuture < Optional < StaticResource > > ? avoid INVALID constant in StaticResource isValid check I think</technical_language>

Target:
public CompletableFuture<Optional<StaticResource>> getResource(String name) { Optional<StaticResource> template = templates.get(name); if (template != null) { return CompletableFuture.completedFuture(template); } return delegate .getResource(name) .exceptionally((th) -> { return Optional.empty(); } ) .thenApply( (file) -> { templates.put(name, file); return file; }); }
Source:
<code>public void handleMessage(Message msg) { switch(msg.what) { case EVENT_RADIO_TECHNOLOGY_CHANGED: mOutgoingPhone = ((PhoneBase)mActivePhone).getPhoneName(); Log.d(LOG_TAG, "Switching phone from " + mOutgoingPhone + "Phone to " + (mOutgoingPhone.equals("GSM") ? "CDMAPhone" : "GSMPhone") ); if(mOutgoingPhone.equals("GSM")) { PhoneProxy.setRadioTechnologyChangeGsmToCdma(true); Log.d(LOG_TAG, "Make a new CDMAPhone and destroy the old GSMPhone."); ((GSMPhone)mActivePhone).dispose(); mActivePhone = null; <START> System.gc(); <END> mActivePhone = PhoneFactory.getCdmaPhone(); } else { PhoneProxy.setRadioTechnologyChangeCdmaToGsm(true); Log.d(LOG_TAG, "Make a new GSMPhone and destroy the old CDMAPhone."); ((CDMAPhone)mActivePhone).dispose(); mActivePhone = null; System.gc(); mActivePhone = PhoneFactory.getGsmPhone(); } mIccSmsInterfaceManagerProxy.setmIccSmsInterfaceManager( mActivePhone.getIccSmsInterfaceManager()); mIccPhoneBookInterfaceManagerProxy.setmIccPhoneBookInterfaceManager( mActivePhone.getIccPhoneBookInterfaceManager()); mPhoneSubInfoProxy.setmPhoneSubInfo(this.mActivePhone.getPhoneSubInfo()); mCommandsInterface = ((PhoneBase)mActivePhone).mCM; System.gc(); Intent intent = new Intent(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED); intent.putExtra(Phone.PHONE_NAME_KEY, mActivePhone.getPhoneName()); ActivityManagerNative.broadcastStickyIntent(intent, null); break; default: Log.e(LOG_TAG, "Error! This handler was not registered for this message type. Message: " + msg.what); break; } super.handleMessage(msg); }</code><technical_language>recommended call system.gc() here. allow VM care of it. Is reason this in other places</technical_language>

Target:
public void handleMessage(Message msg) { switch(msg.what) { case EVENT_RADIO_TECHNOLOGY_CHANGED: mOutgoingPhone = ((PhoneBase)mActivePhone).getPhoneName(); Log.d(LOG_TAG, "Switching phone from " + mOutgoingPhone + "Phone to " + (mOutgoingPhone.equals("GSM") ? "CDMAPhone" : "GSMPhone") ); if(mOutgoingPhone.equals("GSM")) { Log.d(LOG_TAG, "Make a new CDMAPhone and destroy the old GSMPhone."); ((GSMPhone)mActivePhone).dispose(); mActivePhone = null; System.gc(); mActivePhone = PhoneFactory.getCdmaPhone(); } else { Log.d(LOG_TAG, "Make a new GSMPhone and destroy the old CDMAPhone."); ((CDMAPhone)mActivePhone).dispose(); mActivePhone = null; System.gc(); mActivePhone = PhoneFactory.getGsmPhone(); } mIccSmsInterfaceManagerProxy.setmIccSmsInterfaceManager( mActivePhone.getIccSmsInterfaceManager()); mIccPhoneBookInterfaceManagerProxy.setmIccPhoneBookInterfaceManager( mActivePhone.getIccPhoneBookInterfaceManager()); mPhoneSubInfoProxy.setmPhoneSubInfo(this.mActivePhone.getPhoneSubInfo()); mCommandsInterface = ((PhoneBase)mActivePhone).mCM; System.gc(); Intent intent = new Intent(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED); intent.putExtra(Phone.PHONE_NAME_KEY, mActivePhone.getPhoneName()); ActivityManagerNative.broadcastStickyIntent(intent, null); break; default: Log.e(LOG_TAG, "Error! This handler was not registered for this message type. Message: " + msg.what); break; } super.handleMessage(msg); }
Source:
<code>public String getOriginSite() { if(getPageUrl() == null || getPageUrl().getHost() ==null) { <START> return "unknown"; <END> } String host = getPageUrl().getHost(); for (String modHost : Constants.ACCEPTED_MOD_HOSTS) { if (host.endsWith(modHost)) { return modHost; } } return "unknown"; }</code><technical_language>Change "unknown" null. model responsible for formatting output for user</technical_language>

Target:
public String getOriginSite() { if(getPageUrl() != null && getPageUrl().getHost() != null) { String host = getPageUrl().getHost(); for (String modHost : Constants.ACCEPTED_MOD_HOSTS) { if (host.endsWith(modHost)) { return modHost; } } } return null; }
Source:
<code>public ApacheClient() { this(new DefaultHttpClient()); DefaultHttpClient client = (DefaultHttpClient) this.client; <START> this.redirectHandler = new RedirectHandler(); <END> client.setRedirectHandler(this.redirectHandler); }</code><technical_language>Drop this this next line</technical_language>

Target:
public ApacheClient() { this(new DefaultHttpClient()); }
Source:
<code>public void customize(ConfigurableEmbeddedServletContainer container) { if (container instanceof TomcatEmbeddedServletContainerFactory) { TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container; Connector ajpConnector = new Connector("AJP/1.3"); <START> ajpConnector.setProtocol("AJP/1.3"); <END> ajpConnector.setAttribute("address", bindAddress); ajpConnector.setPort(port); ajpConnector.setSecure(false); ajpConnector.setAllowTrace(false); ajpConnector.setScheme("http"); tomcat.addAdditionalTomcatConnectors(ajpConnector); } }</code><technical_language>set constructor</technical_language>

Target:
public void customize(ConfigurableEmbeddedServletContainer container) { if (container instanceof TomcatEmbeddedServletContainerFactory) { TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container; Connector ajpConnector = new Connector("AJP/1.3"); ajpConnector.setAttribute("address", bindAddress); ajpConnector.setPort(port); ajpConnector.setSecure(false); ajpConnector.setAllowTrace(false); ajpConnector.setScheme("http"); tomcat.addAdditionalTomcatConnectors(ajpConnector); } }
Source:
<code>public SignatureBuilder typeVariableConstraints(List<TypeVariableConstraint> typeVariableConstraints) { <START> this.typeVariableConstraints = unmodifiableList(new ArrayList<>(requireNonNull(typeVariableConstraints, "typeVariableConstraints is null"))); <END> return this; }</code><technical_language>This is longer needed if moving SPI</technical_language>

Target:
public SignatureBuilder typeVariableConstraints(List<TypeVariableConstraint> typeVariableConstraints) { this.typeVariableConstraints = ImmutableList.copyOf(requireNonNull(typeVariableConstraints, "typeVariableConstraints is null")); return this; }
Source:
<code>public void visitSwitchStatement(SwitchStatementTree tree) { List<List<StatementTree>> normalizedBranches = new ArrayList<>(); boolean hasDefault = false; boolean hasFallthrough = false; int lastIndex = tree.cases().size() - 1; for (int i = 0; i < tree.cases().size(); i++) { SwitchCaseClauseTree switchCaseClause = tree.cases().get(i); List<StatementTree> statements = switchCaseClause.statements(); if (switchCaseClause.is(Kind.DEFAULT_CLAUSE)) { hasDefault = true; } if (!statements.isEmpty()) { normalizedBranches.add(normalize(statements)); if (i != lastIndex && !endsWithBreak(statements)) { hasFallthrough = true; } } } if (!normalizedBranches.isEmpty()) { <START> checkBranches("case", normalizedBranches, hasDefault && !hasFallthrough, tree.switchToken()); <END> } super.visitSwitchStatement(tree); }</code><technical_language>hasDefault && !hasFallthrough means reportAllEquivalent</technical_language>

Target:
public void visitSwitchStatement(SwitchStatementTree tree) { List<List<StatementTree>> normalizedBranches = new ArrayList<>(); boolean hasDefault = false; boolean hasFallthrough = false; int lastIndex = tree.cases().size() - 1; for (int i = 0; i < tree.cases().size(); i++) { SwitchCaseClauseTree switchCaseClause = tree.cases().get(i); List<StatementTree> statements = switchCaseClause.statements(); if (switchCaseClause.is(Kind.DEFAULT_CLAUSE)) { hasDefault = true; } if (!statements.isEmpty()) { normalizedBranches.add(normalize(statements)); if (i != lastIndex && !endsWithBreak(statements)) { hasFallthrough = true; } } } if (!normalizedBranches.isEmpty()) { boolean reportAllDuplicate = hasDefault && !hasFallthrough; checkBranches("case", normalizedBranches, reportAllDuplicate, tree.switchToken()); } super.visitSwitchStatement(tree); }
Source:
<code>protected PlanNodeStatsEstimate visitLogicalBinaryExpression(LogicalBinaryExpression node, Void context) { PlanNodeStatsEstimate leftStats = process(node.getLeft()); PlanNodeStatsEstimate andStats = new FilterExpressionStatsCalculatingVisitor(leftStats, session, types).process(node.getRight()); switch (node.getType()) { case AND: return andStats; case OR: PlanNodeStatsEstimate rightStats = process(node.getRight()); PlanNodeStatsEstimate sumStats = addStatsAndSumDistinctValues(leftStats, rightStats); return differenceInNonRangeStats(sumStats, andStats); default: <START> throw new IllegalStateException(format("Unimplemented logical binary operator expression %s", node.getType())); <END> } }</code><technical_language>typically unknown stats returned in case, com.facebook.presto.cost.ComparisonStatsCalculator#comparisonSymbolToLiteralStats. need for format</technical_language>

Target:
protected PlanNodeStatsEstimate visitLogicalBinaryExpression(LogicalBinaryExpression node, Void context) { PlanNodeStatsEstimate leftStats = process(node.getLeft()); PlanNodeStatsEstimate andStats = new FilterExpressionStatsCalculatingVisitor(leftStats, session, types).process(node.getRight()); switch (node.getType()) { case AND: return andStats; case OR: PlanNodeStatsEstimate rightStats = process(node.getRight()); PlanNodeStatsEstimate sumStats = addStatsAndSumDistinctValues(leftStats, rightStats); return differenceInNonRangeStats(sumStats, andStats); default: throw new IllegalStateException("Unimplemented logical binary operator expression " + node.getType()); } }
Source:
<code>public AsyncQuery storeResults(AsyncQuery asyncQuery, Observable<String> result) { log.debug("store AsyncResults for Download"); try (BufferedWriter writer = getWriter(asyncQuery.getId())) { result .map(s -> s.concat(System.getProperty("line.separator"))) .subscribe( s -> { writer.write(s); writer.flush(); }, <START> t -> { <END> throw new IllegalStateException(t); }, () -> { writer.flush(); } ); } catch (IOException e) { throw new IllegalStateException(e); } return asyncQuery; }</code><technical_language>add longer names for s t is clear are</technical_language>

Target:
public AsyncQuery storeResults(AsyncQuery asyncQuery, Observable<String> result) { log.debug("store AsyncResults for Download"); try (BufferedWriter writer = getWriter(asyncQuery.getId())) { result .map(record -> record.concat(System.getProperty("line.separator"))) .subscribe( recordCharArray -> { writer.write(recordCharArray); writer.flush(); }, throwable -> { throw new IllegalStateException(throwable); }, () -> { writer.flush(); } ); } catch (IOException e) { throw new IllegalStateException(e); } return asyncQuery; }
Source:
<code>public ICleanUpFix createFix(CleanUpContext context) throws CoreException { ICleanUpFixCore fixCore= coreCleanUp.createFixCore(context); return fixCore == null ? null : new <START> CleanUpFixWrapper(coreCleanUp.createFixCore(context)); <END> }</code><technical_language>this 'fixCore' instead of creating object</technical_language>

Target:
public ICleanUpFix createFix(CleanUpContext context) throws CoreException { ICleanUpFixCore fixCore= coreCleanUp.createFixCore(context); return fixCore == null ? null : new CleanUpFixWrapper(fixCore); }
Source:
<code>protected void processWatch(String propertyName, WatchedEvent event) { if (_readWindowMs > 0 && _executorService != null) { <START> int midPoint = _readWindowMs / 2; <END> int delay = midPoint + ThreadLocalRandom.current().nextInt(midPoint); _executorService.schedule(() -> _zk.getChildren(getPath(propertyName), this, this, false), delay, TimeUnit.MILLISECONDS); } else { _zk.getChildren(getPath(propertyName), this, this, false); } }</code><technical_language>delay is in range of [midPoint, readWindowMs] -- [0, readWindowMs]? is need explicitly add latency for calls</technical_language>

Target:
protected void processWatch(String propertyName, WatchedEvent event) { if (_zookeeperReadWindowMs > 0 && _executorService != null) { int midPoint = _zookeeperReadWindowMs / 2; int delay = midPoint + ThreadLocalRandom.current().nextInt(midPoint); _executorService.schedule(() -> _zk.getChildren(getPath(propertyName), this, this, false), delay, TimeUnit.MILLISECONDS); } else { _zk.getChildren(getPath(propertyName), this, this, false); } }
Source:
<code><START> public JPQLQuery<?> from(EntityPath<?>... from) { <END> return query().from(from); }</code><technical_language>return type JPAQuery<?></technical_language>

Target:
public JPAQuery<?> from(EntityPath<?>... from) { return query().from(from); }
Source:
<code>public static SmartThread asyncLoop(final Callable afn, boolean isDaemon, final Thread.UncaughtExceptionHandler eh, int priority, final boolean isFactory, boolean startImmediately, String threadName) { SmartThread thread = new SmartThread(new Runnable() { public void run() { try { final Callable<Long> fn = isFactory ? (Callable<Long>) afn.call() : afn; while (true) { final Long s = fn.call(); if (s==null) break; if (s>0) <START> Thread.sleep(s); <END> } } catch (Throwable t) { if (Utils.exceptionCauseIsInstanceOf( InterruptedException.class, t)) { LOG.info("Async loop interrupted!"); return; } LOG.error("Async loop died!", t); throw new RuntimeException(t); } } }); if (eh != null) { thread.setUncaughtExceptionHandler(eh); } else { thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { LOG.error("Async loop died!", e); Utils.exitProcess(1, "Async loop died!"); } }); } thread.setDaemon(isDaemon); thread.setPriority(priority); if (threadName != null && !threadName.isEmpty()) { thread.setName(thread.getName() +"-"+ threadName); } if (startImmediately) { thread.start(); } return thread; }</code><technical_language>This needs Time.sleep if want simulated time work properly...</technical_language>

Target:
public static SmartThread asyncLoop(final Callable afn, boolean isDaemon, final Thread.UncaughtExceptionHandler eh, int priority, final boolean isFactory, boolean startImmediately, String threadName) { SmartThread thread = new SmartThread(new Runnable() { public void run() { try { final Callable<Long> fn = isFactory ? (Callable<Long>) afn.call() : afn; while (true) { final Long s = fn.call(); if (s==null) break; if (s>0) Time.sleep(s); } } catch (Throwable t) { if (Utils.exceptionCauseIsInstanceOf( InterruptedException.class, t)) { LOG.info("Async loop interrupted!"); return; } LOG.error("Async loop died!", t); throw new RuntimeException(t); } } }); if (eh != null) { thread.setUncaughtExceptionHandler(eh); } else { thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { LOG.error("Async loop died!", e); Utils.exitProcess(1, "Async loop died!"); } }); } thread.setDaemon(isDaemon); thread.setPriority(priority); if (threadName != null && !threadName.isEmpty()) { thread.setName(thread.getName() +"-"+ threadName); } if (startImmediately) { thread.start(); } return thread; }
Source:
<code>public static Path getTribbleFileInJimfs(String vcf, String index, FileSystem fileSystem) throws IOException, URISyntaxException { final FileSystem fs = fileSystem; final Path root = fs.getPath("/"); final Path vcfPath = Paths.get(vcf); if (index != null) { final Path idxPath = Paths.get(index); final Path idxDestination = Paths.get(AbstractFeatureReader.isTabix(vcf, index) ? Tribble.tabixIndexFile(vcf) : Tribble.indexFile(vcf)); <START> Files.copy(idxPath, root.resolve(idxDestination.getFileName().toString())); <END> } return Files.copy(vcfPath, root.resolve(vcfPath.getFileName().toString())); }</code><technical_language>resolve root __vcfPath__ for JimfsFileSystem before, Tribble methods for get idxDestination name need resolve root</technical_language>

Target:
public static Path getTribbleFileInJimfs(String vcf, String index, FileSystem fileSystem) throws IOException, URISyntaxException { final FileSystem fs = fileSystem; final Path root = fs.getPath("/"); final Path vcfPath = Paths.get(vcf); final Path vcfDestination = root.resolve(vcfPath.getFileName().toString()); if (index != null) { final Path idxPath = Paths.get(index); final Path idxDestination = AbstractFeatureReader.isTabix(vcf, index) ? Tribble.tabixIndexPath(vcfDestination) : Tribble.indexPath(vcfDestination); Files.copy(idxPath, idxDestination); } return Files.copy(vcfPath, vcfDestination); }
Source:
<code>public Collection<MessageReceiver> get(ActiveMQSessionFactory sessionFactory) { List<MessageReceiver> messageReceivers = new LinkedList<>(); ActiveMQContextListener.getActiveMQListeners(this.config).forEach(listenerClass -> { try { Class<?> clazz = this.getClass().getClassLoader().loadClass(listenerClass); messageReceivers.add(buildEventMessageReceiver(sessionFactory, (EventListener) injector.getInstance(clazz))); } catch (Exception e) { log.warn("Unable to register listener {}", listenerClass, e); } }); <START> int maxJobs = config.getInt(ConfigProperties.ASYNC_JOBS_THREADS); log.info("Adding job receivers with filter: {}", maxJobs, this.amqpFilter); <END> return messageReceivers; }</code><technical_language>2 lines longer needed, removed below. want add this logging place creates threads (JobMessageReceiver) instead</technical_language>

Target:
public Collection<MessageReceiver> get(ActiveMQSessionFactory sessionFactory) { List<MessageReceiver> messageReceivers = new LinkedList<>(); ActiveMQContextListener.getActiveMQListeners(this.config).forEach(listenerClass -> { try { Class<?> clazz = this.getClass().getClassLoader().loadClass(listenerClass); messageReceivers.add(buildEventMessageReceiver(sessionFactory, (EventListener) injector.getInstance(clazz))); } catch (Exception e) { log.warn("Unable to register listener {}", listenerClass, e); } }); return messageReceivers; }
Source:
<code>public VmSnapshotCreatePopupWidget(CommonApplicationConstants constants) { <START> memoryEditor = new EntityModelCheckBoxEditor(Align.RIGHT); <END> initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); localize(constants); ViewIdHandler.idHandler.generateAndSetIds(this); driver.initialize(this); }</code><technical_language>nicer extract init method (e.g. initEditors())</technical_language>

Target:
public VmSnapshotCreatePopupWidget(CommonApplicationConstants constants) { initEditors(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); localize(constants); ViewIdHandler.idHandler.generateAndSetIds(this); driver.initialize(this); }
Source:
<code>public Object[][] checkDuplicateMarkingDataProvider() { return new Object[][]{ <START> {Paths.get(TEST_FILES_DIR, "pass_queryname.sam"), 0}, <END> {Paths.get(TEST_FILES_DIR, "pass_coordinate.sam"), 0}, {Paths.get(TEST_FILES_DIR, "fail_mate_queryname.sam"), 1}, {Paths.get(TEST_FILES_DIR, "fail_mate_coordinate.sam"), 1}, {Paths.get(TEST_FILES_DIR, "fail_supplementary_queryname_1.sam"), 1}, {Paths.get(TEST_FILES_DIR, "fail_supplementary_coordinate_1.sam"), 1}, {Paths.get(TEST_FILES_DIR, "fail_supplementary_queryname_2.sam"), 1}, {Paths.get(TEST_FILES_DIR, "fail_supplementary_coordinate_2.sam"), 1}, {Paths.get(TEST_FILES_DIR, "fail_secondary_queryname.sam"), 1}, {Paths.get(TEST_FILES_DIR, "fail_secondary_coordinate.sam"), 1}, }; }</code><technical_language>a minor avoid duplication changing this suggestion {"pass_queryname.sam", 0}, Paths.get(TEST_FILES_DIR, input) below</technical_language>

Target:
public Object[][] checkDuplicateMarkingDataProvider() { return new Object[][]{ {"pass_queryname.sam", 0}, {"pass_coordinate.sam", 0}, {"fail_mate_queryname.sam", 1}, {"fail_mate_coordinate.sam", 1}, {"fail_supplementary_queryname_1.sam", 1}, {"fail_supplementary_coordinate_1.sam", 1}, {"fail_supplementary_queryname_2.sam", 1}, {"fail_supplementary_coordinate_2.sam", 1}, {"fail_secondary_queryname.sam", 1}, {"fail_secondary_coordinate.sam", 1}, }; }
Source:
<code>public UserAccount getUser(UserFilter userFilter) { String username = ""; String name = ""; String announcement; String closedDateAsString; String data = USER + String.format(QUERY_USER_ATTRIBUTES, userFilter.getUid()); Log.d(TAG, String.format("getUserAttributesApiCall(%s) -> %s", USER, data)); try { String response = executeCall(DHIS_PULL_API+data); JsonNode jsonNode = parseResponse(response); JsonNode jsonNodeArray = jsonNode.get(ATTRIBUTEVALUES); String newMessage = ""; String closeDate = ""; for (int i = 0; i < jsonNodeArray.size(); i++) { newMessage = getUserAnnouncement(jsonNodeArray, newMessage, i, UserDB.ATTRIBUTE_USER_ANNOUNCEMENT); closeDate = getUserCloseDate(jsonNodeArray, closeDate, i); } announcement =newMessage; closedDateAsString=closeDate; username = getUsername(jsonNode); name = getName(jsonNode); } catch (Exception ex) { <START> Log.e(TAG, "Cannot read user last updated from server with"); <END> ex.printStackTrace(); return null; } UserAccount userAccount = new UserAccount(name, username, userFilter.getUid(), announcement, parseClosedDate(closedDateAsString)); return userAccount; }</code><technical_language>return null UserAccount avoid work nulls, throw exception if in network throw exception repository return local data</technical_language>

Target:
public UserAccount getUser(UserFilter userFilter) throws GetUserAccountException { String username = ""; String name = ""; String announcement; String closedDateAsString; String data = USER + String.format(QUERY_USER_ATTRIBUTES, userFilter.getUid()); Log.d(TAG, String.format("getUserAttributesApiCall(%s) -> %s", USER, data)); try { String response = executeCall(DHIS_PULL_API+data); JsonNode jsonNode = parseResponse(response); JsonNode jsonNodeArray = jsonNode.get(ATTRIBUTEVALUES); String newMessage = ""; String closeDate = ""; for (int i = 0; i < jsonNodeArray.size(); i++) { newMessage = getUserAnnouncement(jsonNodeArray, newMessage, i, UserDB.ATTRIBUTE_USER_ANNOUNCEMENT); closeDate = getUserCloseDate(jsonNodeArray, closeDate, i); } announcement =newMessage; closedDateAsString=closeDate; username = getUsername(jsonNode); name = getName(jsonNode); } catch (Exception ex) { Log.e(TAG, "Cannot read user last updated from server with"); ex.printStackTrace(); throw new GetUserAccountException(); } UserAccount userAccount = new UserAccount(name, username, userFilter.getUid(), announcement, parseClosedDate(closedDateAsString)); return userAccount; }