text:
package org.wso2.ei.businessprocess.integration.tests.humantasks;

import org.apache.axis2.AxisFault;
import org.apache.axis2.databinding.types.URI;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import org.wso2.ei.businessprocess.integration.common.clients.humantasks.HumanTaskClientApiClient;
import org.wso2.ei.businessprocess.integration.common.clients.humantasks.HumanTaskPackageManagementClient;
import org.wso2.ei.businessprocess.integration.common.utils.BPSMasterTest;
import org.wso2.ei.businessprocess.integration.common.utils.BPSTestConstants;
import org.wso2.ei.businessprocess.integration.common.utils.RequestSender;
import org.wso2.carbon.automation.engine.FrameworkConstants;
import org.wso2.carbon.automation.engine.context.AutomationContext;
import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil;
import org.wso2.carbon.humantask.stub.ui.task.client.api.types.*;
import org.wso2.carbon.integration.common.admin.client.UserManagementClient;
import org.wso2.carbon.integration.common.utils.LoginLogoutClient;

import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * This test case test followings scenarios.
 * - PeopleAssignment.
 * - Expression Based People Assignment.
 * - Literal Based People Assignment.
 * - Excluded Owner
 * - Xpath functions.
 * - Union
 * - Except
 * - intersect
 */
public class HumanTaskPeopleAssignment extends BPSMasterTest {

	private static final Log log = LogFactory.getLog(HumanTaskPeopleAssignment.class);
	//Test Automation API Clients
	private HumanTaskClientApiClient clerk1Client, clerk2Client, clerk3Client, clerk4Client, clerk5Client, clerk6Client,
			manager1Client, manager2Client, manager3Client;
	private HumanTaskPackageManagementClient humanTaskPackageManagementClient;
	private UserManagementClient userManagementClient;
	private RequestSender requestSender;
	private URI taskID = null;

	@BeforeClass(alwaysRun = true)
	public void setEnvironment() throws Exception {
		init();  //init master class
		humanTaskPackageManagementClient = new HumanTaskPackageManagementClient(backEndUrl, sessionCookie);
		requestSender = new RequestSender();
		initialize();

		//initialize HT Client API for Clerk1 user
		AutomationContext clerk1AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001",
				FrameworkConstants.SUPER_TENANT_KEY, "clerk1");
		LoginLogoutClient clerk1LoginLogoutClient = new LoginLogoutClient(clerk1AutomationContext);
		String clerk1SessionCookie = clerk1LoginLogoutClient.login();

		clerk1Client = new HumanTaskClientApiClient(backEndUrl, clerk1SessionCookie);

