auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void beginWindow(long windowId) { if (simulateFailureWindows > 0 && ((simulateFailureAfterCommit && committed) || !simulateFailureAfterCommit) && !failureSimulated) { LOG.info("FailableFibonacciOperator beginWindow {}", windowId, windowCount, simulateFailureWindows); if (windowCount++ == simulateFailureWindows) { failureSimulated = true; LOG.info("FailableFibonacciOperator is simulating failure"); throw new RuntimeException("simulating failure"); } } }

Target:
public void beginWindow(long windowId) { if (simulateFailureWindows > 0 && ((simulateFailureAfterCommit && committed) || !simulateFailureAfterCommit) && !failureSimulated) { LOG.debug("FailableFibonacciOperator beginWindow {}", windowId, windowCount, simulateFailureWindows); if (windowCount++ == simulateFailureWindows) { failureSimulated = true; LOG.debug("FailableFibonacciOperator is simulating failure"); throw new RuntimeException("simulating failure"); } } }
Source:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (obj instanceof ReferenceBindingSetWrapper) { ReferenceBindingSetWrapper other = (ReferenceBindingSetWrapper) obj; return this.referenceBinding.equals(other.referenceBinding); } return false; }

Target:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (obj instanceof ReferenceBindingSetWrapper) { ReferenceBindingSetWrapper other = (ReferenceBindingSetWrapper) obj; return identityEqual(this.referenceBinding, other.referenceBinding); } return false; }
Source:
private static List<Type> removeRedundantBounds(final Type[] bounds) { if (bounds.length == 1) { return Collections.unmodifiableList(new ArrayList<Type>() { { add(bounds[0]); } }); } List<Type> result = new ArrayList<Type>(); for (int i = 0; i < bounds.length; i++) { boolean isRedundant = false; for (int j = 0; j < bounds.length && i != j; j++) { if (Reflections.getRawType(bounds[i]).isAssignableFrom(Reflections.getRawType(bounds[j]))) { isRedundant = true; break; } } if (!isRedundant) { result.add(bounds[i]); } } return result; }

Target:
private static List<Type> removeRedundantBounds(final Type[] bounds) { if (bounds.length == 1) { return Collections.singletonList(bounds[0]); } List<Type> result = new LinkedList<Type>(); for (int i = 0; i < bounds.length; i++) { boolean isRedundant = false; for (int j = 0; j < bounds.length && i != j; j++) { if (Reflections.getRawType(bounds[i]).isAssignableFrom(Reflections.getRawType(bounds[j]))) { isRedundant = true; break; } } if (!isRedundant) { result.add(bounds[i]); } } return result; }
Source:
public void execute() throws BuildException { String generatedPassword=""; if (addproperty == null || addproperty.equals("")) { throw new BuildException("\tThe output property is required for this task."); } if (password == null || password.equals("")) { throw new BuildException("\tThe password property is required for this task."); } try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes()); byte[] bytes = md.digest(); generatedPassword = new String(Base64.encodeBase64(bytes)); } catch (NoSuchAlgorithmException e) { throw new BuildException("\tThere is a problem encrypting the password with MD5 algorithm"); } if (addproperty != null && !addproperty.equals("")) { getProject().setProperty(addproperty, generatedPassword); } }

Target:
public void execute() throws BuildException { String generatedPassword=""; if (addproperty == null || addproperty.equals("")) { throw new BuildException("\tThe output property is required for this task."); } if (password == null || password.equals("")) { throw new BuildException("\tThe password property is required for this task."); } generatedPassword = DigestUtils.sha256Hex(password); if (addproperty != null && !addproperty.equals("")) { getProject().setProperty(addproperty, generatedPassword); } }
Source:
public void addPersistentProperty(ElasticsearchPersistentProperty property) { super.addPersistentProperty(property); if (property.isParentProperty()) { ElasticsearchPersistentProperty parentProperty = this.parentIdProperty; if (parentProperty != null) { throw new MappingException( String.format("Attempt to add parent property %s but already have property %s registered " + "as version. Check your mapping configuration!", property.getField(), parentProperty.getField())); } Assert.isTrue(property.getType() == String.class, String.format("Parent property %s must be of type String", property.getField())); Parent parentAnnotation = property.getType().getAnnotation(Parent.class); this.parentIdProperty = property; this.parentType = parentAnnotation.type(); } if (property.isVersionProperty()) { Assert.isTrue(property.getType() == Long.class, String.format("Version property %s must be of type Long", property.getField())); } }

Target:
public void addPersistentProperty(ElasticsearchPersistentProperty property) { super.addPersistentProperty(property); if (property.isParentProperty()) { ElasticsearchPersistentProperty parentProperty = this.parentIdProperty; if (parentProperty != null) { throw new MappingException( String.format("Attempt to add parent property %s but already have property %s registered " + "as parent property. Check your mapping configuration!", property.getField(), parentProperty.getField())); } Parent parentAnnotation = property.findAnnotation(Parent.class); this.parentIdProperty = property; this.parentType = parentAnnotation.type(); } if (property.isScoreProperty()) { ElasticsearchPersistentProperty scoreProperty = this.scoreProperty; if (scoreProperty != null) { throw new MappingException( String.format("Attempt to add score property %s but already have property %s registered " + "as score property. Check your mapping configuration!", property.getField(), scoreProperty.getField())); } this.scoreProperty = property; } }
Source:
public void provision(String projectName) throws InfrastructureException { OpenShiftClient osClient = clientFactory.createOC(); String stopWorkspacesRoleName = "workspace-stop"; if (osClient.roles().inNamespace(projectName).withName(stopWorkspacesRoleName).get() == null) { createStopWorkspacesRole(osClient, stopWorkspacesRoleName, projectName); } osClient .roleBindings() .inNamespace(projectName) .createOrReplace(createStopWorkspacesRoleBinding(projectName)); }

