auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String extractAuthCodeFromAuthResponse(@NonNull String redirectURLwithParams) throws OAuthException { checkNotNull(redirectURLwithParams, "redirectURLwithParams must not be null"); try { URL redirectURLObject = new URL(redirectURLwithParams); UrlEncoded urlEncoded = new UrlEncoded(redirectURLObject.getQuery()); String stateFromRedirectURL = urlEncoded.getValue(STATE, 0); if (stateFromRedirectURL == null) { if (persistedParams.state == null) { return urlEncoded.getValue(CODE, 0); } throw new OAuthException(String.format("state from redirectURL is incorrect. Expected: %s Found: %s", persistedParams.state, stateFromRedirectURL)); } else { if (stateFromRedirectURL.equals(persistedParams.state)) { return urlEncoded.getValue(CODE, 0); } throw new OAuthException(String.format("state from redirectURL is incorrect. Expected: %s Found: %s", persistedParams.state, stateFromRedirectURL)); } } catch (MalformedURLException e) { throw new OAuthException("Redirect URL is malformed", e); } }

Target:
public String extractAuthCodeFromAuthResponse(@NonNull String redirectURLwithParams) throws OAuthException { try { URL redirectURLObject = new URL(redirectURLwithParams); UrlEncoded urlEncoded = new UrlEncoded(redirectURLObject.getQuery()); String stateFromRedirectURL = urlEncoded.getValue(STATE, 0); if (stateFromRedirectURL == null) { if (persistedParams.state == null) { return urlEncoded.getValue(CODE, 0); } throw new OAuthException(String.format("state from redirectURL is incorrect. Expected: %s Found: %s", persistedParams.state, stateFromRedirectURL)); } else { if (stateFromRedirectURL.equals(persistedParams.state)) { return urlEncoded.getValue(CODE, 0); } throw new OAuthException(String.format("state from redirectURL is incorrect. Expected: %s Found: %s", persistedParams.state, stateFromRedirectURL)); } } catch (MalformedURLException e) { throw new OAuthException("Redirect URL is malformed", e); } }
Source:
public JdbcComputePushdown( FunctionMetadataManager functionMetadataManager, StandardFunctionResolution functionResolution, DeterminismEvaluator determinismEvaluator, ExpressionOptimizer expressionOptimizer, String identifierQuote, Set<Class<?>> functionTranslators) { this.expressionOptimizer = requireNonNull(expressionOptimizer); this.jdbcFilterToSqlTranslator = new JdbcFilterToSqlTranslator( requireNonNull(functionMetadataManager), buildFunctionTranslator(requireNonNull(functionTranslators)), requireNonNull(identifierQuote)); this.logicalRowExpressions = new LogicalRowExpressions( requireNonNull(determinismEvaluator), requireNonNull(functionResolution), requireNonNull(functionMetadataManager)); }

Target:
public JdbcComputePushdown( FunctionMetadataManager functionMetadataManager, StandardFunctionResolution functionResolution, DeterminismEvaluator determinismEvaluator, ExpressionOptimizer expressionOptimizer, String identifierQuote, Set<Class<?>> functionTranslators) { requireNonNull(functionMetadataManager, "functionMetadataManager is null"); requireNonNull(identifierQuote, "identifierQuote is null"); requireNonNull(functionTranslators, "functionTranslators is null"); requireNonNull(determinismEvaluator, "determinismEvaluator is null"); requireNonNull(functionResolution, "functionResolution is null"); this.expressionOptimizer = requireNonNull(expressionOptimizer, "expressionOptimizer is null"); this.jdbcFilterToSqlTranslator = new JdbcFilterToSqlTranslator( functionMetadataManager, buildFunctionTranslator(functionTranslators), identifierQuote); this.logicalRowExpressions = new LogicalRowExpressions( determinismEvaluator, functionResolution, functionMetadataManager); }
Source:
protected Result check() throws Exception { counter = counter + 1; try { hazelcastConnection.getHazelcast().getMap("health_check").put(uuid, counter); int toCheck = (int) hazelcastConnection.getHazelcast().getMap("health_check").get(uuid); return toCheck == counter ? Result.healthy("UUID=" + uuid + " - OK") : Result.unhealthy("UUID=" + uuid + " Something is wrong: health_check count is not updating"); } catch (Exception e) { return Result.healthy("UUID=" + uuid + " - Error: " + e.getMessage()); } }

Target:
protected Result check() throws Exception { counter = counter + 1; try { hazelcastConnection.getHazelcast().getMap(HEALTHCHECK_MAP).put(uuid, counter); int toCheck = (int) hazelcastConnection.getHazelcast().getMap(HEALTHCHECK_MAP).get(uuid); return toCheck == counter ? Result.healthy("UUID:" + uuid + ", counter: " + counter + " - OK") : Result.unhealthy("UUID:" + uuid + ", counter: " + counter + " Something is wrong: healthCheck count is not updating"); } catch (Exception e) { return Result.healthy("UUID:" + uuid + " - Error: " + e.getMessage()); } }
Source:
public RequestIdPolicy(RequestIdPolicyOptions requestIdPolicyOptions) { this.requestIdPolicyOptions = Objects.requireNonNull(requestIdPolicyOptions, "'retryPolicyOptions' cannot be null."); }

Target:
public RequestIdPolicy(RequestIdPolicyOptions requestIdPolicyOptions) { this.requestIdPolicyOptions = requestIdPolicyOptions; }
Source:
public boolean isBootCompleted() throws DeviceNotAvailableException { return getProp(SYSPROP_SYS_BOOT_COMPLETED) == "1" && getProp(SYSPROP_DEV_BOOTCOMPLETE) == "1"; }

Target:
public boolean isBootCompleted() throws DeviceNotAvailableException { return getProp(SYSPROP_SYS_BOOT_COMPLETED).equals("1") && getProp(SYSPROP_DEV_BOOTCOMPLETE).equals("1"); }
Source:
public List<GlusterServerService> getByClusterIdAndServiceType(Guid clusterId, ServiceType serviceType) { MapSqlParameterSource paramSource = getCustomMapSqlParameterSource(); paramSource.addValue("cluster_id", clusterId); paramSource.addValue("servive_type", serviceType); return getCallsHandler().executeReadList("GetGlusterServerServicesByClusterIdAndServiceType", serviceRowMapper, paramSource); }