		//initialize HT Client API for Clerk2 user
		AutomationContext clerk2AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001",
				FrameworkConstants.SUPER_TENANT_KEY, "clerk2");
		LoginLogoutClient clerk2LoginLogoutClient = new LoginLogoutClient(clerk2AutomationContext);
		String clerk2SessionCookie = clerk2LoginLogoutClient.login();

		clerk2Client = new HumanTaskClientApiClient(backEndUrl, clerk2SessionCookie);

		//initialize HT Client API for Clerk3 user
		AutomationContext clerk3AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001",
				FrameworkConstants.SUPER_TENANT_KEY, "clerk3");
		LoginLogoutClient clerk3LoginLogoutClient = new LoginLogoutClient(clerk3AutomationContext);
		String clerk3SessionCookie = clerk3LoginLogoutClient.login();

		clerk3Client = new HumanTaskClientApiClient(backEndUrl, clerk3SessionCookie);

		//initialize HT Client API for Clerk4 user
		AutomationContext clerk4AutomationContext =
				new AutomationContext("BPS", "bpsServerInstance0001", FrameworkConstants.SUPER_TENANT_KEY, "clerk4");
		LoginLogoutClient clerk4LoginLogoutClient = new LoginLogoutClient(clerk4AutomationContext);
		String clerk4SessionCookie = clerk4LoginLogoutClient.login();

		clerk4Client = new HumanTaskClientApiClient(backEndUrl, clerk4SessionCookie);

		//initialize HT Client API for Clerk5 user
		AutomationContext clerk5AutomationContext =
				new AutomationContext("BPS", "bpsServerInstance0001", FrameworkConstants.SUPER_TENANT_KEY, "clerk5");
		LoginLogoutClient clerk5LoginLogoutClient = new LoginLogoutClient(clerk5AutomationContext);
		String clerk5SessionCookie = clerk5LoginLogoutClient.login();

		clerk5Client = new HumanTaskClientApiClient(backEndUrl, clerk5SessionCookie);

		//initialize HT Client API for Clerk6 user
		AutomationContext clerk6AutomationContext =
				new AutomationContext("BPS", "bpsServerInstance0001", FrameworkConstants.SUPER_TENANT_KEY, "clerk6");
		LoginLogoutClient clerk6LoginLogoutClient = new LoginLogoutClient(clerk6AutomationContext);
		String clerk6SessionCookie = clerk6LoginLogoutClient.login();

		clerk6Client = new HumanTaskClientApiClient(backEndUrl, clerk6SessionCookie);

		//initialize HT Client API for Manager1 user
		AutomationContext manager1AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001",
				FrameworkConstants.SUPER_TENANT_KEY, "manager1");
		LoginLogoutClient manager1LoginLogoutClient = new LoginLogoutClient(manager1AutomationContext);
		String manager1SessionCookie = manager1LoginLogoutClient.login();
		manager1Client = new HumanTaskClientApiClient(backEndUrl, manager1SessionCookie);

		//initialize HT Client API for Manager2 user
		AutomationContext manager2AutomationContext =
				new AutomationContext("BPS", "bpsServerInstance0001", FrameworkConstants.SUPER_TENANT_KEY, "manager2");
		LoginLogoutClient manager2LoginLogoutClient = new LoginLogoutClient(manager2AutomationContext);
		String manager2SessionCookie = manager2LoginLogoutClient.login();
		manager2Client = new HumanTaskClientApiClient(backEndUrl, manager2SessionCookie);

		//initialize HT Client API for Manager3 user
		AutomationContext manager3AutomationContext = new AutomationContext("BPS", "bpsServerInstance0001",
				FrameworkConstants.SUPER_TENANT_KEY, "manager3");
		LoginLogoutClient manager3LoginLogoutClient = new LoginLogoutClient(manager3AutomationContext);
		String manager3SessionCookie = manager3LoginLogoutClient.login();
		manager3Client = new HumanTaskClientApiClient(backEndUrl, manager3SessionCookie);
	}

	@BeforeGroups(groups = {"wso2.bps.task.people.assignment"})
	protected void initialize() throws Exception {
		log.info("Initializing HumanTask task creation Test...");
		userManagementClient = new UserManagementClient(backEndUrl, sessionCookie);
		addRoles();
		humanTaskPackageManagementClient = new HumanTaskPackageManagementClient(backEndUrl, sessionCookie);
		log.info("Add users success !");
		deployArtifact();
		requestSender.waitForProcessDeployment(backEndUrl + HumanTaskTestConstants.CLAIM_SERVICE);
	}

	/**
	 * deployArtifact() test1 sample Generic Human Roles.
	 * potentialOwners - htd:getInput("ClaimApprovalRequest")/test10:cust/test10:owners
	 * businessAdministrators - htd:union(htd:getInput("ClaimApprovalRequest")/test10:cust/test10:globleAdmins,htd:getInput("ClaimApprovalRequest")/test10:cust/test10:regionalAdmins)
	 * excludedOwners - htd:getInput("ClaimApprovalRequest")/test10:cust/test10:excludedOwners
	 */
	public void deployArtifact() throws Exception {
		final String artifactLocation = FrameworkPathUtil.getSystemResourceLocation() + BPSTestConstants.DIR_ARTIFACTS
				+ File.separator + BPSTestConstants.DIR_HUMAN_TASK + File.separator + HumanTaskTestConstants.DIR_PEOPLE_ASSIGNMENT
				+ File.separator + "test1";
		uploadHumanTaskForTest(HumanTaskTestConstants.CLAIMS_APPROVAL_PACKAGE_ORG_ENTITY_NAME, artifactLocation);
	}

	private void addRoles() throws Exception {
		String[] rc1 = new String[]{HumanTaskTestConstants.CLERK1_USER, HumanTaskTestConstants.CLERK2_USER, HumanTaskTestConstants.CLERK3_USER};
		String[] rc2 = new String[]{HumanTaskTestConstants.CLERK3_USER, HumanTaskTestConstants.CLERK4_USER, HumanTaskTestConstants.CLERK5_USER};
		String[] rc3 = new String[]{HumanTaskTestConstants.CLERK4_USER, HumanTaskTestConstants.CLERK5_USER, HumanTaskTestConstants.CLERK6_USER};
		String[] rm1 = new String[]{HumanTaskTestConstants.MANAGER1_USER, HumanTaskTestConstants.MANAGER2_USER};
		String[] rm2 = new String[]{HumanTaskTestConstants.MANAGER2_USER, HumanTaskTestConstants.MANAGER3_USER};

		userManagementClient.addRole(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE, rc1,
				new String[]{"/permission/admin/login",
						"/permission/admin/manage/humantask/viewtasks"}, false);
		userManagementClient.addRole(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE_2, rc2,
				new String[]{"/permission/admin/login",
						"/permission/admin/manage/humantask/viewtasks"}, false);
		userManagementClient.addRole(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE_3, rc3,
				new String[]{"/permission/admin/login",
						"/permission/admin/manage/humantask/viewtasks"}, false);
		userManagementClient.addRole(HumanTaskTestConstants.REGIONAL_MANAGER_ROLE, rm1,
				new String[]{"/permission/admin/login",
						"/permission/admin/manage/humantask"}, false);
		userManagementClient.addRole(HumanTaskTestConstants.REGIONAL_MANAGER_ROLE_2, rm2,
				new String[]{"/permission/admin/login",
						"/permission/admin/manage/humantask"}, false);
	}

	@Test(groups = {"wso2.bps.task.createTask"}, description = "Create Task 1", priority = 1, singleThreaded = true)
	public void createTask() throws Exception {
		String soapBody =
				"<sch:ClaimApprovalData xmlns:sch=\"http://www.example.com/claims/schema\" xmlns:ns=\"http://docs.oasis-open.org/ns/bpel4people/ws-humantask/types/200803\">\n" +
						"         <sch:cust>\n" +
						"            <sch:id>123</sch:id>\n" +
						"            <sch:firstname>Hasitha</sch:firstname>\n" +
						"            <sch:lastname>Aravinda</sch:lastname>\n" +
						"            <sch:owners>\n" +
						"               <ns:group>" + HumanTaskTestConstants.REGIONAL_CLERKS_ROLE + "</ns:group>\n" +
						"            </sch:owners>\n" +
						"            <sch:excludedOwners>\n" +
						"               <ns:user>" + HumanTaskTestConstants.CLERK3_USER + "</ns:user>\n" +
						"            </sch:excludedOwners>\n" +
						"            <sch:globleAdmins>\n" +
						"               <ns:group>" + HumanTaskTestConstants.REGIONAL_MANAGER_ROLE + "</ns:group>\n" +
						"            </sch:globleAdmins>\n" +
						"            <sch:regionalAdmins>\n" +
						"               <ns:group>" + HumanTaskTestConstants.REGIONAL_MANAGER_ROLE_2 + "</ns:group>\n" +
						"            </sch:regionalAdmins>\n" +
						"         </sch:cust>\n" +
						"         <sch:amount>2500</sch:amount>\n" +
						"         <sch:region>lk</sch:region>\n" +
						"         <sch:priority>9</sch:priority>\n" +
						"      </sch:ClaimApprovalData>";
		String operation = "approve";
		String serviceName = "ClaimService";
		List<String> expectedOutput = new ArrayList<String>();
		expectedOutput.add("taskid>");
		log.info("Calling Service: " + backEndUrl + serviceName);
		requestSender.sendRequest(backEndUrl + serviceName, operation, soapBody, 1, expectedOutput, true);
	}

	@Test(groups = {"wso2.bps.task.createTask"}, description = "Check created Task", priority = 2, singleThreaded = true)
	public void checkCreatedTask() throws Exception {
		//Clerk1 can claim this task.
		TSimpleQueryInput queryInput = new TSimpleQueryInput();
		queryInput.setPageNumber(0);
		queryInput.setSimpleQueryCategory(TSimpleQueryCategory.CLAIMABLE);

		//Query as Clerk1 user
		TTaskSimpleQueryResultSet taskResults = clerk1Client.simpleQuery(queryInput);

		TTaskSimpleQueryResultRow[] rows = taskResults.getRow();

		Assert.assertNotNull(rows, "No tasks found. Task creation has failed. ");
		Assert.assertTrue(rows.length == 1, "There should be only one claimable task in the engine, but found " + rows.length + " tasks.");
	}

	@Test(groups = {"wso2.bps.task.claim"}, description = "Clerk1 claim task", priority = 3, singleThreaded = true)
	public void clerk1Claim() throws Exception {
		//Clerk1 can claim this task.
		TSimpleQueryInput queryInput = new TSimpleQueryInput();
		queryInput.setPageNumber(0);
		queryInput.setSimpleQueryCategory(TSimpleQueryCategory.CLAIMABLE);

		//Query as Clerk1 user
		TTaskSimpleQueryResultSet taskResults = clerk1Client.simpleQuery(queryInput);

		TTaskSimpleQueryResultRow[] rows = taskResults.getRow();
		TTaskSimpleQueryResultRow b4pTask = rows[0];
		this.taskID = b4pTask.getId();
		clerk1Client.claim(taskID);

		TTaskAbstract loadedTask = clerk1Client.loadTask(taskID);
		Assert.assertEquals(loadedTask.getActualOwner().getTUser(), HumanTaskTestConstants.CLERK1_USER,
				"The assignee should be clerk1 !");
		Assert.assertEquals(loadedTask.getStatus().toString(), "RESERVED",
				"The task status should be RESERVED!");
	}

	@Test(groups = {"wso2.bps.task.claim"}, description = "Clerk2 claim task which is RESERVED", priority = 4, singleThreaded = true, expectedExceptions = AxisFault.class)
	public void clerk2Claim() throws Exception {
		//Clerk2 can't claim this task since clerk1 already claimed it.
		//Claim As Clerk2 user
		clerk2Client.claim(this.taskID);
	}

	@Test(groups = {"wso2.bps.task.claim"}, description = "Clerk1 release task", priority = 5, singleThreaded = true)
	public void clerk1Release() throws Exception {
		//Release As Clerk1 user
		clerk1Client.release(this.taskID);
		TTaskAbstract loadedTask = clerk1Client.loadTask(taskID);
		Assert.assertNull(loadedTask.getActualOwner(), "Task has an actual owner. Task Release failed");
		Assert.assertEquals(loadedTask.getStatus().toString(), "READY", "The task status should be READY!");
	}

	@Test(groups = {"wso2.bps.task.claim"}, description = "Clerk2 re-claim task and release", priority = 6, singleThreaded = true)
	public void clerk2ReClaimAndRelease() throws Exception {
		//Login As Clerk2 user
		clerk2Client.claim(this.taskID);
		TTaskAbstract loadedTask = clerk2Client.loadTask(taskID);
		Assert.assertEquals(loadedTask.getActualOwner().getTUser(), HumanTaskTestConstants.CLERK2_USER,
				"The assignee should be clerk2 !");
		Assert.assertEquals(loadedTask.getStatus().toString(), "RESERVED",
				"The task status should be RESERVED!");
		clerk2Client.release(this.taskID);
		loadedTask = clerk2Client.loadTask(taskID);
		Assert.assertNull(loadedTask.getActualOwner(), "Task has an actual owner. Task Release failed");
		Assert.assertEquals(loadedTask.getStatus().toString(), "READY", "The task status should be READY!");
	}

	@Test(groups = {"wso2.bps.task.claim"}, description = "Clerk3 (an excluded owner) try to claim", priority = 7, singleThreaded = true, expectedExceptions = AxisFault.class)
	public void clerk3Claim() throws Exception {
		//Login As Clerk3 user
		clerk3Client.claim(this.taskID);
	}

	@Test(groups = { "wso2.bps.task.xpath" }, description = "Test Xpath operation -Union", priority = 10,
			singleThreaded = true)
	public void testUnion() throws Exception {
		// All 3 manager users should able to perform administrative task.

		//Login As manager1 user
		TPriority tPriority = new TPriority();
		tPriority.setTPriority(BigInteger.valueOf(2));
		manager1Client.setPriority(taskID, tPriority);

		TTaskAbstract taskAfterPriorityChange1 = manager1Client.loadTask(taskID);
		TPriority prio1 = taskAfterPriorityChange1.getPriority();
		int newPriority1Int = prio1.getTPriority().intValue();
		Assert.assertEquals(newPriority1Int, 2, "The new priority should be 2 after the set priority operation");

		//Login As manager3 user
		tPriority = new TPriority();
		tPriority.setTPriority(BigInteger.valueOf(3));
		manager3Client.setPriority(taskID, tPriority);

		taskAfterPriorityChange1 = manager3Client.loadTask(taskID);
		TPriority prio2 = taskAfterPriorityChange1.getPriority();
		int newPriority1Int2 = prio2.getTPriority().intValue();
		Assert.assertEquals(newPriority1Int2, 3, "The new priority should be 3 after the set priority operation");

	}

	/**
	 * deployArtifact() test2 artifact. Sample Generic Human Roles.
	 * potentialOwners - htd:getInput("ClaimApprovalRequest")/test10:cust/test10:owners
	 * businessAdministrators - htd:except(htd:getInput("ClaimApprovalRequest")/test10:cust/test10:globleAdmins,htd:getInput("ClaimApprovalRequest")/test10:cust/test10:regionalAdmins)
	 * excludedOwners - htd:getInput("ClaimApprovalRequest")/test10:cust/test10:excludedOwners
	 */
	@Test(groups = { "wso2.bps.task.xpath" }, description = "Deploy and Create Except HumanTask", priority = 20,
			singleThreaded = true)
	public void deployAndCreateExceptHumanTask() throws Exception {

		final String artifactLocation =
				FrameworkPathUtil.getSystemResourceLocation() + BPSTestConstants.DIR_ARTIFACTS + File.separator +
						BPSTestConstants.DIR_HUMAN_TASK + File.separator + HumanTaskTestConstants.DIR_PEOPLE_ASSIGNMENT +
						File.separator + "test2";
		uploadHumanTaskForTest(HumanTaskTestConstants.CLAIMS_APPROVAL_PACKAGE_ORG_ENTITY_NAME, artifactLocation);
		Thread.sleep(30000); // Wait for new version of task deploy.
		createTask(); // create task
		TSimpleQueryInput queryInput = new TSimpleQueryInput();
		queryInput.setPageNumber(0);
		queryInput.setSimpleQueryCategory(TSimpleQueryCategory.ALL_TASKS);

		//Login As Clerk1 user
		TTaskSimpleQueryResultSet taskResults = clerk1Client.simpleQuery(queryInput);
		TTaskSimpleQueryResultRow[] rows = taskResults.getRow();
		TTaskSimpleQueryResultRow b4pTask = null;
		Assert.assertNotNull(rows, "No tasks found. Task creation has failed. ");
		// looking for the latest task
		for (TTaskSimpleQueryResultRow row : rows) {
			if (b4pTask == null) {
				b4pTask = row;
			} else {
				if (Long.parseLong(b4pTask.getId().toString()) < Long.parseLong(row.getId().toString())) {
					b4pTask = row;
				}
			}
		}

		// Validating Task
		Assert.assertNotNull(b4pTask, "Task creation has failed");
		Assert.assertNotEquals(b4pTask.getId().toString(), this.taskID.toString(), "Task creation failed.");
		this.taskID = b4pTask.getId();

	}

	@Test(groups = {"wso2.bps.task.xpath" }, description = "Test Xpath operation -Except", priority = 21,
			singleThreaded = true)
	public void testExcept() throws Exception {
		// Only Manager1 able to change the priority.
		final int newPriority = 7;
		TPriority tPriority = new TPriority();
		TTaskAbstract taskAfterPriorityChange1;

		tPriority.setTPriority(BigInteger.valueOf(newPriority));
		//Login As manager3 user
		manager1Client.setPriority(taskID, tPriority);
		taskAfterPriorityChange1 = manager1Client.loadTask(taskID);
		TPriority prio2 = taskAfterPriorityChange1.getPriority();
		int newPriority1Int2 = prio2.getTPriority().intValue();
		Assert.assertEquals(newPriority1Int2, newPriority,
				"The new priority should change after setPriority operation.");

	}

	@Test(groups = { "wso2.bps.task.xpath" }, description = "Test Xpath operation - Except negative case",
			priority = 21,
			singleThreaded = true, expectedExceptions = AxisFault.class)
	public void testExceptNegative() throws Exception {
		// Only Manager1 able to change the priority.
		final int newPriority = 8;
		TPriority tPriority = new TPriority();
		TTaskAbstract taskAfterPriorityChange1;

		tPriority.setTPriority(BigInteger.valueOf(newPriority));
		//Login As manager3 user
		manager3Client.setPriority(taskID, tPriority);
		taskAfterPriorityChange1 = manager3Client.loadTask(taskID);
		TPriority prio2 = taskAfterPriorityChange1.getPriority();
		int newPriority1Int2 = prio2.getTPriority().intValue();
		Assert.assertNotEquals(newPriority1Int2, newPriority, "Task priority should not changed.");

	}

	/**
	 * deployArtifact() test3 artifact. Sample Generic Human Roles.
	 * potentialOwners - htd:getInput("ClaimApprovalRequest")/test10:cust/test10:owners
	 * businessAdministrators - htd:intersect(htd:getInput("ClaimApprovalRequest")/test10:cust/test10:globleAdmins,htd:getInput("ClaimApprovalRequest")/test10:cust/test10:regionalAdmins)
	 * excludedOwners - htd:getInput("ClaimApprovalRequest")/test10:cust/test10:excludedOwners
	 */
	@Test(groups = { "wso2.bps.task.xpath" }, description = "Deploy and Create Except HumanTask", priority = 30,
			singleThreaded = true)
	public void deployAndCreateIntersectHumanTask() throws Exception {

		final String artifactLocation =
				FrameworkPathUtil.getSystemResourceLocation() + BPSTestConstants.DIR_ARTIFACTS + File.separator +
						BPSTestConstants.DIR_HUMAN_TASK + File.separator + HumanTaskTestConstants.DIR_PEOPLE_ASSIGNMENT +
						File.separator + "test3";
		uploadHumanTaskForTest(HumanTaskTestConstants.CLAIMS_APPROVAL_PACKAGE_ORG_ENTITY_NAME, artifactLocation);
		Thread.sleep(30000); // Wait for new version of task deploy.
		createTask(); // create task
		TSimpleQueryInput queryInput = new TSimpleQueryInput();
		queryInput.setPageNumber(0);
		queryInput.setSimpleQueryCategory(TSimpleQueryCategory.ALL_TASKS);

		//Login As Clerk1 user
		TTaskSimpleQueryResultSet taskResults = clerk1Client.simpleQuery(queryInput);
		TTaskSimpleQueryResultRow[] rows = taskResults.getRow();
		TTaskSimpleQueryResultRow b4pTask = null;
		Assert.assertNotNull(rows, "No tasks found. Task creation has failed. ");
		// looking for the latest task
		for (TTaskSimpleQueryResultRow row : rows) {
			if (b4pTask == null) {
				b4pTask = row;
			} else {
				if (Long.parseLong(b4pTask.getId().toString()) < Long.parseLong(row.getId().toString())) {
					b4pTask = row;
				}
			}
		}

		// Validating Task
		Assert.assertNotNull(b4pTask, "Task creation has failed");
		Assert.assertNotEquals(b4pTask.getId().toString(), this.taskID.toString(), "Task creation failed.");
		this.taskID = b4pTask.getId();
	}

	@Test(groups = { "wso2.bps.task.xpath" }, description = "Test Xpath operation - Intersect", priority = 31,
			singleThreaded = true)
	public void testIntersect() throws Exception {
		// Only Manager 2 able to change the priority.
		final int newPriority = 8;
		TPriority tPriority = new TPriority();
		TTaskAbstract taskAfterPriorityChange1;

		tPriority.setTPriority(BigInteger.valueOf(newPriority));
		//Login As manager2 user
		manager2Client.setPriority(taskID, tPriority);
		taskAfterPriorityChange1 = manager2Client.loadTask(taskID);
		TPriority prio2 = taskAfterPriorityChange1.getPriority();
		int newPriority1Int2 = prio2.getTPriority().intValue();
		Assert.assertEquals(newPriority1Int2, newPriority,
				"The new priority should change after setPriority operation.");

	}

	@Test(groups = { "wso2.bps.task.xpath" }, description = "Test Xpath operation - Intersect Negative test case",
			priority = 32,
			singleThreaded = true, expectedExceptions = AxisFault.class)
	public void testIntersectNegative() throws Exception {
		// Only Manager1 able to change the priority.
		final int newPriority = 7;
		TPriority tPriority = new TPriority();
		TTaskAbstract taskAfterPriorityChange1;

		tPriority.setTPriority(BigInteger.valueOf(newPriority));
		//Login As manager3 user
		manager3Client.setPriority(taskID, tPriority);
		taskAfterPriorityChange1 = manager3Client.loadTask(taskID);
		TPriority prio2 = taskAfterPriorityChange1.getPriority();
		int newPriority1Int2 = prio2.getTPriority().intValue();
		Assert.assertNotEquals(newPriority1Int2, newPriority, "Task priority should not changed.");

	}

	/**
	 * deployArtifact() test4 artifact.
	 * Potential owners :
	 * <htt:user>clerk1</htt:user>
	 * <htt:user>clerk2</htt:user>
	 * <htt:user>clerk3</htt:user>
	 * <htt:group>regionalClerksRole2</htt:group>
	 */
	@Test(groups = { "wso2.bps.task.literal" }, description = "Deploy and Create Literal based HumanTask",
			priority = 40, singleThreaded = true)
	public void deployAndCreateLiteralBasedHumanTask() throws Exception {

		final String artifactLocation =
				FrameworkPathUtil.getSystemResourceLocation() + BPSTestConstants.DIR_ARTIFACTS + File.separator +
						BPSTestConstants.DIR_HUMAN_TASK + File.separator + HumanTaskTestConstants.DIR_PEOPLE_ASSIGNMENT +
						File.separator + "test4";
		uploadHumanTaskForTest(HumanTaskTestConstants.CLAIMS_APPROVAL_PACKAGE_ORG_ENTITY_NAME, artifactLocation);
		Thread.sleep(30000); // Wait for new version of task deploy.
		createTask(); // create task
		TSimpleQueryInput queryInput = new TSimpleQueryInput();
		queryInput.setPageNumber(0);
		queryInput.setSimpleQueryCategory(TSimpleQueryCategory.ALL_TASKS);

		//Login As Clerk1 user
		TTaskSimpleQueryResultSet taskResults = clerk1Client.simpleQuery(queryInput);
		TTaskSimpleQueryResultRow[] rows = taskResults.getRow();
		TTaskSimpleQueryResultRow b4pTask = null;
		Assert.assertNotNull(rows, "No tasks found. Task creation has failed. ");
		// looking for the latest task
		for (TTaskSimpleQueryResultRow row : rows) {
			if (b4pTask == null) {
				b4pTask = row;
			} else {
				if (Long.parseLong(b4pTask.getId().toString()) < Long.parseLong(row.getId().toString())) {
					b4pTask = row;
				}
			}
		}

		// Validating Task
		Assert.assertNotNull(b4pTask, "Task creation has failed");
		Assert.assertNotEquals(b4pTask.getId().toString(), this.taskID.toString(), "Task creation failed.");
		this.taskID = b4pTask.getId();
	}

	@Test(groups = { "wso2.bps.task.literal" }, description = "Perform humanTask",
			priority = 41, singleThreaded = true, expectedExceptions = AxisFault.class)
	public void testLiteralBasedPeopleAssignment() throws Exception {
		// clerk1, clerk2, clerk4, clerk5 users will able to work on task. Clerk3 will be a excluded used.
		boolean failed = false;
		try {
			clerk1Client.start(taskID);
			clerk1Client.release(taskID);
			clerk2Client.start(taskID);
			clerk2Client.release(taskID);
			clerk4Client.start(taskID);
			clerk4Client.release(taskID);
			clerk5Client.start(taskID);
			clerk5Client.release(taskID);
		} catch (Exception e) {
			failed = true;
		}
		Assert.assertTrue(!failed, "Expected users can't perform task");
		clerk6Client.start(taskID);
	}

	@Test(groups = { "wso2.bps.task.clean" }, description = "Clean up server", priority = 100, singleThreaded = true)
	public void cleanTestEnvironment() throws Exception {
		userManagementClient.deleteRole(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE);
		userManagementClient.deleteRole(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE_2);
		userManagementClient.deleteRole(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE_3);
		userManagementClient.deleteRole(HumanTaskTestConstants.REGIONAL_MANAGER_ROLE);
		userManagementClient.deleteRole(HumanTaskTestConstants.REGIONAL_MANAGER_ROLE_2);
		Assert.assertFalse(userManagementClient.roleNameExists(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE));
		Assert.assertFalse(userManagementClient.roleNameExists(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE_2));
		Assert.assertFalse(userManagementClient.roleNameExists(HumanTaskTestConstants.REGIONAL_CLERKS_ROLE_3));
		Assert.assertFalse(userManagementClient.roleNameExists(HumanTaskTestConstants.REGIONAL_MANAGER_ROLE));
		Assert.assertFalse(userManagementClient.roleNameExists(HumanTaskTestConstants.REGIONAL_MANAGER_ROLE_2));
		humanTaskPackageManagementClient.unDeployHumanTask(HumanTaskTestConstants.CLAIMS_APPROVAL_PACKAGE_ORG_ENTITY_NAME, "ApproveClaim");
		loginLogoutClient.logout();
	}

}


