text:
package com.evolveum.midpoint.testing.story;

import static org.testng.AssertJUnit.assertTrue;
import static com.evolveum.midpoint.test.IntegrationTestTools.display;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;

import java.io.File;
import java.util.Collection;

import javax.xml.namespace.QName;

import com.evolveum.midpoint.notifications.api.transports.Message;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.Entry;
import org.opends.server.types.LDIFImportConfig;
import org.opends.server.types.SearchResultEntry;
import org.opends.server.util.LDIFException;
import org.opends.server.util.LDIFReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.evolveum.icf.dummy.resource.DummyAccount;
import com.evolveum.icf.dummy.resource.DummyObjectClass;
import com.evolveum.icf.dummy.resource.DummyResource;
import com.evolveum.icf.dummy.resource.DummySyncStyle;
import com.evolveum.midpoint.common.InternalsConfig;
import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition;
import com.evolveum.midpoint.common.refinery.RefinedResourceSchema;
import com.evolveum.midpoint.common.refinery.ShadowDiscriminatorObjectDelta;
import com.evolveum.midpoint.model.api.ModelExecuteOptions;
import com.evolveum.midpoint.model.api.PolicyViolationException;
import com.evolveum.midpoint.model.api.context.ModelContext;
import com.evolveum.midpoint.model.common.expression.evaluator.LiteralExpressionEvaluatorFactory;
import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest;
import com.evolveum.midpoint.prism.Containerable;
import com.evolveum.midpoint.prism.PrismContainer;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismProperty;
import com.evolveum.midpoint.prism.PrismPropertyDefinition;
import com.evolveum.midpoint.prism.PrismPropertyValue;
import com.evolveum.midpoint.prism.PrismReferenceValue;
import com.evolveum.midpoint.prism.delta.ChangeType;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.prism.delta.ReferenceDelta;
import com.evolveum.midpoint.prism.match.MatchingRule;
import com.evolveum.midpoint.prism.match.MatchingRuleRegistry;
import com.evolveum.midpoint.prism.match.StringIgnoreCaseMatchingRule;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.util.PrismAsserts;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.processor.ResourceAttribute;
import com.evolveum.midpoint.schema.processor.ResourceAttributeContainer;
import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.schema.util.MiscSchemaUtil;
import com.evolveum.midpoint.schema.util.ResourceTypeUtil;
import com.evolveum.midpoint.schema.util.ShadowUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.test.DummyResourceContoller;
import com.evolveum.midpoint.test.IntegrationTestTools;
import com.evolveum.midpoint.test.ProvisioningScriptSpec;
import com.evolveum.midpoint.test.util.MidPointTestConstants;
import com.evolveum.midpoint.test.util.TestUtil;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.MiscUtil;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ConstructionType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.MappingType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectFactory;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceAttributeDefinitionType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;

/**
 * @author Radovan Semancik
 *
 */