Target:
public List<GlusterServerService> getByClusterIdAndServiceType(Guid clusterId, ServiceType serviceType) { MapSqlParameterSource paramSource = getCustomMapSqlParameterSource(); paramSource.addValue("cluster_id", clusterId); paramSource.addValue("service_type", EnumUtils.nameOrNull(serviceType)); return getCallsHandler().executeReadList("GetGlusterServerServicesByClusterIdAndServiceType", serviceRowMapper, paramSource); }
Source:
public ExpressionTransformer(Schema schema) { _timeColumn = schema.getTimeColumnName(); for (FieldSpec fieldSpec : schema.getAllFieldSpecs()) { ExpressionEvaluator expressionEvaluator = ExpressionEvaluatorFactory.getExpressionEvaluator(fieldSpec); if (expressionEvaluator != null) { _expressionEvaluators.put(fieldSpec.getName(), expressionEvaluator); } } }

Target:
public ExpressionTransformer(Schema schema) { for (FieldSpec fieldSpec : schema.getAllFieldSpecs()) { if (!fieldSpec.isVirtualColumn()) { ExpressionEvaluator expressionEvaluator = ExpressionEvaluatorFactory.getExpressionEvaluator(fieldSpec); if (expressionEvaluator != null) { _expressionEvaluators.put(fieldSpec.getName(), expressionEvaluator); } } } }
Source:
int readRemote(long position, byte[] b, int offset, int length) throws IOException { if (position < 0) { throw new IllegalArgumentException("attempting to read from negative offset"); } if (position >= contentLength) { return -1; } if (b == null) { throw new IllegalArgumentException("null byte array passed in to read() method"); } if (offset >= b.length) { throw new IllegalArgumentException("offset greater than length of array"); } if (length < 0) { throw new IllegalArgumentException("requested read length is less than zero"); } if (length > (b.length - offset)) { throw new IllegalArgumentException("requested read length is more than will fit after requested offset in buffer"); } final AbfsRestOperation op; AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "readRemote", "read")) { op = client.read(path, position, b, offset, length, tolerateOobAppends ? "*" : eTag, this.authzStatus); this.authzStatus = op.getAuthorizationStatus(); perfInfo.registerResult(op.getResult()).registerSuccess(true); } catch (AzureBlobFileSystemException ex) { if (ex instanceof AbfsRestOperationException) { AbfsRestOperationException ere = (AbfsRestOperationException) ex; if (ere.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { throw new FileNotFoundException(ere.getMessage()); } } throw new IOException(ex); } long bytesRead = op.getResult().getBytesReceived(); if (bytesRead > Integer.MAX_VALUE) { throw new IOException("Unexpected Content-Length"); } return (int) bytesRead; }

Target:
int readRemote(long position, byte[] b, int offset, int length) throws IOException { if (position < 0) { throw new IllegalArgumentException("attempting to read from negative offset"); } if (position >= contentLength) { return -1; } if (b == null) { throw new IllegalArgumentException("null byte array passed in to read() method"); } if (offset >= b.length) { throw new IllegalArgumentException("offset greater than length of array"); } if (length < 0) { throw new IllegalArgumentException("requested read length is less than zero"); } if (length > (b.length - offset)) { throw new IllegalArgumentException("requested read length is more than will fit after requested offset in buffer"); } final AbfsRestOperation op; AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "readRemote", "read")) { op = client.read(path, position, b, offset, length, tolerateOobAppends ? "*" : eTag); perfInfo.registerResult(op.getResult()).registerSuccess(true); } catch (AzureBlobFileSystemException ex) { if (ex instanceof AbfsRestOperationException) { AbfsRestOperationException ere = (AbfsRestOperationException) ex; if (ere.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { throw new FileNotFoundException(ere.getMessage()); } } throw new IOException(ex); } long bytesRead = op.getResult().getBytesReceived(); if (bytesRead > Integer.MAX_VALUE) { throw new IOException("Unexpected Content-Length"); } return (int) bytesRead; }
Source:
protected void executeCommand() { if ((_oldStoragePool.getQuotaEnforcementType() == QuotaEnforcmentTypeEnum.DISABLED) && (getStoragePool().getQuotaEnforcementType() != QuotaEnforcmentTypeEnum.DISABLED)) { QuotaHelper.getInstance().setDefaultQuotaAsRegularQuota(_oldStoragePool); } storage_pool storagePool = getStoragePool(); getStoragePoolDAO().updatePartial(storagePool); updateStoragePoolFormatType(); if (storagePool.getstatus() != StoragePoolStatus.Up) { setSucceeded(true); return; } String spName = storagePool.getname(); Guid spId = storagePool.getId(); VDSBrokerFrontend resourceManager = Backend.getInstance() .getResourceManager(); if (!StringHelper.EqOp(_oldStoragePool.getname(), spName)) { SetStoragePoolDescriptionVDSCommandParameters parameters = new SetStoragePoolDescriptionVDSCommandParameters(spId, spName); resourceManager.RunVdsCommand( VDSCommandType.SetStoragePoolDescription, parameters); } setSucceeded(true); }