text:
package main

import (
	"os"

	"github.com/Abramovic/logrus_influxdb"
	log "github.com/Sirupsen/logrus"
	client "github.com/influxdata/influxdb/client/v2"
)

func initLog() {
	log.SetOutput(os.Stdout)
}

// MUST BE CALLED AFTER CONFIG IS READ (ReadConfig())
func configureLog() {
	configureInflux()
}

func configureInflux() {
	if config.InfluxAvailable() {

		log.Info("Connecting to influxdb: " + config.GetInfluxHost())

		cnf := &logrus_influxdb.Config{
			Tags:     []string{"cbatch"}, // use the following tags
			Database: config.GetInfluxDatabase(),
		}

		c, err := client.NewHTTPClient(client.HTTPConfig{
			Addr:     config.GetInfluxHost(),
			Username: config.GetInfluxUser(),
			Password: config.GetInfluxPassword(),
		})

		if err != nil {
			log.Fatal(err)
		}

		hook, err := logrus_influxdb.NewInfluxDB(cnf, c)
		if err == nil {
			log.AddHook(hook)
		}

		log.Info("Connected to influxdb: " + config.GetInfluxHost())
	}

	log.Info("InfluxDB not configured")
}

redpajama_set_name: RedPajamaGithub


text:
package akka.crdt.convergent

import akka.remote.testkit.MultiNodeConfig
import akka.crdt._
import akka.remote.testkit.MultiNodeSpec
import akka.remote.testconductor.RoleName
import akka.actor._
import akka.cluster._
import scala.util._
import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory
import scala.concurrent.Await
import akka.util.Timeout

object PNCounterClusterSpecConfig extends MultiNodeConfig {
  val node1 = role("node1")
  val node2 = role("node2")
  val node3 = role("node3")

  commonConfig(ConfigFactory.parseString("""
    akka.crdt.convergent.leveldb.destroy-on-shutdown = on
    akka.convergent.batching-window = 10ms
    akka.actor.provider = akka.cluster.ClusterActorRefProvider
    akka.cluster.auto-join = off
    akka.cluster.auto-down = on
    akka.loggers = ["akka.testkit.TestEventListener"]
    akka.loglevel = INFO
    akka.remote.log-remote-lifecycle-events = off
  """))
}

