auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void configureAddressPolicy(ActiveMQServer server) { super.configureAddressPolicy(server); AddressSettings addressSettings = server.getConfiguration().getAddressesSettings().get("#"); addressSettings.setDefaultGroupFirstKey(SimpleString.toSimpleString("JMSXFirstInGroupID")); }

Target:
protected void configureAddressPolicy(ActiveMQServer server) { super.configureAddressPolicy(server); AddressSettings addressSettings = new AddressSettings(); addressSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); addressSettings.setAutoCreateQueues(isAutoCreateQueues()); addressSettings.setAutoCreateAddresses(isAutoCreateAddresses()); addressSettings.setDeadLetterAddress(SimpleString.toSimpleString(getDeadLetterAddress())); addressSettings.setExpiryAddress(SimpleString.toSimpleString(getDeadLetterAddress())); addressSettings.setDefaultGroupFirstKey(SimpleString.toSimpleString("JMSXFirstInGroupID")); server.getConfiguration().getAddressesSettings().put("GroupFirst.#", addressSettings); }
Source:
private URL promptForWorkspace(Shell shell, ChooseWorkspaceData launchData, boolean force) { URL url = null; do { new ChooseWorkspaceDialog(shell, launchData, false, true) { @Override protected Shell getParentShell() { return null; } }.prompt(force); String instancePath = launchData.getSelection(); if (instancePath == null) { return null; } force = true; if (instancePath.length() <= 0) { MessageDialog .openError( shell, IDEWorkbenchMessages.IDEApplication_workspaceEmptyTitle, IDEWorkbenchMessages.IDEApplication_workspaceEmptyMessage); continue; } File workspace = new File(instancePath); if (!workspace.exists()) { workspace.mkdir(); } try { String path = workspace.getAbsolutePath().replace( File.separatorChar, '/'); url = new URL("file", null, path); } catch (MalformedURLException e) { MessageDialog .openError( shell, IDEWorkbenchMessages.IDEApplication_workspaceInvalidTitle, IDEWorkbenchMessages.IDEApplication_workspaceInvalidMessage); continue; } boolean validWorkspace = checkValidWorkspace(shell, url); if (!validWorkspace) { throw new OperationCanceledException(); } return url; } while (true); }

Target:
private URL promptForWorkspace(Shell shell, ChooseWorkspaceData launchData, boolean force) { URL url = null; do { new ChooseWorkspaceDialog(shell, launchData, false, true) { @Override protected Shell getParentShell() { return null; } }.prompt(force); String instancePath = launchData.getSelection(); if (instancePath == null) { return null; } force = true; if (instancePath.length() <= 0) { MessageDialog .openError( shell, IDEWorkbenchMessages.IDEApplication_workspaceEmptyTitle, IDEWorkbenchMessages.IDEApplication_workspaceEmptyMessage); continue; } File workspace = new File(instancePath); if (!workspace.exists()) { workspace.mkdir(); } try { String path = workspace.getAbsolutePath().replace( File.separatorChar, '/'); url = new URL("file", null, path); } catch (MalformedURLException e) { MessageDialog .openError( shell, IDEWorkbenchMessages.IDEApplication_workspaceInvalidTitle, IDEWorkbenchMessages.IDEApplication_workspaceInvalidMessage); continue; } boolean validWorkspace = checkValidWorkspace(shell, url); if (!validWorkspace) { throw new OperationCanceledException("Invalid workspace location: " + url); } return url; } while (true); }
Source:
public static void main(String[] args) { try { ClientArgs clientArgs = new ClientArgs(args); final NettyPerfClient nettyPerfClient = new NettyPerfClient(clientArgs.host, clientArgs.port, clientArgs.path, clientArgs.concurrency, clientArgs.postBlobTotalSize, clientArgs.postBlobChunkSize, clientArgs.sslPropsFilePath, clientArgs.serviceId, clientArgs.targetAccountName, clientArgs.targetContainerName, clientArgs.customHeaders); Runtime.getRuntime().addShutdownHook(new Thread(() -> { logger.info("Received shutdown signal. Requesting NettyPerfClient shutdown"); nettyPerfClient.shutdown(); })); nettyPerfClient.start(); if (clientArgs.testTime != null) { ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.schedule(nettyPerfClient::shutdown, clientArgs.testTime, TimeUnit.SECONDS); nettyPerfClient.awaitShutdown(); scheduler.shutdownNow(); } } catch (Exception e) { logger.error("Exception during execution of NettyPerfClient", e); } }

Target:
public static void main(String[] args) { try { ClientArgs clientArgs = new ClientArgs(args); final NettyPerfClient nettyPerfClient = new NettyPerfClient(clientArgs.host, clientArgs.port, clientArgs.path, clientArgs.concurrency, clientArgs.postBlobTotalSize, clientArgs.postBlobChunkSize, clientArgs.sslPropsFilePath, clientArgs.serviceId, clientArgs.targetAccountName, clientArgs.targetContainerName, clientArgs.customHeaders); Runtime.getRuntime().addShutdownHook(new Thread(() -> { logger.info("Received shutdown signal. Requesting NettyPerfClient shutdown"); nettyPerfClient.shutdown(); })); nettyPerfClient.start(); ScheduledExecutorService scheduler = null; if (clientArgs.testTime != null) { scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.schedule(nettyPerfClient::shutdown, clientArgs.testTime, TimeUnit.SECONDS); } nettyPerfClient.awaitShutdown(); if (scheduler != null) { Utils.shutDownExecutorService(scheduler, 30, TimeUnit.SECONDS); } } catch (Exception e) { logger.error("Exception during execution of NettyPerfClient", e); } }
Source:
public void visitToken(DetailAST ast) { if (ast.getType() == TokenTypes.PACKAGE_DEF) { samePackageDomainsRegExp = createSamePackageRegexp( samePackageMatchingDepth, ast); } else { final String importFullPath = getFullImportIdent(ast); final int lineNo = ast.getLineNo(); final int endLineNo = ast.getLastChild().getLineNo(); final boolean isStatic = ast.getType() == TokenTypes.STATIC_IMPORT; importToGroupList.add(new ImportDetails(importFullPath, lineNo, endLineNo, getImportGroup(isStatic, importFullPath), isStatic, ast)); } }