Target:
protected void executeCommand() { if ((_oldStoragePool.getQuotaEnforcementType() == QuotaEnforcmentTypeEnum.DISABLED) && (getStoragePool().getQuotaEnforcementType() != QuotaEnforcmentTypeEnum.DISABLED)) { QuotaHelper.getInstance().setDefaultQuotaAsRegularQuota(_oldStoragePool); } storage_pool storagePool = getStoragePool(); getStoragePoolDAO().updatePartial(storagePool); updateStoragePoolFormatType(); if (storagePool.getstatus() != StoragePoolStatus.Up) { setSucceeded(true); return; } String spName = storagePool.getname(); if (!StringHelper.EqOp(_oldStoragePool.getname(), spName)) { Guid spId = storagePool.getId(); VDSBrokerFrontend resourceManager = Backend.getInstance() .getResourceManager(); SetStoragePoolDescriptionVDSCommandParameters parameters = new SetStoragePoolDescriptionVDSCommandParameters(spId, spName); resourceManager.RunVdsCommand( VDSCommandType.SetStoragePoolDescription, parameters); } setSucceeded(true); }
Source:
private static ArrayList<String> parseJson(Response resp, String languageCodeTo) { ArrayList<String> res = new ArrayList<String>(); List<Tuc> tucs = resp.getTuc(); if (tucs == null) { return res; } for (Tuc tuc : tucs) { if (tuc == null) { continue; } List<Meaning> meanings = tuc.getMeanings(); if (meanings != null) { for (Meaning meaning : meanings) { if (meaning == null) { continue; } if (meaning.getLanguage() == null) { continue; } if (languageCodeTo.contains(meaning.getLanguage())) { String unescappedString = HtmlUtil.unescape(meaning.getText()); res.add(unescappedString); } } } Phrase phrase = tuc.getPhrase(); if (phrase != null) { if (phrase.getLanguageCode() == null) { continue; } if (phrase.getLanguageCode().contentEquals(languageCodeTo)) { String unescappedString = HtmlUtil.unescape(phrase.getText()); res.add(unescappedString); } } } return res; }

Target:
private static ArrayList<String> parseJson(Response resp, String languageCodeTo) { ArrayList<String> res = new ArrayList<String>(); List<Tuc> tucs = resp.getTuc(); if (tucs == null) { return res; } String desiredLang = LanguagesListerGlosbe .requestToResponseLangCode(languageCodeTo); for (Tuc tuc : tucs) { if (tuc == null) { continue; } List<Meaning> meanings = tuc.getMeanings(); if (meanings != null) { for (Meaning meaning : meanings) { if (meaning == null) { continue; } if (meaning.getLanguage() == null) { continue; } if (meaning.getLanguage().contentEquals(desiredLang)) { String unescappedString = HtmlUtil.unescape(meaning .getText()); res.add(unescappedString); } } } Phrase phrase = tuc.getPhrase(); if (phrase != null) { if (phrase.getLanguage() == null) { continue; } if (phrase.getLanguage().contentEquals(desiredLang)) { String unescappedString = HtmlUtil.unescape(phrase .getText()); res.add(unescappedString); } } } return res; }
Source:
public BuildIndexScheduleTask(RegionCoprocessorEnvironment env) { this.env = env; this.rebuildIndexBatchSize = env.getConfiguration().getLong( QueryServices.INDEX_FAILURE_HANDLING_REBUILD_BATCH_SIZE_ATTRIB, HConstants.LATEST_TIMESTAMP); }

Target:
public BuildIndexScheduleTask(RegionCoprocessorEnvironment env) { this.env = env; this.rebuildIndexBatchSize = env.getConfiguration().getLong( QueryServices.INDEX_FAILURE_HANDLING_REBUILD_PERIOD, HConstants.LATEST_TIMESTAMP); this.configuredBatches = env.getConfiguration().getLong( QueryServices.INDEX_FAILURE_HANDLING_REBUILD_NUMBER_OF_BATCHES_PER_TABLE, configuredBatches); }
Source:
private boolean sendGETRequest(String servicePath, HashMap<String, String> params, String loginSecret, SEHTTPResponseHandler handler) { HashMap<String, String> headers = headers(); String url = servicePath; if (!loginSecret.isEmpty()){ headers = loginSecretHeaders(loginSecret); } if (params != null) { url = url.concat(SETools.paramsToString(params)); } Log.v("tag", "url " + url); return SERestClient.get(url, handler, headers); }

Target:
private boolean sendGETRequest(String servicePath, HashMap<String, String> params, String loginSecret, SEHTTPResponseHandler handler) { HashMap<String, String> headers = headers(); String url = servicePath; if (!loginSecret.isEmpty()){ headers = loginSecretHeaders(loginSecret); } if (params != null) { url = url.concat(SETools.paramsToString(params)); } return SERestClient.get(url, handler, headers); }
Source:
private synchronized void refreshPool() { blacklist.checkAndUpdate(cassandra.getPools()); if (config.autoRefreshNodes()) { setServersInPoolTo(cassandra.refreshTokenRangesAndGetServers()); } else { setServersInPoolTo(config.servers().thrift()); } cassandra.debugLogStateOfPool(); }

Target:
private synchronized void refreshPool() { blacklist.checkAndUpdate(cassandra.getPools()); if (config.autoRefreshNodes()) { setServersInPoolTo(cassandra.refreshTokenRangesAndGetServers()); } else { config.servers().visit((thrift, cql) -> { setServersInPoolTo(thrift); return null; }); } cassandra.debugLogStateOfPool(); }
Source:
public static void unzip(File zipFile, File destFolder) throws IOException { ZipInputStream zis = null; try { zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry entry = zis.getNextEntry(); if (entry == null) { throw new IOException(MessageFormat.format("File ''{0}'' has no entries", zipFile)); } do { if (!entry.isDirectory()) { final File file = new File(destFolder, entry.getName()); Files.createParentDirs(file); Files.asByteSink(file, FileWriteMode.APPEND).writeFrom(zis); } } while ((entry = zis.getNextEntry()) != null); } finally { Closeables.close(zis, true); } }