Target:
public void provision(String projectName) throws InfrastructureException { if (stopWorkspaceRoleEnabled && installationLocation != null) { OpenShiftClient osClient = clientFactory.createOC(); String stopWorkspacesRoleName = "workspace-stop"; if (osClient.roles().inNamespace(projectName).withName(stopWorkspacesRoleName).get() == null) { osClient .roles() .inNamespace(projectName) .createOrReplace(createStopWorkspacesRole(stopWorkspacesRoleName)); } osClient .roleBindings() .inNamespace(projectName) .createOrReplace(createStopWorkspacesRoleBinding(projectName)); } else { LOG.warn( "Stop workspace Role and RoleBinding will not be provisioned to the '{}' namespace. 'che.workspace.stop.role.enabled' property is set to '{}'", installationLocation, stopWorkspaceRoleEnabled); } }
Source:
public void onThemesChanged(ThemeStore.OnThemesChanged event) { if (mThemeBrowserFragment != null) { mThemeBrowserFragment.setRefreshing(false); mThemeBrowserFragment.refreshView(); } if (event.origin == ThemeAction.FETCH_INSTALLED_THEMES) { mIsFetchingInstalledPlugins = false; } if (event.isError()) { AppLog.e(T.THEMES, "Error fetching themes: " + event.error.message); ToastUtils.showToast(this, R.string.theme_fetch_failed, ToastUtils.Duration.SHORT); } else { if (event.origin == ThemeAction.FETCH_WP_COM_THEMES) { AppLog.d(T.THEMES, "WordPress.com Theme fetch successful!"); AppPrefs.setLastWpComThemeSync(System.currentTimeMillis()); } else if (event.origin == ThemeAction.FETCH_INSTALLED_THEMES) { AppLog.d(T.THEMES, "Installed themes fetch successful!"); } } }

Target:
public void onThemesChanged(ThemeStore.OnThemesChanged event) { if (mThemeBrowserFragment != null) { mThemeBrowserFragment.setRefreshing(false); mThemeBrowserFragment.refreshView(); } if (event.origin == ThemeAction.FETCH_INSTALLED_THEMES) { mIsFetchingInstalledThemes = false; } if (event.isError()) { AppLog.e(T.THEMES, "Error fetching themes: " + event.error.message); ToastUtils.showToast(this, R.string.theme_fetch_failed, ToastUtils.Duration.SHORT); } else { if (event.origin == ThemeAction.FETCH_WP_COM_THEMES) { AppLog.d(T.THEMES, "WordPress.com Theme fetch successful!"); AppPrefs.setLastWpComThemeSync(System.currentTimeMillis()); } else if (event.origin == ThemeAction.FETCH_INSTALLED_THEMES) { AppLog.d(T.THEMES, "Installed themes fetch successful!"); } } }
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) { Optional<String> publishIdOptional = Optional.ofNullable(request.getParameter("publish_id")); if (publishIdOptional.isEmpty()) { return; } String publishId = publishIdOptional.get(); db.single(Publish.class).where("publish_id=?", publishId).execute().ifPresent(publish -> { Optional<String> encode = Optional.ofNullable(request.getParameter("encode")); String fileName = publishId + ".csv"; boolean showHeader = Boolean.parseBoolean(request.getParameter("header")); csvDownload(response, fileName, publish.getDatasource(), publish.getQueryId(), encode.orElse(DEFAULT_ENCODE), showHeader); }); }

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) { Optional<String> publishIdOptional = Optional.ofNullable(request.getParameter("publish_id")); if (publishIdOptional.isEmpty()) { return; } String publishId = publishIdOptional.get(); db.single(Publish.class).where("publish_id=?", publishId).execute().ifPresent(publish -> { Optional<String> encode = Optional.ofNullable(request.getParameter("encode")); String fileName = publishId + ".csv"; boolean showHeader = getOrDefaultParameter(request, "header", true); csvDownload(response, fileName, publish.getDatasource(), publish.getQueryId(), encode.orElse(DEFAULT_ENCODE), showHeader); }); }
Source:
public static boolean parseReturningKeyword(final char[] query, int offset) { if (query.length < (offset + 9)) { return false; } return (query[offset - 1] == ' ') && (query[offset] | 32) == 'r' && (query[offset + 1] | 32) == 'e' && (query[offset + 2] | 32) == 't' && (query[offset + 3] | 32) == 'u' && (query[offset + 4] | 32) == 'r' && (query[offset + 5] | 32) == 'n' && (query[offset + 6] | 32) == 'i' && (query[offset + 7] | 32) == 'n' && (query[offset + 8] | 32) == 'g' && (query[offset + 9] == ' '); }

Target:
public static boolean parseReturningKeyword(final char[] query, int offset) { if (query.length < (offset + 9)) { return false; } return (query[offset] | 32) == 'r' && (query[offset + 1] | 32) == 'e' && (query[offset + 2] | 32) == 't' && (query[offset + 3] | 32) == 'u' && (query[offset + 4] | 32) == 'r' && (query[offset + 5] | 32) == 'n' && (query[offset + 6] | 32) == 'i' && (query[offset + 7] | 32) == 'n' && (query[offset + 8] | 32) == 'g'; }
Source:
void denyUserInTree(String userName, String resourceId, String action, boolean updateCache) throws UserStoreException { write.lock(); try { SearchResult sr = getNode(root, PermissionTreeUtil.toComponenets(resourceId)); if (sr.getUnprocessedPaths() != null) { List<String> paths = sr.getUnprocessedPaths(); TreeNode tn = sr.getLastNode().create(paths); tn.denyUser(userName, PermissionTreeUtil.actionToPermission(action)); } else { sr.getLastNode().denyUser(userName, PermissionTreeUtil.actionToPermission(action)); } if (updateCache) { invalidateCache(root); } } catch (Exception e) { throw new UserStoreException(e.getMessage(),e); } finally { write.unlock(); } }

Target:
void denyUserInTree(String userName, String resourceId, String action, boolean updateCache) throws UserStoreException { write.lock(); try { SearchResult sr = getNode(root, PermissionTreeUtil.toComponenets(resourceId)); if (sr.getUnprocessedPaths() != null) { List<String> paths = sr.getUnprocessedPaths(); TreeNode tn = sr.getLastNode().create(paths); tn.denyUser(userName, PermissionTreeUtil.actionToPermission(action)); } else { sr.getLastNode().denyUser(userName, PermissionTreeUtil.actionToPermission(action)); } if (updateCache) { invalidateCache(root); } } catch (IllegalArgumentException e) { throw new UserStoreException("Error while denying user: " + userName + "in permission tree for resource id: " + resourceId + "for action: " + action, e); } finally { write.unlock(); } }
Source:
public DesiredCapabilities getCapabilities(DesiredCapabilities capabilities) { DesiredCapabilities tempCapabilities = capabilities; MobileTestSession mobileSession = Grid.getMobileTestSession(); tempCapabilities = SelendroidCapabilities.android(); if ((new File(mobileSession.getAppLocation()).exists()) && ((new File(mobileSession.getAppLocation() + File.separator + mobileSession.getAppName())).exists())) { tempCapabilities.setBrowserName(SELENDROID); } else { tempCapabilities.setBrowserName(ANDROID); } tempCapabilities.setCapability(MOBILE_NODE_TYPE, mobileSession.getMobileNodeType().getAsString()); tempCapabilities.setCapability(SelendroidCapabilities.AUT, mobileSession.getAppName()); tempCapabilities.setCapability(SelendroidCapabilities.LOCALE, mobileSession.getAppLocale()); if (StringUtils.isNotBlank(mobileSession.getDeviceType())) { tempCapabilities.setCapability(SelendroidCapabilities.MODEL, mobileSession.getDeviceType()); } if (StringUtils.isNotBlank(mobileSession.getPlatformVersion())) { tempCapabilities.setCapability(SelendroidCapabilities.PLATFORM_VERSION, mobileSession.getPlatformVersion()); } if (StringUtils.isNotBlank(mobileSession.getdeviceSerial())) { tempCapabilities.setCapability(SelendroidCapabilities.SERIAL, mobileSession.getdeviceSerial()); } return tempCapabilities; }