Target:
public void visitToken(DetailAST ast) { if (ast.getType() == TokenTypes.PACKAGE_DEF) { samePackageDomainsRegExp = createSamePackageRegexp( samePackageMatchingDepth, ast); } else { final String importFullPath = getFullImportIdent(ast); final boolean isStatic = ast.getType() == TokenTypes.STATIC_IMPORT; importToGroupList.add(new ImportDetails(importFullPath, getImportGroup(isStatic, importFullPath), isStatic, ast)); } }
Source:
protected Map<String, Pair<String, String>> getExclusiveLocks() { if (isImageLockNeeded()) { return Collections.singletonMap(getDisk().getId().toString(), LockMessagesMatchUtil.DISK); } return Collections.EMPTY_MAP; }

Target:
protected Map<String, Pair<String, String>> getExclusiveLocks() { if (getDisk() != null && isImageLockNeeded()) { return Collections.singletonMap(getDisk().getId().toString(), LockMessagesMatchUtil.DISK); } return null; }
Source:
public void testHeaderVersions() throws Exception { for (final String version : SAMFileHeader.ACCEPTABLE_VERSIONS) { testHeaderVersion(version, true); } testHeaderVersion("1.7", false); }

Target:
public void testHeaderVersions() throws Exception { for (final String version : SAMFileHeader.ACCEPTABLE_VERSIONS) { testHeaderVersion(version, true); } testHeaderVersion("1.1", false); }
Source:
public LabelWithToolTip(SafeHtml text) { super(text); tooltipPanel.setWidget(tooltip); tooltipPanel.getElement().getStyle().setZIndex(1); setTitle(text); registerHandlers(); }

Target:
public LabelWithToolTip(SafeHtml text) { this(text.asString()); }
Source:
protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { VmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true); disks.addAll(ImagesHandler.getCinderLeafImages(getDiskDao().getAllForVm(vm.getId()), false)); } for (DiskImage image : disks) { image.setStorageIds(null); } Version clusterCompatibilityVersion = ClusterUtils.getCompatibilityVersion(vm); if (vm.getCustomCompatibilityVersion() == null) { vm.setCustomCompatibilityVersion(clusterCompatibilityVersion); } return new OvfManager().exportVm(vm, new ArrayList<>(disks), clusterCompatibilityVersion); }

Target:
protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { VmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true); disks.addAll(ImagesHandler.getCinderLeafImages(getDiskDao().getAllForVm(vm.getId()), false)); } for (DiskImage image : disks) { image.setStorageIds(null); } return new OvfManager().exportVm(vm, new ArrayList<>(disks), ClusterUtils.getCompatibilityVersion(vm)); }
Source:
public static boolean runJobs(List<Jobby> jobs, HadoopDruidIndexerConfig config) { String failedMessage = null; for (Jobby job : jobs) { if (failedMessage == null) { if (!job.run()) { failedMessage = String.format("Job[%s] failed!", job.getClass()); } } } if (!config.getSchema().getTuningConfig().isLeaveIntermediate()) { if (failedMessage == null || config.getSchema().getTuningConfig().isCleanupOnFailure()) { Path workingPath = config.makeIntermediatePath(); log.info("Deleting path[%s]", workingPath); try { if( workingPath.getFileSystem(injectSystemProperties(new Configuration())).delete(workingPath, true) ){ existing.clear(); } } catch (IOException e) { log.error(e, "Failed to cleanup path[%s]", workingPath); } } } if (failedMessage != null) { throw new ISE(failedMessage); } return true; }

Target:
public static boolean runJobs(List<Jobby> jobs, HadoopDruidIndexerConfig config) { String failedMessage = null; for (Jobby job : jobs) { if (failedMessage == null) { if (!job.run()) { failedMessage = String.format("Job[%s] failed!", job.getClass()); } } } if (!config.getSchema().getTuningConfig().isLeaveIntermediate()) { if (failedMessage == null || config.getSchema().getTuningConfig().isCleanupOnFailure()) { Path workingPath = config.makeIntermediatePath(); log.info("Deleting path[%s]", workingPath); try { workingPath.getFileSystem(injectSystemProperties(new Configuration())).delete(workingPath, true); } catch (IOException e) { log.error(e, "Failed to cleanup path[%s]", workingPath); } } } if (failedMessage != null) { throw new ISE(failedMessage); } return true; }
Source:
public Builder<SecurityConfiguration> configure(OperationContext context, ModelNode model) throws OperationFailedException { ModelNode sslContextRef = SSL_CONTEXT.resolveModelAttribute(context, model); if (sslContextRef.isDefined()) { this.sslContextDependency = new InjectedValueDependency<>(CommonUnaryRequirement.SSL_CONTEXT.getServiceName(context, sslContextRef.asString()), SSLContext.class); } return this; }

Target:
public Builder<SecurityConfiguration> configure(OperationContext context, ModelNode model) throws OperationFailedException { String sslContext = SSL_CONTEXT.resolveModelAttribute(context, model).asStringOrNull(); this.sslContextDependency = (sslContext != null) ? new InjectedValueDependency<>(CommonUnaryRequirement.SSL_CONTEXT.getServiceName(context, sslContext), SSLContext.class) : null; return this; }
Source:
public static VmPropertiesUtils getInstance() { if (vmPropertiesUtils == null) { vmPropertiesUtils = new VmPropertiesUtils(); } return vmPropertiesUtils; }