class PNCounterClusterSpecMultiJvmNode1 extends PNCounterClusterSpec
class PNCounterClusterSpecMultiJvmNode2 extends PNCounterClusterSpec
class PNCounterClusterSpecMultiJvmNode3 extends PNCounterClusterSpec

class PNCounterClusterSpec extends MultiNodeSpec(PNCounterClusterSpecConfig) with STMultiNodeSpec {

  import PNCounterClusterSpecConfig._

  implicit def roleNameToAddress(role: RoleName): Address = testConductor.getAddressFor(role).await
  implicit val sys: ActorSystem = system

  def initialParticipants = roles.size

  "A ConvergentReplicatedDataTypeDatabase" must {

    "Make sure that a PNCounter, used by multiple nodes, eventually converge to a consistent value" in {
      val cluster = Cluster(system)
      val db = ConvergentReplicatedDataTypeDatabase(system)

      implicit val ec = system.dispatcher
      val duration = 10 seconds

      runOn(node1) { cluster join node1 }
      runOn(node2) { cluster join node1 }
      runOn(node3) { cluster join node1 }

      Thread.sleep(5000)

      // create CRDT on node1
      runOn(node1) {
        db.create[PNCounter]("jonas").value must be(0)
      }
      enterBarrier("stored pn-counter on node1")

      // find CRDT by id on the other nodes
      runOn(node2, node3) {
        awaitAssert(Await.result(db.findById[PNCounter]("jonas"), duration)) // wait until it does not throw exception
      }
      enterBarrier("pn-counter exists on all nodes")

      // let each node update the counter (incrementing or decrementing)
      runOn(node1) {
        db.findById[PNCounter]("jonas") map (_ + (node1.name, 2)) foreach (db.update(_))
      }
      runOn(node2) {
        db.findById[PNCounter]("jonas") map (_ - node2.name) foreach (db.update(_))
      }
      runOn(node3) {
        db.findById[PNCounter]("jonas") map (_ + node3.name) foreach (db.update(_))
        db.findById[PNCounter]("jonas") map (_ - node3.name) foreach (db.update(_))
      }
      enterBarrier("updated-counter-on-all-nodes")

      // make sure each node sees the converged counter value of 3
      runOn(node1, node2, node3) {
        awaitCond(Await.result(db.findById[PNCounter]("jonas"), 100 millis).value == 1, 10 seconds)
      }

      enterBarrier("verified-counter-on-all-nodes")

      db.shutdown()
      enterBarrier("after-shutdown")
    }
  }
}


text:
package code.model;

import code.AbstractTile;
import code.controller.Assets;
import com.almasb.fxgl.entity.RenderLayer;
import com.almasb.fxgl.physics.HitBox;
import javafx.geometry.BoundingBox;

/**
 * Created by eric on 11/4/15.
 */
public class Player extends AbstractTile {

    public Player() {
        super(Type.PLAYER);

        setCollidable(true);
        setPosition(Tile.BLOCK_SIZE, Tile.BLOCK_SIZE);
        setGenerateHitBoxesFromView(false);
        addHitBox(generatePlayerHitbox());

        try {
            view.addNode(Assets.getInstance().getAssetManager().cache().getTexture("chipDown.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        view.setRenderLayer(new RenderLayer() {
            public String name() {
                return "Player";
            }

            public int index() {
                return 10;
            }
        });
    }

    private HitBox generatePlayerHitbox() {
        return new HitBox("PLAYER", new BoundingBox(1, 1, Tile.BLOCK_SIZE - 2, Tile.BLOCK_SIZE - 2));
    }
}


text:
<!DOCTYPE html>

FEEDBACK

                Let us know what you think!

If you would like to ask a question, leave us your email address and we'll get back to you.

                <textarea id="feed" autofocus style="width: 525px;height: 125px;border-radius: 5px" ng-maxlength="300" spellcheck="true" ></textarea>

                Cancel
                <button type="button" class="btn btn-primary"  ng-click="sendFeedback()">Send</button>


text:
module DeviseControllerMacros
  def login_admin
    let(:current_admin) do
      FactoryGirl.create(:admin)
    end

    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:admin]
      sign_in current_admin
    end
  end
end

module DeviseControllerHelpers
  def admin_token_auth(admin)
    request.env["HTTP_X_ADMIN_AUTH_TOKEN"] = admin.authentication_token
  end
end

module DeviseFeatureMacros
  def login_admin
    before(:each) do
      @current_admin = if(defined?(current_admin)) then current_admin else FactoryGirl.create(:admin) end

      Warden.test_mode!
      login_as(@current_admin, :scope => :admin)

      # FIXME: When running standalone feature tests, sometimes the first test
      # inexplicably fails. The pages appear to load, but interacting with the
      # forms and trying to save fail (it's almost like the javascript hasn't
      # fully loaded if things aren't warmed up). However, this issue goes away
      # on subsequent tests, so the super hacky workaround is to load the index
      # page once before any tests and that seems to fix the issue. We should
      # revisit sometime to try to figure out if this is a Capybara/poltergeist
      # issue or something with our app.
      #
      # rubocop:disable Style/GlobalVars
      unless($admin_loaded_once)
        visit "/admin/"
        page.should have_content("API Umbrella")
        $admin_loaded_once = true
      end
      # rubocop:enable Style/GlobalVars
    end

    after(:each) do
      Warden.test_reset!
    end
  end
end

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
  config.include DeviseControllerHelpers, :type => :controller
  config.extend DeviseControllerMacros, :type => :controller

  config.include Warden::Test::Helpers, :type => :feature
  config.extend DeviseFeatureMacros, :type => :feature
end


text:
/*
 * Open Payments Cloud Application API
 * Open Payments Cloud API
 *
 * OpenAPI spec version: 1.0.0
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */

package com.ixaris.ope.applications.client.model;

import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import com.ixaris.ope.applications.client.model.Transfer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;

/**
 * Transfers
 */
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-30T15:46:40.836+02:00")
public class Transfers {
  @SerializedName("transfers")
  private List<Transfer> transfers = new ArrayList<Transfer>();

  @SerializedName("count")
  private Integer count = null;

  /**
   * Gets or Sets actions
   */
  public enum ActionsEnum {
    @SerializedName("CREATE")
    CREATE("CREATE");

    private String value;

    ActionsEnum(String value) {
      this.value = value;
    }

    @Override
    public String toString() {
      return String.valueOf(value);
    }
  }

  @SerializedName("actions")
  private List<ActionsEnum> actions = new ArrayList<ActionsEnum>();

  public Transfers transfers(List<Transfer> transfers) {
    this.transfers = transfers;
    return this;
  }

  public Transfers addTransfersItem(Transfer transfersItem) {
    this.transfers.add(transfersItem);
    return this;
  }

   /**
   * Get transfers
   * @return transfers
  **/
  @ApiModelProperty(example = "null", value = "")
  public List<Transfer> getTransfers() {
    return transfers;
  }

  public void setTransfers(List<Transfer> transfers) {
    this.transfers = transfers;
  }

  public Transfers count(Integer count) {
    this.count = count;
    return this;
  }

   /**
   * The total number of entries that match the given filter, including any entries which were not returned due to paging constraints.
   * @return count
  **/
  @ApiModelProperty(example = "null", value = "The total number of entries that match the given filter, including any entries which were not returned due to paging constraints.")
  public Integer getCount() {
    return count;
  }

  public void setCount(Integer count) {
    this.count = count;
  }

  public Transfers actions(List<ActionsEnum> actions) {
    this.actions = actions;
    return this;
  }

  public Transfers addActionsItem(ActionsEnum actionsItem) {
    this.actions.add(actionsItem);
    return this;
  }

   /**
   * The actions that can be performed on this particular resource instance.
   * @return actions
  **/
  @ApiModelProperty(example = "null", value = "The actions that can be performed on this particular resource instance.")
  public List<ActionsEnum> getActions() {
    return actions;
  }

  public void setActions(List<ActionsEnum> actions) {
    this.actions = actions;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    Transfers transfers = (Transfers) o;
    return Objects.equals(this.transfers, transfers.transfers) &&
        Objects.equals(this.count, transfers.count) &&
        Objects.equals(this.actions, transfers.actions);
  }