Target:
public DesiredCapabilities getCapabilities(DesiredCapabilities capabilities) { MobileTestSession mobileSession = Grid.getMobileTestSession(); DesiredCapabilities tempCapabilities = SelendroidCapabilities.android(); if ((new File(mobileSession.getAppLocation()).exists()) && ((new File(mobileSession.getAppLocation() + File.separator + mobileSession.getAppName())).exists())) { tempCapabilities.setBrowserName(SELENDROID); } else { tempCapabilities.setBrowserName(ANDROID); } tempCapabilities.setCapability(MOBILE_NODE_TYPE, mobileSession.getMobileNodeType().getAsString()); tempCapabilities.setCapability(SelendroidCapabilities.AUT, mobileSession.getAppName()); tempCapabilities.setCapability(SelendroidCapabilities.LOCALE, mobileSession.getAppLocale()); if (StringUtils.isNotBlank(mobileSession.getDeviceType())) { tempCapabilities.setCapability(SelendroidCapabilities.MODEL, mobileSession.getDeviceType()); } if (StringUtils.isNotBlank(mobileSession.getPlatformVersion())) { tempCapabilities.setCapability(SelendroidCapabilities.PLATFORM_VERSION, mobileSession.getPlatformVersion()); } if (StringUtils.isNotBlank(mobileSession.getdeviceSerial())) { tempCapabilities.setCapability(SelendroidCapabilities.SERIAL, mobileSession.getdeviceSerial()); } return tempCapabilities; }
Source:
public static void main(String[] args) throws GeneralSecurityException, IOException, URISyntaxException { PipelineOptionsFactory.register(Options.class); pipelineOptions = PipelineOptionsFactory.fromArgs(args) .withValidation().as(Options.class); Options.Methods.validateOptions(pipelineOptions); pipelineOptions.setTempLocation(pipelineOptions.getTempPath()); auth = GenomicsOptions.Methods.getGenomicsAuth(pipelineOptions); p = Pipeline.create(pipelineOptions); String BAMFilePath = pipelineOptions.getBAMFilePath(); if (!Strings.isNullOrEmpty(BAMFilePath)) { if (GCSURLExists(BAMFilePath)) { System.out.println(BAMFilePath + " is present, good."); } else { System.out.println("Error: " + BAMFilePath + " not found."); return; } if (pipelineOptions.isShardBAMReading()) { String BAMIndexPath = BAMFilePath + ".bai"; if (GCSURLExists(BAMIndexPath)) { System.out.println(BAMIndexPath + " is present, good."); } else { System.out.println("Error: " + BAMIndexPath + " not found."); return; } } } PCollection<Read> reads = getReads(); reads.apply(ParDo.of(new ReadToRowConverter())) .apply(BigQueryIO.writeTableRows() .to(pipelineOptions.getBigQueryTablePath()) .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED) .withSchema(ReadToRowConverter.getSchema())); PipelineResult result = p.run(); if(pipelineOptions.getWait()) { result.waitUntilFinish(); } }

Target:
public static void main(String[] args) throws GeneralSecurityException, IOException, URISyntaxException { PipelineOptionsFactory.register(Options.class); pipelineOptions = PipelineOptionsFactory.fromArgs(args) .withValidation().as(Options.class); Options.Methods.validateOptions(pipelineOptions); pipelineOptions.setTempLocation(pipelineOptions.getTempPath()); auth = GenomicsOptions.Methods.getGenomicsAuth(pipelineOptions); p = Pipeline.create(pipelineOptions); String BamFilePath = pipelineOptions.getBamFilePath(); if (!Strings.isNullOrEmpty(BamFilePath)) { try { checkGcsUrlExists(BamFilePath); } catch (Exception x) { System.err.println("Error: BAM file " + BamFilePath + " not found. A BAM file is " + "required."); System.err.println("Exception: " + x.getMessage()); return; } if (pipelineOptions.getMaxShardSizeMB() > 0) { String BamIndexPath = BamFilePath + ".bai"; try { checkGcsUrlExists(BamIndexPath); } catch (Exception x) { System.err.println("Error: Index file " + BamIndexPath + " not found. An index is " + "required for sharded export."); System.err.println("Exception: " + x.getMessage()); return; } } } PCollection<Read> reads = getReadsFromBamFile(); reads.apply(ParDo.of(new ReadToRowConverter())) .apply(BigQueryIO.writeTableRows() .to(pipelineOptions.getBigQueryTablePath()) .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED) .withSchema(ReadToRowConverter.getSchema())); PipelineResult result = p.run(); if (pipelineOptions.getWait()) { result.waitUntilFinish(); } }
Source:
public static void checkDirectoryStructure(File dir) throws IOException { if (!dir.exists()) { File parent = dir.getParentFile(); File preV3versionFile = new File(dir.getParent(), BookKeeperConstants.VERSION_FILENAME); final AtomicBoolean oldDataExists = new AtomicBoolean(false); parent.list((dir1, name) -> { if (name.endsWith(".txn") || name.endsWith(".idx") || name.endsWith(".log")) { oldDataExists.set(true); } return true; }); if (preV3versionFile.exists() || oldDataExists.get()) { String err = "Directory layout version is less than 3, upgrade needed"; LOG.error(err); throw new IOException(err); } if (!dir.mkdirs()) { String err = "Unable to create directory " + dir; LOG.error(err); throw new IOException(err); } } }