@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class TestVillage extends AbstractStoryTest {

	public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "village");

	public static final File SYSTEM_CONFIGURATION_FILE = new File(TEST_DIR, "system-configuration.xml");

	public static final File OBJECT_TEMPLATE_USER_FILE = new File(TEST_DIR, "object-template-user.xml");
	public static final String OBJECT_TEMPLATE_USER_OID = "10000000-0000-0000-0000-000000000222";

	protected static final File RESOURCE_DUMMY_SOURCE_FILE = new File(TEST_DIR, "resource-dummy-source.xml");
	protected static final String RESOURCE_DUMMY_SOURCE_ID = "SRC";
	protected static final String RESOURCE_DUMMY_SOURCE_OID = "10000000-0000-0000-0000-000000000001";
	protected static final String RESOURCE_DUMMY_SOURCE_NAMESPACE = MidPointConstants.NS_RI;

	protected static final File RESOURCE_OPENDJ_FILE = new File(TEST_DIR, "resource-opendj.xml");
	protected static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000003";
	protected static final String RESOURCE_OPENDJ_NAMESPACE = MidPointConstants.NS_RI;
	protected static final QName OPENDJ_ASSOCIATION_GROUP_NAME = new QName(RESOURCE_OPENDJ_NAMESPACE, "group");

	private static final String DUMMY_ACCOUNT_ATTRIBUTE_SRC_FIRST_NAME = "firstname";
	private static final String DUMMY_ACCOUNT_ATTRIBUTE_SRC_LAST_NAME = "lastname";
	private static final String DUMMY_ACCOUNT_ATTRIBUTE_SRC_TYPE = "type";
	private static final String DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC = "loc";
	private static final String DUMMY_ACCOUNT_ATTRIBUTE_SRC_ORG = "org";

	public static final File ROLE_BASIC_FILE = new File(TEST_DIR, "role-basic.xml");
	public static final String ROLE_BASIC_OID = "10000000-0000-0000-0000-000000000601";
	public static final String ROLE_BASIC_NAME = "Basic";

	public static final File ROLE_SIMPLE_FILE = new File(TEST_DIR, "role-account-construction.xml");
	public static final String ROLE_SIMPLE_OID = "10000000-0000-0000-0000-000000000602";
	public static final String ROLE_SIMPLE_NAME = "Simple account construction";

	public static final File ROLE_META_FUNCTIONAL_ORG_FILE = new File(TEST_DIR, "role-meta-functional-org.xml");
	public static final String ROLE_META_FUNCTIONAL_ORG_OID = "74aac2c8-ca0f-11e3-bb29-001e8c717e5b";

	public static final File ROLE_META_PROJECT_ORG_FILE = new File(TEST_DIR, "role-meta-project-org.xml");
	public static final String ROLE_META_PROJECT_ORG_OID = "ab33ec1e-0c0b-11e4-ba88-001e8c717e5b";

	protected static final File ORGS_FILE = new File(TEST_DIR, "orgs.xml");
	public static final String ORG_GOV_NAME = "Gov";
	public static final String ORG_EXEC_NAME = "Exec";
	public static final String ORG_INFRA_NAME = "Infra";

	public static final String ORG_INFRA_OID = "00000000-8888-6666-0000-100000000004";
	private static final String GLOBAL_PASSWORD_POLICY_OID = "81818181-76e0-59e2-8888-3d4f02d3fffc";
	private static final String ORG_PASSWORD_POLICY_OID = "81818181-76e0-59e2-8888-3d4f02d3fffe";
	private static final File GLOBAL_PASSWORD_POLICY_FILE = new File(TEST_DIR, "global-password-policy.xml");
	private static final File ORG_PASSWORD_POLICY_FILE = new File(TEST_DIR, "org-password-policy.xml");

	public static final File ORG_PROJECT_JOLLY_ROGER_FILE = new File(TEST_DIR, "org-project-jolly-roger.xml");
	public static final String ORG_PROJECT_JOLLY_ROGER_OID = "a9ac1aa2-0c0f-11e4-9214-001e8c717e5b";

	protected static final File TASK_LIVE_SYNC_DUMMY_SOURCE_FILE = new File(TEST_DIR, "task-dumy-source-livesync.xml");
	protected static final String TASK_LIVE_SYNC_DUMMY_SOURCE_OID = "10000000-0000-0000-5555-555500000001";

	private static final File USER_MIKE_FILE = new File(COMMON_DIR, "user-mike.xml");
	private static final String USER_MIKE_OID = "c0c010c0-d34d-b33f-f00d-222333111111";

	private static final File USER_MURRAY_FILE = new File(TEST_DIR, "user-murray.xml");
	private static final String USER_MURRAY_OID = "c0c010c0-d34d-b33f-f00d-1111111111aa";

	private static final String ACCOUNT_HERMAN_USERNAME = "ht";
	private static final String ACCOUNT_HERMAN_FIST_NAME = "Herman";
	private static final String ACCOUNT_HERMAN_LAST_NAME = "Toothrot";
	private static final String ACCOUNT_HERMAN_LOC = "Monkey Island";
	private static final String ACCOUNT_HERMAN_ORG = "Gov";
	private static final String USER_HERMAN_NAME = "G."+ACCOUNT_HERMAN_FIST_NAME+"."+ACCOUNT_HERMAN_LAST_NAME;

	private static final String ACCOUNT_LEMONHEAD_USERNAME = "lemonhead";
	private static final String ACCOUNT_LEMONHEAD_FIST_NAME = "Lemonhead";
	private static final String ACCOUNT_LEMONHEAD_LAST_NAME = "Canibal";
	private static final String ACCOUNT_LEMONHEAD_LOC = "Monkey Island";
	private static final String ACCOUNT_LEMONHEAD_ORG = "Exec";
	private static final String USER_LEMONHEAD_NAME = "E."+ACCOUNT_LEMONHEAD_FIST_NAME+"."+ACCOUNT_LEMONHEAD_LAST_NAME;

	private static final String ACCOUNT_SHARPTOOTH_USERNAME = "sharptooth";
	private static final String ACCOUNT_SHARPTOOTH_FIST_NAME = "Sharptooth";
	private static final String ACCOUNT_SHARPTOOTH_LAST_NAME = "Canibal";

	private static final String ACCOUNT_GUYBRUSH_USERNAME = "guybrush";
	private static final String ACCOUNT_GUYBRUSH_FIST_NAME = "Guybrush";
	private static final String ACCOUNT_GUYBRUSH_LAST_NAME = "Threepwood";

	private static final String ACCOUNT_MANCOMB_USERNAME = "mancomb";
	private static final String ACCOUNT_MANCOMB_FIST_NAME = "Mancomb";
	private static final String ACCOUNT_MANCOMB_LAST_NAME = "Seepgood";
	private static final String ACCOUNT_MANCOMB_LOC = "-";
	private static final String ACCOUNT_MANCOMB_ORG = "-";
	private static final String USER_MANCOMB_NAME = ACCOUNT_MANCOMB_FIST_NAME+"."+ACCOUNT_MANCOMB_LAST_NAME;

	private static final String ACCOUNT_COBB_USERNAME = "cobb";
	private static final String ACCOUNT_COBB_FIST_NAME = "Cobb";
	private static final String ACCOUNT_COBB_LAST_NAME = "Loom";

	private static final String ACCOUNT_LARGO_USERNAME = "largo";
	private static final String ACCOUNT_LARGO_FIST_NAME = "Largo";
	private static final String ACCOUNT_LARGO_LAST_NAME = "LaGrande";

	private static final String ACCOUNT_STAN_USERNAME = "stan";
	private static final String ACCOUNT_STAN_FIST_NAME = "Stan";
	private static final String ACCOUNT_STAN_LAST_NAME = "Salesman";

	private static final String ACCOUNT_CAPSIZE_USERNAME = "capsize";
	private static final String ACCOUNT_CAPSIZE_FIST_NAME = "Kate";
	private static final String ACCOUNT_CAPSIZE_LAST_NAME = "Capsize";

	private static final String ACCOUNT_WALLY_USERNAME = "wally";
	private static final String ACCOUNT_WALLY_FIST_NAME = "Wally";
	private static final String ACCOUNT_WALLY_LAST_NAME = "Feed";
	private static final String USER_WALLY_NAME = ACCOUNT_WALLY_FIST_NAME+"."+ACCOUNT_WALLY_LAST_NAME;

	private static final String ACCOUNT_AUGUSTUS_USERNAME = "augustus";
	private static final String ACCOUNT_AUGUSTUS_FIST_NAME = "Augustus";
	private static final String ACCOUNT_AUGUSTUS_LAST_NAME = "DeWaat";

	private static final String ACCOUNT_ROGERSSR_USERNAME = "rogers,sr";
	private static final String ACCOUNT_ROGERSSR_FIST_NAME = "Rum";
	private static final String ACCOUNT_ROGERSSR_LAST_NAME = "Rogers, Sr.";

	private static final String ACCOUNT_TELEKE_USERNAME = "tőlőkë";
	private static final String ACCOUNT_TELEKE_FIST_NAME = "Félix";
	private static final String ACCOUNT_TELEKE_LAST_NAME = "Tőlőkë";

	private static final File GROUP_GOV_MONKEY_ISLAND_LDIF_FILE = new File(TEST_DIR, "group-gov-monkey-island.ldif");
	private static final File GROUP_EXEC_MONKEY_ISLAND_LDIF_FILE = new File(TEST_DIR, "group-exec-monkey-island.ldif");

	protected static DummyResource dummyResourceSrc;
	protected static DummyResourceContoller dummyResourceCtlSrc;
	protected ResourceType resourceDummySrcType;
	protected PrismObject<ResourceType> resourceDummySrc;

	protected ResourceType resourceOpenDjType;
	protected PrismObject<ResourceType> resourceOpenDj;

	@Override
    protected void startResources() throws Exception {
        openDJController.startCleanServer();
    }

    @AfterClass
    public static void stopResources() throws Exception {
        openDJController.stop();
    }

	@Override
	public void initSystem(Task initTask, OperationResult initResult) throws Exception {
		super.initSystem(initTask, initResult);

		// Resources
		dummyResourceCtlSrc = DummyResourceContoller.create(RESOURCE_DUMMY_SOURCE_ID, resourceDummySrc);
		DummyObjectClass dummyAdAccountObjectClass = dummyResourceCtlSrc.getDummyResource().getAccountObjectClass();
		dummyResourceCtlSrc.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_SRC_FIRST_NAME, String.class, false, false);
		dummyResourceCtlSrc.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_SRC_LAST_NAME, String.class, false, false);
		dummyResourceCtlSrc.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_SRC_TYPE, String.class, false, false);
		dummyResourceCtlSrc.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC, String.class, false, false);
		dummyResourceCtlSrc.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_SRC_ORG, String.class, false, false);
		dummyResourceSrc = dummyResourceCtlSrc.getDummyResource();
		resourceDummySrc = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_SOURCE_FILE, RESOURCE_DUMMY_SOURCE_OID, initTask, initResult);
		resourceDummySrcType = resourceDummySrc.asObjectable();
		dummyResourceCtlSrc.setResource(resourceDummySrc);
		dummyResourceSrc.setSyncStyle(DummySyncStyle.SMART);

		resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, RESOURCE_OPENDJ_FILE, RESOURCE_OPENDJ_OID, initTask, initResult);
		resourceOpenDjType = resourceOpenDj.asObjectable();
		openDJController.setResource(resourceOpenDj);

		// Object Templates
		importObjectFromFile(OBJECT_TEMPLATE_USER_FILE, initResult);
		setDefaultUserTemplate(OBJECT_TEMPLATE_USER_OID);

		// Role
		importObjectFromFile(ROLE_BASIC_FILE, initResult);
		importObjectFromFile(ROLE_SIMPLE_FILE, initResult);
		importObjectFromFile(ROLE_META_FUNCTIONAL_ORG_FILE, initResult);
		importObjectFromFile(ROLE_META_PROJECT_ORG_FILE, initResult);

		// Org
		repoAddObjectsFromFile(ORGS_FILE, OrgType.class, initResult);

		// LDAP content
		openDJController.addEntryFromLdifFile(GROUP_GOV_MONKEY_ISLAND_LDIF_FILE);
		openDJController.addEntryFromLdifFile(GROUP_EXEC_MONKEY_ISLAND_LDIF_FILE);

		// Tasks
		importObjectFromFile(TASK_LIVE_SYNC_DUMMY_SOURCE_FILE, initResult);

	}

	@Override
	protected File getSystemConfigurationFile() {
		return SYSTEM_CONFIGURATION_FILE;
	}

	@Test
    public void test000Sanity() throws Exception {
		final String TEST_NAME = "test000Sanity";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        OperationResult testResultHr = modelService.testResource(RESOURCE_DUMMY_SOURCE_OID, task);
        TestUtil.assertSuccess(testResultHr);

        OperationResult testResultOpenDj = modelService.testResource(RESOURCE_OPENDJ_OID, task);
        TestUtil.assertSuccess(testResultOpenDj);

        SystemConfigurationType systemConfiguration = getSystemConfiguration();
        assertNotNull("No system configuration", systemConfiguration);
        display("System config", systemConfiguration);

        waitForTaskStart(TASK_TRIGGER_SCANNER_OID, true);
        waitForTaskStart(TASK_VALIDITY_SCANNER_OID, true);
        waitForTaskStart(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, false);
	}

	@Test
    public void test100AddSrcAccountHerman() throws Exception {
		final String TEST_NAME = "test100AddSrcAccountHerman";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        DummyAccount newAccount = new DummyAccount(ACCOUNT_HERMAN_USERNAME);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_FIRST_NAME, ACCOUNT_HERMAN_FIST_NAME);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LAST_NAME, ACCOUNT_HERMAN_LAST_NAME);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC, ACCOUNT_HERMAN_LOC);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_ORG, ACCOUNT_HERMAN_ORG);

        // WHEN
        dummyResourceSrc.addAccount(newAccount);
        waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true);

        // THEN
        PrismObject<UserType> user = findUserByUsername(USER_HERMAN_NAME);
        assertUserNoRole(user, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG);
        assertLocGov(user, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
	}

	@Test
    public void test101HermanAssignBasicRole() throws Exception {
		final String TEST_NAME = "test101HermanAssignBasicRole";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        PrismObject<UserType> user = findUserByUsername(USER_HERMAN_NAME);

        // WHEN
        assignRole(user.getOid(), ROLE_BASIC_OID);

        // THEN
        PrismObject<UserType> userAfter = getUser(user.getOid());
        assertUserLdap(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG);
        assertLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
        assertLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
	}

	@Test
    public void test102HermanUnAssignBasicRole() throws Exception {
		final String TEST_NAME = "test102HermanUnAssignBasicRole";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        PrismObject<UserType> user = findUserByUsername(USER_HERMAN_NAME);

        // WHEN
        unassignRole(user.getOid(), ROLE_BASIC_OID);

        // THEN
        PrismObject<UserType> userAfter = getUser(user.getOid());
        assertUserNoRole(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG);
        assertLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
        assertNoLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
	}

	@Test
    public void test103HermanAssignBasicAndSimpleRole() throws Exception {
		final String TEST_NAME = "test103HermanAssignBasicAndSimpleRole";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        PrismObject<UserType> user = findUserByUsername(USER_HERMAN_NAME);

        // WHEN
        assignRole(user.getOid(), ROLE_SIMPLE_OID);
        assignRole(user.getOid(), ROLE_BASIC_OID);

        // THEN
        PrismObject<UserType> userAfter = getUser(user.getOid());
        assertUserLdap(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG, 2);
        assertAssignedRole(userAfter, ROLE_SIMPLE_OID);
        assertLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
        assertLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
	}

	@Test
    public void test104HermanUnAssignSimpleRoleThenBasic() throws Exception {
		final String TEST_NAME = "test104HermanUnAssignSimpleRoleThenBasic";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        PrismObject<UserType> user = findUserByUsername(USER_HERMAN_NAME);

        // WHEN
        unassignRole(user.getOid(), ROLE_BASIC_OID);

        // THEN
        PrismObject<UserType> userAfter = getUser(user.getOid());
        assertAssignedRole(userAfter, ROLE_SIMPLE_OID);
//        assertUserLdap(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG);
        assertLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
        assertNoLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);

        // WHEN
        unassignRole(user.getOid(), ROLE_SIMPLE_OID);

        // THEN
        userAfter = getUser(user.getOid());
        assertUserNoRole(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG);
        assertLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
        assertNoLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
	}

	@Test
    public void test105ModifySrcAccountHermanRemoveLoc() throws Exception {
		final String TEST_NAME = "test105ModifySrcAccountHermanRemoveLoc";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME);

        // WHEN
        account.replaceAttributeValues(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC);
        waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true);

        // THEN
        PrismObject<UserType> user = findUserByUsername(USER_HERMAN_NAME);
        assertUserNoRole(user, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG);
        assertLocGov(user, null, ACCOUNT_HERMAN_ORG);
	}

	@Test
    public void test106HermanAssignBasicRole() throws Exception {
		final String TEST_NAME = "test106HermanAssignBasicRole";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        PrismObject<UserType> user = findUserByUsername(USER_HERMAN_NAME);

        // WHEN
        assignRole(user.getOid(), ROLE_BASIC_OID);

        // THEN
        PrismObject<UserType> userAfter = getUser(user.getOid());
        assertUserLdap(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG);
        assertLocGov(userAfter, null, ACCOUNT_HERMAN_ORG);
        assertNoLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
	}

	@Test
    public void test107ModifySrcAccountHermanAddLoc() throws Exception {
		final String TEST_NAME = "test107ModifySrcAccountHermanAddLoc";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME);

        // WHEN
        account.replaceAttributeValues(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC, ACCOUNT_HERMAN_LOC);
        waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true);

        // THEN
        PrismObject<UserType> user = findUserByUsername(USER_HERMAN_NAME);
        assertUserLdap(user, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG);
        assertLocGov(user, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
        assertLdapLocGov(user, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
	}

	@Test
    public void test108ModifySrcAccountHermanRemoveLoc() throws Exception {
		final String TEST_NAME = "test108ModifySrcAccountHermanRemoveLoc";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME);

        // WHEN
        account.replaceAttributeValues(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC);
        waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true);

        // THEN
        PrismObject<UserType> user = findUserByUsername(USER_HERMAN_NAME);
        assertUserLdap(user, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG);
        assertLocGov(user, null, ACCOUNT_HERMAN_ORG);
        assertNoLdapLocGov(user, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
	}

	@Test
    public void test109HermanUnAssignBasicRole() throws Exception {
		final String TEST_NAME = "test109HermanUnAssignBasicRole";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        PrismObject<UserType> user = findUserByUsername(USER_HERMAN_NAME);

        // WHEN
        unassignRole(user.getOid(), ROLE_BASIC_OID);

        // THEN
        PrismObject<UserType> userAfter = getUser(user.getOid());
        assertUserNoRole(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG);
        assertLocGov(userAfter, null, ACCOUNT_HERMAN_ORG);
        assertNoLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG);
	}

	@Test
    public void test110AddSrcAccountLemonhead() throws Exception {
		final String TEST_NAME = "test110AddSrcAccountLemonhead";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        DummyAccount newAccount = new DummyAccount(ACCOUNT_LEMONHEAD_USERNAME);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_FIRST_NAME, ACCOUNT_LEMONHEAD_FIST_NAME);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LAST_NAME, ACCOUNT_LEMONHEAD_LAST_NAME);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_TYPE, ROLE_BASIC_NAME);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC, ACCOUNT_LEMONHEAD_LOC);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_ORG, ACCOUNT_LEMONHEAD_ORG);

        // WHEN
        dummyResourceSrc.addAccount(newAccount);
        waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true);

        // THEN
        PrismObject<UserType> userAfter = findUserByUsername(USER_LEMONHEAD_NAME);
        assertUserLdap(userAfter, ACCOUNT_LEMONHEAD_FIST_NAME, ACCOUNT_LEMONHEAD_LAST_NAME, ACCOUNT_LEMONHEAD_ORG);
        assertLocGov(userAfter, ACCOUNT_LEMONHEAD_LOC, ACCOUNT_LEMONHEAD_ORG);
        assertLdapLocGov(userAfter, ACCOUNT_LEMONHEAD_LOC, ACCOUNT_LEMONHEAD_ORG);
	}

	/**
	 * Wally has no org. User without an org should be created.
	 */
	@Test
    public void test120AddSrcAccountWally() throws Exception {
		final String TEST_NAME = "test120AddSrcAccountWally";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        DummyAccount newAccount = new DummyAccount(ACCOUNT_WALLY_USERNAME);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_FIRST_NAME, ACCOUNT_WALLY_FIST_NAME);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LAST_NAME, ACCOUNT_WALLY_LAST_NAME);

        // WHEN
        dummyResourceSrc.addAccount(newAccount);
        waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true);

        // THEN
        PrismObject<UserType> userAfter = findUserByUsername(USER_WALLY_NAME);
        assertUserNoRole(userAfter, ACCOUNT_WALLY_FIST_NAME, ACCOUNT_WALLY_LAST_NAME, null);
        assertLocGov(userAfter, null, null);
	}

	@Test
    public void test121WallyAssignBasicRole() throws Exception {
		final String TEST_NAME = "test121WallyAssignBasicRole";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        PrismObject<UserType> user = findUserByUsername(USER_WALLY_NAME);

        // WHEN
        assignRole(user.getOid(), ROLE_BASIC_OID);

        // THEN
        PrismObject<UserType> userAfter = getUser(user.getOid());
        assertUserLdap(userAfter, ACCOUNT_WALLY_FIST_NAME, ACCOUNT_WALLY_LAST_NAME, null);
        assertLocGov(userAfter, null, null);
	}

	@Test
    public void test122WallyUnAssignBasicRole() throws Exception {
		final String TEST_NAME = "test122WallyUnAssignBasicRole";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        PrismObject<UserType> user = findUserByUsername(USER_WALLY_NAME);

        // WHEN
        unassignRole(user.getOid(), ROLE_BASIC_OID);

        // THEN
        PrismObject<UserType> userAfter = getUser(user.getOid());
        assertUserNoRole(userAfter, ACCOUNT_WALLY_FIST_NAME, ACCOUNT_WALLY_LAST_NAME, null);
        assertLocGov(userAfter, null, null);
	}

	/**
	 * Wally has no org. User without an org should be created.
	 */
	@Test
    public void test130AddSrcAccountMancomb() throws Exception {
		final String TEST_NAME = "test130AddSrcAccountMancomb";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        DummyAccount newAccount = new DummyAccount(ACCOUNT_MANCOMB_USERNAME);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_FIRST_NAME, ACCOUNT_MANCOMB_FIST_NAME);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LAST_NAME, ACCOUNT_MANCOMB_LAST_NAME);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC, ACCOUNT_MANCOMB_LOC);
        newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_ORG, ACCOUNT_MANCOMB_ORG);

        // WHEN
        dummyResourceSrc.addAccount(newAccount);
        waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true);

        // THEN
        PrismObject<UserType> userAfter = findUserByUsername(USER_MANCOMB_NAME);
        assertUserNoRole(userAfter, ACCOUNT_MANCOMB_FIST_NAME, ACCOUNT_MANCOMB_LAST_NAME, null);
        assertLocGov(userAfter, ACCOUNT_MANCOMB_LOC, ACCOUNT_MANCOMB_ORG);
	}

	@Test
    public void test131MancombAssignBasicRole() throws Exception {
		final String TEST_NAME = "test131WallyAssignBasicRole";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        PrismObject<UserType> user = findUserByUsername(USER_MANCOMB_NAME);

        // WHEN
        assignRole(user.getOid(), ROLE_BASIC_OID);

        // THEN
        PrismObject<UserType> userAfter = getUser(user.getOid());
        assertUserLdap(userAfter, ACCOUNT_MANCOMB_FIST_NAME, ACCOUNT_MANCOMB_LAST_NAME, null);
        assertLocGov(userAfter, ACCOUNT_MANCOMB_LOC, ACCOUNT_MANCOMB_ORG);
	}

	@Test
    public void test132MancombUnAssignBasicRole() throws Exception {
		final String TEST_NAME = "test132MancombUnAssignBasicRole";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        PrismObject<UserType> user = findUserByUsername(USER_MANCOMB_NAME);

        // WHEN
        unassignRole(user.getOid(), ROLE_BASIC_OID);

        // THEN
        PrismObject<UserType> userAfter = getUser(user.getOid());
        assertUserNoRole(userAfter, ACCOUNT_MANCOMB_FIST_NAME, ACCOUNT_MANCOMB_LAST_NAME, null);
        assertLocGov(userAfter, ACCOUNT_MANCOMB_LOC, ACCOUNT_MANCOMB_ORG);
	}

	/**
	 * Change of org should trigger rename
	 */
	@Test
    public void test150ModifySrcAccountHermanReplaceOrg() throws Exception {
		final String TEST_NAME = "test150ModifySrcAccountHermanReplaceOrg";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME);

        // WHEN
        account.replaceAttributeValues(DUMMY_ACCOUNT_ATTRIBUTE_SRC_ORG, ORG_INFRA_NAME);
        waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true);

        // THEN
        PrismObject<UserType> user = findUserByUsername(getUsername(ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ORG_INFRA_NAME));
        assertUserNoRole(user, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ORG_INFRA_NAME);
        assertLocGov(user, null, ORG_INFRA_NAME);

        PrismObject<UserType> userGone = findUserByUsername(USER_HERMAN_NAME);
        assertNull("Original herman is not gone", userGone);
	}

	/**
	 * Change of org should trigger rename
	 */
	@Test
    public void test152ModifySrcAccountHermanDeleteOrg() throws Exception {
		final String TEST_NAME = "test152ModifySrcAccountHermanDeleteOrg";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);

        DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME);

        // WHEN
        TestUtil.displayWhen(TEST_NAME);
        account.replaceAttributeValues(DUMMY_ACCOUNT_ATTRIBUTE_SRC_ORG);
        waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true);

        // THEN
        TestUtil.displayThen(TEST_NAME);
        PrismObject<UserType> user = findUserByUsername(getUsername(ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, null));
        assertUserNoRole(user, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, null);
        assertLocGov(user, null, null);

        PrismObject<UserType> userGone = findUserByUsername(USER_HERMAN_NAME);
        assertNull("Original herman is not gone", userGone);
        userGone = findUserByUsername(getUsername(ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ORG_INFRA_NAME));
        assertNull("First renamed herman is not gone", userGone);
	}

	@Test
	public void test200createUserAssignOrgPwdPolicy() throws Exception{

		final String TEST_NAME = "test200createUserAssignOrgPwdPolicy";
        TestUtil.displayTestTile(this, TEST_NAME);
		Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME);
		OperationResult result = new OperationResult(TEST_NAME);

		//prepare password policies
		addObject(GLOBAL_PASSWORD_POLICY_FILE);
		addObject(ORG_PASSWORD_POLICY_FILE);

		ObjectDelta orgPasswordPolicyRefDelta = ObjectDelta.createModificationAddReference(OrgType.class, ORG_INFRA_OID, OrgType.F_PASSWORD_POLICY_REF, prismContext, ORG_PASSWORD_POLICY_OID);

		Collection deltas = MiscUtil.createCollection(orgPasswordPolicyRefDelta);
		modelService.executeChanges(deltas, null, task, result);

		InternalsConfig.avoidLoggingChange = true;
		ObjectDelta sysConfigPasswordPolicyRefDelta = ObjectDelta.createModificationAddReference(SystemConfigurationType.class, SYSTEM_CONFIGURATION_OID, SystemConfigurationType.F_GLOBAL_PASSWORD_POLICY_REF, prismContext, GLOBAL_PASSWORD_POLICY_OID);
		deltas = MiscUtil.createCollection(sysConfigPasswordPolicyRefDelta);
		modelService.executeChanges(deltas, null, task, result);
		InternalsConfig.avoidLoggingChange = false;

		//add user + assign role + assign org with the password policy specified
		PrismObject<UserType> objectToAdd = PrismTestUtil.parseObject(USER_MIKE_FILE);
		ObjectDelta<UserType> addUser = ObjectDelta.createAddDelta(objectToAdd);

		deltas = MiscUtil.createCollection(addUser);
		//The user's password has length 4..if the policy is not chosen correctly, it fails
		modelService.executeChanges(deltas, null, task, result);

		//TODO: assert added user

	}

	@Test
	public void test201unassignRole() throws Exception{
		final String TEST_NAME = "test201unassignRole";
        TestUtil.displayTestTile(this, TEST_NAME);
		unassignRole(USER_MIKE_OID, ROLE_BASIC_OID);
		//TODO: assertions
	}

	@Test
	public void test202assignRoleOrgPwdPolicy() throws Exception{
		final String TEST_NAME = "test202assignRoleOrgPwdPolicy";
        TestUtil.displayTestTile(this, TEST_NAME);

        //this will throw exception, if incorrect pwd policy is selected...but some assertion will be nice :)
        assignRole(USER_MIKE_OID, ROLE_BASIC_OID);

		//TODO: assertion
	}

	@Test
    public void test300AddProjectJollyRoger() throws Exception {
		final String TEST_NAME = "test300AddProjectJollyRoger";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);
        OperationResult result = task.getResult();

        // WHEN
        TestUtil.displayWhen(TEST_NAME);
        addObject(ORG_PROJECT_JOLLY_ROGER_FILE, task, result);

        // THEN
        TestUtil.displayThen(TEST_NAME);
        result.computeStatus();
        TestUtil.assertSuccess(result);

        PrismObject<OrgType> org = getObject(OrgType.class, ORG_PROJECT_JOLLY_ROGER_OID);
        display("Org", org);
        assertLinks(org, 2);

        SearchResultEntry ouEntry = openDJController.fetchAndAssertEntry("ou=Jolly Roger,dc=example,dc=com", "organizationalUnit");
        SearchResultEntry groupEntry = openDJController.fetchAndAssertEntry("cn=admins,ou=Jolly Roger,dc=example,dc=com", "groupOfUniqueNames");
      //TODO: more assertions
	}

	@Test
    public void test319DeleteProjectJollyRoger() throws Exception {
		final String TEST_NAME = "test319DeleteProjectJollyRoger";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);
        OperationResult result = task.getResult();

        // WHEN
        TestUtil.displayWhen(TEST_NAME);
        deleteObject(OrgType.class, ORG_PROJECT_JOLLY_ROGER_OID, task, result);

        // THEN
        TestUtil.displayThen(TEST_NAME);
        result.computeStatus();
        TestUtil.assertSuccess(result);

        assertNoObject(OrgType.class, ORG_PROJECT_JOLLY_ROGER_OID, task, result);
        openDJController.assertNoEntry("ou=Jolly Roger,dc=example,dc=com");
        openDJController.assertNoEntry("cn=admins,ou=Jolly Roger,dc=example,dc=com");
	}

	/**
	 * User is added to repo directly, so he does not have OID in employee number.
	 * Recompute should fix that. This is a migration scenario.
	 */
	@Test
    public void test350AddRepoUserNoEmployeeNumberRecompute() throws Exception {
		final String TEST_NAME = "test350AddRepoUserNoEmployeeNumberRecompute";
        TestUtil.displayTestTile(this, TEST_NAME);
        Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME);
        OperationResult result = task.getResult();

        PrismObject<UserType> user = PrismTestUtil.parseObject(USER_MURRAY_FILE);
        repositoryService.addObject(user, null, result);

        // WHEN
        TestUtil.displayWhen(TEST_NAME);
        recomputeUser(USER_MURRAY_OID, task, result);

        // THEN
        TestUtil.displayThen(TEST_NAME);
        result.computeStatus();
        TestUtil.assertSuccess(result);

        user = getUser(USER_MURRAY_OID);
        assertEmployeeNumber(user);
	}

	private void assertLocGov(PrismObject<UserType> user, String expLoc, String expOrg) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException {
		UserType userType = user.asObjectable();
		PrismAsserts.assertEqualsPolyString("Wrong locality in "+user, expLoc, userType.getLocality());
		if (expOrg == null) {
			assertTrue("Unexpected organization in "+user+": "+userType.getOrganization(), userType.getOrganization().isEmpty());
		} else {
			PrismAsserts.assertEqualsCollectionUnordered("Wrong organization in "+user, userType.getOrganization(),
				PrismTestUtil.createPolyStringType(expOrg));
		}
		if (expLoc == null || expOrg == null) {
			assertNull("Wrong costCenter in "+user+", expected empty but was "+userType.getCostCenter(), userType.getCostCenter());
		} else {
			assertEquals("Wrong costCenter in "+user, userType.getCostCenter(), expOrg+":"+expLoc);
		}
		if (expOrg != null && !expOrg.equals("-")) {
			PrismObject<OrgType> org = findObjectByName(OrgType.class, expOrg);
			assertAssigned(user, org.getOid(), OrgType.COMPLEX_TYPE);
			String orgId = org.asObjectable().getIdentifier();
			PrismAsserts.assertEqualsCollectionUnordered("Wrong organizationalUnit in "+user,
					userType.getOrganizationalUnit(), PrismTestUtil.createPolyStringType(orgId));
			assertEquals("Wrong title in "+user, "Member of "+orgId, userType.getTitle().getOrig());
		} else {
			assertAssignments(user, OrgType.class, 0);
			assertTrue("Unexpected organizationalUnit in "+user+": "+userType.getOrganizationalUnit(), userType.getOrganizationalUnit().isEmpty());
			assertNull("Unexpected title in "+user+": "+userType.getDescription(), userType.getTitle());
		}
	}

	private void assertUserNoRole(PrismObject<UserType> user, String firstName, String lastName, String orgName) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException {
		String username = getUsername(firstName, lastName, orgName);
		assertNotNull("No "+username+" user", user);
        display("User", user);
   		assertUser(user, user.getOid(), username, firstName+" "+lastName,
   				firstName, lastName);
   		assertEmployeeNumber(user);
   		assertLinks(user, 1);
        assertAccount(user, RESOURCE_DUMMY_SOURCE_OID);
        assertAssignments(user, RoleType.class, 0);

        openDJController.assertNoEntry("uid="+username+",ou=people,dc=example,dc=com");
	}

	private void assertUserLdap(PrismObject<UserType> user, String firstName, String lastName, String orgName) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException {
		assertUserLdap(user, firstName, lastName, orgName, 1);
	}

	private void assertUserLdap(PrismObject<UserType> user, String firstName, String lastName, String orgName, int assignments) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException {
		String username = getUsername(firstName, lastName, orgName);
		assertNotNull("No "+username+" user", user);
        display("User", user);
   		assertUser(user, user.getOid(), username, firstName+" "+lastName,
   				firstName, lastName);
   		assertEmployeeNumber(user);
        assertLinks(user, 2);
        assertAccount(user, RESOURCE_DUMMY_SOURCE_OID);

        assertAssignments(user, RoleType.class, assignments);
        assertAssignedRole(user, ROLE_BASIC_OID);

        assertAccount(user, RESOURCE_OPENDJ_OID);
        PrismReferenceValue linkRef = getLinkRef(user, RESOURCE_OPENDJ_OID);
        PrismObject<ShadowType> shadow = getShadowModel(linkRef.getOid());
		display("OpenDJ shadow linked to "+user, shadow);
		IntegrationTestTools.assertSecondaryIdentifier(shadow, "uid="+username+",ou=people,dc=example,dc=com");
	}

	private void assertEmployeeNumber(PrismObject<UserType> user) {
		String employeeNumber = user.asObjectable().getEmployeeNumber();
		assertEquals("Wrong employeeNumber in "+user, user.getOid(), employeeNumber);
	}

	private String getUsername(String firstName, String lastName, String orgName) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException {
		String username = firstName+"."+lastName;
		if (orgName != null) {
			PrismObject<OrgType> org = findObjectByName(OrgType.class, orgName);
			username = org.asObjectable().getIdentifier()+"."+username;
		}
		return username;
	}

	private void assertLdapLocGov(PrismObject<UserType> user, String expLoc, String expOrg) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException {
		UserType userType = user.asObjectable();

		String groupCn = expOrg+":"+expLoc;
		String groupDn = "cn="+groupCn+",ou=groups,"+openDJController.getSuffix();
		SearchResultEntry groupEntry = openDJController.fetchAndAssertEntry(groupDn, "groupOfUniqueNames");
		display("Group entry", groupEntry);

		PrismReferenceValue accountLinkRef = getLinkRef(user, RESOURCE_OPENDJ_OID);
		PrismObject<ShadowType> accountShadow = getShadowModel(accountLinkRef.getOid());
		String accountDn = IntegrationTestTools.getSecondaryIdentifier(accountShadow);
		openDJController.assertUniqueMember(groupEntry, accountDn);
	}

	private void assertNoLdapLocGov(PrismObject<UserType> user, String expLoc, String expOrg) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException {
		UserType userType = user.asObjectable();

		String groupCn = expOrg+":"+expLoc;
		String groupDn = "cn="+groupCn+",ou=groups,"+openDJController.getSuffix();
		SearchResultEntry groupEntry = openDJController.fetchAndAssertEntry(groupDn, "groupOfUniqueNames");
		display("Group entry", groupEntry);
		String accountDn = "uid="+userType.getName()+",ou=people,"+openDJController.getSuffix();
		openDJController.assertNoUniqueMember(groupEntry, accountDn);
	}

}