Target:
public static void unzip(File zipFile, File destFolder) throws IOException { ZipInputStream zis = null; try { zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry entry = zis.getNextEntry(); if (entry == null) { throw new IOException(MessageFormat.format("''{0}'' is empty or not a ZIP file.", zipFile)); } do { if (!entry.isDirectory()) { final File file = new File(destFolder, entry.getName()); Files.createParentDirs(file); Files.asByteSink(file, FileWriteMode.APPEND).writeFrom(zis); } } while ((entry = zis.getNextEntry()) != null); } finally { Closeables.close(zis, true); } }
Source:
public Indexed<Comparable> getDimValueLookup(String dimension) { final Column column = input.getColumn(dimension); if (column == null) { return null; } final DictionaryEncodedColumn dict = column.getDictionaryEncoding(); if (dict == null) { return null; } List values = Lists.newArrayList(new Indexed<Comparable>() { @Override public Class<? extends Comparable> getClazz() { return Comparable.class; } @Override public int size() { return dict.getCardinality(); } @Override public Comparable get(int index) { return dict.lookupName(index); } @Override public int indexOf(Comparable value) { return dict.lookupId(value); } @Override public Iterator<Comparable> iterator() { return IndexedIterable.create(this).iterator(); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("dict", dict); } }); int count = 0; for (Object val : values) { if (val == null) { count++; } } if (count > 1) { throw new ISE("God save me!!"); } return new Indexed<Comparable>() { @Override public Class<? extends Comparable> getClazz() { return Comparable.class; } @Override public int size() { return dict.getCardinality(); } @Override public Comparable get(int index) { return dict.lookupName(index); } @Override public int indexOf(Comparable value) { return dict.lookupId(value); } @Override public Iterator<Comparable> iterator() { return IndexedIterable.create(this).iterator(); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("dict", dict); } }; }

Target:
public Indexed<Comparable> getDimValueLookup(String dimension) { final Column column = input.getColumn(dimension); if (column == null) { return null; } final DictionaryEncodedColumn dict = column.getDictionaryEncoding(); if (dict == null) { return null; } return new Indexed<Comparable>() { @Override public Class<? extends Comparable> getClazz() { return Comparable.class; } @Override public int size() { return dict.getCardinality(); } @Override public Comparable get(int index) { return dict.lookupName(index); } @Override public int indexOf(Comparable value) { return dict.lookupId(value); } @Override public Iterator<Comparable> iterator() { return IndexedIterable.create(this).iterator(); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("dict", dict); } }; }
Source:
public static void die(Throwable th, boolean usage, String name, Command command) { String errorMsg = th.getClass().getSimpleName(); String errorDetails = th.getMessage(); if (errorDetails != null && !errorDetails.isEmpty()) { errorMsg += ": " + errorDetails; } die(errorMsg, usage, name, command); }

Target:
public static void die(Throwable th, boolean usage, String name, Command command) { die(th.toString(), usage, name, command); }
Source:
public void VEMediaTests_003_uploadImageWithCustomFileName() { String testFileUploadName = "TestFile"; String testFullFileName = testFileUploadName + ".png"; ImageLicense testImageLicense = ImageLicense.CCBYSA; base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); VisualEditorPageObject ve = base.openNewArticleEditModeVisual(wikiURL); VisualEditorAddMediaDialog mediaDialog = (VisualEditorAddMediaDialog) ve.openDialogFromMenu(InsertDialog.MEDIA); ve = mediaDialog.uploadImage(PageContent.file2Png, testFileUploadName, testImageLicense); VisualEditorSaveChangesDialog save = ve.clickPublishButton(); ArticlePageObject article = save.savePage(); article.verifyVEPublishComplete(); FilePagePageObject filePage = base.openFilePage(wikiURL, testFullFileName); filePage.verifyImageLicense(testImageLicense); filePage.selectHistoryTab(); filePage.verifyArticleName(URLsContent.fileNameSpace + testFullFileName); DeletePageObject deletePage = filePage.deleteVersion(1); WikiBasePageObject base = deletePage.submitDeletion(); base.logOut(wikiURL); }

Target:
public void VEMediaTests_003_uploadImageWithCustomFileName() { String testFileUploadName = "TestFile"; testFullFileName = testFileUploadName + ".png"; testImageLicense = ImageLicense.CCBYSA; base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); VisualEditorPageObject ve = base.openNewArticleEditModeVisual(wikiURL); VisualEditorAddMediaDialog mediaDialog = (VisualEditorAddMediaDialog) ve.openDialogFromMenu(InsertDialog.MEDIA); ve = mediaDialog.uploadImage(PageContent.file2Png, testFileUploadName, testImageLicense); VisualEditorSaveChangesDialog save = ve.clickPublishButton(); ArticlePageObject article = save.savePage(); article.verifyVEPublishComplete(); }
Source:
public void acceptsInstanceMethodReferences() throws Exception { this.validateCheckstyle( "Main.java", true, Matchers.containsString(CheckstyleValidatorTest.NO_VIOLATIONS) ); }

Target:
public void acceptsInstanceMethodReferences() throws Exception { this.validateCheckstyle( "InstanceMethodRef.java", true, Matchers.containsString(CheckstyleValidatorTest.NO_VIOLATIONS) ); }
Source:
private Path getConfigTemplatePath() { URI fileUri; URL fileUrl = getClass() .getResource("/org/eclipse/che/selenium/dashboard/expectedWorkspaceConfTemplate.txt"); try { fileUri = fileUrl.toURI(); } catch (URISyntaxException ex) { LOG.info("Parsed url: has wrong syntax and can't be converted to URI", fileUrl); throw new RuntimeException(ex.getLocalizedMessage(), ex); } return Paths.get(fileUri); }

Target:
private Path getConfigTemplatePath() throws URISyntaxException { URL fileUrl = getClass() .getResource("/org/eclipse/che/selenium/dashboard/expectedWorkspaceConfTemplate.txt"); return Paths.get(fileUrl.toURI()); }
Source:
private void maybeShowLocalhostRunningInfo() { maybeTriggerDisplayHandler("bitcoinLocalhostNode", displayLocalhostHandler, localBitcoinNode.isUsable().get()); }