Target:
public static VmPropertiesUtils getInstance() { if (vmPropertiesUtils == null) { synchronized (VmPropertiesUtils.class) { if (vmPropertiesUtils == null) { vmPropertiesUtils = new VmPropertiesUtils(); } } } return vmPropertiesUtils; }
Source:
public void testRebaseWithUncommittedTopicChange() throws Exception { writeTrashFile(FILE1, "file1"); git.add().addFilepattern(FILE1).call(); RevCommit commit = git.commit().setMessage("commit1").call(); createBranch(commit, "refs/heads/topic"); checkoutBranch("refs/heads/topic"); writeTrashFile("file2", "file2"); git.add().addFilepattern("file2").call(); git.commit().setMessage("commit2").call(); checkoutBranch("refs/heads/master"); writeTrashFile(FILE1, "modified file1"); git.add().addFilepattern(FILE1).call(); git.commit().setMessage("commit3").call(); checkoutBranch("refs/heads/topic"); File uncommittedFile = writeTrashFile("file2", "uncommitted file2"); git.add().addFilepattern("file2").call(); RebaseResult result = git.rebase().setUpstream("refs/heads/master") .call(); assertEquals(result.getStatus(), Status.CONFLICTS); assertEquals(result.getConflicts().size(), 1); assertEquals(result.getConflicts().get(0), "file2"); checkFile(uncommittedFile, "uncommitted file2"); assertEquals(RepositoryState.SAFE, git.getRepository().getRepositoryState()); }

Target:
public void testRebaseWithUncommittedTopicChange() throws Exception { writeTrashFile(FILE1, "file1"); git.add().addFilepattern(FILE1).call(); RevCommit commit = git.commit().setMessage("commit1").call(); createBranch(commit, "refs/heads/topic"); checkoutBranch("refs/heads/topic"); writeTrashFile("file2", "file2"); git.add().addFilepattern("file2").call(); git.commit().setMessage("commit2").call(); checkoutBranch("refs/heads/master"); writeTrashFile(FILE1, "modified file1"); git.add().addFilepattern(FILE1).call(); git.commit().setMessage("commit3").call(); checkoutBranch("refs/heads/topic"); File uncommittedFile = writeTrashFile("file2", "uncommitted file2"); git.add().addFilepattern("file2").call(); RebaseResult result = git.rebase().setUpstream("refs/heads/master") .call(); assertEquals(Status.CONFLICTS, result.getStatus()); assertEquals(1, result.getConflicts().size()); assertEquals("file2", result.getConflicts().get(0)); checkFile(uncommittedFile, "uncommitted file2"); assertEquals(RepositoryState.SAFE, git.getRepository().getRepositoryState()); }
Source:
private DbUser buildUser(T params, String authzName) { DbUser dbUser = dbUserDao.getByExternalId(authzName, params.getPrincipalId()); DbUser user = new DbUser(dbUser); user.setId(dbUser == null ? Guid.newGuid() : dbUser.getId()); user.setExternalId(params.getPrincipalId()); user.setDomain(authzName); user.setEmail(params.getEmail()); user.setFirstName(params.getFirstName()); user.setLastName(params.getLastName()); user.setNamespace(params.getNamespace()); user.setLoginName(params.getPrincipalName()); List<Guid> groupIds = new ArrayList<>(); List<String> groupRecordIds = new ArrayList<>(); flatGroups((Collection<ExtMap>) params.getGroupIds(), groupRecordIds); for (String groupId : groupRecordIds) { DbGroup dbGroup = dbGroupDao.getByExternalId(authzName, groupId); if (dbGroup != null) { groupIds.add(dbGroup.getId()); } } user.setGroupIds(groupIds); if (dbUser == null) { dbUserDao.save(user); } else if (!dbUser.equals(user)) { dbUserDao.update(user); } return user; }

Target:
private DbUser buildUser(T params, String authzName) { DbUser dbUser = dbUserDao.getByExternalId(authzName, params.getPrincipalId()); DbUser user = dbUser != null ? new DbUser(dbUser) : new DbUser(); user.setId(dbUser == null ? Guid.newGuid() : dbUser.getId()); user.setExternalId(params.getPrincipalId()); user.setDomain(authzName); user.setEmail(params.getEmail()); user.setFirstName(params.getFirstName()); user.setLastName(params.getLastName()); user.setNamespace(params.getNamespace()); user.setLoginName(params.getPrincipalName()); List<Guid> groupIds = new ArrayList<>(); List<String> groupRecordIds = new ArrayList<>(); flatGroups((Collection<ExtMap>) params.getGroupIds(), groupRecordIds); for (String groupId : groupRecordIds) { DbGroup dbGroup = dbGroupDao.getByExternalId(authzName, groupId); if (dbGroup != null) { groupIds.add(dbGroup.getId()); } } user.setGroupIds(groupIds); boolean isAdmin = !roleDao.getAnyAdminRoleForUserAndGroups(user.getId(), StringUtils.join(user.getGroupIds(), ",")).isEmpty(); user.setAdmin(isAdmin); if (dbUser == null) { dbUserDao.save(user); } else if (!dbUser.equals(user)) { dbUserDao.update(user); } return user; }
Source:
boolean mergeWithDefaults(OCD ocd, Map<String, Object> properties) throws KuraException { boolean changed = false; Set<String> keys; if (properties != null) { keys = properties.keySet(); } else { keys = new HashSet<String>(); } Map<String, Object> defaults = getDefaultProperties(ocd); Set<String> defaultsKeys = defaults.keySet(); defaultsKeys.removeAll(keys); if (!defaultsKeys.isEmpty()) { changed = true; s_logger.info("Merging configuration for pid: {}", ocd.getId()); for (String key : defaultsKeys) { Object value = defaults.get(key); properties.put(key, value); s_logger.debug("Merged configuration properties with property with name: and default value {}", key, value); } } return changed; }