text:
@interface ClickableTextField : NSTextField

@end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.cardpay.pccredit.intopieces.dao.IntoPiecesDao" >

 	<resultMap id="IntoPiecesResultMap" type="com.cardpay.pccredit.intopieces.model.IntoPieces">
		<result property="id" column="id" />
		<result property="customerId" column="customer_id" />
		<result property="tyCustomerId" column="ty_customer_id" />
		<result property="chineseName" column="chinese_name" />
		<result property="productId" column="product_id" />
		<result property="productName" column="product_name" />
		<result property="cardId" column="card_id" />
		<result property="applyQuota" column="apply_quota" />
		<result property="actualQuote" column="actual_quote" />
		<result property="status" column="status" />
		<result property="decisionRefuseReason" column="DECISION_REFUSEREASON" />
		<result property="displayName" column="display_name" />
	</resultMap>

    <select id="checkValue" resultType="int">
  		select count(1) from account_manager_parameter a, manager_customer_type c   where  a.level_information = c.level_id  and  a.user_id=#{userId} and c.customer_type =#{valueType}
    </select>

   <select id="selectCardId" resultMap="IntoPiecesResultMap">
  		select card_id as cardId from basic_customer_information where id=#{id}
    </select>

	<select id="findIntoPiecesList" resultMap="IntoPiecesResultMap" parameterType="com.cardpay.pccredit.intopieces.model.IntoPieces">
					SELECT * FROM
			(SELECT ROW_.*,ROWNUM ROWNUM_
				FROM (
				select t.id,
		               t.customer_id,
		               b.ty_customer_id,
		               b.chinese_name,
		               t.product_id,
		               p.product_name,
		               b.card_id,
		               t.apply_quota,
		               t.actual_quote,
		               t.status,
		               t.DECISION_REFUSEREASON,a.display_name,a.id as userId
		          from customer_application_info  t,
		               basic_customer_information b,
		               product_attribute          p,sys_user a
		         where t.customer_id = b.id
		               and t.product_id = p.id and a.id=b.user_id
					<if test="custManagerIds != null and custManagerIds != '' ">
 					  	AND b.user_id in ${custManagerIds}
					</if>

					<if test="userId != null and userId != '' ">
 					  	AND b.user_id = #{userId}
					 </if>

					<if test="productName != null and productName != '' ">
						and p.product_name like '%'||#{productName}||'%'
					 </if>

					 <if test="id != null and id != '' ">
						and t.id like '%'||#{id}||'%'
					 </if>

					 <if test="status != null and status != '' ">
						and t.status= #{status}
					 </if>

					 <if test="cardId != null and cardId != '' ">
						and b.card_id like '%'||#{cardId}||'%'
					 </if>

					  <if test="chineseName != null and chineseName != '' ">
						and b.chinese_name like '%'||#{chineseName}||'%'
					  </if>
					  order by t.status asc
		 <![CDATA[
							) ROW_
						WHERE ROWNUM <= #{limit}*#{page} + #{limit})
					WHERE ROWNUM_ > #{limit}*#{page}
					]]>
	</select>

	<select id="findIntoPiecesCountList" resultType="int" parameterType="com.cardpay.pccredit.intopieces.model.IntoPieces">
		  select  count(*)
		          from customer_application_info  t,
		               basic_customer_information b,
		               product_attribute          p
		         where t.customer_id = b.id
		               and t.product_id = p.id
					 <if test="custManagerIds != null and custManagerIds != '' ">
 					  	AND b.user_id in ${custManagerIds}
					 </if>

					 <if test="userId != null and userId != '' ">
 					  	AND b.user_id = #{userId}
					 </if>

					 <if test="productName != null and productName != '' ">
						and p.product_name like '%'||#{productName}||'%'
					 </if>

					 <if test="id != null and id != '' ">
						and t.id like '%'||#{id}||'%'
					 </if>

					 <if test="status != null and status != '' ">
						and t.status= #{status}
					 </if>

					 <if test="cardId != null and cardId != '' ">
						and b.card_id like '%'||#{cardId}||'%'
					 </if>

					 <if test="chineseName != null and chineseName != '' ">
						and b.chinese_name like '%'||#{chineseName}||'%'
					 </if>
	</select>

	<update id="updateCustomerApplicationInfo" parameterType="com.cardpay.pccredit.intopieces.model.IntoPieces">
		update customer_application_info
		<set>
			status = #{status}
		</set>
		<if test="jjh != null and jjh != '' ">
			,jjh = #{jjh}
		 </if>
		 <if test="jkrq != null and jkrq != '' ">
			,jkrq = #{jkrq}
		 </if>
		where id = #{id}
	</update>

	<update id="updateCustomerApplicationInfoJn" parameterType="com.cardpay.pccredit.intopieces.model.IntoPieces">
		update customer_application_info
		<set>
			id = #{id}
		</set>

		<if test="status != null and status != '' ">
			,STATUS = #{status}
		</if>

		<if test="repayStatus != null and repayStatus != '' ">
			,REPAY_STATUS = #{repayStatus}
		</if>

		<if test="actualAmt != null and actualAmt != '' ">
			,ACTUAL_QUOTE = #{actualAmt}
		</if>
		where id = #{id}
	</update>

</mapper>


text:
(function () {
    'use strict';

    var app = angular.module('app', [
        // Angular modules
        'ngAnimate',        // animations
        'ngRoute',          // routing
        'ngSanitize',       // sanitizes html bindings (ex: sidebar.js)
        "ui.bootstrap",
        "ui.bootstrap.tpls",

        // Custom modules
        'common',           // common functions, logger, spinner
        'common.bootstrap', // bootstrap dialog wrapper functions

        // 3rd Party Modules
        'ui.bootstrap'      // ui-bootstrap (ex: carousel, pagination, dialog)
    ]);

    // Handle routing errors and success events
    app.run(['$route',  function ($route) {
            // Include $route to kick start the router.
        }]);
})();


text:
<?php

use Twig\Extension\SandboxExtension;

class_exists('Twig\Extension\SandboxExtension');

if (\false) {
    class Twig_Extension_Sandbox extends SandboxExtension
    {
    }
}


text:
using Awful.Parser.Core;
using Awful.Parser.Handlers;
using Awful.Parser.Models.Bans;
using Awful.Parser.Models.Forums;
using Awful.Parser.Models.Threads;
using Awful.Parser.Models.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Awful.Parser.Managers
{
    public class BanManager
    {
        private readonly WebClient _webManager;

        public BanManager(WebClient webManager)
        {
            _webManager = webManager;
        }

        public async Task<BanPage> GetBanPageAsync(int page = 1)
        {
            if (!_webManager.IsAuthenticated)
                throw new Exception("User must be authenticated before using this method.");

            var result = await _webManager.GetDataAsync(string.Format(EndPoints.RapSheet, page));
            var document = await _webManager.Parser.ParseAsync(result.ResultHtml);
            return BanHandler.ParseBanPage(document);
        }

        public async Task<ProbationItem> CheckForProbation()
        {
            if (!_webManager.IsAuthenticated)
                throw new Exception("User must be authenticated before using this method.");

            var result = await _webManager.GetDataAsync(EndPoints.BaseUrl);
            var document = await _webManager.Parser.ParseAsync(result.ResultHtml);
            var prob = BanHandler.ParseForProbation(document);
            _webManager.Probation = prob;
            return prob;
        }
    }
}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.impala.catalog;

import static org.junit.Assert.fail;

import java.util.Map;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import org.apache.impala.testutil.CatalogServiceTestCatalog;
import org.apache.impala.analysis.LiteralExpr;
import org.apache.impala.common.AnalysisException;
import org.apache.impala.common.ImpalaException;
import org.apache.impala.thrift.ImpalaInternalServiceConstants;
import org.apache.impala.thrift.TAccessLevel;
import org.apache.impala.thrift.THBaseTable;
import org.apache.impala.thrift.THdfsPartition;
import org.apache.impala.thrift.THdfsTable;
import org.apache.impala.thrift.TTable;
import org.apache.impala.thrift.TTableType;
import com.google.common.collect.Lists;

/**
 * Test suite to verify proper conversion of Catalog objects to/from Thrift structs.
 */
public class CatalogObjectToFromThriftTest {
  private static CatalogServiceCatalog catalog_;

  @BeforeClass
  public static void setUp() throws Exception {
    catalog_ = CatalogServiceTestCatalog.create();
  }

  @AfterClass
  public static void cleanUp() { catalog_.close(); }

  @Test
  public void TestPartitionedTable() throws CatalogException {
    String[] dbNames = {"functional", "functional_avro", "functional_parquet",
                        "functional_seq"};
    for (String dbName: dbNames) {
      Table table = catalog_.getOrLoadTable(dbName, "alltypes");
      TTable thriftTable = table.toThrift();
      Assert.assertEquals(thriftTable.tbl_name, "alltypes");
      Assert.assertEquals(thriftTable.db_name, dbName);
      Assert.assertTrue(thriftTable.isSetTable_type());
      Assert.assertEquals(thriftTable.getClustering_columns().size(), 2);
      Assert.assertEquals(thriftTable.getTable_type(), TTableType.HDFS_TABLE);
      THdfsTable hdfsTable = thriftTable.getHdfs_table();
      Assert.assertTrue(hdfsTable.hdfsBaseDir != null);

      // The table has 24 partitions + the default partition
      Assert.assertEquals(hdfsTable.getPartitions().size(), 25);
      Assert.assertTrue(hdfsTable.getPartitions().containsKey(
          new Long(ImpalaInternalServiceConstants.DEFAULT_PARTITION_ID)));

      for (Map.Entry<Long, THdfsPartition> kv: hdfsTable.getPartitions().entrySet()) {
        if (kv.getKey() == ImpalaInternalServiceConstants.DEFAULT_PARTITION_ID) {
          Assert.assertEquals(kv.getValue().getPartitionKeyExprs().size(), 0);
        } else {
          Assert.assertEquals(kv.getValue().getPartitionKeyExprs().size(), 2);
        }
      }

      // Now try to load the thrift struct.
      Table newTable = Table.fromThrift(catalog_.getDb(dbName), thriftTable);
      Assert.assertTrue(newTable instanceof HdfsTable);
      Assert.assertEquals(newTable.name_, thriftTable.tbl_name);
      Assert.assertEquals(newTable.numClusteringCols_, 2);
      // Currently only have table stats on "functional.alltypes"
      if (dbName.equals("functional")) Assert.assertEquals(7300, newTable.numRows_);

      HdfsTable newHdfsTable = (HdfsTable) newTable;
      Assert.assertEquals(newHdfsTable.getPartitions().size(), 25);
      boolean foundDefaultPartition = false;
      for (HdfsPartition hdfsPart: newHdfsTable.getPartitions()) {
        if (hdfsPart.getId() == ImpalaInternalServiceConstants.DEFAULT_PARTITION_ID) {
          Assert.assertEquals(foundDefaultPartition, false);
          foundDefaultPartition = true;
        } else {
          Assert.assertEquals(hdfsPart.getFileDescriptors().size(), 1);
          Assert.assertTrue(
              hdfsPart.getFileDescriptors().get(0).getFileBlocks().size() > 0);

          // Verify the partition access level is getting set properly. The alltypes_seq
          // table has two partitions that are read_only.
          if (dbName.equals("functional_seq") && (
              hdfsPart.getPartitionName().equals("year=2009/month=1") ||
              hdfsPart.getPartitionName().equals("year=2009/month=3"))) {
            Assert.assertEquals(TAccessLevel.READ_ONLY, hdfsPart.getAccessLevel());
          } else {
            Assert.assertEquals(TAccessLevel.READ_WRITE, hdfsPart.getAccessLevel());
          }
        }
      }
      Assert.assertEquals(foundDefaultPartition, true);
    }
  }

  /**
   * Validates proper to/fromThrift behavior for a table whose column definition does not
   * match its Avro schema definition. The expected behavior is that the Avro schema
   * definition will override any columns defined in the table.
   */
  @Test
  public void TestMismatchedAvroAndTableSchemas() throws CatalogException {
    Table table = catalog_.getOrLoadTable("functional_avro_snap",
        "schema_resolution_test");
    TTable thriftTable = table.toThrift();
    Assert.assertEquals(thriftTable.tbl_name, "schema_resolution_test");
    Assert.assertTrue(thriftTable.isSetTable_type());
    Assert.assertEquals(thriftTable.getColumns().size(), 8);
    Assert.assertEquals(thriftTable.getClustering_columns().size(), 0);
    Assert.assertEquals(thriftTable.getTable_type(), TTableType.HDFS_TABLE);

    // Now try to load the thrift struct.
    Table newTable = Table.fromThrift(catalog_.getDb("functional_avro_snap"),
        thriftTable);
    Assert.assertEquals(newTable.getColumns().size(), 8);

    // The table schema does not match the Avro schema - it has only 2 columns.
    Assert.assertEquals(newTable.getMetaStoreTable().getSd().getCols().size(), 2);
  }

  @Test
  public void TestHBaseTables() throws CatalogException {
    String dbName = "functional_hbase";
    Table table = catalog_.getOrLoadTable(dbName, "alltypes");
    TTable thriftTable = table.toThrift();
    Assert.assertEquals(thriftTable.tbl_name, "alltypes");
    Assert.assertEquals(thriftTable.db_name, dbName);
    Assert.assertTrue(thriftTable.isSetTable_type());
    Assert.assertEquals(thriftTable.getClustering_columns().size(), 1);
    Assert.assertEquals(thriftTable.getTable_type(), TTableType.HBASE_TABLE);
    THBaseTable hbaseTable = thriftTable.getHbase_table();
    Assert.assertEquals(hbaseTable.getFamilies().size(), 13);
    Assert.assertEquals(hbaseTable.getQualifiers().size(), 13);
    Assert.assertEquals(hbaseTable.getBinary_encoded().size(), 13);
    for (boolean isBinaryEncoded: hbaseTable.getBinary_encoded()) {
      // None of the columns should be binary encoded.
      Assert.assertTrue(!isBinaryEncoded);
    }

    Table newTable = Table.fromThrift(catalog_.getDb(dbName), thriftTable);
    Assert.assertTrue(newTable instanceof HBaseTable);
    HBaseTable newHBaseTable = (HBaseTable) newTable;
    Assert.assertEquals(newHBaseTable.getColumns().size(), 13);
    Assert.assertEquals(newHBaseTable.getColumn("double_col").getType(),
        Type.DOUBLE);
    Assert.assertEquals(newHBaseTable.getNumClusteringCols(), 1);
  }

  @Test
  public void TestHBaseTableWithBinaryEncodedCols()
      throws CatalogException {
    String dbName = "functional_hbase";
    Table table = catalog_.getOrLoadTable(dbName, "alltypessmallbinary");
    TTable thriftTable = table.toThrift();
    Assert.assertEquals(thriftTable.tbl_name, "alltypessmallbinary");
    Assert.assertEquals(thriftTable.db_name, dbName);
    Assert.assertTrue(thriftTable.isSetTable_type());
    Assert.assertEquals(thriftTable.getClustering_columns().size(), 1);
    Assert.assertEquals(thriftTable.getTable_type(), TTableType.HBASE_TABLE);
    THBaseTable hbaseTable = thriftTable.getHbase_table();
    Assert.assertEquals(hbaseTable.getFamilies().size(), 13);
    Assert.assertEquals(hbaseTable.getQualifiers().size(), 13);
    Assert.assertEquals(hbaseTable.getBinary_encoded().size(), 13);

    // Count the number of columns that are binary encoded.
    int numBinaryEncodedCols = 0;
    for (boolean isBinaryEncoded: hbaseTable.getBinary_encoded()) {
      if (isBinaryEncoded) ++numBinaryEncodedCols;
    }
    Assert.assertEquals(numBinaryEncodedCols, 10);

    // Verify that creating a table from this thrift struct results in a valid
    // Table.
    Table newTable = Table.fromThrift(catalog_.getDb(dbName), thriftTable);
    Assert.assertTrue(newTable instanceof HBaseTable);
    HBaseTable newHBaseTable = (HBaseTable) newTable;
    Assert.assertEquals(newHBaseTable.getColumns().size(), 13);
    Assert.assertEquals(newHBaseTable.getColumn("double_col").getType(),
        Type.DOUBLE);
    Assert.assertEquals(newHBaseTable.getNumClusteringCols(), 1);
  }

  @Test
  public void TestTableLoadingErrors() throws ImpalaException {
    Table table = catalog_.getOrLoadTable("functional", "hive_index_tbl");
    TTable thriftTable = table.toThrift();
    Assert.assertEquals(thriftTable.tbl_name, "hive_index_tbl");
    Assert.assertEquals(thriftTable.db_name, "functional");

    table = catalog_.getOrLoadTable("functional", "alltypes");
    HdfsTable hdfsTable = (HdfsTable) table;
    // Get any partition with valid HMS parameters to create a
    // dummy partition.
    HdfsPartition part = null;
    for (HdfsPartition partition: hdfsTable.getPartitions()) {
      if (!partition.isDefaultPartition()) {
        part = partition;
        break;
      }
    }
    // Create a dummy partition with an invalid decimal type.
    try {
      HdfsPartition dummyPart = new HdfsPartition(hdfsTable, part.toHmsPartition(),
        Lists.newArrayList(LiteralExpr.create("1.1", ScalarType.createDecimalType(1, 0)),
            LiteralExpr.create("1.1", ScalarType.createDecimalType(1, 0))),
        null, Lists.<HdfsPartition.FileDescriptor>newArrayList(),
        TAccessLevel.READ_WRITE);
      fail("Expected metadata to be malformed.");
    } catch (AnalysisException e) {
      Assert.assertTrue(e.getMessage().contains("invalid DECIMAL(1,0) value: 1.1"));
    }
  }

  @Test
  public void TestView() throws CatalogException {
    Table table = catalog_.getOrLoadTable("functional", "view_view");
    TTable thriftTable = table.toThrift();
    Assert.assertEquals(thriftTable.tbl_name, "view_view");
    Assert.assertEquals(thriftTable.db_name, "functional");
    Assert.assertFalse(thriftTable.isSetHdfs_table());
    Assert.assertFalse(thriftTable.isSetHbase_table());
    Assert.assertTrue(thriftTable.isSetMetastore_table());
  }
}


text:
package org.gradle.nativeplatform.test.googletest;

import org.gradle.api.Incubating;
import org.gradle.nativeplatform.test.NativeTestSuiteSpec;

/**
 * Test suite of Google Test tests.
 */
@Incubating
public interface GoogleTestTestSuiteSpec extends NativeTestSuiteSpec {
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RefOutNullable
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Random random = new Random();
        public int ReturnThreeValues(out double half, out int twice)
        {
            int value = random.Next(1000);
            half = ((double)value) / 2;
            twice = value * 2;
            return value;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int a;
            double b;
            int c;
            a = ReturnThreeValues(out b, out c);
            Console.WriteLine("value = {0}, half = {1}, double = {2}", a, b, c);
        }

        public void ModifyAnIntAndButton(ref int value, ref Button button)
        {
            int i = value;
            i *= 5;
            value = i - 3;
            button = button1;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int q = 100;
            Button b = button1;
            ModifyAnIntAndButton(ref q, ref b);
            Console.WriteLine("q = {0}, b.Text = {1}", q, b.Text);
        }

        void CheckTemperature(double temperature, double tooHigh = 99.5, double tooLow = 96.5)
        {
            if (temperature < tooHigh && temperature > tooLow)
                Console.WriteLine("Feeling good!");
            else
                Console.WriteLine("Uh-oh -- better see a doctor!");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            // Those values are fine for your average person
            CheckTemperature(101.3);

            // A dog's temperature should be between 100.5 and 102.5 Fahrenheit
            CheckTemperature(101.3, 102.5, 100.5);

            // Bob's temperature is always a little low, so set tooLow to 95.5
            CheckTemperature(96.2, tooLow: 95.5);
        }
    }
}