Target:
private void maybeShowLocalhostRunningInfo() { maybeTriggerDisplayHandler("bitcoinLocalhostNode", displayLocalhostHandler, localBitcoinNode.shouldBeUsed()); }
Source:
public synchronized void handleRunningExperiment(String experimentID) { boolean exit = false; BenchFlowExperimentState experimentState; RunningState runningState; try { experimentState = experimentModelDAO.getExperimentState(experimentID); runningState = experimentModelDAO.getRunningState(experimentID); while (!exit) { BenchFlowExperimentState prevExperimentState = experimentState; RunningState prevRunningState = runningState; try { experimentState = handleExperimentState(experimentID); } catch (BenchFlowExperimentIDDoesNotExistException e) { e.printStackTrace(); break; } runningState = experimentModelDAO.getRunningState(experimentID); logger.info("handleRunningExperiment: prevExperimentState == " + prevExperimentState); logger.info("handleRunningExperiment: runningState == " + runningState); if (prevExperimentState == TERMINATED) { exit = true; } else if (runningState == RunningState.HANDLE_TRIAL_RESULT || runningState == RunningState.TERMINATING && prevRunningState == RunningState.HANDLE_TRIAL_RESULT) { exit = true; } } } catch (BenchFlowExperimentIDDoesNotExistException e) { e.printStackTrace(); } }

Target:
public synchronized void handleRunningExperiment(String experimentID) { BenchFlowExperimentState experimentState; BenchFlowExperimentState prevExperimentState; RunningState runningState; RunningState prevRunningState; try { experimentState = experimentModelDAO.getExperimentState(experimentID); runningState = experimentModelDAO.getRunningState(experimentID); logger.info("handleRunningExperiment: experimentState == " + experimentState); logger.info("handleRunningExperiment: runningState == " + runningState); while (true) { prevExperimentState = experimentState; prevRunningState = runningState; try { handleExperimentState(experimentID); } catch (BenchFlowExperimentIDDoesNotExistException e) { e.printStackTrace(); break; } experimentState = experimentModelDAO.getExperimentState(experimentID); runningState = experimentModelDAO.getRunningState(experimentID); logger.info("handleRunningExperiment: (while) experimentState == " + experimentState); logger.info("handleRunningExperiment: (while) runningState == " + runningState); logger.info("handleRunningExperiment: (while) prevRunningState == " + prevRunningState); if (prevExperimentState == TERMINATED) { break; } if (runningState == RunningState.HANDLE_TRIAL_RESULT) { break; } } } catch (BenchFlowExperimentIDDoesNotExistException e) { e.printStackTrace(); } }
Source:
public FormValidation doCheckUpstreamProjectName( @AncestorInPath Job<?,?> project, @QueryParameter String upstreamProjectName ) { upstreamProjectName = StringUtils.trim(upstreamProjectName); if (StringUtils.isBlank(upstreamProjectName)) { return FormValidation.error(Messages.DownstreamBuildSelector_UpstreamProjectName_Required()); } if (containsVariable(upstreamProjectName)) { return FormValidation.ok(); } Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { return FormValidation.ok(); } AbstractProject<?,?> upstreamRoot; if(project != null && project instanceof AbstractProject) { upstreamRoot = ((AbstractProject) project).getRootProject(); } else { upstreamRoot = null; } AbstractProject<?,?> upstreamProject = jenkins.getItem( upstreamProjectName, upstreamRoot, AbstractProject.class ); if (upstreamProject == null || !upstreamProject.hasPermission(Item.READ)) { return FormValidation.error(Messages.DownstreamBuildSelector_UpstreamProjectName_NotFound()); } return FormValidation.ok(); }

Target:
public FormValidation doCheckUpstreamProjectName( @AncestorInPath Job<?,?> project, @QueryParameter String upstreamProjectName ) { upstreamProjectName = StringUtils.trim(upstreamProjectName); if (StringUtils.isBlank(upstreamProjectName)) { return FormValidation.error(Messages.DownstreamBuildSelector_UpstreamProjectName_Required()); } if (containsVariable(upstreamProjectName)) { return FormValidation.ok(); } Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { return FormValidation.ok(); } if (project == null) { return FormValidation.ok(Messages.CopyArtifact_AncestorIsNull()); } Job<?,?> upstreamRoot = (project instanceof AbstractProject) ? ((AbstractProject<?,?>) project).getRootProject() : project; Job<?,?> upstreamProject = jenkins.getItem( upstreamProjectName, upstreamRoot, Job.class ); if (upstreamProject == null || !upstreamProject.hasPermission(Item.READ)) { return FormValidation.error(Messages.DownstreamBuildSelector_UpstreamProjectName_NotFound()); } return FormValidation.ok(); }
Source:
public void edit(String path, String putAfterString, String toBeInserted) throws IOException { paths.add(path); String currentFile = Util.getFileNameFromPath(path); files.add(currentFile); FileUtils.deleteQuietly(new File(currentFile)); FileUtils.deleteQuietly(new File("."+currentFile+".crc")); FileUtils.deleteQuietly(new File(currentFile+".bck")); FileUtils.deleteQuietly(new File("tmp")); Path file = new Path(path); if(fs.exists(file)){ fs.copyToLocalFile(file, new Path(currentFile)); FileUtils.copyFile(new File(currentFile), new File(currentFile + ".bck")); BufferedWriter bufwriter = new BufferedWriter(new FileWriter ("tmp")); BufferedReader br = new BufferedReader(new FileReader(currentFile)); String line ; boolean isInserted = false ; while( (line = br.readLine()) != null) { bufwriter.write(line); bufwriter.write('\n'); if(line.contains(putAfterString) && !isInserted) { bufwriter.write(toBeInserted); isInserted = true ; } } br.close(); bufwriter.close(); FileUtils.deleteQuietly(new File(currentFile)); FileUtils.copyFile(new File("tmp"), new File(currentFile)); FileUtils.deleteQuietly(new File("tmp")); fs.delete(file,false); File crcFile = new File("."+currentFile+".crc"); if(crcFile.exists()) crcFile.delete(); fs.copyFromLocalFile(new Path(currentFile),file); } else { System.out.println("Nothing to do, " + currentFile + " does not exists"); } }