Target:
public static void checkDirectoryStructure(File dir) throws IOException { if (!dir.exists()) { File parent = dir.getParentFile(); File preV3versionFile = new File(dir.getParent(), BookKeeperConstants.VERSION_FILENAME); final AtomicBoolean oldDataExists = new AtomicBoolean(false); parent.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.endsWith(".txn") || name.endsWith(".idx") || name.endsWith(".log")) { oldDataExists.set(true); } return true; } }); if (preV3versionFile.exists() || oldDataExists.get()) { String err = "Directory layout version is less than 3, upgrade needed"; LOG.error(err); throw new IOException(err); } if (!dir.mkdirs()) { String err = "Unable to create directory " + dir; LOG.error(err); throw new IOException(err); } } }
Source:
private Point getBlockTransclusionLocation(int index) { String boundingScript = "return jQuery.data( $('" + blockTransclusionString + "')["+ index +"] ).view.getBoundingRect();"; JavascriptExecutor js = (JavascriptExecutor) driver; Object templateBounding = js.executeScript(boundingScript); JSONObject json; int tempLeft = 0, tempTop = 0; try { json = new JSONObject(templateBounding.toString()); tempLeft = (int) json.get("left"); tempTop = (int) json.get("top"); } catch (JSONException e) { e.printStackTrace(); } return new Point(tempLeft, tempTop); }

Target:
private Point getBlockTransclusionLocation(int index) { JavascriptExecutor js = (JavascriptExecutor) driver; Object templateBounding = js.executeScript(VEContent.boundingScript, blockTransclusionString, index); JSONObject json; int tempLeft = 0, tempTop = 0; try { json = new JSONObject(templateBounding.toString()); tempLeft = (int) json.get("left"); tempTop = (int) json.get("top"); } catch (JSONException e) { e.printStackTrace(); } return new Point(tempLeft, tempTop); }
Source:
public Object getMetricObjectValue(int rowOffset, int aggOffset) { final Aggregator[] aggs = aggList.get(rowOffset); if (null == aggs) { return null; } return aggs[aggOffset].get(); }

Target:
public Object getMetricObjectValue(int rowOffset, int aggOffset) { return concurrentGet(rowOffset)[aggOffset].get(); }
Source:
public synchronized void stop(StopContext context) { for (JarFile jarFile : jarFiles) { log.debugf("Closing %s jar file which was added as resource root for %s module identifier", jarFile.toString(), moduleIdentifier.getName()); VFSUtils.safeClose(jarFile); log.debugf("Closed %s jar file which was added as resource root for %s module identifier", jarFile.toString(), moduleIdentifier.getName()); } jarFiles.clear(); jarFiles = null; moduleDefinition = null; }

Target:
public synchronized void stop(StopContext context) { for (JarFile jarFile : jarFiles) { log.debugf("Closing %s jar file which was added as resource root for %s module identifier", jarFile.getName(), moduleIdentifier.getName()); VFSUtils.safeClose(jarFile); } jarFiles.clear(); jarFiles = null; moduleDefinition = null; }
Source:
public boolean shouldSkipField(FieldAttributes f) { boolean skip = super.shouldSkipField(f); if (!skip) { LogLevel logLevel = f.getAnnotation(LogLevel.class); skip = (logLevel != null && logLevel.value() == Log4jLevel.Off); } return skip; }

Target:
public boolean shouldSkipField(FieldAttributes f) { Param param = f.getAnnotation(Param.class); boolean skip = (param != null && param.isSensitive()); if (!skip) { skip = super.shouldSkipField(f); } return skip; }
Source:
private String removeSpacesAroundRDN(String dn) { if (dn == null || StringUtils.isEmpty(dn)) { return dn; } List<String> strings = new ArrayList<>(); String[] splitted = dn.split(","); for (String aSplitted : splitted) { String element = aSplitted.trim(); strings.add(element); } StringBuilder sb = new StringBuilder(); Iterator<String> idIterator = strings.iterator(); while (idIterator.hasNext()){ sb.append(idIterator.next().trim()); if (idIterator.hasNext()) sb.append(','); } return sb.toString(); }

Target:
private String removeSpacesAroundRDN(String dn) { if (StringUtils.isEmpty(dn)) { return dn; } List<String> strings = new ArrayList<>(); String[] splitted = dn.split(","); for (String aSplitted : splitted) { String element = aSplitted.trim(); strings.add(element); } StringBuilder sb = new StringBuilder(); Iterator<String> idIterator = strings.iterator(); while (idIterator.hasNext()){ sb.append(idIterator.next().trim()); if (idIterator.hasNext()) sb.append(','); } return sb.toString(); }
Source:
public PluginLoader(SitePaths sitePaths, PluginGuiceEnvironment pe, ServerInformationImpl sii, PluginUser.Factory puf, Provider<PluginCleanerTask> pct, @GerritServerConfig Config cfg, @CanonicalWebUrl Provider<String> provider) { pluginsDir = sitePaths.plugins_dir; dataDir = sitePaths.data_dir; tmpDir = sitePaths.tmp_dir; env = pe; srvInfoImpl = sii; pluginUserFactory = puf; running = Maps.newConcurrentMap(); disabled = Maps.newConcurrentMap(); broken = Maps.newHashMap(); toCleanup = Queues.newArrayDeque(); cleanupHandles = Maps.newConcurrentMap(); cleaner = pct; urlProvider = provider; remoteInstall = cfg.getBoolean("plugins", null, "allowRemoteAdmin", false); long checkFrequency = ConfigUtil.getTimeUnit(cfg, "plugins", null, "checkFrequency", TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS); if (checkFrequency > 0) { scanner = new PluginScannerThread(this, checkFrequency); } else { scanner = null; } }