text:
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements.  Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////

#ifndef __UNIX_FILTERENTRY_H
#define __UNIX_FILTERENTRY_H

#include "CIM_FilterEntryBase.h"

#include "UNIX_FilterEntryDeps.h"

#define PROPERTY_TRAFFIC_TYPE				"TrafficType"
#define PROPERTY_OTHER_TRAFFIC_TYPE				"OtherTrafficType"
#define PROPERTY_MATCH_CONDITION_TYPE				"MatchConditionType"
#define PROPERTY_OTHER_MATCH_CONDITION_TYPE				"OtherMatchConditionType"
#define PROPERTY_MATCH_CONDITION_VALUE				"MatchConditionValue"
#define PROPERTY_ACTION				"Action"
#define PROPERTY_DEFAULT_FILTER				"DefaultFilter"
#define PROPERTY_TRAFFIC_CLASS				"TrafficClass"

class UNIX_FilterEntry :
	public CIM_FilterEntryBase
{
public:

	UNIX_FilterEntry();
	~UNIX_FilterEntry();

	virtual Boolean initialize();
	virtual Boolean load(int&);
	virtual Boolean finalize();
	virtual Boolean find(Array<CIMKeyBinding>&);
	virtual Boolean validateKey(CIMKeyBinding&) const;
	virtual void setScope(CIMName);

	virtual Boolean getInstanceID(CIMProperty&) const;
	virtual String getInstanceID() const;
	virtual Boolean getCaption(CIMProperty&) const;
	virtual String getCaption() const;
	virtual Boolean getDescription(CIMProperty&) const;
	virtual String getDescription() const;
	virtual Boolean getElementName(CIMProperty&) const;
	virtual String getElementName() const;
	virtual Boolean getInstallDate(CIMProperty&) const;
	virtual CIMDateTime getInstallDate() const;
	virtual Boolean getName(CIMProperty&) const;
	virtual String getName() const;
	virtual Boolean getOperationalStatus(CIMProperty&) const;
	virtual Array<Uint16> getOperationalStatus() const;
	virtual Boolean getStatusDescriptions(CIMProperty&) const;
	virtual Array<String> getStatusDescriptions() const;
	virtual Boolean getStatus(CIMProperty&) const;
	virtual String getStatus() const;
	virtual Boolean getHealthState(CIMProperty&) const;
	virtual Uint16 getHealthState() const;
	virtual Boolean getCommunicationStatus(CIMProperty&) const;
	virtual Uint16 getCommunicationStatus() const;
	virtual Boolean getDetailedStatus(CIMProperty&) const;
	virtual Uint16 getDetailedStatus() const;
	virtual Boolean getOperatingStatus(CIMProperty&) const;
	virtual Uint16 getOperatingStatus() const;
	virtual Boolean getPrimaryStatus(CIMProperty&) const;
	virtual Uint16 getPrimaryStatus() const;
	virtual Boolean getSystemCreationClassName(CIMProperty&) const;
	virtual String getSystemCreationClassName() const;
	virtual Boolean getSystemName(CIMProperty&) const;
	virtual String getSystemName() const;
	virtual Boolean getCreationClassName(CIMProperty&) const;
	virtual String getCreationClassName() const;
	virtual Boolean getIsNegated(CIMProperty&) const;
	virtual Boolean getIsNegated() const;
	virtual Boolean getTrafficType(CIMProperty&) const;
	virtual Uint16 getTrafficType() const;
	virtual Boolean getOtherTrafficType(CIMProperty&) const;
	virtual String getOtherTrafficType() const;
	virtual Boolean getMatchConditionType(CIMProperty&) const;
	virtual Uint16 getMatchConditionType() const;
	virtual Boolean getOtherMatchConditionType(CIMProperty&) const;
	virtual String getOtherMatchConditionType() const;
	virtual Boolean getMatchConditionValue(CIMProperty&) const;
	virtual String getMatchConditionValue() const;
	virtual Boolean getAction(CIMProperty&) const;
	virtual Uint16 getAction() const;
	virtual Boolean getDefaultFilter(CIMProperty&) const;
	virtual Boolean getDefaultFilter() const;
	virtual Boolean getTrafficClass(CIMProperty&) const;
	virtual String getTrafficClass() const;

private:
	CIMName currentScope;

#	include "UNIX_FilterEntryPrivate.h"

};