Target:
public void edit(String path, String putAfterString, String toBeInserted) throws IOException { paths.add(path); String currentFile = Util.getFileNameFromPath(path); files.add(currentFile); FileUtils.deleteQuietly(new File(currentFile)); FileUtils.deleteQuietly(new File("."+currentFile+".crc")); FileUtils.deleteQuietly(new File(currentFile+".bck")); FileUtils.deleteQuietly(new File("tmp")); Path file = new Path(path); if(fs.exists(file)){ fs.copyToLocalFile(file, new Path(currentFile)); FileUtils.copyFile(new File(currentFile), new File(currentFile + ".bck")); BufferedWriter bufwriter = new BufferedWriter(new FileWriter ("tmp")); BufferedReader br = new BufferedReader(new FileReader(currentFile)); String line ; boolean isInserted = false ; while( (line = br.readLine()) != null) { bufwriter.write(line); bufwriter.write('\n'); if(line.contains(putAfterString) && !isInserted) { bufwriter.write(toBeInserted); isInserted = true ; } } br.close(); bufwriter.close(); FileUtils.deleteQuietly(new File(currentFile)); FileUtils.copyFile(new File("tmp"), new File(currentFile)); FileUtils.deleteQuietly(new File("tmp")); fs.delete(file,false); File crcFile = new File("."+currentFile+".crc"); if(crcFile.exists()) crcFile.delete(); fs.copyFromLocalFile(new Path(currentFile),file); } else { logger.info("Nothing to do, " + currentFile + " does not exists"); } }
Source:
public Single<List<Optional<java.io.File>>> downloadAllFilesInDriveFolder(@NonNull final RemoteBackupMetadata remoteBackupMetadata, @NonNull final java.io.File downloadLocation) { Preconditions.checkNotNull(remoteBackupMetadata); Preconditions.checkNotNull(downloadLocation); return mDriveStreamsManager.getFilesInFolder(remoteBackupMetadata.getId().getId()) .flatMap(fileList -> { List<Optional<java.io.File>> javaFileList = new ArrayList<>(); for (File file : fileList.getFiles()) { String filename = file.getId() + "__" + file.getOriginalFilename(); Optional<java.io.File> single = mDriveStreamsManager.download(file.getId(), new java.io.File(downloadLocation, filename)).blockingGet(); if (single.isPresent()) { javaFileList.add(Optional.of(single.get())); } } return Single.just(javaFileList); }); }

Target:
public Single<List<java.io.File>> downloadAllFilesInDriveFolder(@NonNull final RemoteBackupMetadata remoteBackupMetadata, @NonNull final java.io.File downloadLocation) { Preconditions.checkNotNull(remoteBackupMetadata); Preconditions.checkNotNull(downloadLocation); return mDriveStreamsManager.getFilesInFolder(remoteBackupMetadata.getId().getId()) .flatMap(fileList -> { List<java.io.File> javaFileList = new ArrayList<>(); for (File file : fileList.getFiles()) { String filename = file.getId() + "__" + file.getOriginalFilename(); Optional<java.io.File> optional = mDriveStreamsManager.download(file.getId(), new java.io.File(downloadLocation, filename)).blockingGet(); if (optional.isPresent()) { javaFileList.add(optional.get()); } } return Single.just(javaFileList); }); }
Source:
public void execute(IProgressMonitor m) throws CoreException { if (pullResult != null) throw new CoreException(new Status(IStatus.ERROR, Activator .getPluginId(), CoreText.OperationAlreadyExecuted)); IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor mymonitor) throws CoreException { PullCommand pull = new Git(repository).pull(); try { pull.setProgressMonitor(new EclipseGitProgressTransformer( mymonitor)); pull.setTimeout(timeout); pullResult = pull.call(); } catch (GitAPIException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } catch (JGitInternalException e) { Throwable cause = e.getCause() != null ? e.getCause() : e; throw new CoreException(Activator.error(cause.getMessage(), cause)); } } }; ResourcesPlugin.getWorkspace().run(action, monitor); }

Target:
public void execute(IProgressMonitor m) throws CoreException { if (pullResult != null) throw new CoreException(new Status(IStatus.ERROR, Activator .getPluginId(), CoreText.OperationAlreadyExecuted)); IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor mymonitor) throws CoreException { PullCommand pull = new Git(repository).pull(); try { pull.setProgressMonitor(new EclipseGitProgressTransformer( mymonitor)); pull.setTimeout(timeout); pullResult = pull.call(); } catch (GitAPIException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } catch (JGitInternalException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } } }; ResourcesPlugin.getWorkspace().run(action, monitor); }
Source:
public JavaParameters buildMavenServerParameters() { JavaParameters parameters = new JavaParameters(); parameters.setJavaExecutable(System.getProperties().getProperty("java.home") + "/bin/java"); parameters.setWorkingDirectory(System.getProperty("java.io.tmpdir")); parameters.setMainClassName(MAVEN_SERVER_MAIN); List<String> classPath = new ArrayList<>(); addDirToClasspath(classPath, new File(mavenServerPath)); String mavenHome = System.getenv("M2_HOME"); addDirToClasspath(classPath, new File(mavenHome, "lib")); File bootDir = new File(mavenHome, "boot"); File[] classworlds = bootDir.listFiles((dir, name) -> name.contains("classworlds")); if (classworlds != null) { for (File file : classworlds) { classPath.add(file.getAbsolutePath()); } } parameters.getClassPath().addAll(classPath); String vmArguments = MoreObjects.firstNonNull( System.getenv("CHE_WORKSPACE_MAVEN_SERVER_JAVA_OPTIONS"), MoreObjects.firstNonNull( System.getenv("CHE_WORKSPACE_MAVEN_SERVER_JAVA_OPTIONS_DEFAULT"), "-Xmx128m")); Arrays.stream(vmArguments.split(" ")) .map(String::trim) .filter(v -> !v.isEmpty()) .forEach(parameters.getVmParameters()::add); return parameters; }