  @Override
  public int hashCode() {
    return Objects.hash(transfers, count, actions);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class Transfers {\n");

    sb.append("    transfers: ").append(toIndentedString(transfers)).append("\n");
    sb.append("    count: ").append(toIndentedString(count)).append("\n");
    sb.append("    actions: ").append(toIndentedString(actions)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }

}


text:
CREATE TABLE entity_edit_types_sparse_and_usage AS (
	SELECT year_month_page_title, page_views, number_of_revisions, page_title, year, month, namespace, anon_edits, bot_edits, human_edits, semi_automated_edits
	FROM entity_edit_types_sparse_and_usage_sub_table_1
	UNION ALL
	SELECT year_month_page_title, page_views, number_of_revisions, page_title, year, month, namespace, anon_edits, bot_edits, human_edits, semi_automated_edits
	FROM entity_edit_types_sparse_and_usage_sub_table_2
	UNION ALL
	SELECT year_month_page_title, page_views, number_of_revisions, page_title, year, month, namespace, anon_edits, bot_edits, human_edits, semi_automated_edits
	FROM entity_edit_types_sparse_and_usage_sub_table_3
	UNION ALL
	SELECT year_month_page_title, page_views, number_of_revisions, page_title, year, month, namespace, anon_edits, bot_edits, human_edits, semi_automated_edits
	FROM entity_edit_types_sparse_and_usage_sub_table_4
	UNION ALL
	SELECT year_month_page_title, page_views, number_of_revisions, page_title, year, month, namespace, anon_edits, bot_edits, human_edits, semi_automated_edits
	FROM entity_edit_types_sparse_and_usage_sub_table_5
);


text:
package org.uiautomation.ios.wkrdp;

import org.json.JSONObject;

/**
 * when something goes wrong with the WKRDP. Typically a remote JS error or an access to a non
 * existing node.
 */
public class RemoteExceptionException extends RuntimeException {

  private int code;
  private String message;
  private JSONObject command;

  public RemoteExceptionException(int code, String message, JSONObject command) {
    this.code = code;
    this.message = message;
    this.command = command;
  }

  public RemoteExceptionException(JSONObject error, JSONObject command) {
    this.code = error.optInt("code", -1);
    this.message = error.optString("message", "No message for the error.");
    this.command = command;
  }

  @Override
  public String getMessage() {
    return message;
  }

  public int getCode() {
    return code;
  }
}


text:
#import <Foundation/Foundation.h>

/**
 * Simply encapsulates a width and height.
 */
@interface ZXDimension : NSObject

@property (nonatomic, assign, readonly) int height;
@property (nonatomic, assign, readonly) int width;

- (id)initWithWidth:(int)width height:(int)height;

@end


text:
"""Methods for implementing the `datalab delete` command."""

from __future__ import absolute_import

from . import utils

description = ("""`{0} {1}` deletes the given Datalab instance's
Google Compute Engine VM.

By default, the persistent disk's auto-delete configuration determines
whether or not that disk is also deleted.

If you wish to override that setting, you can pass in one of either the
`--delete-disk` flag or the `--keep-disk` flag.

For more information on disk auto-deletion, see
https://cloud.google.com/compute/docs/disks/persistent-disks#updateautodelete
""")

_DELETE_DISK_HELP = ("""Whether or not to delete the instance's persistent disk
regardless of the disks' auto-delete configuration.""")

_KEEP_DISK_HELP = ("""Whether or not to keep the instance's persistent disk
regardless of the disks' auto-delete configuration.""")

_DELETE_BASE_PROMPT = ("""The following instance will be deleted:
 - [{}] in [{}]

The corresponding notebooks disk {}.
""")

def flags(parser):
    """Add command line flags for the `delete` subcommand.

    Args:
      parser: The argparse parser to which to add the flags.
    """
    parser.add_argument(
        'instance',
        metavar='NAME',
        help='name of the instance to delete')

    auto_delete_override = parser.add_mutually_exclusive_group()
    auto_delete_override.add_argument(
        '--delete-disk',
        dest='delete_disk',
        action='store_true',
        help=_DELETE_DISK_HELP)
    auto_delete_override.add_argument(
        '--keep-disk',
        dest='keep_disk',
        action='store_true',
        help=_KEEP_DISK_HELP)
    return

def run(args, gcloud_compute, gcloud_zone=None, **unused_kwargs):
    """Implementation of the `datalab delete` subcommand.

    Args:
      args: The Namespace instance returned by argparse
      gcloud_compute: Function that can be used to invoke `gcloud compute`
      gcloud_zone: The zone that gcloud is configured to use
    Raises:
      subprocess.CalledProcessError: If a nested `gcloud` calls fails
    """
    instance = args.instance
    utils.maybe_prompt_for_zone(args, gcloud_compute, instance)

    base_cmd = ['instances', 'delete', '--quiet']
    if args.zone:
        base_cmd.extend(['--zone', args.zone])
        instance_zone = args.zone
    else:
        instance_zone = gcloud_zone

    if args.delete_disk:
        base_cmd.extend(['--delete-disks', 'data'])
        notebooks_disk_message_part = 'will be deleted'
    elif args.keep_disk:
        base_cmd.extend(['--keep-disks', 'data'])
        notebooks_disk_message_part = 'will not be deleted'
    else:
        disk_cfg = utils.instance_notebook_disk(args, gcloud_compute, instance)
        if not disk_cfg:
            notebooks_disk_message_part = 'is not attached'
        elif disk_cfg['autoDelete']:
            notebooks_disk_message_part = 'will be deleted'
        else:
            notebooks_disk_message_part = 'will not be deleted'

    message = _DELETE_BASE_PROMPT.format(
        instance, instance_zone, notebooks_disk_message_part)
    if not utils.prompt_for_confirmation(
            args=args,
            message=message,
            accept_by_default=True):
        print('Deletion aborted by user; Exiting.')
        return

    print('Deleting {0}'.format(instance))
    gcloud_compute(args, base_cmd + [instance])
    return


text:
const DrawCard = require('../../drawcard.js');
const AbilityDsl = require('../../abilitydsl');
const { Players, CardTypes } = require('../../Constants');

class InvocationOfAsh extends DrawCard {
    setupCardAbilities() {
        this.action({
            title: 'Move to another character',
            cost: AbilityDsl.costs.payHonor(1),
            target: {
                cardType: CardTypes.Character,
                controller: Players.Self,
                gameAction: AbilityDsl.actions.sequential([
                    AbilityDsl.actions.attach(context => ({ attachment: context.source })),
                    AbilityDsl.actions.removeFate()
                ])
            },
            effect: 'move {1} to {0}, then remove a fate from {0}',
            effectArgs: context => context.source
        });
    }
}

InvocationOfAsh.id = 'invocation-of-ash';

module.exports = InvocationOfAsh;


text:
\section{Generating codes}

\slide{QR}
{
\begin{itemize}
\item QR codes are auto-generated
\item Put \emph{txt} file in \emph{qr/} directory
\item Insert text there
\item Image will be auto-generated
\end{itemize}

\begin{center}
% NOTE: explain diagram in depth
\includegraphics[scale=0.1]{qr/some_info}
\end{center}
}


text:
FactoryBot.define do
  factory :hospital_centre, class: "Renalware::Hospitals::Centre" do
    initialize_with do
      Renalware::Hospitals::Centre.find_or_create_by!(code: code, name: name)
    end

    name { "King's College Hospital" }
    code { "RJZ" }
    host_site { true }
  end
end


text:
#ifndef _XEN_XENBUS_H
#define _XEN_XENBUS_H

#include <linux/device.h>
#include <linux/notifier.h>
#include <linux/mutex.h>
#include <linux/completion.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <xen/interface/xen.h>
#include <xen/interface/grant_table.h>
#include <xen/interface/io/xenbus.h>
#include <xen/interface/io/xs_wire.h>

/* Register callback to watch this node. */
struct xenbus_watch
{
	struct list_head list;

	/* Path being watched. */
	const char *node;

	/* Callback (executed in a process context with no locks held). */
	void (*callback)(struct xenbus_watch *,
			 const char **vec, unsigned int len);
};

/* A xenbus device. */
struct xenbus_device {
	const char *devicetype;
	const char *nodename;
	const char *otherend;
	int otherend_id;
	struct xenbus_watch otherend_watch;
	struct device dev;
	enum xenbus_state state;
	struct completion down;
};

static inline struct xenbus_device *to_xenbus_device(struct device *dev)
{
	return container_of(dev, struct xenbus_device, dev);
}

struct xenbus_device_id
{
	/* .../device/<device_type>/<identifier> */
	char devicetype[32]; 	/* General class of device. */
};

/* A xenbus driver. */
struct xenbus_driver {
	char *name;
	struct module *owner;
	const struct xenbus_device_id *ids;
	int (*probe)(struct xenbus_device *dev,
		     const struct xenbus_device_id *id);
	void (*otherend_changed)(struct xenbus_device *dev,
				 enum xenbus_state backend_state);
	int (*remove)(struct xenbus_device *dev);
	int (*suspend)(struct xenbus_device *dev);
	int (*resume)(struct xenbus_device *dev);
	int (*uevent)(struct xenbus_device *, struct kobj_uevent_env *);
	struct device_driver driver;
	int (*read_otherend_details)(struct xenbus_device *dev);
	int (*is_ready)(struct xenbus_device *dev);
};

static inline struct xenbus_driver *to_xenbus_driver(struct device_driver *drv)
{
	return container_of(drv, struct xenbus_driver, driver);
}

int __must_check __xenbus_register_frontend(struct xenbus_driver *drv,
					    struct module *owner,
					    const char *mod_name);

static inline int __must_check
xenbus_register_frontend(struct xenbus_driver *drv)
{
	WARN_ON(drv->owner != THIS_MODULE);
	return __xenbus_register_frontend(drv, THIS_MODULE, KBUILD_MODNAME);
}

int __must_check __xenbus_register_backend(struct xenbus_driver *drv,
					   struct module *owner,
					   const char *mod_name);
static inline int __must_check
xenbus_register_backend(struct xenbus_driver *drv)
{
	WARN_ON(drv->owner != THIS_MODULE);
	return __xenbus_register_backend(drv, THIS_MODULE, KBUILD_MODNAME);
}

void xenbus_unregister_driver(struct xenbus_driver *drv);

struct xenbus_transaction
{
	u32 id;
};

/* Nil transaction ID. */
#define XBT_NIL ((struct xenbus_transaction) { 0 })

char **xenbus_directory(struct xenbus_transaction t,
			const char *dir, const char *node, unsigned int *num);
void *xenbus_read(struct xenbus_transaction t,
		  const char *dir, const char *node, unsigned int *len);
int xenbus_write(struct xenbus_transaction t,
		 const char *dir, const char *node, const char *string);
int xenbus_mkdir(struct xenbus_transaction t,
		 const char *dir, const char *node);
int xenbus_exists(struct xenbus_transaction t,
		  const char *dir, const char *node);
int xenbus_rm(struct xenbus_transaction t, const char *dir, const char *node);
int xenbus_transaction_start(struct xenbus_transaction *t);
int xenbus_transaction_end(struct xenbus_transaction t, int abort);

/* Single read and scanf: returns -errno or num scanned if > 0. */
int xenbus_scanf(struct xenbus_transaction t,
		 const char *dir, const char *node, const char *fmt, ...)
	__attribute__((format(scanf, 4, 5)));

/* Single printf and write: returns -errno or 0. */
int xenbus_printf(struct xenbus_transaction t,
		  const char *dir, const char *node, const char *fmt, ...)
	__attribute__((format(printf, 4, 5)));

/* Generic read function: NULL-terminated triples of name,
 * sprintf-style type string, and pointer. Returns 0 or errno.*/
int xenbus_gather(struct xenbus_transaction t, const char *dir, ...);

/* notifer routines for when the xenstore comes up */
extern int xenstored_ready;
int register_xenstore_notifier(struct notifier_block *nb);
void unregister_xenstore_notifier(struct notifier_block *nb);

int register_xenbus_watch(struct xenbus_watch *watch);
void unregister_xenbus_watch(struct xenbus_watch *watch);
void xs_suspend(void);
void xs_resume(void);
void xs_suspend_cancel(void);

/* Used by xenbus_dev to borrow kernel's store connection. */
void *xenbus_dev_request_and_reply(struct xsd_sockmsg *msg);

struct work_struct;

/* Prepare for domain suspend: then resume or cancel the suspend. */
void xenbus_suspend(void);
void xenbus_resume(void);
void xenbus_probe(struct work_struct *);
void xenbus_suspend_cancel(void);

#define XENBUS_IS_ERR_READ(str) ({			\
	if (!IS_ERR(str) && strlen(str) == 0) {		\
		kfree(str);				\
		str = ERR_PTR(-ERANGE);			\
	}						\
	IS_ERR(str);					\
})

#define XENBUS_EXIST_ERR(err) ((err) == -ENOENT || (err) == -ERANGE)

int xenbus_watch_path(struct xenbus_device *dev, const char *path,
		      struct xenbus_watch *watch,
		      void (*callback)(struct xenbus_watch *,
				       const char **, unsigned int));
int xenbus_watch_pathfmt(struct xenbus_device *dev, struct xenbus_watch *watch,
			 void (*callback)(struct xenbus_watch *,
					  const char **, unsigned int),
			 const char *pathfmt, ...)
	__attribute__ ((format (printf, 4, 5)));

int xenbus_switch_state(struct xenbus_device *dev, enum xenbus_state new_state);
int xenbus_grant_ring(struct xenbus_device *dev, unsigned long ring_mfn);
int xenbus_map_ring_valloc(struct xenbus_device *dev,
			   int gnt_ref, void **vaddr);