Target:
boolean mergeWithDefaults(OCD ocd, Map<String, Object> properties) throws KuraException { boolean changed = false; Set<String> keys = properties.keySet(); Map<String, Object> defaults = getDefaultProperties(ocd); Set<String> defaultsKeys = defaults.keySet(); defaultsKeys.removeAll(keys); if (!defaultsKeys.isEmpty()) { changed = true; logger.info("Merging configuration for pid: {}", ocd.getId()); for (String key : defaultsKeys) { Object value = defaults.get(key); properties.put(key, value); logger.debug("Merged configuration properties with property with name: and default value {}", key, value); } } return changed; }
Source:
private ComponentDto getByKey(DbSession dbSession, String key, String label) { return checkComponent(() -> dbClient.componentDao().selectByKey(dbSession, key), () -> format("%s key '%s' not found", label, key)); }

Target:
private ComponentDto getByKey(DbSession dbSession, String key, String label) { return checkComponent(dbClient.componentDao().selectByKey(dbSession, key), "%s key '%s' not found", label, key); }
Source:
private Optional<AttributeValidationReport> generateValidationReports( List<AttributeValidationReport> validationReportList) { if (CollectionUtils.isEmpty(validationReportList)) { return Optional.empty(); } AttributeValidationReportImpl result = new AttributeValidationReportImpl(); for (AttributeValidationReport attributeValidationReport : validationReportList) { Set<ValidationViolation> validationViolations = attributeValidationReport.getAttributeValidationViolations(); Set<String> suggestedValues = attributeValidationReport.getSuggestedValues(); if (CollectionUtils.isEmpty(validationViolations)) { return Optional.empty(); } result.addViolations(validationViolations); if (CollectionUtils.isNotEmpty(suggestedValues)) { result.addSuggestedValues(suggestedValues); } } return Optional.of(result); }

Target:
private Optional<AttributeValidationReport> generateValidationReports( List<AttributeValidationReport> validationReportList) { if (CollectionUtils.isEmpty(validationReportList)) { return Optional.empty(); } AttributeValidationReportImpl result = new AttributeValidationReportImpl(); for (AttributeValidationReport attributeValidationReport : validationReportList) { Set<ValidationViolation> validationViolations = attributeValidationReport.getAttributeValidationViolations(); Set<String> suggestedValues = attributeValidationReport.getSuggestedValues(); result.addViolations(validationViolations); if (CollectionUtils.isNotEmpty(suggestedValues)) { result.addSuggestedValues(suggestedValues); } } return Optional.of(result); }
Source:
public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException { opRef.getValue().getOperatorTag(); if (hasRun && !firstOpRef.equals(opRef)) { return false; } else { firstOpRef = opRef; } boolean modified = false; boolean modified_last_pass; do { usedVariables.clear(); modified_last_pass = rewritePreTrackingUsedVariables(opRef, context); if (modified_last_pass) { modified = modified_last_pass; } } while (modified_last_pass); hasRun = true; return modified; }

Target:
public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException { if (hasRun && !firstOpRef.equals(opRef)) { return false; } else { firstOpRef = opRef; } boolean modified = false; boolean modified_last_pass; do { usedVariables.clear(); modified_last_pass = rewritePreTrackingUsedVariables(opRef, context); if (modified_last_pass) { modified = modified_last_pass; } } while (modified_last_pass); hasRun = true; return modified; }
Source:
public ProjectApi create(ProjectInput in) throws RestApiException { try { if (name == null) { throw new RestApiException("Project already exists"); } if (in.name != null && !name.equals(in.name)) { throw new RestApiException("name must match input.name"); } createProjectFactory.get().create(name) .apply(TopLevelResource.INSTANCE, in); return projectApi.create(projects.parse(name)); } catch (BadRequestException | UnprocessableEntityException | ResourceConflictException | ResourceNotFoundException | ProjectCreationFailedException | IOException e) { throw new RestApiException("Cannot create project", e); } }

Target:
public ProjectApi create(ProjectInput in) throws RestApiException { try { if (name == null) { throw new ResourceConflictException("Project already exists"); } if (in.name != null && !name.equals(in.name)) { throw new RestApiException("name must match input.name"); } createProjectFactory.get().create(name) .apply(TopLevelResource.INSTANCE, in); return projectApi.create(projects.parse(name)); } catch (BadRequestException | UnprocessableEntityException | ResourceNotFoundException | ProjectCreationFailedException | IOException e) { throw new RestApiException("Cannot create project", e); } }
Source:
public List<String> getParameterDefinitionNames() { return new AbstractList<String>() { public String get(int index) { if (parameterDefinitions != null && parameterDefinitions.get(index) != null) { return parameterDefinitions.get(index).getName(); } else { return ""; } } public int size() { if (parameterDefinitions != null) { return parameterDefinitions.size(); } else { return 0; } } }; }

Target:
public List<String> getParameterDefinitionNames() { return new AbstractList<String>() { public String get(int index) { return parameterDefinitions.get(index).getName(); } public int size() { return parameterDefinitions.size(); } }; }
Source:
protected void testExecute_withCourseIdAndSectionName_shouldUpdatePrivilegesInSectionLevel() { InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); String[] submissionParams = new String[] { Const.ParamsNames.INSTRUCTOR_ID, instructor1OfCourse1.getGoogleId(), Const.ParamsNames.COURSE_ID, instructor1OfCourse1.courseId, }; InstructorPrivilegeUpdateRequest reqBody = new InstructorPrivilegeUpdateRequest(); reqBody.setCanViewStudentInSections(false); reqBody.setCanSubmitSessionInSections(true); reqBody.setSectionName("TUT1"); UpdateInstructorPrivilegeAction action = getAction(reqBody, submissionParams); JsonResult result = getJsonResult(action); assertEquals(HttpStatus.SC_OK, result.getStatusCode()); InstructorPrivilegeData response = (InstructorPrivilegeData) result.getOutput(); assertTrue(response.isCanModifyCourse()); assertTrue(response.isCanModifySession()); assertTrue(response.isCanModifyStudent()); assertTrue(response.isCanModifyInstructor()); assertFalse(response.isCanViewStudentInSections()); assertTrue(response.isCanSubmitSessionInSections()); assertFalse(response.isCanViewSessionInSections()); assertFalse(response.isCanModifySessionCommentsInSections()); }