Target:
public JavaParameters buildMavenServerParameters() { JavaParameters parameters = new JavaParameters(); parameters.setJavaExecutable(System.getProperties().getProperty("java.home") + "/bin/java"); parameters.setWorkingDirectory(System.getProperty("java.io.tmpdir")); parameters.setMainClassName(MAVEN_SERVER_MAIN); List<String> classPath = new ArrayList<>(); addDirToClasspath(classPath, new File(mavenServerPath)); String mavenHome = System.getenv("M2_HOME"); addDirToClasspath(classPath, new File(mavenHome, "lib")); File bootDir = new File(mavenHome, "boot"); File[] classworlds = bootDir.listFiles((dir, name) -> name.contains("classworlds")); if (classworlds != null) { for (File file : classworlds) { classPath.add(file.getAbsolutePath()); } } parameters.getClassPath().addAll(classPath); parameters.getVmParameters().addAll(mavenServerJavaOptionsList); return parameters; }
Source:
private static Model getDefaultAcl() { final String rootAcl = System.getProperty(ROOT_ACL_PROPERTY); if (rootAcl != null && new File(rootAcl).isFile()) { LOGGER.debug("Getting Root ACL from file: {}", rootAcl); return RDFDataMgr.loadModel(rootAcl); } else { LOGGER.debug("Getting Root ACL from classpath: {}", ROOT_ACL_LOCATION); final Model model = createDefaultModel(); final InputStream is = WebACRolesProvider.class.getResourceAsStream(ROOT_ACL_LOCATION); RDFDataMgr.read(model, is, Lang.TTL); return model; } }

Target:
private static Model getDefaultAcl() { final String rootAcl = System.getProperty(ROOT_AUTHORIZATION_PROPERTY); final Model model = createDefaultModel(); if (rootAcl != null && new File(rootAcl).isFile()) { try { LOGGER.debug("Getting root authorization from file: {}", rootAcl); return model.read(rootAcl); } catch (final JenaException ex) { LOGGER.error("Error parsing root authorization file: {}", ex.getMessage()); } } try (final InputStream is = WebACRolesProvider.class.getResourceAsStream(ROOT_AUTHORIZATION_LOCATION)) { LOGGER.debug("Getting root authorization from classpath: {}", ROOT_AUTHORIZATION_LOCATION); return model.read(is, null, TTL.getName()); } catch (final IOException ex) { LOGGER.error("Error reading root authorization file: {}", ex.getMessage()); } catch (final JenaException ex) { LOGGER.error("Error parsing root authorization file: {}", ex.getMessage()); } return createDefaultModel(); }
Source:
public void likePost(Long postId, String likerUsername) { Post post = postRepository.findOne(postId); if (post == null) { throw new PostNotFoundException(postId); } User user = userService.findUserByUsername(likerUsername).get(); if (post.isNotAlreadyLikedBy(likerUsername)) { post.addLike(user); postRepository.save(post); PostNotificationEvent event = new PostNotificationEvent(post, user, likerUsername); domainEvents.raise(event); } }

Target:
public void likePost(Long postId, String likerUsername) { Post post = postRepository.findOne(postId); if (post == null) { throw new PostNotFoundException(postId); } User user = userService.findUserByUsername(likerUsername).get(); if (post.isNotAlreadyLikedBy(likerUsername)) { post.addLike(user); postRepository.save(post); LikePostEvent likePostEvent = new LikePostEvent(post, likerUsername); domainEvents.raise(likePostEvent); } }
Source:
public void init() throws Exception { context = new AutomationContext("AS", "appServerInstance0002", ContextXpathConstants.SUPER_TENANT, ContextXpathConstants.ADMIN); authenticatorClient = new AuthenticatorClient(context.getContextUrls().getBackEndUrl()); AutomationContext context = new AutomationContext(); h2DBURL = context.getConfigurationValue(String.format(ASIntegrationConstants.DB_URL, "H2DB")); }

Target:
public void init() throws XPathExpressionException, AxisFault { automationContext = new AutomationContext(ASIntegrationConstants.AS_PRODUCT_GROUP, ASIntegrationConstants.AS_INSTANCE_0002, ContextXpathConstants.SUPER_TENANT, ContextXpathConstants.SUPER_ADMIN); authenticatorClient = new AuthenticatorClient(automationContext.getContextUrls().getBackEndUrl()); dataSourceBean = CarbonCommandToolsUtil.getDataSourceInformation("default"); }
Source:
public void testVpnMeterednessWithNonNullUnderlyingNetwork() throws Exception { if (!supportedHardware()) { return; } Network wifi = ensureWifiConnected(); assertEquals(wifi, mCM.getActiveNetwork()); ArrayList<Network> underlyingNetworks = new ArrayList<>(1); underlyingNetworks.add(wifi); String allowedApps = mPackageName; startVpn( new String[] {"192.0.2.2/32", "2001:db8:1:2::ffe/128"}, new String[] {"0.0.0.0/0", "::/0"}, allowedApps, "", null, underlyingNetworks, false); assertEquals(mNetwork, mCM.getActiveNetwork()); ensureVpnTransportContains(NetworkCapabilities.TRANSPORT_WIFI); assertEquals(isNetworkMetered(wifi), isNetworkMetered(mNetwork)); assertEquals(isNetworkMetered(mNetwork), mCM.isActiveNetworkMetered()); }

Target:
public void testVpnMeterednessWithNonNullUnderlyingNetwork() throws Exception { if (!supportedHardware()) { return; } Network wifi = getWifiNetwork(); assertEquals(wifi, mCM.getActiveNetwork()); ArrayList<Network> underlyingNetworks = new ArrayList<>(1); underlyingNetworks.add(wifi); String allowedApps = mPackageName; startVpn( new String[] {"192.0.2.2/32", "2001:db8:1:2::ffe/128"}, new String[] {"0.0.0.0/0", "::/0"}, allowedApps, "", null, underlyingNetworks, false ); assertEquals(mNetwork, mCM.getActiveNetwork()); ensureVpnTransportContains(NetworkCapabilities.TRANSPORT_WIFI); assertEquals(isNetworkMetered(wifi), isNetworkMetered(mNetwork)); assertEquals(isNetworkMetered(mNetwork), mCM.isActiveNetworkMetered()); }
Source:
static LogoutResponse from(Response response) { if (response.code() == 204 ) { return new LogoutResponse(); } try { String serverResponse = response.body().string(); return new LogoutResponse(AuthServerResponse.createError(serverResponse, response.code())); } catch (IOException e) { ObjectServerError error = new ObjectServerError(ErrorCode.IO_EXCEPTION, e); return new LogoutResponse(error); } }