Target:
public PluginLoader(SitePaths sitePaths, PluginGuiceEnvironment pe, ServerInformationImpl sii, PluginUser.Factory puf, Provider<PluginCleanerTask> pct, @GerritServerConfig Config cfg, @CanonicalWebUrl Provider<String> provider) { pluginsDir = sitePaths.plugins_dir; dataDir = sitePaths.data_dir; tmpDir = sitePaths.tmp_dir; env = pe; srvInfoImpl = sii; pluginUserFactory = puf; running = Maps.newConcurrentMap(); disabled = Maps.newConcurrentMap(); broken = Maps.newHashMap(); toCleanup = Queues.newArrayDeque(); cleanupHandles = Maps.newConcurrentMap(); cleaner = pct; urlProvider = provider; remoteAdmin = cfg.getBoolean("plugins", null, "allowRemoteAdmin", false); long checkFrequency = ConfigUtil.getTimeUnit(cfg, "plugins", null, "checkFrequency", TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS); if (checkFrequency > 0) { scanner = new PluginScannerThread(this, checkFrequency); } else { scanner = null; } }
Source:
private static Retry createRetry(AmqpRetryOptions options) { if (options.getDelay() == null || options.getDelay().equals(Duration.ZERO)) { return Retry.max(0L); } final Duration delay = options.getDelay().plus(SERVER_BUSY_WAIT_TIME); final RetryBackoffSpec retrySpec; switch (options.getMode()) { case FIXED: retrySpec = Retry.fixedDelay(options.getMaxRetries(), delay); break; case EXPONENTIAL: retrySpec = Retry.backoff(options.getMaxRetries(), delay); break; default: LOGGER.warning("Unknown: '{}'. Using exponential delay. Delay: {}. Max Delay: {}. Max Retries: {}.", options.getMode(), options.getDelay(), options.getMaxDelay(), options.getMaxRetries()); retrySpec = Retry.backoff(options.getMaxRetries(), delay); break; } return retrySpec.jitter(JITTER_FACTOR) .maxBackoff(options.getMaxDelay()) .filter(error -> error instanceof TimeoutException || error instanceof AmqpException && ((AmqpException) error).isTransient()); }

Target:
private static Retry createRetry(AmqpRetryOptions options) { if (options.getDelay() == null || options.getDelay().equals(Duration.ZERO)) { return Retry.max(0L); } final Duration delay = options.getDelay().plus(SERVER_BUSY_WAIT_TIME); final RetryBackoffSpec retrySpec; switch (options.getMode()) { case FIXED: retrySpec = Retry.fixedDelay(options.getMaxRetries(), delay); break; case EXPONENTIAL: retrySpec = Retry.backoff(options.getMaxRetries(), delay); break; default: LOGGER.warning("Unknown: '{}'. Using exponential delay. Delay: {}. Max Delay: {}. Max Retries: {}.", options.getMode(), options.getDelay(), options.getMaxDelay(), options.getMaxRetries()); retrySpec = Retry.backoff(options.getMaxRetries(), delay); break; } return retrySpec.jitter(JITTER_FACTOR) .maxBackoff(options.getMaxDelay()) .filter(error -> error instanceof TimeoutException || (error instanceof AmqpException && ((AmqpException) error).isTransient())); }
Source:
public String convert(Sort sort) { if (sort == null || sort.getSort() == null) { return ""; } List<SortField> fields = Arrays.asList(sort.getSort()); String sortString = fields.stream() .filter(sortField -> sortField.getField() != null) .map(sortField -> { String key = this.converterImpl.convertKey(sortField.getField()); String value = ASC; if (sortField.getReverse()) { value = DESC; } return key + " " + value; }).collect(Collectors.joining(",")); return sortString; }

Target:
public String convert(Sort sort) { if (sort == null || sort.getSort() == null) { return ""; } List<SortField> fields = Arrays.asList(sort.getSort()); String sortString = fields.stream() .filter(sortField -> sortField.getField() != null) .map(sortField -> { String key = this.converterImpl.convertKey(sortField.getField()); String sortDirection = ASC; if (sortField.getReverse()) { sortDirection = DESC; } return key + " " + sortDirection; }).collect(Collectors.joining(",")); return sortString; }
Source:
private ShadowDOM.Update createShadowDOMUpdate() { mDOMProvider.verifyThreadAccess(); if (mDOMProvider.getRootElement() != mShadowDOM.getRootElement()) { throw new IllegalStateException(); } ShadowDOM.UpdateBuilder updateBuilder = mShadowDOM.beginUpdate(); ListAccumulator<Object> childrenAccumulator = acquireChildrenAccumulator(); Queue<Object> queue = new ArrayDeque<>(); queue.add(mDOMProvider.getRootElement()); while (!queue.isEmpty()) { final Object element = queue.remove(); NodeDescriptor descriptor = mDOMProvider.getNodeDescriptor(element); mObjectIdMapper.putObject(element); descriptor.getChildren(element, childrenAccumulator); updateBuilder.setElementChildren(element, childrenAccumulator); for (int i = 0, N = childrenAccumulator.size(); i < N; ++i) { queue.add(childrenAccumulator.get(i)); } childrenAccumulator.clear(); } releaseChildrenAccumulator(childrenAccumulator); return updateBuilder.build(); }

Target:
private ShadowDOM.Update createShadowDOMUpdate() { mDOMProvider.verifyThreadAccess(); if (mDOMProvider.getRootElement() != mShadowDOM.getRootElement()) { throw new IllegalStateException(); } ArrayListAccumulator<Object> childrenAccumulator = acquireChildrenAccumulator(); ShadowDOM.UpdateBuilder updateBuilder = mShadowDOM.beginUpdate(); Queue<Object> queue = new ArrayDeque<>(); queue.add(mDOMProvider.getRootElement()); while (!queue.isEmpty()) { final Object element = queue.remove(); NodeDescriptor descriptor = mDOMProvider.getNodeDescriptor(element); mObjectIdMapper.putObject(element); descriptor.getChildren(element, childrenAccumulator); updateBuilder.setElementChildren(element, childrenAccumulator); for (int i = 0, N = childrenAccumulator.size(); i < N; ++i) { queue.add(childrenAccumulator.get(i)); } childrenAccumulator.clear(); } releaseChildrenAccumulator(childrenAccumulator); return updateBuilder.build(); }
Source:
public abstract void append(Event event) throws EventDeliveryException; @Override public abstract void appendBatch(List<Event> events) throws EventDeliveryException; @Override public abstract boolean isActive(); @Override public abstract void close() throws FlumeException; protected abstract void configure(Properties properties) throws FlumeException; public static int parseBatchSize(Properties properties) { String strBatchSize = properties.getProperty( RpcClientConfigurationConstants.CONFIG_BATCH_SIZE); logger.debug("Batch size string = " + strBatchSize); int _batchSize = RpcClientConfigurationConstants.DEFAULT_BATCH_SIZE; if (strBatchSize != null && !strBatchSize.isEmpty()) { try { int parsedBatch = Integer.parseInt(strBatchSize); if (parsedBatch < 1) { logger.warn("Invalid value for batchSize: {}; Using default value.", parsedBatch); } else { _batchSize = parsedBatch; } } catch (NumberFormatException e) { logger.warn("Batchsize is not valid for RpcClient: " + strBatchSize + ". Default value assigned.", e); } } return _batchSize; }