int xenbus_map_ring(struct xenbus_device *dev, int gnt_ref,
			   grant_handle_t *handle, void *vaddr);

int xenbus_unmap_ring_vfree(struct xenbus_device *dev, void *vaddr);
int xenbus_unmap_ring(struct xenbus_device *dev,
		      grant_handle_t handle, void *vaddr);

int xenbus_alloc_evtchn(struct xenbus_device *dev, int *port);
int xenbus_bind_evtchn(struct xenbus_device *dev, int remote_port, int *port);
int xenbus_free_evtchn(struct xenbus_device *dev, int port);

enum xenbus_state xenbus_read_driver_state(const char *path);

__attribute__((format(printf, 3, 4)))
void xenbus_dev_error(struct xenbus_device *dev, int err, const char *fmt, ...);
__attribute__((format(printf, 3, 4)))
void xenbus_dev_fatal(struct xenbus_device *dev, int err, const char *fmt, ...);

const char *xenbus_strstate(enum xenbus_state state);
int xenbus_dev_is_online(struct xenbus_device *dev);
int xenbus_frontend_closed(struct xenbus_device *dev);

#endif /* _XEN_XENBUS_H */


text:
<?xml version="1.0" encoding="UTF-8"?>
<buildm>
<physicalAsset>
	<buildingCount>1</buildingCount>
	<columnCount>0</columnCount>
	<componentCount>194</componentCount>
	<doorCount>0</doorCount>
	<floorCount>3</floorCount>
	<identifier>3QWRRBumf4tQUMJzy0uGGC</identifier>
	<latitude>42.358428955</latitude>
	<longitude>-71.0597763061111</longitude>
	<name>Haus</name>
	<name>Haus3</name>
	<spaceCount>0</spaceCount>
	<streetAddress>address</streetAddress>
	<wallCount>14</wallCount>
	<windowCount>0</windowCount>
	<owner>owner1</owner>
	<owner>owner2</owner>
	<buildingArea>9898</buildingArea>
	<numberOfRooms>8787</numberOfRooms>
	<function>function1</function>
	<function>function2</function>
	<architecturalStyle>style</architecturalStyle>
	<architecturalStyle>style2</architecturalStyle>
	<description>desc1</description>
	<description>desc2</description>
	<location>location</location>
	<postalCodeStart>1</postalCodeStart>
	<postalCodeEnd>2</postalCodeEnd>
	<postOfficeBoxNumber>43</postOfficeBoxNumber>
	<addressRegion>graz</addressRegion>
	<postalLocality>graz</postalLocality>
	<architect>architect1</architect>
	<architect>architect2</architect>
	<contributor>cont1</contributor>
	<contributor>cont2</contributor>
	<startDate>Wed Jul 15 2015 17:29:42 GMT+0200 (CEST)</startDate>
	<completionDate>Wed Jul 15 2015 17:29:42 GMT+0200 (CEST)</completionDate>
	<constructionTime>Wed Jul 15 2015 17:29:42 GMT+0200 (CEST)</constructionTime>
	<rebuildingDate>Wed Jul 15 2015 17:29:42 GMT+0200 (CEST)</rebuildingDate>
	<rebuildingDate>Wed Jul 15 2015 17:29:42 GMT+0200 (CEST)</rebuildingDate>
	<modificationDetails>mod1</modificationDetails>
	<modificationDetails>mod2</modificationDetails>
	<cost>1</cost>
	<cost>2</cost>
	<rightsDetails>detail1</rightsDetails>
	<rightsDetails>detail2</rightsDetails>
</physicalAsset>
<digitalObject>
	<actorCount>0</actorCount>
	<authoringTool>20120221_2030(x64)</authoringTool>
	<authoringTool>Autodesk Revit 2013</authoringTool>
	<creator>morten jensen</creator>
	<creator>mh</creator>
	<dateCreated>2013-03-01T11:21:05</dateCreated>
	<dimensionCount>3</dimensionCount>
	<entityCount>67</entityCount>
	<fileSchema>IFC2X3</fileSchema>
	<geometricPrecision>1e-06</geometricPrecision>
	<hasType>Annotation</hasType>
	<hasType>Model</hasType>
	<instanceCount>4061</instanceCount>
	<name>Barcelona_Pavillon.ifc</name>
	<name>asdf</name>
	<optionalAttributesSet>0.461189044756179</optionalAttributesSet>
	<relationshipCount>617</relationshipCount>
	<unit>MILLICUBIC_METRE</unit>
	<unit>MILLISQUARE_METRE</unit>
	<Identifier>test</Identifier>
	<isPartOf>identifier1</isPartOf>
	<isPartOf>identifier2</isPartOf>
	<hasPart>identifier1</hasPart>
	<hasPart>identifier2</hasPart>
	<format>format1</format>
	<hasFormatDetails>details</hasFormatDetails>
	<description>desct1</description>
	<description>desc2</description>
	<provenance>prov1</provenance>
	<provenance>prov2</provenance>
	<license>lic1</license>
	<unitCode>MEM</unitCode>
	<levelOfDetail>asdf:3</levelOfDetail>
	<event>event1</event>
	<event>event2</event>
</digitalObject>
</buildm>


text:
/// <binding BeforeBuild='default' ProjectOpened='watch' />
'use strict'

var gulp = require('gulp')
var browserify = require('browserify')
var source = require('vinyl-source-stream')
var tsify = require('tsify')
var uglify = require('gulp-uglify')
var sourcemaps = require('gulp-sourcemaps')
var buffer = require('vinyl-buffer')
var del = require('del')
var sass = require('gulp-sass')

gulp.task('clean-typescript', function () {
    return del([
        'Assets/scripts/**/*'
    ])
})

gulp.task('clean-sass', function () {
    return del([
        'Assets/css/**/*'
    ])
})

gulp.task('sass', ['clean-sass'], function () {
    return gulp.src([
            'scss/main.scss',
            'scss/materialize.light.scss',
            'scss/materialize.complete.scss',
            'scss/offline.scss'
        ])
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(sass({ outputStyle: 'compressed' }))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('Assets/css'))
})