Target:
static LogoutResponse from(Response response) { if (response.isSuccessful()) { return new LogoutResponse(); } try { String serverResponse = response.body().string(); return new LogoutResponse(AuthServerResponse.createError(serverResponse, response.code())); } catch (IOException e) { ObjectServerError error = new ObjectServerError(ErrorCode.IO_EXCEPTION, e); return new LogoutResponse(error); } }
Source:
public List<String> checkComplimentaryCriteriaAllRequired(List<String> criterionToCheck, List<String> complimentaryCertNumbers, List<String> allCriteriaMet) { List<String> errors = new ArrayList<String>(); boolean hasAnyCert = hasAnyCert(criterionToCheck, allCriteriaMet); if (hasAnyCert) { for (String complimentaryCert : complimentaryCertNumbers) { boolean hasComplimentaryCert = hasCert(complimentaryCert, allCriteriaMet); if (!hasComplimentaryCert) { String criterionErrorString = ""; for(int i = 0; i < criterionToCheck.size(); i++) { String checkedCriteria = criterionToCheck.get(i); if(i > 0) { criterionErrorString += " or "; } criterionErrorString += checkedCriteria; } errors.add("Certification criterion " + criterionErrorString + " was found so " + complimentaryCert + " is required but was not found."); } } } return errors; }

Target:
protected List<String> checkComplimentaryCriteriaAllRequired(List<String> criterionToCheck, List<String> complimentaryCertNumbers, List<String> allCriteriaMet) { List<String> errors = new ArrayList<String>(); boolean hasAnyCert = hasAnyCert(criterionToCheck, allCriteriaMet); if (hasAnyCert) { for (String complimentaryCert : complimentaryCertNumbers) { boolean hasComplimentaryCert = hasCert(complimentaryCert, allCriteriaMet); if (!hasComplimentaryCert) { String criterionErrorString = ""; for(int i = 0; i < criterionToCheck.size(); i++) { String checkedCriteria = criterionToCheck.get(i); if(i > 0) { criterionErrorString += " or "; } criterionErrorString += checkedCriteria; } errors.add("Certification criterion " + criterionErrorString + " was found so " + complimentaryCert + " is required but was not found."); } } } return errors; }
Source:
public void waitItemCheckBoxToBeIndeterminate(String itemName) { new WebDriverWait(seleniumWebDriver, 5) .until( (ExpectedCondition<Boolean>) webDriver -> seleniumWebDriver .findElement( By.xpath( String.format(Locators.TREE_ITEM_CHECK_BOX + " .getAttribute("id") .endsWith("indeterminate")); }

Target:
public void waitItemCheckBoxToBeIndeterminate(String itemName) { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( (ExpectedCondition<Boolean>) webDriver -> seleniumWebDriver .findElement( By.xpath( String.format(Locators.TREE_ITEM_CHECK_BOX + " .getAttribute("id") .endsWith("indeterminate")); }
Source:
public void addTable(TableDescriptor tableDescriptor) { this.addTableDescriptor(tableDescriptor); }

Target:
public void addTable(TableDescriptor tableDescriptor) { Preconditions.checkState(!tableDescriptors.containsKey(tableDescriptor.getTableId()), String.format("add table descriptors multiple times with the same tableId: %s", tableDescriptor.getTableId())); tableDescriptors.put(tableDescriptor.getTableId(), tableDescriptor); }
Source:
public ListBoxModel doFillServerNameItems() { ListBoxModel items = new ListBoxModel(); ArrayList<GerritServer> servers = PluginImpl.getInstance().getServers(); for (GerritServer s : servers) { items.add(s.getName()); } return items; }

Target:
public ListBoxModel doFillServerNameItems() { ListBoxModel items = new ListBoxModel(); LinkedList<String> serverNames = PluginImpl.getInstance().getServerNames(); for (String s : serverNames) { items.add(s); } return items; }
Source:
public int countUsedAndDeletedObjectsReference(String bucketName, String checksum) throws SQLException { PreparedStatement p = null; ResultSet result = null; try { StringBuilder q = new StringBuilder("SELECT COUNT(*) FROM objects a, buckets b WHERE a.bucketId = b.bucketId"); q.append(" AND a.status IN (?,?)"); q.append(" AND bucketName=?"); q.append(" AND checksum=?"); p = connectionLocal.get().prepareStatement(q.toString()); p.setInt(1, Status.USED.getValue()); p.setInt(2, Status.DELETED.getValue()); p.setString(3, bucketName); p.setString(4, checksum); result = p.executeQuery(); if (result.next()) return result.getInt(1); else return 0; } finally { closeDbStuff(result, p); } }

Target:
public int countUsedAndDeletedObjectsReference(String bucketName, String checksum) throws SQLException { PreparedStatement p = null; ResultSet result = null; StringBuilder q = new StringBuilder("SELECT COUNT(*) FROM objects a, buckets b WHERE a.bucketId = b.bucketId"); q.append(" AND a.status IN (?,?)"); q.append(" AND bucketName=?"); q.append(" AND checksum=?"); try { p = connectionLocal.get().prepareStatement(q.toString()); p.setInt(1, Status.USED.getValue()); p.setInt(2, Status.DELETED.getValue()); p.setString(3, bucketName); p.setString(4, checksum); result = p.executeQuery(); if (result.next()) return result.getInt(1); else return 0; } finally { closeDbStuff(result, p); } }
Source:
public void copyFileToContainer(MountableFile mountableLocalFile, String containerPath) { if (!isRunning() && !isCreated()) { throw new IllegalStateException("opyFileToContainer can only be used with created / running container"); } this.dockerClient .copyArchiveToContainerCmd(this.containerId) .withHostResource(mountableLocalFile.getResolvedPath()) .withRemotePath(containerPath) .exec(); }

Target:
public void copyFileToContainer(MountableFile mountableLocalFile, String containerPath) { if (!isCreated()) { throw new IllegalStateException("copyFileToContainer can only be used with created / running container"); } this.dockerClient .copyArchiveToContainerCmd(this.containerId) .withHostResource(mountableLocalFile.getResolvedPath()) .withRemotePath(containerPath) .exec(); }