Target:
public abstract void append(Event event) throws EventDeliveryException; @Override public abstract void appendBatch(List<Event> events) throws EventDeliveryException; @Override public abstract boolean isActive(); @Override public abstract void close() throws FlumeException; protected abstract void configure(Properties properties) throws FlumeException; public static int parseBatchSize(Properties properties) { String strBatchSize = properties.getProperty( RpcClientConfigurationConstants.CONFIG_BATCH_SIZE); logger.debug("Batch size string = " + strBatchSize); int batchSize = RpcClientConfigurationConstants.DEFAULT_BATCH_SIZE; if (strBatchSize != null && !strBatchSize.isEmpty()) { try { int parsedBatch = Integer.parseInt(strBatchSize); if (parsedBatch < 1) { logger.warn("Invalid value for batchSize: {}; Using default value.", parsedBatch); } else { batchSize = parsedBatch; } } catch (NumberFormatException e) { logger.warn("Batchsize is not valid for RpcClient: " + strBatchSize + ". Default value assigned.", e); } } return batchSize; }
Source:
public void visit(LambdaExpr n, Object arg) { printJavaComment(n.getComment(), arg); List<Parameter> parameters = n.getParameters(); boolean printPar = n.isParametersEnclosed(); if (printPar) { printer.print("("); } if (parameters != null) { for (Iterator<Parameter> i = parameters.iterator(); i.hasNext();) { Parameter p = i.next(); p.accept(this, arg); if (i.hasNext()) { printer.print(", "); } } } if (printPar) { printer.print(")"); } printer.print(" -> "); Statement body = n.getBody(); if (body instanceof ExpressionStmt) { ((ExpressionStmt) body).getExpression().accept(this, arg); } else { body.accept(this, arg); } }

Target:
public void visit(LambdaExpr n, Object arg) { printJavaComment(n.getComment(), arg); final List<Parameter> parameters = n.getParameters(); final boolean printPar = n.isParametersEnclosed(); if (printPar) { printer.print("("); } if (parameters != null) { for (Iterator<Parameter> i = parameters.iterator(); i.hasNext();) { Parameter p = i.next(); p.accept(this, arg); if (i.hasNext()) { printer.print(", "); } } } if (printPar) { printer.print(")"); } printer.print(" -> "); final Statement body = n.getBody(); if (body instanceof ExpressionStmt) { ((ExpressionStmt) body).getExpression().accept(this, arg); } else { body.accept(this, arg); } }
Source:
private Set<MpackInstance> copyAndEnrichMpackInstances(ClusterTopology topology) { Set<MpackInstance> mpacks = topology.getMpacks().stream().map(MpackInstance::copy).collect(toSet()); Map<StackId, Set<String>> mpackServices = topology.getComponents().collect(toMap( ResolvedComponent::stackId, comp -> ImmutableSet.of(comp.serviceInfo().getName()), (set1, set2) -> ImmutableSet.copyOf(Sets.union(set1, set2)) )); for (MpackInstance mpack: mpacks) { if (!mpackServices.containsKey(mpack.getStackId())) { LOG.warn("No services declared for mpack {}.", mpack.getStackId()); } else { Set<String> existingMpackServices = mpack.getServiceInstances().stream().map(ServiceInstance::getType).collect(toSet()); for(String service: mpackServices.get(mpack.getStackId())) { if (existingMpackServices.contains(service)) { LOG.debug("Mpack instance already contains service {}", mpack.getStackId(), service); } else { LOG.debug("Adding service to mpack instance {}", service, mpack.getStackId()); mpack.getServiceInstances().add(new ServiceInstance(service, service, null, mpack)); } } } } return mpacks; }