#endif /* UNIX_FILTERENTRY */


text:
<?php

namespace Drupal\Tests\user\Kernel;

use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\KernelTests\KernelTestBase;
use Drupal\user\Entity\Role;

/**
 * Ensures the user action for adding and removing roles have valid config
 * schema.
 *
 * @group user
 */
class UserActionConfigSchemaTest extends KernelTestBase {

  use SchemaCheckTestTrait;

  /**
   * Modules to enable.
   *
   * @var array
   */
  protected static $modules = ['system', 'user'];

  /**
   * Tests whether the user action config schema are valid.
   */
  public function testValidUserActionConfigSchema() {
    $rid = strtolower($this->randomMachineName(8));
    Role::create(['id' => $rid, 'label' => $rid])->save();

    // Test user_add_role_action configuration.
    $config = $this->config('system.action.user_add_role_action.' . $rid);
    $this->assertEquals('user_add_role_action.' . $rid, $config->get('id'));
    $this->assertConfigSchema(\Drupal::service('config.typed'), $config->getName(), $config->get());

    // Test user_remove_role_action configuration.
    $config = $this->config('system.action.user_remove_role_action.' . $rid);
    $this->assertEquals('user_remove_role_action.' . $rid, $config->get('id'));
    $this->assertConfigSchema(\Drupal::service('config.typed'), $config->getName(), $config->get());
  }

}