Target:
protected void testExecute_withCourseIdAndSectionName_shouldUpdatePrivilegesInSectionLevel() { InstructorAttributes helper1OfCourse1 = typicalBundle.instructors.get("helperOfCourse1"); assertFalse(helper1OfCourse1.privileges.isAllowedForPrivilege( "TUT1", Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_STUDENT_IN_SECTIONS)); assertFalse(helper1OfCourse1.privileges.isAllowedForPrivilege( "TUT1", Const.ParamsNames.INSTRUCTOR_PERMISSION_SUBMIT_SESSION_IN_SECTIONS)); assertFalse(helper1OfCourse1.privileges.isAllowedForPrivilege( "TUT1", Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_SESSION_IN_SECTIONS)); assertFalse(helper1OfCourse1.privileges.isAllowedForPrivilege( "TUT1", Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION_COMMENT_IN_SECTIONS)); String[] submissionParams = new String[] { Const.ParamsNames.INSTRUCTOR_EMAIL, helper1OfCourse1.getEmail(), Const.ParamsNames.COURSE_ID, helper1OfCourse1.courseId, }; InstructorPrivilegeUpdateRequest reqBody = new InstructorPrivilegeUpdateRequest(); reqBody.setCanViewStudentInSections(true); reqBody.setCanSubmitSessionInSections(true); reqBody.setCanViewSessionInSections(true); reqBody.setCanModifySessionCommentsInSections(true); reqBody.setSectionName("TUT1"); UpdateInstructorPrivilegeAction action = getAction(reqBody, submissionParams); JsonResult result = getJsonResult(action); assertEquals(HttpStatus.SC_OK, result.getStatusCode()); InstructorPrivilegeData response = (InstructorPrivilegeData) result.getOutput(); assertFalse(response.isCanModifyCourse()); assertFalse(response.isCanModifySession()); assertFalse(response.isCanModifyStudent()); assertFalse(response.isCanModifyInstructor()); assertTrue(response.isCanViewStudentInSections()); assertTrue(response.isCanSubmitSessionInSections()); assertTrue(response.isCanViewSessionInSections()); assertTrue(response.isCanModifySessionCommentsInSections()); }
Source:
private static Set<String> getGroupKeys(List<VariableReferenceExpression> groupingKeys) { Set<String> groupKeySet = new HashSet<>(); for (VariableReferenceExpression groupingKey : groupingKeys) { groupKeySet.add(groupingKey.getName()); } return groupKeySet; }

Target:
private static Set<String> getGroupKeys(List<VariableReferenceExpression> groupingKeys) { Set<String> groupKeySet = new HashSet<>(); groupingKeys.forEach(groupingKey -> groupKeySet.add(groupingKey.getName())); return groupKeySet; }
Source:
private boolean isConstructor(TypeSet types) { boolean isUnknown = types.contains(Kind.UNKNOWN); boolean isConstructor = true; Type type = types.getType(); if (type != null) { if (type.callability().equals(Callability.NON_CALLABLE)) { isConstructor = false; } else if (considerJSDoc && type.kind().equals(Kind.FUNCTION)) { isConstructor = hasJSDocAnnotation(((FunctionType) type).functionTree()); } } return isConstructor; }

Target:
private boolean isConstructor(TypeSet types) { boolean isConstructor = true; Type type = types.getUniqueKnownType(); if (type != null) { if (type.callability().equals(Callability.NON_CALLABLE)) { isConstructor = false; } else if (considerJSDoc && type.kind().equals(Kind.FUNCTION)) { isConstructor = hasJSDocAnnotation(((FunctionType) type).functionTree()); } } return isConstructor; }
Source:
public ValidationResult(VdcBllMessages message, String... variableReplacements) { if (message == null) { throw new IllegalArgumentException("message must not be null"); } this.message = message; this.variableReplacements = variableReplacements == null ? null : Collections.unmodifiableList(Arrays.asList(variableReplacements)); }

Target:
public ValidationResult(VdcBllMessages message, String... variableReplacements) { if (message == null) { throw new IllegalArgumentException("message must not be null"); } this.message = message; if (variableReplacements != null) { this.variableReplacements = Collections.unmodifiableList(Arrays.asList(variableReplacements)); } }
Source:
public AddProblemFactChangesCommand() { super(); }

Target:
public AddProblemFactChangesCommand() { }
Source:
public void installMaven() { if (!new File(System.getProperty("user.home") + "\\apache-maven-" + mvnVersion).exists()) { String downloadPath = System.getProperty("user.home") + "\\mvn_setup.zip"; download("<LINK_0>" + mvnVersion + "-bin.zip", downloadPath); unzipFile(downloadPath, System.getProperty("user.home")); } mvnCommand = System.getProperty("user.home") + "\\apache-maven-" + mvnVersion + "\\bin\\mvn" + addSystemEnding(); }

Target:
public void installMaven() throws Exception { File tmp = File.createTempFile("mvn_setup", "zip"); List<?> mirrors = getListOfMirrors(); for (int i = 0; i < mirrors.size(); i++) { if (download(String.valueOf(mirrors.get(i)) + "apache-maven-" + readMvnVersionFromPropFile() + "-bin.zip", tmp.getAbsolutePath())) { break; } if (i == mirrors.size() - 1) { log.error("No valid mirror found!"); } } if (mirrors.size() != 0) { unzipFile(tmp.getAbsolutePath(), System.getProperty("karaf.data")); } }
Source:
protected Name decomposeName(CompositeName compositeName) throws NamingException { if (compositeName.isEmpty()) { return new SimpleName(); } final NameParser parser = getNativeNameParser(); final Name name = parser.parse(compositeName.get(0)); if(name.isEmpty())name.add(""); for (int i = 1; i < compositeName.size(); i ++) { final String part = compositeName.get(i); final Name parsed = parser.parse(part); if (parsed.isEmpty()) parsed.add(""); name.addAll(parsed); } return name; }