Target:
private Set<MpackInstance> copyAndEnrichMpackInstances(ClusterTopology topology) { Set<MpackInstance> mpacks = topology.getMpacks().stream().map(MpackInstance::copy).collect(toSet()); Map<StackId, Set<String>> mpackServices = topology.getComponents().collect( groupingBy(ResolvedComponent::stackId, mapping(comp -> comp.serviceInfo().getName(), toSet()))); for (MpackInstance mpack: mpacks) { if (!mpackServices.containsKey(mpack.getStackId())) { LOG.warn("No services declared for mpack {}.", mpack.getStackId()); } else { Set<String> existingMpackServices = mpack.getServiceInstances().stream().map(ServiceInstance::getType).collect(toSet()); for(String service: mpackServices.get(mpack.getStackId())) { if (existingMpackServices.contains(service)) { LOG.debug("Mpack instance already contains service {}", mpack.getStackId(), service); } else { LOG.debug("Adding service to mpack instance {}", service, mpack.getStackId()); mpack.getServiceInstances().add(new ServiceInstance(service, service, null, mpack)); } } } } return mpacks; }
Source:
public Thread newThread(Runnable r) { Thread t = new Thread(group, r, "junit-timeout-thread-" + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; }

Target:
public Thread newThread(Runnable r) { return new Thread(r, "junit-timeout-thread-" + threadNumber.getAndIncrement()); }
Source:
public Set<String> keySet() { Set<String> keys = new HashSet<>(); keys.addAll(this.jdbcTemplate.queryForList(this.getAllKeysQuery, new Object[]{this.region}, String.class)); return Collections.unmodifiableSet(keys); }

Target:
public Set<String> keySet() { Set<String> keys = new HashSet<>(); keys.addAll(this.jdbcTemplate.queryForList(this.getAllKeysQuery, String.class, this.region)); return Collections.unmodifiableSet(keys); }
Source:
public void testLatestVersion() { APIVersion expectedLatest = APIVersion.VALID_VERSIONS.values() .stream() .max(Comparator.comparingInt(v -> v.version)) .orElseThrow(); assertEquals(expectedLatest, APIVersion.latest()); }

Target:
public void testLatestVersion() { APIVersion expectedLatest = APIVersion.VALID_VERSIONS.values() .stream() .max(APIVersion.COMPARATOR) .orElseThrow(); assertEquals(expectedLatest, APIVersion.latest()); }
Source:
public HttpResponseException(final int statusCode, final String s) { super(s == null || s.isEmpty() ? Integer.toString(statusCode) : s); this.statusCode = statusCode; }

Target:
public HttpResponseException(final int statusCode, final String s) { super(TextUtils.isBlank(s) ? Integer.toString(statusCode) : s); this.statusCode = statusCode; }
Source:
public List<DiffEntry> call() throws GitAPIException, IOException { final DiffFormatter diffFmt = new DiffFormatter(null); diffFmt.setRepository(repo); try { if (cached) { if (oldTree == null) { ObjectId head = repo.resolve(HEAD + "^{tree}"); if (head == null) throw new NoHeadException(JGitText.get().cannotReadTree); CanonicalTreeParser p = new CanonicalTreeParser(); ObjectReader reader = repo.newObjectReader(); try { p.reset(reader, head); } finally { reader.release(); } oldTree = p; } newTree = new DirCacheIterator(repo.readDirCache()); } else if (oldTree == null) { oldTree = new DirCacheIterator(repo.readDirCache()); newTree = new FileTreeIterator(repo); } else if (newTree == null) newTree = new FileTreeIterator(repo); diffFmt.setPathFilter(pathFilter); if (showNameAndStatusOnly) { return diffFmt.scan(oldTree, newTree); } else { throw new UnsupportedOperationException(); } } finally { diffFmt.release(); } }

Target:
public List<DiffEntry> call() throws GitAPIException, IOException { final DiffFormatter diffFmt = new DiffFormatter(null); diffFmt.setRepository(repo); try { if (cached) { if (oldTree == null) { ObjectId head = repo.resolve(HEAD + "^{tree}"); if (head == null) throw new NoHeadException(JGitText.get().cannotReadTree); CanonicalTreeParser p = new CanonicalTreeParser(); ObjectReader reader = repo.newObjectReader(); try { p.reset(reader, head); } finally { reader.release(); } oldTree = p; } newTree = new DirCacheIterator(repo.readDirCache()); } else { if (oldTree == null) oldTree = new DirCacheIterator(repo.readDirCache()); if (newTree == null) newTree = new FileTreeIterator(repo); } diffFmt.setPathFilter(pathFilter); if (showNameAndStatusOnly) { return diffFmt.scan(oldTree, newTree); } else { throw new UnsupportedOperationException(); } } finally { diffFmt.release(); } }
Source:
public void setTypeMap(Map<String, Class<?>> map) throws SQLException { Map<String, Class<?>> newMap = new HashMap<>(map); Map<Class<?>, Set<String>> newDirectMap = new HashMap<>(); Map<Class<?>, Set<String>> newInheritedMap = new HashMap<>(); for (Map.Entry<String, Class<?>> entry : newMap.entrySet()) { String type = entry.getKey(); Class<?> directClass = entry.getValue(); addInference(newDirectMap, directClass, type); for (Class<?> clazz : getAllClasses(directClass)) { addInference(newInheritedMap, clazz, type); } } makeValuesUnmodifiable(newDirectMap); makeValuesUnmodifiable(newInheritedMap); synchronized (typemapLock) { typemap = Collections.unmodifiableMap(newMap); inferenceMapDirect = Collections.unmodifiableMap(newDirectMap); inferenceMapInherited = Collections.unmodifiableMap(newInheritedMap); } LOGGER.log(Level.FINE, " setTypeMap = {0}", map); }

Target:
public void setTypeMap(Map<String, Class<?>> map) throws SQLException { checkClosed(); if (map == null || map.isEmpty()) { udtMap = UdtMap.EMPTY; } else { udtMap = new UdtMap(new LinkedHashMap<String, Class<?>>(map)); } LOGGER.log(Level.FINE, " setTypeMap = {0}", map); }
Source:
private String getCurrentSuitePrefix(ITestResult iTestResult){ return "{" + getCurrentSuiteName(iTestResult.getTestContext()) +"}"; }

Target:
private String getCurrentSuitePrefix(ITestResult iTestResult){ return "{" + getCurrentSuiteTitle(iTestResult.getTestContext()) + "}"; }
Source:
public static void setDefaultNightMode(@NightMode int mode) { switch (mode) { case MODE_NIGHT_NO: case MODE_NIGHT_YES: case MODE_NIGHT_FOLLOW_SYSTEM: case MODE_NIGHT_AUTO_TIME: case MODE_NIGHT_AUTO_BATTERY: if (sDefaultNightMode != mode) { sDefaultNightMode = mode; synchronized (sActiveDelegatesLock) { applyDayNightToActiveDelegates(); } } break; default: Log.d(TAG, "setDefaultNightMode() called with an unknown mode"); break; } }

Target:
public static void setDefaultNightMode(@NightMode int mode) { switch (mode) { case MODE_NIGHT_NO: case MODE_NIGHT_YES: case MODE_NIGHT_FOLLOW_SYSTEM: case MODE_NIGHT_AUTO_TIME: case MODE_NIGHT_AUTO_BATTERY: if (sDefaultNightMode != mode) { sDefaultNightMode = mode; applyDayNightToActiveDelegates(); } break; default: Log.d(TAG, "setDefaultNightMode() called with an unknown mode"); break; } }
Source:
public void testZeroLengthPutHasContentLengthHeader() throws IOException, InterruptedException { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().addHeader(ETAG, "ABCDEF")); server.play(); S3Client client = getS3Client(server.getUrl("/")); S3Object nada = client.newS3Object(); nada.getMetadata().setKey("object"); nada.setPayload(new byte[] {}); assertEquals(client.putObject("bucket", nada), "ABCDEF"); RecordedRequest request = server.takeRequest(); assertEquals(request.getRequestLine(), "PUT /bucket/object HTTP/1.1"); assertEquals(request.getHeaders(CONTENT_LENGTH), ImmutableList.of("0")); assert request.getHeaders(EXPECT).isEmpty(); server.shutdown(); }

Target:
public void testZeroLengthPutHasContentLengthHeader() throws IOException, InterruptedException { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().addHeader(ETAG, "ABCDEF")); server.play(); S3Client client = getS3Client(server.getUrl("/")); S3Object nada = client.newS3Object(); nada.getMetadata().setKey("object"); nada.setPayload(new byte[] {}); assertEquals(client.putObject("bucket", nada), "ABCDEF"); RecordedRequest request = server.takeRequest(); assertEquals(request.getRequestLine(), "PUT /bucket/object HTTP/1.1"); assertEquals(request.getHeaders(CONTENT_LENGTH), ImmutableList.of("0")); assertThat(request.getHeaders(EXPECT)).isEmpty(); server.shutdown(); }
Source:
public Subscription subscribe() { return storIOSQLite .get() .listOfObjects(User.class) .withQuery(UserTableMeta.QUERY_ALL) .prepare() .createObservableStream() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<List<User>>() { @Override public void onError(Throwable e) { fail("Error occurred: " + e); } @Override public void onNext(List<User> users) { onNextObtained(users); } @Override public void onCompleted() { } }); }