gulp.task('typescript', ['clean-typescript'], function () {
    return browserify({
        basedir: '.',
        debug: true,
        entries: ['scripts/main.ts', 'scripts/offline.min.js'],
        cache: {},
        packageCache: {}
    })
        .plugin(tsify)
        .bundle()
        .pipe(source('bundle.min.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(uglify())
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('Assets/scripts'))
})

gulp.task('default', ['typescript', 'sass'])

gulp.task('watch', function () {
    gulp.watch('scripts/**/*.ts', ['typescript'])
    gulp.watch('scripts/**/*.js', ['typescript'])
    gulp.watch('scss/**/*.scss', ['sass'])
})


text:
from IPython.core.display import display_html
from IPython import get_ipython

comm = None
listeners = {}

def setListener(topic, callback):
    listeners[topic] = callback

def dispatch(msg):
    # Note: because of the way comms are run, you can't print in these functions.
    # You can, however, hijack the comm_manager's logger, which prints to the kernel
    # stdout (wherever you have it running.)
    # e.g. get_ipython().kernel.comm_manager.log.error(...)
    msg = msg['content']['data']

    if listeners.has_key(msg['topic']):
        listeners[msg['topic']](msg['data'])

def handle_open(_comm, msg):
    global comm
    assert msg['content']['data'] == 'ipycomms.opened'
    comm = _comm
    _comm.on_msg(dispatch)

def send(topic, data):
    msg = {'topic': topic, 'data': data}
    comm.send(msg)

# The channel name is arbitrary.
get_ipython().kernel.comm_manager.register_target('ipycomms.channel', handle_open)

display_html('''
<script>

IPython.ipycomms = {
    init: function(){
        console.log("[ipycomms] initializing")
        this.comm = IPython.notebook.kernel.comm_manager.new_comm(
            'ipycomms.channel',
            "ipycomms.opened",  // Initial data sent with open (arbitrary)
            function(){},       // Callbacks
            "ipycomms.meta")    // Metadata (arbitrary)
        this.comm.on_msg(_.bind(this.dispatch, this))
    },
    dispatch: function(msg){
        msg = msg.content.data;

        if (!this.topicHandlers.hasOwnProperty(msg.topic)){
            console.log("[ipycomms] topic with no callback", msg.topic)
            return;
        }

        this.topicHandlers[msg.topic](msg.data)
    },
    topicHandlers: {},
    setListener: function(topic, callback){
        this.topicHandlers[topic] = callback
    },
    send: function(topic, data){
        this.comm.send({topic: topic, data: data})
    }
}

IPython.ipycomms.init()
</script>
''', raw=True)
print "Injected script."


text:
"use strict";

angular.module('arethusa.core').service('spinner', function() {
  var self = this;

  this.spinning = 0;

  this.spin = function() {
    self.spinning++;
  };

  this.stop = function() {
    self.spinning--;
  };
});


text:
import frappe
import json
from frappe.permissions import get_valid_perms, get_linked_doctypes

def execute():
    user_permissions = frappe.get_all('User Permission', fields=['allow', 'name', 'user'])

    doctype_to_skip_map = {}

    for permission in user_permissions:
        doctype_to_skip_map[permission.name] = get_doctypes_to_skip(permission.allow, permission.user)

    if not doctype_to_skip_map: return

    for perm_name, doctype_to_skip in doctype_to_skip_map.items():
        if not doctype_to_skip: continue
        doctype_to_skip = '\n'.join(doctype_to_skip)
        frappe.db.set_value('User Permission', perm_name, 'skip_for_doctype', doctype_to_skip)

def get_doctypes_to_skip(doctype, user):
    ''' Returns doctypes to be skipped from user permission check'''
    doctypes_to_skip = []
    valid_perms = get_user_valid_perms(user) or []

    for perm in valid_perms:

        parent_doctype = perm.parent

        try:
            if doctype not in get_linked_doctypes(parent_doctype): continue
        except frappe.DoesNotExistError:
            # if doctype not found (may be due to rename) it should not be considered for skip
            continue

        if not perm.apply_user_permission:
            # add doctype to skip list if any of the perm does not apply user permission
            doctypes_to_skip.append(doctype)

        elif parent_doctype not in doctypes_to_skip:

            user_permission_doctypes = get_user_permission_doctypes(perm)

            # "No doctypes present" indicates that user permission will be applied to each link field
            if not user_permission_doctypes: continue

            elif doctype in user_permission_doctypes: continue

            else: doctypes_to_skip.append(doctype)

    # to remove possible duplicates
    doctypes_to_skip = list(set(doctypes_to_skip))

    return doctypes_to_skip

# store user's valid perms to avoid repeated query
user_valid_perm = {}

def get_user_valid_perms(user):
    if not user_valid_perm.get(user):
        user_valid_perm[user] = get_valid_perms(user=user)
    return user_valid_perm.get(user)

def get_user_permission_doctypes(perm):
    try:
        return json.loads(perm.user_permission_doctypes or '[]')
    except ValueError:
        return []


text:
<meta name="robots" content="noindex,noarchive"/>

  <meta name="title" content="Amazon.co.uk: Nicholas Tinning: Wishlist" />
  <link rel="image_src" href="http://g-ecx.images-amazon.com/images/G/02/x-locale/communities/wishlist/uwl/UWL_SWF_shims._V203758293_.png" />

<title>Amazon.co.uk: Nicholas Tinning: Wishlist</title>

<link rel="stylesheet" type="text/css" href="http://z-ecx.images-amazon.com/images/G/01/nav2/gamma/fruitCSS/GB/combined-3127367498._V200499207_.css" />

<link rel="stylesheet" type="text/css" href="http://z-ecx.images-amazon.com/images/G/02/x-locale/common/errors-alerts/error-styles._V244707745_.css" />

<link type='text/css' href='http://z-ecx.images-amazon.com/images/G/01/browser-scripts/uk-site-wide-1.4.2/site-wide-6051803711.css._V198493426_.css' rel='stylesheet'>
<link type='text/css' href='http://z-ecx.images-amazon.com/images/G/01/nav2/gamma/share-with-friends-css/share-with-friends-css-share-4653._V199382900_.css' rel='stylesheet'>

  amazon.co.uk

  Hello.
  Sign in to get personalised recommendations.
  New Customer? Start here.

            Visit our new Pet Supplies Store

        Your Amazon.co.uk
         |
        Deals of the Week
         |
        Gift Cards
         |
        Gifts & Wish Lists

        Your Account
         |
        Help

  Shop All Departments

      Basket

  Wish List

Amazon.co.uk

            Wish List

            Wedding List

            Gift Certificates

            Gift Central

            Gift services

<form style="display: none;" id="RegistryGlobalForm" action="/registry/wishlist/2F1084Q1YMV45/update">

<input type="hidden" name="sid" value="000-0000000-0000000" />
<input type="hidden" name="gid" value="A3NPR5U3TZ8VUE" />
<input type="hidden" name="cid" value="0" />
</form>

</%method>

  Hello. If this is your Wish List, please sign in.

Nicholas Tinning

This list is for:	Nicholas Tinning

Dispatch to:	No address entered

Birthday:	None entered

About me:	Nothing entered

Wish Lists

Wishlist

        0 items item
        (default)

  </%init>

  <form name="create-list"  method="post" action="/gp/registry/wishlist/2F1084Q1YMV45">

    <input type="hidden" name="dest-list" value="new-wishlist">
    <input type="hidden" name="no-update" value="1">
    <input type="hidden" name="movecopy" value="createnew">

A problem occurred while saving

        • Please enter a valid List Name.

          List Name:

            <input type="text" id="createNewWLContent_t" name="list-name" value="New Wish List" maxlength="60" size="30"/>

              <input type="radio" id="createNewWLContent_r0" name="isPrivate" value="U" checked="checked" />

                Make this list public

                Anyone can see this list.

                <input type="checkbox" id="createNewWLContent_c0" name="isSearchable" value="Y"  checked= "checked" />
                Make this list searchable on Amazon

              <input type="radio" id="createNewWLContent_r1" name="isPrivate" value="Y"  />

                Make this list private

                Only you can see this list.

      <input type="image" src="http://g-ecx.images-amazon.com/images/G/02/misc/transparent-pixel._V192263529_.gif"  width="1" alt="Save Changes" name="submit.movecopy" class="wlSprite wl_save" id="createNewWLSave" height="1" border="0" />
      Cancel

  </form>

Close

The owner still needs to add some items to this Wish List.

(Undo)

    If you need a gift, take a look at the suggestions below, explore our Gift Ideas, or search for something specific.

Close

The owner still needs to add some items to this Wish List.

(Undo)

    If you need a gift, take a look at the suggestions below, explore our Gift Ideas, or search for something specific.

Close

The owner still needs to add some items to this Wish List.

(Undo)

    If you need a gift, take a look at the suggestions below, explore our Gift Ideas, or search for something specific.

Close

The owner still needs to add some items to this Wish List.

(Undo)

    If you need a gift, take a look at the suggestions below, explore our Gift Ideas, or search for something specific.

<form action="/gp/registry/search.html?ie=UTF8&type=wishlist" name="search-box" method="post"><input value="us-xml-wishlist" name="index" type="hidden" /><input value="templates/search/us-xml-wishlist-result.html" name="registry-error-page" type="hidden" />

		Find a Wish List

		<input value="Enter name or e-mail" name="field-name" onclick="this.select()" id="wishlistSearchFieldName" type="text" size="15" />

		<input type="image" src="http://g-ecx.images-amazon.com/images/G/02/misc/transparent-pixel._V192263529_.gif"  width="1" alt="Go" id="wishlistSearchInputID" class="swSprite s_goTan" height="1" border="0" />

</form>

<form>
  Wishlist

        Print this List

</form>

Amazon.co.uk Gift Certificates

  Amazon.co.uk Gift Certificates

         Give them the perfect present with a gift certificate. You can e-mail Amazon.co.uk Gift Certificates, print them from home, or send them by post (and they're always delivered for free).

         › Shop now

Get to Know Us

Careers

Investor Relations

Press Releases

Amazon and Our Planet

Make Money with Us

Sell on Amazon

Associates Programme

Fulfilment by Amazon

› See all

Let Us Help You

Delivery Rates & Policies

Amazon Prime

Returns

Help

          Canada |
China |
France |
Germany |
Japan |
United States

             And don't forget:
AbeBooks |
Audible |
DPReview |
IMDb |
Javari |
Shopbop |
SoundUnwound

          Conditions of Use & Sale |
Privacy Notice

 © 1996-2010, Amazon.com, Inc. or its affiliates


text:
At this point, anyone can enter phone book page since no authorization
defined. We will define two permission:

- A permission to **enter phone book page**.
- A permission to **create new person** (which is a child permission
  of first one, as naturally).

## Permission for Entering Phone Book Page

### Define the permission

Go to **AppAuthorizationProvider** class and add a new permission as shown below:

```csharp
pages.CreateChildPermission(AppPermissions.Pages_Tenant_PhoneBook, L("PhoneBook"), multiTenancySides: MultiTenancySides.Tenant);
```

A permission should have a unique name. We define permission names as constant strings in **AppPermissions** class. It's a simple constant string:

```csharp
public const string Pages_Tenant_PhoneBook = "Pages.Tenant.PhoneBook";
```

Unique name of this permission is "**Pages.Tenant.PhoneBook**". While you can set any string (as long as it's unique), it's suggested to use this convention. A permission can have a localizable display name: "**PhoneBook**" here. (See "Adding a New Page" section for more about localization, since it's very similar). Lastly, we set this as a **tenant** level permission.

### Add AbpAuthorize attribute

**AbpAuthorize** attribute can be used as **class level** or **method level** to protect an application service or service method from unauthorized users. Since all server side code is located in PersonAppService class, we can declare a class level attribute as shown below:

```csharp
[AbpAuthorize(AppPermissions.Pages_Tenant_PhoneBook)]
public class PersonAppService : PhoneBookAppServiceBase, IPersonAppService
{
    //...
}
```

Now, let's try to enter Phone Book page by clicking the menu item:

We get an error message. This exception is thrown when any method of PersonAppService is called without required permission.

### Hide Unauthorized Menu Item

This secures the service, but we should also **hide** the Phone book **menu item**. It's easy, open **AppNavigationProvider** and add requiredPermissionName as shown below:

```csharp
new MenuItemDefinition(
    PageNames.App.Tenant.PhoneBook,
    L("PhoneBook"),
    url: "tenant.phonebook",
    icon: "glyphicon glyphicon-book",
    requiredPermissionName: AppPermissions.Pages_Tenant_PhoneBook
)
```

### Grant permission

So, how we can enter the page now? Simple, go to **Role Management** page and edit **admin** role:

We see that a **new permission** named "**Phone book**" added to **permissions** tab. So, we can check it and save the role. After saving, we need to **refresh** the whole page to refresh permissions for the current user. We could also grant this permission for a specific user. Now, we can enter the Phone book page again.

## Permission for Create New Person

While a permission for a page is useful and probably needed always, we
may need to define additional permissions to perform some **specific
actions** on a page, like creating a new person.

### Define the Permission

Defining a permission is similar:

```csharp
var phoneBook = pages.CreateChildPermission(AppPermissions.Pages_Tenant_PhoneBook, L("PhoneBook"), multiTenancySides: MultiTenancySides.Tenant);
phoneBook.CreateChildPermission(AppPermissions.Pages_Tenant_PhoneBook_CreatePerson, L("CreateNewPerson"), multiTenancySides: MultiTenancySides.Tenant);
```

First permission was defined before. In the second line, we are creating a child permission of first one.

### Add AbpAuthorize Attribute

This time, we're declaring **AbpAuthorize** attribute just for **CreatePerson** method:

```csharp
[AbpAuthorize(AppPermissions.Pages_Tenant_PhoneBook_CreatePerson)]
public async Task CreatePerson(CreatePersonInput input)
{
    //...
}
```

### Hide Unauthorized Button

If we run the application and try to create a person, we get an authorization error after clicking the save button. But, it's good to **completely hide Create New Person button** if we don't have the permission. It's very simple:

Open the **index.cshtml** razor view and use **IsGranted** method:

```html
@if (IsGranted(AppPermissions.Pages_Tenant_PhoneBook_CreatePerson))
{
    <button id="CreateNewPersonButton" class="btn btn-primary blue"><i class="fa fa-plus"></i> @L("CreateNewPerson")</button>
}
```

In this way, the "Create New Person" button does not rendered in server and user can not see this button.

### Grant permission

To see the button again, we can go to role or user manager and grant related permission as shown below:

As shown above, **Create new person** permission is a child permission of the **Phone book**.

## Authorization for MVC Controllers

We added Authorize attributes to PersonAppService. This prevents unauthorized calls to this service. But unauthorized clients **still can call** actions of PhoneBookController actions. Since PhoneBookController uses PersonAppService, they will get authorization exception and can not use the service. But we can also secure MVC Controllers. This is suggested since some MVC actions may not use application services. Also,
it's better to prevent unauthorized attempts at the very beginning.

We use **AbpMvcAuthorize** attribute for MVC Controllers as shown below:

```csharp
[AbpMvcAuthorize(AppPermissions.Pages_Tenant_PhoneBook)]
public class PhoneBookController : PhoneBookControllerBase
{
    ...

    [AbpMvcAuthorize(AppPermissions.Pages_Tenant_PhoneBook_CreatePerson)]
    public PartialViewResult CreatePersonModal()
    {
        ...
    }

    ...
}
```

See [authorization documentation](https://aspnetboilerplate.com/Pages/Documents/Authorization) for more information on authorization.

## Next

- [Deleting a Person](Developing-Step-By-Step-Core-Deleting-Person.md)


text:
package portallocator

// Encapsulates the semantics of a port allocation 'transaction':
// It is better to leak ports than to double-allocate them,
// so we allocate immediately, but defer release.
// On commit we best-effort release the deferred releases.
// On rollback we best-effort release any allocations we did.
//
// Pattern for use:
//
//	op := StartPortAllocationOperation(...)
//	defer op.Finish
//	...
//	write(updatedOwner)
//
// /  op.Commit()
type PortAllocationOperation struct {
	pa              Interface
	allocated       []int
	releaseDeferred []int
	shouldRollback  bool
	dryRun          bool
}

// Creates a portAllocationOperation, tracking a set of allocations & releases
// If dryRun is specified, never actually allocate or release anything
func StartOperation(pa Interface, dryRun bool) *PortAllocationOperation {
	op := &PortAllocationOperation{}
	op.pa = pa
	op.allocated = []int{}
	op.releaseDeferred = []int{}
	op.shouldRollback = true
	op.dryRun = dryRun
	return op
}

// Will rollback unless marked as shouldRollback = false by a Commit().  Call from a defer block
func (op *PortAllocationOperation) Finish() {
	if op.shouldRollback {
		op.Rollback()
	}
}

// (Try to) undo any operations we did
func (op *PortAllocationOperation) Rollback() []error {
	if op.dryRun {
		return nil
	}

	errors := []error{}

	for _, allocated := range op.allocated {
		err := op.pa.Release(allocated)
		if err != nil {
			errors = append(errors, err)
		}
	}

	if len(errors) == 0 {
		return nil
	}
	return errors
}

// (Try to) perform any deferred operations.
// Note that even if this fails, we don't rollback; we always want to err on the side of over-allocation,
// and Commit should be called _after_ the owner is written
func (op *PortAllocationOperation) Commit() []error {
	if op.dryRun {
		return nil
	}

	errors := []error{}

	for _, release := range op.releaseDeferred {
		err := op.pa.Release(release)
		if err != nil {
			errors = append(errors, err)
		}
	}

	// Even on error, we don't rollback
	// Problems should be fixed by an eventual reconciliation / restart
	op.shouldRollback = false

	if len(errors) == 0 {
		return nil
	}

	return errors
}

// Allocates a port, and record it for future rollback
func (op *PortAllocationOperation) Allocate(port int) error {
	if op.dryRun {
		if op.pa.Has(port) {
			return ErrAllocated
		}
		for _, a := range op.allocated {
			if port == a {
				return ErrAllocated
			}
		}
		op.allocated = append(op.allocated, port)
		return nil
	}

	err := op.pa.Allocate(port)
	if err == nil {
		op.allocated = append(op.allocated, port)
	}
	return err
}

// Allocates a port, and record it for future rollback
func (op *PortAllocationOperation) AllocateNext() (int, error) {
	if op.dryRun {
		// Find the max element of the allocated ports array.
		// If no ports are already being allocated by this operation,
		// then choose a sensible guess for a dummy port number
		var lastPort int
		for _, allocatedPort := range op.allocated {
			if allocatedPort > lastPort {
				lastPort = allocatedPort
			}
		}
		if len(op.allocated) == 0 {
			lastPort = 32768
		}

		// Try to find the next non allocated port.
		// If too many ports are full, just reuse one,
		// since this is just a dummy value.
		for port := lastPort + 1; port < 100; port++ {
			err := op.Allocate(port)
			if err == nil {
				return port, nil
			}
		}
		op.allocated = append(op.allocated, lastPort+1)
		return lastPort + 1, nil
	}

	port, err := op.pa.AllocateNext()
	if err == nil {
		op.allocated = append(op.allocated, port)
	}
	return port, err
}

// Marks a port so that it will be released if this operation Commits
func (op *PortAllocationOperation) ReleaseDeferred(port int) {
	op.releaseDeferred = append(op.releaseDeferred, port)
}


text:
import { InputNode } from '../core/InputNode.js';

class PropertyNode extends InputNode {

	constructor( object, property, type ) {

		super( type );

		this.object = object;
		this.property = property;

	}

	get value() {

		return this.object[ this.property ];

	}

	set value( val ) {

		this.object[ this.property ] = val;

	}

	toJSON( meta ) {

		let data = this.getJSONNode( meta );

		if ( ! data ) {

			data = this.createJSONNode( meta );

			data.value = this.value;
			data.property = this.property;

		}

		return data;

	}

}

PropertyNode.prototype.nodeType = 'Property';

export { PropertyNode };


text:
template<class T> class SharedRingBufferReader;

template<class T>
class SharedRingBuffer : public ARingBuffer<T>
{
    friend class SharedRingBufferWriter<T>;
    friend class SharedRingBufferReader<T>;

    public:
        SharedRingBuffer<T>(int capacity);
        SharedRingBuffer<T>(T* buffer, int capacity);

        SharedRingBufferWriter<T> * getWriter() override;

    private:
        SharedRingBufferWriter<T> writer;
};

template<class T>
SharedRingBuffer<T>::SharedRingBuffer(int capacity) :
    ARingBuffer<T>(capacity), writer(this)
{ }

template<class T>
SharedRingBuffer<T>::SharedRingBuffer(T* buffer, int capacity) :
    ARingBuffer<T>(buffer, capacity), writer(this)
{ }

template<class T>
SharedRingBufferWriter<T> * SharedRingBuffer<T>::getWriter()
{
    return &writer;
}

#endif // SHAREDRINGBUFFER_H


text:
package hcsshim

import "github.com/Sirupsen/logrus"

// PrepareLayer finds a mounted read-write layer matching layerId and enables the
// the filesystem filter for use on that layer.  This requires the paths to all
// parent layers, and is necessary in order to view or interact with the layer
// as an actual filesystem (reading and writing files, creating directories, etc).
// Disabling the filter must be done via UnprepareLayer.
func PrepareLayer(info DriverInfo, layerId string, parentLayerPaths []string) error {
	title := "hcsshim::PrepareLayer "
	logrus.Debugf(title+"flavour %d layerId %s", info.Flavour, layerId)

	// Generate layer descriptors
	layers, err := layerPathsToDescriptors(parentLayerPaths)
	if err != nil {
		return err
	}

	// Convert info to API calling convention
	infop, err := convertDriverInfo(info)
	if err != nil {
		logrus.Error(err)
		return err
	}

	err = prepareLayer(&infop, layerId, layers)
	if err != nil {
		err = makeErrorf(err, title, "layerId=%s flavour=%d", layerId, info.Flavour)
		logrus.Error(err)
		return err
	}

	logrus.Debugf(title+"succeeded flavour=%d layerId=%s", info.Flavour, layerId)
	return nil
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syesis 16: 85 (1984)

#### Original name
Szczawinskia A. Funk

### Remarks
null


text:
NProgress.configure({
  showSpinner: false,
  ease: 'ease',
  speed: 500
});

window.onbeforeunload = function(e) {
  NProgress.start();
};

$(function(){
  // set timeout for alert close
  window.setTimeout(function() { $(".noty").alert('close'); }, 8000);

  // done progress bar when page loaded
  NProgress.set(0.2);
  NProgress.done();
});

// =================================
// CAMPAIGNS VIEW
// =================================
$(function(){
  // init datatable
  $('#campains-table, #adgroups-table, #ads-table, #keywords-table').DataTable({
    columnDefs: [{ targets: 'no-sort', orderable: false }],
    "dom": 'lCfrtip',
    "order": [],
    "colVis": {
      "buttonText": "Columns",
      "overlayFade": 0,
      "align": "right"
    },
    "language": {
      "lengthMenu": '_MENU_ entries per page',
      "search": '',
      "paginate": {
        "previous": '',
        "next": ''
      }
    }
  });

  // init select2 for account selector
  $('#selected_account_ids').select2();

  // init datepicker
  $('.datepicker').datepicker({
    format: 'yyyy-mm-dd',
    todayBtn: true,
    autoclose: true,
    todayHighlight: true
  });

  // toggle show the start_date and end_date input
  toggleShow();
  $('#date_range_type').change(toggleShow());

  // current tab's index in campaign's detail
  $('.nav-tabs li').click(function(){
    $('#tab_index').val($('.nav-tabs li').index($(this)));
  });
});

function toggleShow() {
  if($('#date_range_type').val() == 'CUSTOM_DATE'){
    $('#custom_start_date_group, #custom_end_date_group').show();
  }
  else{
    $('#custom_start_date_group, #custom_end_date_group').hide();
  }
}


text:
// Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT. See LICENSE in the project root for license information.

using System;
using System.Linq.Expressions;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal;

namespace Pomelo.EntityFrameworkCore.MySql.Query.Internal
{
    public class MySqlCompiledQueryCacheKeyGenerator : RelationalCompiledQueryCacheKeyGenerator
    {
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public MySqlCompiledQueryCacheKeyGenerator(
            [NotNull] CompiledQueryCacheKeyGeneratorDependencies dependencies,
            [NotNull] RelationalCompiledQueryCacheKeyGeneratorDependencies relationalDependencies)
            : base(dependencies, relationalDependencies)
        {
        }

        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public override object GenerateCacheKey(Expression query, bool async)
        {
            var extensions = RelationalDependencies.ContextOptions.FindExtension<MySqlOptionsExtension>();
            return new MySqlCompiledQueryCacheKey(
                GenerateCacheKeyCore(query, async),
                extensions?.ServerVersion,
                extensions?.NoBackslashEscapes ?? false);
        }

        private readonly struct MySqlCompiledQueryCacheKey
        {
            private readonly RelationalCompiledQueryCacheKey _relationalCompiledQueryCacheKey;
            private readonly ServerVersion _serverVersion;
            private readonly bool _noBackslashEscapes;

            public MySqlCompiledQueryCacheKey(
                RelationalCompiledQueryCacheKey relationalCompiledQueryCacheKey,
                ServerVersion serverVersion,
                bool noBackslashEscapes)
            {
                _relationalCompiledQueryCacheKey = relationalCompiledQueryCacheKey;
                _serverVersion = serverVersion;
                _noBackslashEscapes = noBackslashEscapes;
            }

            public override bool Equals(object obj)
                => !(obj is null)
                   && obj is MySqlCompiledQueryCacheKey key
                   && Equals(key);

            private bool Equals(MySqlCompiledQueryCacheKey other)
                => _relationalCompiledQueryCacheKey.Equals(other._relationalCompiledQueryCacheKey)
                   && Equals(_serverVersion, other._serverVersion)
                   && _noBackslashEscapes == other._noBackslashEscapes
                ;

            public override int GetHashCode()
                => HashCode.Combine(_relationalCompiledQueryCacheKey,
                    _serverVersion,
                    _noBackslashEscapes);
        }
    }
}