Target:
protected Name decomposeName(CompositeName compositeName) throws NamingException { final NameParser parser = getNativeNameParser(); if (compositeName.isEmpty()) { return parser.parse(""); } final Name name = parser.parse(compositeName.get(0)); if(name.isEmpty())name.add(""); for (int i = 1; i < compositeName.size(); i ++) { final String part = compositeName.get(i); final Name parsed = parser.parse(part); if (parsed.isEmpty()) parsed.add(""); name.addAll(parsed); } return name; }
Source:
public CompletableFuture<YarnWorkerNode> requestResource(TaskExecutorProcessSpec taskExecutorProcessSpec) { final Optional<Resource> containerResourceOptional = getContainerResource(taskExecutorProcessSpec); final CompletableFuture<YarnWorkerNode> requestResourceFuture = new CompletableFuture<>(); if (containerResourceOptional.isPresent()) { resourceManagerClient.addContainerRequest(getContainerRequest(containerResourceOptional.get())); resourceManagerClient.setHeartbeatInterval(containerRequestHeartbeatIntervalMillis); requestResourceFutures.computeIfAbsent(taskExecutorProcessSpec, ignore -> new ArrayList<>()).add(requestResourceFuture); log.info("Requesting new TaskExecutor container with resource {}.", taskExecutorProcessSpec); } else { requestResourceFuture.completeExceptionally( new ResourceManagerException(String.format("Could not compute the container Resource from the given TaskExecutorProcessSpec %s.", taskExecutorProcessSpec))); } return requestResourceFuture; }

Target:
public CompletableFuture<YarnWorkerNode> requestResource(TaskExecutorProcessSpec taskExecutorProcessSpec) { final Optional<Resource> containerResourceOptional = getContainerResource(taskExecutorProcessSpec); final CompletableFuture<YarnWorkerNode> requestResourceFuture = new CompletableFuture<>(); if (containerResourceOptional.isPresent()) { resourceManagerClient.addContainerRequest(getContainerRequest(containerResourceOptional.get())); resourceManagerClient.setHeartbeatInterval(containerRequestHeartbeatIntervalMillis); requestResourceFutures.computeIfAbsent(taskExecutorProcessSpec, ignore -> new LinkedList<>()).add(requestResourceFuture); log.info("Requesting new TaskExecutor container with resource {}.", taskExecutorProcessSpec); } else { requestResourceFuture.completeExceptionally( new ResourceManagerException(String.format("Could not compute the container Resource from the given TaskExecutorProcessSpec %s.", taskExecutorProcessSpec))); } return requestResourceFuture; }
Source:
public void init(TableDefinition tableDefinition, StreamEventFactory storeEventPool, StreamEventCloner storeEventCloner, ConfigReader configReader, SiddhiAppContext siddhiAppContext, RecordTableHandler recordTableHandler) { if (recordTableHandler != null) { recordTableHandler.init(tableDefinition, new RecordTableHandlerCallback(this), siddhiAppContext); } this.recordTableHandler = recordTableHandler; this.storeEventPool = storeEventPool; init(tableDefinition, configReader); init(tableDefinition, siddhiAppContext, storeEventCloner, configReader); }

Target:
public void init(TableDefinition tableDefinition, StreamEventFactory storeEventPool, StreamEventCloner storeEventCloner, ConfigReader configReader, SiddhiAppContext siddhiAppContext, RecordTableHandler recordTableHandler) { if (recordTableHandler != null) { recordTableHandler.init(tableDefinition, new RecordTableHandlerCallback(this), siddhiAppContext); } this.recordTableHandler = recordTableHandler; this.storeEventPool = storeEventPool; init(tableDefinition, configReader); initCache(tableDefinition, siddhiAppContext, storeEventCloner, configReader); }
Source:
public void setDependencies(List<DependencyNode> dependencies) { if (dependencies == null) { this.dependencies = Collections.emptyList(); this.allDependencies = Collections.emptySet(); } else { this.dependencies = dependencies; Set<String> allDependencies = new HashSet<>(); dependencies.forEach(dependencyNode -> { allDependencies.add(dependencyNode.artifactId); allDependencies.addAll(dependencyNode.allDependencies); }); this.allDependencies = allDependencies; } }

Target:
public void setDependencies(List<DependencyNode> dependencies) { if (dependencies == null) { return; } this.dependencies = dependencies; Set<String> allDependencies = new HashSet<>(); dependencies.forEach(dependencyNode -> { allDependencies.add(dependencyNode.artifactId); allDependencies.addAll(dependencyNode.allDependencies); }); this.allDependencies = allDependencies; }
Source:
public void execute(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, CoreText.IgnoreOperation_taskName, paths.size()); try { for (IPath path : paths) { if (monitor.isCanceled()) { break; } if (RepositoryUtil.canBeAutoIgnored(path)) { addIgnore(progress.newChild(1), path); } progress.worked(1); } } catch (CoreException e) { throw e; } catch (Exception e) { throw new CoreException(Activator.error( CoreText.IgnoreOperation_error, e)); } }