Target:
public Subscription subscribe() { return storIOSQLite .get() .listOfObjects(User.class) .withQuery(UserTableMeta.QUERY_ALL) .prepare() .createObservable() .subscribeOn(Schedulers.io()) .subscribe(new Action1<List<User>>() { @Override public void call(List<User> users) { onNextObtained(users); } }); }
Source:
public void query( IndexProgressor.NodeValueClient cursor, IndexOrder indexOrder, IndexQuery... predicates ) throws IndexNotApplicableKernelException { if ( predicates.length > 1 ) { luceneReader.query( cursor, indexOrder, predicates ); return; } if ( predicates[0] instanceof ExactPredicate ) { ExactPredicate exactPredicate = (ExactPredicate) predicates[0]; selector.select( nativeReader, luceneReader, exactPredicate.value() ).query( cursor, indexOrder, predicates ); return; } if ( predicates[0] instanceof NumberRangePredicate ) { nativeReader.query( cursor, indexOrder, predicates[0] ); return; } if ( predicates[0] instanceof ExistsPredicate ) { MultiProgressorNodeValueCursor multiProgressor = new MultiProgressorNodeValueCursor( cursor, propertyKeys ); cursor.initialize( multiProgressor, propertyKeys ); nativeReader.query( multiProgressor, indexOrder, predicates[0] ); luceneReader.query( multiProgressor, indexOrder, predicates[0] ); return; } luceneReader.query( cursor, indexOrder, predicates ); }

Target:
public void query( IndexProgressor.NodeValueClient cursor, IndexOrder indexOrder, IndexQuery... predicates ) throws IndexNotApplicableKernelException { if ( predicates.length > 1 ) { luceneReader.query( cursor, indexOrder, predicates ); return; } if ( predicates[0] instanceof ExactPredicate ) { ExactPredicate exactPredicate = (ExactPredicate) predicates[0]; selector.select( nativeReader, luceneReader, exactPredicate.value() ).query( cursor, indexOrder, predicates ); return; } if ( predicates[0] instanceof NumberRangePredicate ) { nativeReader.query( cursor, indexOrder, predicates[0] ); return; } if ( predicates[0] instanceof ExistsPredicate ) { if ( indexOrder != IndexOrder.NONE ) { throw new UnsupportedOperationException( format( "Tried to query index with unsupported order %s. Supported orders for query %s are %s.", indexOrder, Arrays.toString( predicates ), IndexOrder.NONE ) ); } BridgingIndexProgressor multiProgressor = new BridgingIndexProgressor( cursor, propertyKeys ); cursor.initialize( multiProgressor, propertyKeys ); nativeReader.query( multiProgressor, indexOrder, predicates[0] ); luceneReader.query( multiProgressor, indexOrder, predicates[0] ); return; } luceneReader.query( cursor, indexOrder, predicates ); }
Source:
default Gen<T> intersperse(Gen<T> other) { AtomicReference<Tuple2<Gen<T>, Gen<T>>> interspersedReference = new AtomicReference<>(Tuple.of(other, this)); return random -> interspersedReference.updateAndGet(generators -> Tuple.of(generators._2, generators._1))._1.apply(random); }

Target:
default Gen<T> intersperse(Gen<T> other) { java.util.Iterator<Gen<T>> iter = new java.util.Iterator<Gen<T>>() { boolean genSwitch = false; @Override public boolean hasNext() { return true; } @Override public Gen<T> next() { return (genSwitch = !genSwitch) ? Gen.this : other; } }; return random -> iter.next().apply(random); }
Source:
public void mockEventManager() throws Exception { this.manager = mock(PluginManager.class); this.testPluginContainer = mock(PluginContainer.class); when(this.testPluginContainer.getId()).thenReturn("TestPlugin"); when(this.manager.fromInstance(testPlugin)).thenReturn(Optional.of(this.testPluginContainer)); Game game = mock(Game.class); when(game.getEventManager()).thenReturn(mock(EventManager.class)); CauseStackManager csm = mock(CauseStackManager.class); Mockito.when(game.getCauseStackManager()).thenReturn(csm); Mockito.when(csm.pushCause(null)).thenReturn(csm); Mockito.when(csm.popCause()).thenReturn(null); Mockito.when(csm.getCurrentCause()).thenReturn(Cause.of(EventContext.empty(), this)); TestHooks.setGame(game); }

Target:
public void mockEventManager() throws Exception { this.manager = mock(PluginManager.class); this.testPluginContainer = mock(PluginContainer.class); when(this.testPluginContainer.getId()).thenReturn("TestPlugin"); when(this.manager.fromInstance(this.testPlugin)).thenReturn(Optional.of(this.testPluginContainer)); Game game = mock(Game.class); TestHooks.setInstance("eventManager", mock(EventManager.class)); when(game.getEventManager()).thenReturn(mock(EventManager.class)); CauseStackManager csm = mock(CauseStackManager.class); when(game.getCauseStackManager()).thenReturn(csm); when(csm.pushCause(null)).thenReturn(csm); when(csm.popCause()).thenReturn(null); when(csm.getCurrentCause()).thenReturn(Cause.of(EventContext.empty(), this)); TestHooks.setGame(game); TestHooks.setInstance("causeStackManager", csm); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BoundDimFilter)) { return false; } BoundDimFilter that = (BoundDimFilter) o; if (isLowerStrict() != that.isLowerStrict()) { return false; } if (isUpperStrict() != that.isUpperStrict()) { return false; } if (isAlphaNumeric() != that.isAlphaNumeric()) { return false; } if (!getDimension().equals(that.getDimension())) { return false; } if (!getUpper().equals(that.getUpper())) { return false; } return getLower().equals(that.getLower()); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BoundDimFilter)) { return false; } BoundDimFilter that = (BoundDimFilter) o; if (isLowerStrict() != that.isLowerStrict()) { return false; } if (isUpperStrict() != that.isUpperStrict()) { return false; } if (isAlphaNumeric() != that.isAlphaNumeric()) { return false; } if (!getDimension().equals(that.getDimension())) { return false; } if (getUpper() != null ? !getUpper().equals(that.getUpper()) : that.getUpper() != null) { return false; } return !(getLower() != null ? !getLower().equals(that.getLower()) : that.getLower() != null); }