text:
def extractThenewscifiCom(item):
	'''
	DISABLED

	Parser for 'thenewscifi.com'
	'''
	if 'film' in item['tags']:
		return None

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('PRC',       'PRC',                      'translated'),
		('Loiterous', 'Loiterous',                'oel'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


text:
/**
* @file
* @brief File containing master class Client.
*/

#ifndef CLIENT_HPP
#define CLIENT_HPP

#include <OpenLayer.hpp>
#include "DataModule.hpp"
#include "UtilityModule.hpp"
#include "LogicModule.hpp"
#include "RenderModule.hpp"
#include "NetworkModule.hpp"

/**
* @brief Master class which combines all @ref MODULES_GROUP
* together.
*
* This class is responsible for initializing game and
* managing main game loop.\n
*
* Class has only one instance.\n
* Every member of any module outside of the class hierarchy
* can be called as follows.
* @code
*   Client::getInstance().member;
* @endcode
*/
class Client
    : public virtual DataModule,
      public virtual UtilityModule,
      public virtual LogicModule,
      public virtual RenderModule,
      public virtual NetworkModule
{
    private:
        void loadResourcesThread();
        void mainLoopMenu();
        void mainLoopGame();

    public:
        void init();
        void run();

        /**
        * @brief Instance handler for Client class.
        * @return Client instance.
        */
        inline static Client &getInstance() {
            static Client instance;
            return instance;
        }
};

#endif


text:
% tpm2_getpolicydigest(1) tpm2-tools | General Commands Manual

# NAME

**tpm2_getpolicydigest**(1) - Retrieves the policy digest from session.

# SYNOPSIS

**tpm2_getpolicydigest** [*OPTIONS*] [*ARGUMENT*]

# DESCRIPTION

**tpm2_getpolicydigest**(1) - Returns the policydigest of a session.

Output defaults to *stdout* and binary format unless otherwise specified with
**-o** and **--hex** options respectively.

# OPTIONS

  * **-o**, **\--output**=_FILE_

    Specifies the filename to output the raw bytes to. Defaults to stdout as a
    hex string.

  * **\--hex**

	Convert the output data to hex format without a leading "0x".

  * **-S**, **\--session**=_FILE_:

    The session created using **tpm2_startauthsession**.

## References

[common options](common/options.md) collection of common options that provide
information many users may expect.

[common tcti options](common/tcti.md) collection of options used to configure
the various known TCTI modules.

# EXAMPLES

## Create a session and retrieve policydigest
```bash
tpm2 startauthsession -S session.ctx
tpm2 policypassword -S session.ctx -L test.policy
tpm2 getpolicydigest -S session.ctx -o policy.out
tpm2 flushcontext session.ctx
```

[returns](common/returns.md)

[footer](common/footer.md)


text:
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light.NoTitleBar">

        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

    <style name="LoginFormContainer">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:padding">16dp</item>
    </style>

    <style name="Button">
        <item name="android:layout_height">50dp</item>
        <item name="android:layout_width">110dp</item>
        <item name="android:background">@color/beer</item>
        <item name="android:textAppearance">@android:style/TextAppearance.Medium</item>
        <item name="android:layout_gravity">center_horizontal</item>
    </style>

    <style name="AlertDialogCustom">
        <item name="android:textColor">#000</item>
        <item name="android:background">#FFFFFF</item>
    </style>

</resources>


text:
--TEST--
Test to ensure that void enforcement works when the non-extant retval is actually used
--INI--
augmented_types.enforce_by_default = 1
--FILE--
<?php

/**
 * @return void
 */
function init()
{
/*
	$app_conf = CFG::instance()->application_conf();
	Feature_Instance::$always_cookieable = $app_conf['features']['always_cookieable'];
	static::$features_cache = array();
	static::$features_tested = array();
	*/
	$_GET['123'] = [];
}
init();
echo init();
?>
--EXPECTREGEX--


text:
package red.yelo.http;

import android.os.Bundle;

import retrofit.Callback;

/**
 * Created by anshul1235 on 27/10/14.
 */
public interface RetroCallbackInterface<T> extends Callback<T> {

    public int getRequestId();

    public int setRequestId(int code);

    public void cancel();

    public void setExtras(Bundle extras);

    public boolean isCanceled();

}


text:
using System;
using System.Text;

class ConsecutiveLetters
{
    // Write a program that reads a string from
    // the console and replaces all series of
    // consecutive identical letters with a single
    // one. Example: "aaaaabbbbbcdddeeeedssaa" -> "abcdedsa".

    static void Main()
    {
        //variables
        string text = "aaaaabbbbbcdddeeeedssaa";
        StringBuilder sb = new StringBuilder();
        char currentChar = '@';

        foreach (var item in text)
        {
            if (item != currentChar)
            {
                sb.Append(item);
                currentChar = item;
            }
        }

        Console.WriteLine(sb.ToString());
    }
}


text:
namespace printing {

namespace {

bool Send(IPC::Message* message) {
  return content::UtilityThread::Get()->Send(message);
}

void ReleaseProcessIfNeeded() {
  content::UtilityThread::Get()->ReleaseProcessIfNeeded();
}

}  // namespace

PrintingHandlerWin::PrintingHandlerWin() {}

PrintingHandlerWin::~PrintingHandlerWin() {}

bool PrintingHandlerWin::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(PrintingHandlerWin, message)
    IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RenderPDFPagesToMetafiles,
                        OnRenderPDFPagesToMetafile)
    IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RenderPDFPagesToMetafiles_GetPage,
                        OnRenderPDFPagesToMetafileGetPage)
    IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RenderPDFPagesToMetafiles_Stop,
                        OnRenderPDFPagesToMetafileStop)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void PrintingHandlerWin::OnRenderPDFPagesToMetafile(
    IPC::PlatformFileForTransit pdf_transit,
    const PdfRenderSettings& settings) {
  pdf_rendering_settings_ = settings;
  base::File pdf_file = IPC::PlatformFileForTransitToFile(pdf_transit);
  int page_count = LoadPDF(std::move(pdf_file));
  //int page_count = 1;
  Send(
      new ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageCount(page_count));
}