Target:
public void execute(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, CoreText.IgnoreOperation_taskName, paths.size()); try { for (IPath path : paths) { if (monitor.isCanceled()) { break; } if (RepositoryUtil.canBeAutoIgnored(path)) { addIgnore(progress.newChild(1), path); } else { progress.worked(1); } } } catch (CoreException e) { throw e; } catch (Exception e) { throw new CoreException(Activator.error( CoreText.IgnoreOperation_error, e)); } }
Source:
public static void main(String[] args) throws ParseException, IOException { Options options = new Options(); options.addOption("i", true, "Jupyter notebook file"); options.addOption("o", true, "Zeppelin note file. Default: note.json"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (!cmd.hasOption("i")) { new HelpFormatter().printHelp("java " + JupyterUtil.class.getName(), options); System.exit(1); } Path jupyterPath = Paths.get(cmd.getOptionValue("i")); Path zeppelinPath = Paths.get(cmd.hasOption("o") ? cmd.getOptionValue("o") : "note.json"); Note note = new JupyterUtil() .getNote(new BufferedReader(new FileReader(jupyterPath.toFile())), "python", "md"); try (FileWriter fw = new FileWriter(zeppelinPath.toFile())) { new GsonBuilder().setPrettyPrinting().create() .toJson(note, fw); } }

Target:
public static void main(String[] args) throws ParseException, IOException { Options options = new Options(); options.addOption("i", true, "Jupyter notebook file"); options.addOption("o", true, "Zeppelin note file. Default: note.json"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (!cmd.hasOption("i")) { new HelpFormatter().printHelp("java " + JupyterUtil.class.getName(), options); System.exit(1); } Path jupyterPath = Paths.get(cmd.getOptionValue("i")); Path zeppelinPath = Paths.get(cmd.hasOption("o") ? cmd.getOptionValue("o") : "note.json"); try (BufferedReader in = new BufferedReader(new FileReader(jupyterPath.toFile())); FileWriter fw = new FileWriter(zeppelinPath.toFile())) { Note note = new JupyterUtil().getNote(in, "python", "md"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(note, fw); } }
Source:
public IndexingConfigurationBuilder index(Index index) { if (index != Index.NONE) enabled(true); attributes.attribute(INDEX).set(index); return this; }

Target:
public IndexingConfigurationBuilder index(Index index) { enabled(index != null && index != Index.NONE); attributes.attribute(INDEX).set(index); return this; }
Source:
public final void setInput(final IWorkbenchPart part, final ISelection selection) { if (selection instanceof IStructuredSelection && ((IStructuredSelection) selection).getFirstElement() instanceof EObject) { final EObject selectedElement = (EObject) ((IStructuredSelection) selection).getFirstElement(); final Registry registry = ComposedAdapterFactory.Descriptor.Registry.INSTANCE; final Collection<Object> types = new ArrayList<>(); types.add(selectedElement.eClass().getEPackage()); types.add(IItemPropertySource.class); final Descriptor descriptor = registry.getDescriptor(types); final AdapterFactory adapterFactory = descriptor.createAdapterFactory(); this.page.setPropertySourceProvider(new AdapterFactoryContentProvider(adapterFactory) { @Override protected IPropertySource createPropertySource(final Object object, final IItemPropertySource itemPropertySource) { return GMFDocumentStructureTemplateSection.this.createPropertySource(object, itemPropertySource); } }); } else { this.page.setPropertySourceProvider(null); } super.setInput(part, selection); }

Target:
public final void setInput(final IWorkbenchPart part, final ISelection selection) { if (selection instanceof IStructuredSelection && ((IStructuredSelection) selection).getFirstElement() instanceof EObject) { final EObject selectedElement = (EObject) ((IStructuredSelection) selection).getFirstElement(); final Registry registry = ComposedAdapterFactory.Descriptor.Registry.INSTANCE; final Collection<Object> types = new ArrayList<>(2); types.add(selectedElement.eClass().getEPackage()); types.add(IItemPropertySource.class); final Descriptor descriptor = registry.getDescriptor(types); final AdapterFactory adapterFactory = descriptor.createAdapterFactory(); this.page.setPropertySourceProvider(new AdapterFactoryContentProvider(adapterFactory) { @Override protected IPropertySource createPropertySource(final Object object, final IItemPropertySource itemPropertySource) { return GMFDocumentStructureTemplateSection.this.createPropertySource(object, itemPropertySource); } }); } else { this.page.setPropertySourceProvider(null); } super.setInput(part, selection); }
Source:
public AnnotatedTypeMirror visitArrayAccess(ArrayAccessTree node, AnnotatedTypeFactory f) { Pair<Tree, AnnotatedTypeMirror> preAssCtxt = f.visitorState.getAssignmentContext(); try { f.visitorState.setAssignmentContext(null); AnnotatedTypeMirror type = f.getAnnotatedType(node.getExpression()); if (type instanceof AnnotatedArrayType) { return ((AnnotatedArrayType) type).getComponentType(); } else if (type instanceof AnnotatedWildcardType) { AnnotatedWildcardType wc = (AnnotatedWildcardType) type; AnnotatedTypeMirror wcbound = wc.getExtendsBound(); if (wcbound instanceof AnnotatedArrayType) { return ((AnnotatedArrayType) wcbound).getComponentType(); } } throw new BugInCF("Unexpected type: " + type); } finally { f.visitorState.setAssignmentContext(preAssCtxt); } }

Target:
public AnnotatedTypeMirror visitArrayAccess(ArrayAccessTree node, AnnotatedTypeFactory f) { Pair<Tree, AnnotatedTypeMirror> preAssCtxt = f.visitorState.getAssignmentContext(); try { f.visitorState.setAssignmentContext(null); AnnotatedTypeMirror type = f.getAnnotatedType(node.getExpression()); if (type.getKind() == TypeKind.ARRAY) { return ((AnnotatedArrayType) type).getComponentType(); } else if (type.getKind() == TypeKind.WILDCARD && ((AnnotatedWildcardType) type).isUninferredTypeArgument()) { AnnotatedTypeMirror wcbound = ((AnnotatedWildcardType) type).getExtendsBound(); if (wcbound instanceof AnnotatedArrayType) { return ((AnnotatedArrayType) wcbound).getComponentType(); } } throw new BugInCF("Unexpected type: " + type); } finally { f.visitorState.setAssignmentContext(preAssCtxt); } }
Source:
public String scheduleRequest(String containerId, String payload, String marshallingType) { JobRequestInstance jobRequest = null; if (containerId != null && !containerId.isEmpty()) { logger.debug("About to unmarshal job request from payload: '{}' using container marshaller", payload, containerId); jobRequest = marshallerHelper.unmarshal(containerId, payload, marshallingType, JobRequestInstance.class); jobRequest.getData().put("deploymentId", containerId); } else { logger.debug("About to unmarshal job request from payload: '{}' using server marshaller", payload); jobRequest = marshallerHelper.unmarshal(payload, marshallingType, JobRequestInstance.class); } Long requestId = null; if(!validateCommand(jobRequest.getCommand())){ throw new IllegalArgumentException("Invalid command type"); } if (jobRequest.getScheduledDate() != null) { logger.debug("Scheduling job at future date '{}' for request {}", jobRequest.getScheduledDate(), jobRequest); requestId = executorService.scheduleRequest(jobRequest.getCommand(), jobRequest.getScheduledDate(), new CommandContext(jobRequest.getData())); } else { logger.debug("Scheduling job at current date '{}' for request {}", new Date(), jobRequest); requestId = executorService.scheduleRequest(jobRequest.getCommand(), new CommandContext(jobRequest.getData())); } String response = marshallerHelper.marshal(marshallingType, requestId); return response; }

Target:
public String scheduleRequest(String containerId, String payload, String marshallingType) { JobRequestInstance jobRequest = null; if (containerId != null && !containerId.isEmpty()) { logger.debug("About to unmarshal job request from payload: '{}' using container marshaller", payload, containerId); jobRequest = marshallerHelper.unmarshal(containerId, payload, marshallingType, JobRequestInstance.class); jobRequest.getData().put("deploymentId", containerId); } else { logger.debug("About to unmarshal job request from payload: '{}' using server marshaller", payload); jobRequest = marshallerHelper.unmarshal(payload, marshallingType, JobRequestInstance.class); } Long requestId = null; if(!validateCommand(jobRequest.getCommand())){ throw new IllegalArgumentException("Invalid command type "+jobRequest.getCommand()); } if (jobRequest.getScheduledDate() != null) { logger.debug("Scheduling job at future date '{}' for request {}", jobRequest.getScheduledDate(), jobRequest); requestId = executorService.scheduleRequest(jobRequest.getCommand(), jobRequest.getScheduledDate(), new CommandContext(jobRequest.getData())); } else { logger.debug("Scheduling job at current date '{}' for request {}", new Date(), jobRequest); requestId = executorService.scheduleRequest(jobRequest.getCommand(), new CommandContext(jobRequest.getData())); } String response = marshallerHelper.marshal(marshallingType, requestId); return response; }
Source:
MetadataClientDriver initialize(ClientConfiguration conf, ScheduledExecutorService scheduler, StatsLogger statsLogger, Optional<Object> ctx) throws MetadataException; String getScheme(); RegistrationClient getRegistrationClient(); LedgerManagerFactory getLedgerManagerFactory() throws MetadataException; LayoutManager getLayoutManager(); @Override void close(); @FunctionalInterface interface ConnectionExpiredListener { void onConnectionExpired(); }

Target:
MetadataClientDriver initialize(ClientConfiguration conf, ScheduledExecutorService scheduler, StatsLogger statsLogger, Optional<Object> ctx) throws MetadataException; String getScheme(); RegistrationClient getRegistrationClient(); LedgerManagerFactory getLedgerManagerFactory() throws MetadataException; LayoutManager getLayoutManager(); @Override void close(); @FunctionalInterface interface SessionStateListener { void onSessionExpired(); }
Source:
public void testReadingBounds() { fTrace.indexTrace(true); assertEquals(fTrace.getStartTime(), fTrace.readStart()); assertEquals(fTrace.getEndTime(), fTrace.readEnd()); }

Target:
public void testReadingBounds() { ITmfTimestamp start = fTrace.readStart(); ITmfTimestamp end = fTrace.readEnd(); fTrace.indexTrace(true); assertEquals(fTrace.getStartTime(), start); assertEquals(fTrace.getEndTime(), end); }
Source:
public String render(final GetTapesResult obj) throws JsonProcessingException { final Tapes result = obj.getTapes(); final CommonJsonView view = CommonJsonView.newView(CommonJsonView.Status.OK); if( (result == null) || (null == result.getTapes()) ){ view.message("You do not have any buckets"); return JsonMapper.toJson(view); } return JsonMapper.toJson(view.data(result)); }

Target:
public String render(final GetTapesResult obj) throws JsonProcessingException { final Tapes result = obj.getTapes(); final CommonJsonView view = CommonJsonView.newView(CommonJsonView.Status.OK); if( (result == null) || (null == result.getTapes()) ){ view.message("You do not have any tapes"); return JsonMapper.toJson(view); } return JsonMapper.toJson(view.data(result)); }
Source:
public void setWatchingDirectoryChanges(boolean watchDirectoryChanges) { this.watchingDirectoryChanges = watchDirectoryChanges; }

Target:
public final void setWatchingDirectoryChanges(boolean watchDirectoryChanges) { this.watchingDirectoryChanges = watchDirectoryChanges; }
Source:
CacheEntry<K, V> toCacheEntry(Object o) { if (o instanceof Map.Entry) { Map.Entry<K, V> entry = (Map.Entry<K, V>) o; K key = entry.getKey(); K newKey = keyToStorage(key); V value = entry.getValue(); V newValue = valueToStorage(value); if (key != newKey || value != newValue) { if (o instanceof CacheEntry) { CacheEntry returned = (CacheEntry) o; return convertEntry(newKey, newValue, returned); } else { return entryFactory.create(newKey, newValue, (Metadata) null); } } if (entry instanceof CacheEntry) { return (CacheEntry<K, V>) entry; } else { return entryFactory.create(entry.getKey(), entry.getValue(), (Metadata) null); } } return null; }

Target:
CacheEntry<K, V> toCacheEntry(Object o) { if (o instanceof Map.Entry) { Map.Entry<K, V> entry = (Map.Entry<K, V>) o; K key = entry.getKey(); K newKey = keyToStorage(key); V value = entry.getValue(); V newValue = valueToStorage(value); if (key != newKey || value != newValue) { if (o instanceof CacheEntry) { CacheEntry returned = (CacheEntry) o; return convertEntry(newKey, newValue, returned); } else { return entryFactory.create(newKey, newValue, (Metadata) null); } } if (entry instanceof CacheEntry) { return (CacheEntry<K, V>) entry; } else { return entryFactory.create(key, value, (Metadata) null); } } return null; }