void PrintingHandlerWin::OnRenderPDFPagesToMetafileGetPage(
    int page_number,
    IPC::PlatformFileForTransit output_file) {
  base::File emf_file = IPC::PlatformFileForTransitToFile(output_file);
  float scale_factor = 1.0f;
  bool success =
      RenderPdfPageToMetafile(page_number, std::move(emf_file), &scale_factor);
  Send(new ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageDone(
      success, scale_factor));
}

void PrintingHandlerWin::OnRenderPDFPagesToMetafileStop() {
  ReleaseProcessIfNeeded();
}

int PrintingHandlerWin::LoadPDF(base::File pdf_file) {
  int64_t length64 = pdf_file.GetLength();
  if (length64 <= 0 || length64 > std::numeric_limits<int>::max())
    return 0;
  int length = static_cast<int>(length64);

  pdf_data_.resize(length);
  if (length != pdf_file.Read(0, pdf_data_.data(), pdf_data_.size()))
    return 0;

  int total_page_count = 0;
  if (!chrome_pdf::GetPDFDocInfo(&pdf_data_.front(), pdf_data_.size(),
                                 &total_page_count, nullptr)) {
    return 0;
  }
  return total_page_count;
}

bool PrintingHandlerWin::RenderPdfPageToMetafile(int page_number,
                                                 base::File output_file,
                                                 float* scale_factor) {
  Emf metafile;
  metafile.Init();

  // We need to scale down DC to fit an entire page into DC available area.
  // Current metafile is based on screen DC and have current screen size.
  // Writing outside of those boundaries will result in the cut-off output.
  // On metafiles (this is the case here), scaling down will still record
  // original coordinates and we'll be able to print in full resolution.
  // Before playback we'll need to counter the scaling up that will happen
  // in the service (print_system_win.cc).
  *scale_factor =
      gfx::CalculatePageScale(metafile.context(),
                              pdf_rendering_settings_.area().right(),
                              pdf_rendering_settings_.area().bottom());
  gfx::ScaleDC(metafile.context(), *scale_factor);

  // The underlying metafile is of type Emf and ignores the arguments passed
  // to StartPage.
  metafile.StartPage(gfx::Size(), gfx::Rect(), 1);
  if (!chrome_pdf::RenderPDFPageToDC(
          &pdf_data_.front(),
          pdf_data_.size(),
          page_number,
          metafile.context(),
          pdf_rendering_settings_.dpi(),
          pdf_rendering_settings_.area().x(),
          pdf_rendering_settings_.area().y(),
          pdf_rendering_settings_.area().width(),
          pdf_rendering_settings_.area().height(),
          true,
          false,
          true,
          true,
          pdf_rendering_settings_.autorotate())) {
    return false;
  }
  metafile.FinishPage();
  metafile.FinishDocument();
  return metafile.SaveTo(&output_file);
}

}  // printing


text:
<?php

namespace Zend\Form;

use Zend\InputFilter\InputFilterInterface;
use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class FormAbstractServiceFactory implements AbstractFactoryInterface
{
    /**
     * @var array
     */
    protected $config;

    /**
     * @var string Top-level configuration key indicating forms configuration
     */
    protected $configKey     = 'forms';

    /**
     * @var Factory Form factory used to create forms
     */
    protected $factory;

    /**
     * Can we create the requested service?
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @param  string $name Service name (as resolved by ServiceManager)
     * @param  string $requestedName Name by which service was requested
     * @return bool
     */
    public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
        $config = $this->getConfig($serviceLocator);
        if (empty($config)) {
            return false;
        }

        return (isset($config[$requestedName]) && is_array($config[$requestedName]) && !empty($config[$requestedName]));
    }

    /**
     * Create a form
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @param  string $name Service name (as resolved by ServiceManager)
     * @param  string $requestedName Name by which service was requested
     * @return Form
     */
    public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
        $config  = $this->getConfig($serviceLocator);
        $config  = $config[$requestedName];
        $factory = $this->getFormFactory($serviceLocator);

        $this->marshalInputFilter($config, $serviceLocator, $factory);
        return $factory->createForm($config);
    }

    /**
     * Get forms configuration, if any
     *
     * @param  ServiceLocatorInterface $services
     * @return array
     */
    protected function getConfig(ServiceLocatorInterface $services)
    {
        if ($this->config !== null) {
            return $this->config;
        }

        if (!$services->has('Config')) {
            $this->config = [];
            return $this->config;
        }

        $config = $services->get('Config');
        if (!isset($config[$this->configKey])
            || !is_array($config[$this->configKey])
        ) {
            $this->config = [];
            return $this->config;
        }

        $this->config = $config[$this->configKey];
        return $this->config;
    }

    /**
     * Retrieve the form factory, creating it if necessary
     *
     * @param  ServiceLocatorInterface $services
     * @return Factory
     */
    protected function getFormFactory(ServiceLocatorInterface $services)
    {
        if ($this->factory instanceof Factory) {
            return $this->factory;
        }

        $elements = null;
        if ($services->has('FormElementManager')) {
            $elements = $services->get('FormElementManager');
        }

        $this->factory = new Factory($elements);
        return $this->factory;
    }

    /**
     * Marshal the input filter into the configuration
     *
     * If an input filter is specified:
     * - if the InputFilterManager is present, checks if it's there; if so,
     *   retrieves it and resets the specification to the instance.
     * - otherwise, pulls the input filter factory from the form factory, and
     *   attaches the FilterManager and ValidatorManager to it.
     *
     * @param array $config
     * @param ServiceLocatorInterface $services
     * @param Factory $formFactory
     */
    protected function marshalInputFilter(array &$config, ServiceLocatorInterface $services, Factory $formFactory)
    {
        if (!isset($config['input_filter'])) {
            return;
        }

        if ($config['input_filter'] instanceof InputFilterInterface) {
            return;
        }

        if (is_string($config['input_filter'])
            && $services->has('InputFilterManager')
        ) {
            $inputFilters = $services->get('InputFilterManager');
            if ($inputFilters->has($config['input_filter'])) {
                $config['input_filter'] = $inputFilters->get($config['input_filter']);
                return;
            }
        }

        $inputFilterFactory = $formFactory->getInputFilterFactory();
        $inputFilterFactory->getDefaultFilterChain()->setPluginManager($services->get('FilterManager'));
        $inputFilterFactory->getDefaultValidatorChain()->setPluginManager($services->get('ValidatorManager'));
    }
}


text:
package com.redhat.approval.entities;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.kie.api.definition.type.PropertyReactive;

import com.redhat.approval.value.RequestStatus;

@PropertyReactive
public class VacationRequest implements Serializable {

	/**
	 * generated serial UID
	 */
	private static final long serialVersionUID = -8354225930529331655L;

	private Employee employee;
	private LocalDate startDate;
	private LocalDate endDate;
	private RequestStatus status = RequestStatus.CREATED;
	private String comment;

	public VacationRequest() {
	}

	public VacationRequest(Employee employee, LocalDate startDate, LocalDate endDate) {
		this.employee = employee;
		this.startDate = startDate;
		this.endDate = endDate;
	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public LocalDate getStartDate() {
		return startDate;
	}

	public void setStartDate(LocalDate startDate) {
		this.startDate = startDate;
	}

	public LocalDate getEndDate() {
		return endDate;
	}

	public void setEndDate(LocalDate endDate) {
		this.endDate = endDate;
	}

	public int lengthInDays() {
		return Days.daysBetween(startDate, endDate).getDays();
	}

	public RequestStatus getStatus() {
		return status;
	}

	public void setStatus(RequestStatus status) {
		this.status = status;
	}

	public String getComment() {
		return comment;
	}

	public void setComment(String comments) {
		this.comment = comments;
	}

	/*
	 * This is a hack for expediency
	 */
	public String parseResponse(String json){

		return json.substring(14, 20);
	}

	public Map<String, Object> toProcessDataMap() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("vacationRequest", this);
		if ( this.getEmployee().getManager() != null ){
			map.put("managerId", this.getEmployee().getManager().getUserId());
		}
		map.put("employeeId", this.getEmployee().getUserId());
		return map;
	}

	@Override
	public String toString() {
		return "VacationRequest [employee=" + employee + ", startDate=" + startDate + ", endDate=" + endDate + ", status=" + status + ", comment=" + comment + "]";
	}

}


text:
#include "kmapi.h"
#include "TestLoop.h"
#include "RateReporter.h"

#include <chrono>
#include <functional>

using namespace kuma;
using namespace std::chrono;

class DataSender
{
public:
    using SendCallback = std::function<int(void*, size_t)>;

    DataSender(TestLoop* loop);
    ~DataSender();

    void updateBandwidth(size_t bw_bps);
    void startSendData();
    void doSendData();

    void setSendCallback(SendCallback cb) { sender_ = std::move(cb); }

protected:
    void sendData(size_t bytes_to_send);
    void onTimer();

private:
    TestLoop*   loop_;
    size_t      bandwidth_ = 1*1000*1000; // bps
    size_t      time_slice_ = 20; // ms
    size_t      token_slice_ = 0;

    SendCallback sender_;

    Timer       timer_;
    steady_clock::time_point   last_send_time_;

    RateReporter    send_reporter_;
};


text:
package org.http4s
package booPickle

import boopickle.Default._
import boopickle.Pickler
import cats.Applicative
import cats.effect.Sync
import fs2.Chunk
import java.nio.ByteBuffer
import org.http4s._
import org.http4s.EntityEncoder.chunkEncoder
import org.http4s.headers.`Content-Type`
import scala.util.{Failure, Success}

/**
  * Generic factories for http4s encoders/decoders for boopickle
  * Note that the media type is set for application/octet-stream
  */
trait BooPickleInstances {

  private def booDecoderByteBuffer[F[_]: Sync, A](msg: Message[F])(
      implicit pickler: Pickler[A]): DecodeResult[F, A] =
    EntityDecoder.collectBinary(msg).subflatMap { chunk =>
      val bb = ByteBuffer.wrap(chunk.toArray)
      if (bb.hasRemaining) {
        Unpickle[A](pickler).tryFromBytes(bb) match {
          case Success(bb) => Right(bb)
          case Failure(pf) => Left(MalformedMessageBodyFailure("Invalid binary body", Some(pf)))
        }
      } else
        Left(MalformedMessageBodyFailure("Invalid binary: empty body", None))
    }

  /**
    * Create an `EntityDecoder` for `A` given a `Pickler[A]`
    */
  def booOf[F[_]: Sync, A: Pickler]: EntityDecoder[F, A] =
    EntityDecoder.decodeBy(MediaType.application.`octet-stream`)(booDecoderByteBuffer[F, A])

  /**
    * Create an `EntityEncoder` for `A` given a `Pickler[A]`
    */
  def booEncoderOf[F[_]: Applicative, A: Pickler]: EntityEncoder[F, A] =
    chunkEncoder[F]
      .contramap[A] { v =>
        Chunk.ByteBuffer(Pickle.intoBytes(v))
      }
      .withContentType(`Content-Type`(MediaType.application.`octet-stream`))

}


text:
import * as types from 'constants/MovieUIActionTypes';

export function toggleEditingPriority({ movie }) {
	return { type: types.TOGGLE_EDITING_PRIORITY, movieId: movie.id };
}


text:
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
    xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">

    <property name="now" value="now()" dbms="mysql,h2"/>
    <property name="now" value="current_timestamp" dbms="postgresql"/>
    <property name="now" value="sysdate" dbms="oracle"/>

    <property name="autoIncrement" value="true" dbms="mysql,h2,postgresql"/>
    <property name="autoIncrement" value="false" dbms="oracle"/>

    <property name="floatType" value="float4" dbms="postgresql, h2"/>
    <property name="floatType" value="float" dbms="mysql, oracle"/>

    <!--
        Added the entity Questionnaire.
    -->
    <changeSet id="20151024124701" author="jhipster">
        <createTable tableName="questionnaire">
            <column name="id" type="bigint" autoIncrement="${autoIncrement}" >
                <constraints primaryKey="true" nullable="false"/>
            </column>
            <column name="name" type="varchar(255)">
                <constraints nullable="false" />
            </column>
            <column name="questions" type="varchar(255)">
                <constraints nullable="false" />
            </column>
            <column name="external_id" type="varchar(255)"/>
        </createTable>

    </changeSet>
</databaseChangeLog>


text:
The **basic setup** is for authoring presentations only. The **full setup** gives you access to all reveal.js features and plugins such as speaker notes as well as the development tasks needed to make changes to the source.

### Basic setup

The core of reveal.js is very easy to install. You'll simply need to download a copy of this repository and open the index.html file directly in your browser.

1. Clone this repo.
2. Open index.html in a browser to view it (note: run a local server for the custom Knight Lab typography to work).
3. Edit the slides in index.html with your own content.

### Full setup

Some reveal.js features, like external markdown, require that presentations run from a local web server. The following instructions will set up such a server as well as all of the development tasks needed to make edits to the reveal.js source code.

1. Install [Node.js](http://nodejs.org/)

2. Install [Grunt](http://gruntjs.com/getting-started#installing-the-cli)

4. Clone the reveal.js repository
```sh
$ git clone https://github.com/hakimel/reveal.js.git
```

5. Navigate to the reveal.js folder
```sh
$ cd reveal.js
```

6. Install dependencies
```sh
$ npm install
```

7. Serve the presentation and monitor source files for changes
```sh
$ grunt serve
```

8. Open <http://localhost:8000> to view your presentation

You can change the port by using `grunt serve --port 8001`.

### Theming

If you want to edit the Knight Lab theme or create a new theme, read the [theming documentation](https://github.com/hakimel/reveal.js/blob/master/css/theme/README.md). The Knight Lab theme is controlled in `knightlab.scss`.

### Folder Structure
- **css/** Core styles without which the project does not function
- **js/** Like above but for JavaScript
- **plugin/** Components that have been developed as extensions to reveal.js
- **lib/** All other third party assets (JavaScript, CSS, fonts)