text:
package org.sklsft.generator.skeletons.core.commands.persistence;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.sklsft.generator.model.domain.business.Bean;
import org.sklsft.generator.model.domain.business.OneToManyComponent;
import org.sklsft.generator.model.domain.business.OneToOneComponent;
import org.sklsft.generator.model.domain.business.Property;
import org.sklsft.generator.model.domain.ui.ViewProperty;
import org.sklsft.generator.model.metadata.RelationType;
import org.sklsft.generator.model.metadata.SelectionMode;
import org.sklsft.generator.model.util.naming.JavaClassNaming;
import org.sklsft.generator.skeletons.commands.impl.typed.JavaFileWriteCommand;

public class BaseDaoHibernateImplFileWriteCommand extends JavaFileWriteCommand {

	private Bean bean;

	/*
	 * constructor
	 */
	public BaseDaoHibernateImplFileWriteCommand(Bean bean) {

		super(bean.myPackage.model.project.workspaceFolder + File.separator + bean.myPackage.model.persistenceArtefactName + File.separator + bean.myPackage.model.javaSourcesFolder + File.separator
				+ bean.myPackage.baseDAOImplPackageName.replace(".", File.separator), bean.baseDaoClassName);

		this.bean = bean;

	}

	@Override
	protected void fetchSpecificImports() {

		javaImports.add("import java.util.Date;");
		javaImports.add("import java.time.LocalDate;");
		javaImports.add("import java.math.BigDecimal;");
		javaImports.add("import java.util.List;");
		javaImports.add("import java.util.ArrayList;");

		javaImports.add("import javax.persistence.criteria.CriteriaBuilder;");
		javaImports.add("import javax.persistence.criteria.CriteriaQuery;");
		javaImports.add("import javax.persistence.criteria.Fetch;");
		javaImports.add("import javax.persistence.criteria.Join;");
		javaImports.add("import javax.persistence.criteria.JoinType;");
		javaImports.add("import javax.persistence.criteria.Order;");
		javaImports.add("import javax.persistence.criteria.Predicate;");
		javaImports.add("import javax.persistence.criteria.Root;");
		javaImports.add("import org.hibernate.Session;");
		javaImports.add("import org.hibernate.query.Query;");

		javaImports.add("import static org.sklsft.commons.model.patterns.JpaCriteriaUtils.*;");
		javaImports.add("import org.sklsft.commons.api.model.OrderType;");

		javaImports.add("import org.sklsft.commons.api.exception.repository.ObjectNotFoundException;");
		javaImports.add("import org.sklsft.commons.model.patterns.BaseDaoImpl;");
		javaImports.add("import " + this.bean.myPackage.omPackageName + "." + this.bean.className + ";");
		javaImports.add("import " + this.bean.myPackage.omPackageName + "." + this.bean.className + "_;");
		for (ViewProperty viewProperty:this.bean.basicViewBean.properties) {
			if (viewProperty.referenceBean!=null) {
				Bean currentBean = viewProperty.referenceBean;
				javaImports.add("import " + currentBean.myPackage.omPackageName + "." + currentBean.className + ";");
				javaImports.add("import " + currentBean.myPackage.omPackageName + "." + currentBean.className + "_;");
			}
		}
		javaImports.add("import " + bean.myPackage.filtersPackageName + "." + bean.basicViewBean.filter.className + ";");
		javaImports.add("import " + bean.myPackage.sortingsPackageName + "." + bean.basicViewBean.sortingClassName + ";");
		javaImports.add("import " + this.bean.myPackage.baseDAOInterfacePackageName + "." + this.bean.baseDaoInterfaceName + ";");

		for (OneToManyComponent oneToManyComponent:bean.oneToManyComponentList) {
			Bean currentBean = oneToManyComponent.referenceBean;
			javaImports.add("import " + currentBean.myPackage.omPackageName + "." + currentBean.className + ";");
			javaImports.add("import " + currentBean.myPackage.omPackageName + "." + currentBean.className + "_;");
			javaImports.add("import " + currentBean.myPackage.filtersPackageName + "." + currentBean.basicViewBean.filter.className + ";");
			javaImports.add("import " + currentBean.myPackage.sortingsPackageName + "." + currentBean.basicViewBean.sortingClassName + ";");
		}

		for (OneToOneComponent oneToOneComponent:bean.oneToOneComponentList) {
			Bean currentBean = oneToOneComponent.referenceBean;
			javaImports.add("import " + currentBean.myPackage.omPackageName + "." + currentBean.className + ";");
			javaImports.add("import " + currentBean.myPackage.omPackageName + "." + currentBean.className + "_;");
		}
	}

	@Override
	protected void writeContent() throws IOException {

		writeLine("package " + bean.myPackage.baseDAOImplPackageName + ";");
		skipLine();

		writeImports();
		skipLine();

		writeLine("/**");
		writeLine(" * auto generated base dao class file");
		writeLine(" *
no modification should be done to this file");
		writeLine(" *
processed by skeleton-generator");
		writeLine(" */");
		writeLine("public class " + this.bean.baseDaoClassName  + " extends BaseDaoImpl<" + this.bean.className + ", " + bean.idType + "> implements " + this.bean.baseDaoInterfaceName + " {");
		skipLine();

		writeLine("/**");
		writeLine(" * constructor");
		writeLine(" */");
		writeLine("public " + this.bean.baseDaoClassName + "() {");
		writeLine("super(" + this.bean.className + ".class);");
		write("}");
		skipLine();

		createLoadObjectList();
		createCount();
		createScroll();
		createLoadOneToManyComponentList();
		createCountOneToManyComponent();
		createScrollOneToManyComponent();
		createLoadOneToManyComponent();

		if (bean.cardinality>0) {
			createFindObject();
		}
		if (bean.selectable) {
			if (bean.selectionBehavior.selectionMode.equals(SelectionMode.AUTO_COMPLETE)) {
				createSearch();
			}
		}
		createSaveComponent();
		createDeleteComponent();

		write("}");

	}

	private void createLoadObjectList() {

		writeLine("/**");
		writeLine(" * load object list eagerly");
		writeLine(" */");
		writeLine("@Override");
		writeLine("@SuppressWarnings({\"unused\",\"unchecked\"})");
		writeLine("public List<" + this.bean.className + "> loadListEagerly() {");

		writeLine("Session session = this.sessionFactory.getCurrentSession();");
		writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
		writeLine("CriteriaQuery<" + this.bean.className + "> criteria = builder.createQuery(" + this.bean.className + ".class);");
		skipLine();

		writeLine("Root<" + this.bean.className + "> root = criteria.from(" + this.bean.className + ".class);");
		for (Alias alias : getAllAliases(bean, null)) {
			writeLine("Fetch<" + alias.parentBeanDataType + ", " + alias.beanDataType + "> " + alias.name + "Fetch = " + alias.parentName + ".fetch(" + alias.parentBeanDataType + "_." + alias.propertyName + ", JoinType.LEFT);");
			writeLine("Join<" + alias.parentBeanDataType + ", " + alias.beanDataType + "> " + alias.name + " = (Join<" + alias.parentBeanDataType + ", " + alias.beanDataType + ">)" + alias.name +"Fetch;");
		}
		skipLine();

		writeLine("criteria.select(root);");
		writeLine("List<Order> orders = new ArrayList<>();");
		writeLine("addOrder(builder, orders, root.get(" + bean.className + "_.id), OrderType.DESC);");
		writeLine("criteria.orderBy(orders);");
		skipLine();
		writeLine("return session.createQuery(criteria).getResultList();");
		writeLine("}");
		skipLine();

		for (Property property : this.bean.properties) {
			if (property.referenceBean != null && property.relation.equals(RelationType.MANY_TO_ONE)) {
				writeLine("/**");
				writeLine(" * load object list from " + property.name);
				writeLine(" */");
				writeLine("@Override");
				writeLine("public List<" + this.bean.className + "> loadListFrom" + property.capName + "(" + property.referenceBean.idType + " " + property.name + "Id) {");

				writeLine("Session session = this.sessionFactory.getCurrentSession();");
				writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
				writeLine("CriteriaQuery<" + this.bean.className + "> criteria = builder.createQuery(" + this.bean.className + ".class);");
				skipLine();

				writeLine("Root<" + this.bean.className + "> root = criteria.from(" + this.bean.className + ".class);");
				writeLine("Join<" + bean.className + ", " + property.javaType + "> " + property.name + " = root.join(" + bean.className + "_." + property.name + ", JoinType.LEFT);");
				skipLine();

				writeLine("if (" + property.name + "Id == null){");
				writeLine("criteria.where(builder.isNull(" + property.name + ".get(" + property.javaType + "_.id)));");
				writeLine("} else {");
				writeLine("criteria.where(builder.equal(" + property.name + ".get(" + property.javaType + "_.id), " + property.name + "Id));");
				writeLine("}");
				skipLine();

				writeLine("criteria.select(root);");
				writeLine("List<Order> orders = new ArrayList<>();");
				writeLine("addOrder(builder, orders, root.get(" + bean.className + "_.id), OrderType.DESC);");
				writeLine("criteria.orderBy(orders);");
				skipLine();
				writeLine("return session.createQuery(criteria).getResultList();");
				writeLine("}");
				skipLine();

				writeLine("/**");
				writeLine(" * load object list eagerly from " + property.name);
				writeLine(" */");
				writeLine("@Override");
				writeLine("@SuppressWarnings({\"unused\",\"unchecked\"})");
				writeLine("public List<" + this.bean.className + "> loadListEagerlyFrom" + property.capName + "(" + property.referenceBean.idType + " " + property.name + "Id) {");

				writeLine("Session session = this.sessionFactory.getCurrentSession();");
				writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
				writeLine("CriteriaQuery<" + this.bean.className + "> criteria = builder.createQuery(" + this.bean.className + ".class);");
				skipLine();

				writeLine("Root<" + this.bean.className + "> root = criteria.from(" + this.bean.className + ".class);");
				for (Alias alias : getAllAliases(bean, null)) {
					writeLine("Fetch<" + alias.parentBeanDataType + ", " + alias.beanDataType + "> " + alias.name + "Fetch = " + alias.parentName + ".fetch(" + alias.parentBeanDataType + "_." + alias.propertyName + ", JoinType.LEFT);");
					writeLine("Join<" + alias.parentBeanDataType + ", " + alias.beanDataType + "> " + alias.name + " = (Join<" + alias.parentBeanDataType + ", " + alias.beanDataType + ">)" + alias.name +"Fetch;");
				}
				skipLine();

				writeLine("if (" + property.name + "Id == null){");
				writeLine("criteria.where(builder.isNull(" + property.name + ".get(" + property.javaType + "_.id)));");
				writeLine("} else {");
				writeLine("criteria.where(builder.equal(" + property.name + ".get(" + property.javaType + "_.id), " + property.name + "Id));");
				writeLine("}");
				skipLine();

				writeLine("criteria.select(root);");
				writeLine("List<Order> orders = new ArrayList<>();");
				writeLine("addOrder(builder, orders, root.get(" + bean.className + "_.id), OrderType.DESC);");
				writeLine("criteria.orderBy(orders);");
				skipLine();
				writeLine("return session.createQuery(criteria).getResultList();");
				writeLine("}");
				skipLine();

			}
		}
	}

	private void createCount() {

		writeLine("/**");
		writeLine(" * count filtered object list");
		writeLine(" */");
		writeLine("@Override");
		writeLine("public Long count(" + bean.basicViewBean.filter.className + " filter) {");

		writeLine("Session session = this.sessionFactory.getCurrentSession();");
		writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
		writeLine("CriteriaQuery<Long> criteria = builder.createQuery(Long.class);");
		skipLine();

		writeLine("Root<" + this.bean.className + "> root = criteria.from(" + this.bean.className + ".class);");
		for (Alias alias : getAllAliases(bean, null)) {
			writeLine("Join<" + alias.parentBeanDataType + ", " + alias.beanDataType + "> " + alias.name + " = " + alias.parentName + ".join(" + alias.parentBeanDataType + "_." + alias.propertyName + ", JoinType.LEFT);");
		}
		skipLine();

		writeLine("List<Predicate> predicates = new ArrayList<>();");
		for (ViewProperty property : this.bean.basicViewBean.properties) {
			writeRestriction(property);
		}

		writeLine("criteria.where(predicates.toArray(new Predicate[predicates.size()]));");
		skipLine();

		writeLine("criteria.select(builder.count(root));");
		writeLine("return session.createQuery(criteria).getSingleResult();");
		writeLine("}");
		skipLine();

		for (Property property : this.bean.properties) {
			if (property.referenceBean != null && property.relation.equals(RelationType.MANY_TO_ONE)) {

				writeLine("/**");
				writeLine(" * count object list from " + property.referenceBean.objectName);
				writeLine(" */");
				writeLine("public Long countFrom" + property.capName + "(" + property.referenceBean.idType + " " + property.name + "Id) {");
				writeLine("Session session = this.sessionFactory.getCurrentSession();");
				writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
				writeLine("CriteriaQuery<Long> criteria = builder.createQuery(Long.class);");
				skipLine();

				writeLine("Root<" + this.bean.className + "> root = criteria.from(" + this.bean.className + ".class);");
				writeLine("Join<" + bean.className + ", " + property.javaType + "> " + property.name + " = root.join(" + bean.className + "_." + property.name + ", JoinType.LEFT);");
				skipLine();

				writeLine("if (" + property.name + "Id == null){");
				writeLine("criteria.where(builder.isNull(" + property.name + ".get(" + property.javaType + "_.id)));");
				writeLine("} else {");
				writeLine("criteria.where(builder.equal(" + property.name + ".get(" + property.javaType + "_.id), " + property.name + "Id));");
				writeLine("}");
				skipLine();

				writeLine("criteria.select(builder.count(root));");
				writeLine("return session.createQuery(criteria).getSingleResult();");
				writeLine("}");
				skipLine();

				writeLine("/**");
				writeLine(" * count filtered object list from " + property.referenceBean.objectName);
				writeLine(" */");
				writeLine("public Long countFrom" + property.capName + "(" + property.referenceBean.idType + " " + property.name + "Id, " + bean.basicViewBean.filter.className + " filter) {");
				writeLine("Session session = this.sessionFactory.getCurrentSession();");
				writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
				writeLine("CriteriaQuery<Long> criteria = builder.createQuery(Long.class);");
				skipLine();

				writeLine("Root<" + this.bean.className + "> root = criteria.from(" + this.bean.className + ".class);");
				for (Alias alias : getAllAliases(bean, null)) {
					writeLine("Join<" + alias.parentBeanDataType + ", " + alias.beanDataType + "> " + alias.name + " = " + alias.parentName + ".join(" + alias.parentBeanDataType + "_." + alias.propertyName + ", JoinType.LEFT);");
				}
				skipLine();

				writeLine("List<Predicate> predicates = new ArrayList<>();");
				for (ViewProperty viewProperty : this.bean.basicViewBean.properties) {
					writeRestriction(viewProperty);
				}
				writeLine("if (" + property.name + "Id == null){");
				writeLine("predicates.add(builder.isNull(" + property.name + ".get(" + property.javaType + "_.id)));");
				writeLine("} else {");
				writeLine("predicates.add(builder.equal(" + property.name + ".get(" + property.javaType + "_.id), " + property.name + "Id));");
				writeLine("}");
				skipLine();

				writeLine("criteria.where(predicates.toArray(new Predicate[predicates.size()]));");
				skipLine();

				writeLine("criteria.select(builder.count(root));");
				writeLine("return session.createQuery(criteria).getSingleResult();");
				writeLine("}");
				skipLine();
			}
		}
	}

	private void createScroll() {

		writeLine("/**");
		writeLine(" * scroll filtered object list");
		writeLine(" */");
		writeLine("@Override");
		writeLine("@SuppressWarnings(\"unchecked\")");
		writeLine("public List<" + this.bean.className + "> scroll(" + bean.basicViewBean.filter.className + " filter, " + bean.basicViewBean.sortingClassName + " sorting, Long firstResult, Long maxResults) {");

		writeLine("Session session = this.sessionFactory.getCurrentSession();");
		writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
		writeLine("CriteriaQuery<" + this.bean.className + "> criteria = builder.createQuery(" + this.bean.className + ".class);");
		skipLine();

		writeLine("Root<" + this.bean.className + "> root = criteria.from(" + this.bean.className + ".class);");
		for (Alias alias : getAllAliases(bean, null)) {
			writeLine("Fetch<" + alias.parentBeanDataType + ", " + alias.beanDataType + "> " + alias.name + "Fetch = " + alias.parentName + ".fetch(" + alias.parentBeanDataType + "_." + alias.propertyName + ", JoinType.LEFT);");
			writeLine("Join<" + alias.parentBeanDataType + ", " + alias.beanDataType + "> " + alias.name + " = (Join<" + alias.parentBeanDataType + ", " + alias.beanDataType + ">)" + alias.name + "Fetch;");
		}
		skipLine();

		writeLine("List<Predicate> predicates = new ArrayList<>();");
		for (ViewProperty property : this.bean.basicViewBean.properties) {
			writeRestriction(property);
		}

		writeLine("criteria.where(predicates.toArray(new Predicate[predicates.size()]));");
		skipLine();

		writeLine("criteria.select(root);");
		writeLine("List<Order> orders = new ArrayList<>();");

		for (ViewProperty viewProperty : this.bean.basicViewBean.properties) {
			String joinedAliasName = StringUtils.isEmpty(viewProperty.joinedAliasName)?"root":viewProperty.joinedAliasName;
			writeLine("addOrder(builder, orders, " + joinedAliasName + ".get(" + viewProperty.lastParentBeanClassName + "_." + viewProperty.lastPropertyName + "), sorting.get" + viewProperty.capName + "OrderType());");
		}

		writeLine("addOrder(builder, orders, root.get(" + bean.className + "_.id), OrderType.DESC);");
		writeLine("criteria.orderBy(orders);");
		skipLine();

		writeLine("Query<" + this.bean.className + "> query = session.createQuery(criteria);");
		writeLine("if (firstResult != null){");
		writeLine("query.setFirstResult(firstResult.intValue());");
		writeLine("}");
		writeLine("if (maxResults != null){");
		writeLine("query.setMaxResults(maxResults.intValue());");
		writeLine("}");
		writeLine("return query.getResultList();");
		writeLine("}");
		skipLine();

		for (Property property : this.bean.properties) {
			if (property.referenceBean != null && property.relation.equals(RelationType.MANY_TO_ONE)) {

				writeLine("/**");
				writeLine(" * scroll filtered object list from " + property.referenceBean.objectName);
				writeLine(" */");
				writeLine("@Override");
				writeLine("@SuppressWarnings(\"unchecked\")");
				writeLine("public List<" + this.bean.className + "> scrollFrom" + property.capName + "(" + property.referenceBean.idType + " " + property.name + "Id, " + bean.basicViewBean.filter.className + " filter, " + bean.basicViewBean.sortingClassName + " sorting, Long firstResult, Long maxResults) {");
				writeLine("Session session = this.sessionFactory.getCurrentSession();");
				writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
				writeLine("CriteriaQuery<" + this.bean.className + "> criteria = builder.createQuery(" + this.bean.className + ".class);");
				skipLine();

				writeLine("Root<" + this.bean.className + "> root = criteria.from(" + this.bean.className + ".class);");
				for (Alias alias : getAllAliases(bean, null)) {
					writeLine("Fetch<" + alias.parentBeanDataType + ", " + alias.beanDataType + "> " + alias.name + "Fetch = " + alias.parentName + ".fetch(" + alias.parentBeanDataType + "_." + alias.propertyName + ", JoinType.LEFT);");
					writeLine("Join<" + alias.parentBeanDataType + ", " + alias.beanDataType + "> " + alias.name + " = (Join<" + alias.parentBeanDataType + ", " + alias.beanDataType + ">)" + alias.name + "Fetch;");
				}
				skipLine();

				writeLine("List<Predicate> predicates = new ArrayList<>();");
				for (ViewProperty viewProperty : this.bean.basicViewBean.properties) {
					writeRestriction(viewProperty);
				}
				writeLine("if (" + property.name + "Id == null){");
				writeLine("predicates.add(builder.isNull(" + property.name + ".get(" + property.javaType + "_.id)));");
				writeLine("} else {");
				writeLine("predicates.add(builder.equal(" + property.name + ".get(" + property.javaType + "_.id), " + property.name + "Id));");
				writeLine("}");
				writeLine("criteria.where(predicates.toArray(new Predicate[predicates.size()]));");
				skipLine();

				writeLine("criteria.select(root);");
				writeLine("List<Order> orders = new ArrayList<>();");

				for (ViewProperty viewProperty : this.bean.basicViewBean.properties) {
					String joinedAliasName = StringUtils.isEmpty(viewProperty.joinedAliasName)?"root":viewProperty.joinedAliasName;
					writeLine("addOrder(builder, orders, " + joinedAliasName + ".get(" + viewProperty.lastParentBeanClassName + "_." + viewProperty.lastPropertyName + "), sorting.get" + viewProperty.capName + "OrderType());");
				}

				writeLine("addOrder(builder, orders, root.get(" + bean.className + "_.id), OrderType.DESC);");
				writeLine("criteria.orderBy(orders);");
				skipLine();

				writeLine("Query<" + this.bean.className + "> query = session.createQuery(criteria);");
				writeLine("if (firstResult != null){");
				writeLine("query.setFirstResult(firstResult.intValue());");
				writeLine("}");
				writeLine("if (maxResults != null){");
				writeLine("query.setMaxResults(maxResults.intValue());");
				writeLine("}");
				writeLine("return query.getResultList();");
				writeLine("}");
				skipLine();
			}
		}
	}

	private void createLoadOneToManyComponentList() {
		for (OneToManyComponent oneToManyComponent : this.bean.oneToManyComponentList) {
            Bean currentBean = oneToManyComponent.referenceBean;
            writeLine("/**");
            writeLine(" * load one to many component " + currentBean.className + " list");
            writeLine(" */");
            writeLine("@Override");
			writeLine("public List<" + currentBean.className + "> load" + currentBean.className + "List(" + bean.idType + " " + bean.objectName + "Id) {");

			writeLine("Session session = this.sessionFactory.getCurrentSession();");
			writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
			writeLine("CriteriaQuery<" + currentBean.className + "> criteria = builder.createQuery(" + currentBean.className + ".class);");
			skipLine();

			writeLine("Root<" + currentBean.className + "> root = criteria.from(" + currentBean.className + ".class);");
			writeLine("Join<" + currentBean.className + ", " + oneToManyComponent.referenceProperty.javaType + "> " + oneToManyComponent.referenceProperty.name + " = root.join(" + currentBean.className + "_." + oneToManyComponent.referenceProperty.name + ", JoinType.LEFT);");
			skipLine();

			writeLine("if (" + bean.objectName + "Id == null){");
			writeLine("criteria.where(builder.isNull(" + oneToManyComponent.referenceProperty.name + ".get(" + oneToManyComponent.referenceProperty.javaType + "_.id)));");
			writeLine("} else {");
			writeLine("criteria.where(builder.equal(" + oneToManyComponent.referenceProperty.name + ".get(" + oneToManyComponent.referenceProperty.javaType + "_.id), " + bean.objectName + "Id));");
			writeLine("}");
			skipLine();

			writeLine("criteria.select(root);");
			writeLine("List<Order> orders = new ArrayList<>();");
			writeLine("addOrder(builder, orders, root.get(" + currentBean.className + "_.id), OrderType.DESC);");
			writeLine("criteria.orderBy(orders);");
			skipLine();
			writeLine("return session.createQuery(criteria).getResultList();");
			writeLine("}");
			skipLine();
        }
	}

	private void createCountOneToManyComponent() {
		for (OneToManyComponent oneToManyComponent : this.bean.oneToManyComponentList) {
			Bean currentBean = oneToManyComponent.referenceBean;

			writeLine("/**");
			writeLine(" * count one to many component " + currentBean.className);
			writeLine(" */");
			writeLine("@Override");
			writeLine("public Long count" + currentBean.className + "(" + bean.idType + " " + bean.objectName + "Id) {");

			writeLine("Session session = this.sessionFactory.getCurrentSession();");
			writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
			writeLine("CriteriaQuery<Long> criteria = builder.createQuery(Long.class);");
			skipLine();

			writeLine("Root<" + currentBean.className + "> root = criteria.from(" + currentBean.className + ".class);");
			writeLine("Join<" + currentBean.className + ", " + oneToManyComponent.referenceProperty.javaType + "> " + oneToManyComponent.referenceProperty.name + " = root.join(" + currentBean.className + "_." + oneToManyComponent.referenceProperty.name + ", JoinType.LEFT);");
			skipLine();

			writeLine("if (" + bean.objectName + "Id == null){");
			writeLine("criteria.where(builder.isNull(" + oneToManyComponent.referenceProperty.name + ".get(" + oneToManyComponent.referenceProperty.javaType + "_.id)));");
			writeLine("} else {");
			writeLine("criteria.where(builder.equal(" + oneToManyComponent.referenceProperty.name + ".get(" + oneToManyComponent.referenceProperty.javaType + "_.id), " + bean.objectName + "Id));");
			writeLine("}");
			skipLine();

			writeLine("criteria.select(builder.count(root));");
			writeLine("return session.createQuery(criteria).getSingleResult();");
			writeLine("}");
			skipLine();

			writeLine("/**");
			writeLine(" * count filtered one to many component " + currentBean.className);
			writeLine(" */");
			writeLine("@Override");
			writeLine("public Long count" + currentBean.className + "(" + bean.idType + " " + bean.objectName + "Id, " + currentBean.basicViewBean.filter.className + " filter) {");

			writeLine("Session session = this.sessionFactory.getCurrentSession();");
			writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
			writeLine("CriteriaQuery<Long> criteria = builder.createQuery(Long.class);");
			skipLine();

			writeLine("Root<" + currentBean.className + "> root = criteria.from(" + currentBean.className + ".class);");
			writeLine("Join<" + currentBean.className + ", " + oneToManyComponent.referenceProperty.javaType + "> " + oneToManyComponent.referenceProperty.name + " = root.join(" + currentBean.className + "_." + oneToManyComponent.referenceProperty.name + ", JoinType.LEFT);");
			for (Alias alias : getAllAliases(currentBean, null)) {
				writeLine("Join<" + alias.parentBeanDataType + ", " + alias.beanDataType + "> " + alias.name + " = " + alias.parentName + ".join(" + alias.parentBeanDataType + "_." + alias.propertyName + ", JoinType.LEFT);");
			}
			skipLine();

			writeLine("List<Predicate> predicates = new ArrayList<>();");
			for (ViewProperty viewProperty : currentBean.basicViewBean.properties) {
				writeRestriction(viewProperty);
			}
			writeLine("if (" + bean.objectName + "Id == null){");
			writeLine("predicates.add(builder.isNull(" + oneToManyComponent.referenceProperty.name + ".get(" + oneToManyComponent.referenceProperty.javaType + "_.id)));");
			writeLine("} else {");
			writeLine("predicates.add(builder.equal(" + oneToManyComponent.referenceProperty.name + ".get(" + oneToManyComponent.referenceProperty.javaType + "_.id), " + bean.objectName + "Id));");
			writeLine("}");
			writeLine("criteria.where(predicates.toArray(new Predicate[predicates.size()]));");
			skipLine();

			writeLine("criteria.select(builder.count(root));");
			writeLine("return session.createQuery(criteria).getSingleResult();");
			writeLine("}");
			skipLine();
		}
	}

	private void createScrollOneToManyComponent() {
		for (OneToManyComponent oneToManyComponent : this.bean.oneToManyComponentList) {
			Bean currentBean = oneToManyComponent.referenceBean;

			writeLine("/**");
			writeLine(" * scroll filtered one to many component " + currentBean.className);
			writeLine(" */");
			writeLine("@Override");
			writeLine("public List<" + currentBean.className + "> scroll" + currentBean.className + "(" + bean.idType + " " + bean.objectName + "Id, " + currentBean.basicViewBean.filter.className + " filter, " + currentBean.basicViewBean.sortingClassName + " sorting, Long firstResult, Long maxResults) {");

			writeLine("Session session = this.sessionFactory.getCurrentSession();");
			writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
			writeLine("CriteriaQuery<" + currentBean.className + "> criteria = builder.createQuery(" + currentBean.className + ".class);");
			skipLine();

			writeLine("Root<" + currentBean.className + "> root = criteria.from(" + currentBean.className + ".class);");
			writeLine("Join<" + currentBean.className + ", " + oneToManyComponent.referenceProperty.javaType + "> " + oneToManyComponent.referenceProperty.name + " = root.join(" + currentBean.className + "_." + oneToManyComponent.referenceProperty.name + ", JoinType.LEFT);");
			for (Alias alias : getAllAliases(currentBean, null)) {
				writeLine("Join<" + alias.parentBeanDataType + ", " + alias.beanDataType + "> " + alias.name + " = " + alias.parentName + ".join(" + alias.parentBeanDataType + "_." + alias.propertyName + ", JoinType.LEFT);");
			}
			skipLine();

			writeLine("List<Predicate> predicates = new ArrayList<>();");
			for (ViewProperty viewProperty : currentBean.basicViewBean.properties) {
				writeRestriction(viewProperty);
			}
			writeLine("if (" + bean.objectName + "Id == null){");
			writeLine("predicates.add(builder.isNull(" + oneToManyComponent.referenceProperty.name + ".get(" + oneToManyComponent.referenceProperty.javaType + "_.id)));");
			writeLine("} else {");
			writeLine("predicates.add(builder.equal(" + oneToManyComponent.referenceProperty.name + ".get(" + oneToManyComponent.referenceProperty.javaType + "_.id), " + bean.objectName + "Id));");
			writeLine("}");
			writeLine("criteria.where(predicates.toArray(new Predicate[predicates.size()]));");
			skipLine();

			writeLine("criteria.select(root);");
			writeLine("List<Order> orders = new ArrayList<>();");

			for (ViewProperty viewProperty : currentBean.basicViewBean.properties) {
				String joinedAliasName = StringUtils.isEmpty(viewProperty.joinedAliasName)?"root":viewProperty.joinedAliasName;
				writeLine("addOrder(builder, orders, " + joinedAliasName + ".get(" + viewProperty.lastParentBeanClassName + "_." + viewProperty.lastPropertyName + "), sorting.get" + viewProperty.capName + "OrderType());");
			}

			writeLine("addOrder(builder, orders, root.get(" + currentBean.className + "_.id), OrderType.DESC);");
			writeLine("criteria.orderBy(orders);");
			skipLine();

			writeLine("Query<" + currentBean.className + "> query = session.createQuery(criteria);");
			writeLine("if (firstResult != null){");
			writeLine("query.setFirstResult(firstResult.intValue());");
			writeLine("}");
			writeLine("if (maxResults != null){");
			writeLine("query.setMaxResults(maxResults.intValue());");
			writeLine("}");
			writeLine("return query.getResultList();");
			writeLine("}");
			skipLine();
		}
	}

	private void createLoadOneToManyComponent() {

		for (OneToManyComponent oneToManyComponent : this.bean.oneToManyComponentList) {
            Bean currentBean = oneToManyComponent.referenceBean;
            writeLine("/**");
            writeLine(" * load one to many component " + currentBean.className);
            writeLine(" */");
            writeLine("@Override");
			writeLine("public " + currentBean.className + " load" + currentBean.className + "(" + currentBean.idType + " id) {");
			writeLine(currentBean.className + " " + currentBean.objectName + " = (" + currentBean.className + ")this.sessionFactory.getCurrentSession().get(" + currentBean.className + ".class,id);");
			writeLine("if (" + currentBean.objectName + " == null) {");
			writeLine("throw new ObjectNotFoundException(" + CHAR_34 + currentBean.className + ".notFound" + CHAR_34 + ");");
			writeLine("} else {");
			writeLine("return " + currentBean.objectName + ";");
			writeLine("}");
			writeLine("}");
			skipLine();
        }
	}

	private void createFindObject() {
		boolean start = true;
		List<ViewProperty> findPropertyList = this.bean.referenceViewProperties;

		writeLine("/**");
		writeLine(" * find object or null");
		writeLine(" */");
		writeLine("@Override");
		write("public " + this.bean.className + " findOrNull(");
		for (ViewProperty property:findPropertyList) {
			if (start) start = false; else write(", ");
			write(property.javaType + " " + property.name);
		}
		writeLine(") {");

		writeLine("Session session = this.sessionFactory.getCurrentSession();");
		writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
		writeLine("CriteriaQuery<" + this.bean.className + "> criteria = builder.createQuery(" + this.bean.className + ".class);");
		skipLine();

		writeLine("Root<" + this.bean.className + "> root = criteria.from(" + this.bean.className + ".class);");
		for (Alias alias : getReferenceAliases(bean, "")) {
			writeLine("Join<" + alias.parentBeanDataType + ", " + alias.beanDataType + "> " + alias.name + " = " + alias.parentName + ".join(" + alias.parentBeanDataType + "_." + alias.propertyName + ", JoinType.LEFT);");
		}
		skipLine();

		writeLine("List<Predicate> predicates = new ArrayList<>();");
		for (ViewProperty property : this.bean.referenceViewProperties) {
			writeEqualsRestriction(property);
		}

		writeLine("criteria.where(predicates.toArray(new Predicate[predicates.size()]));");
		skipLine();

		writeLine("criteria.select(root);");
		skipLine();
		writeLine("return session.createQuery(criteria).uniqueResult();");
		writeLine("}");
		skipLine();

		start = true;
		writeLine("/**");
		writeLine(" * find object");
		writeLine(" */");
		writeLine("@Override");
		write("public " + this.bean.className + " find(");
		for (ViewProperty property:findPropertyList) {
			if (start) start = false; else write(", ");
			write(property.javaType + " " + property.name);
		}
		writeLine(") {");

		start = true;
		write("if (");
		for (ViewProperty property:findPropertyList) {
			if (start) start = false; else write(" && ");
			write(property.name + " == null");
		}
		writeLine(") {");

		writeLine("return null;");
		writeLine("}");

		start = true;
		write(this.bean.className + " " + this.bean.objectName + " = findOrNull(");
		for (ViewProperty property:findPropertyList) {
			if (start) start = false; else write(", ");
			write(property.name);
		}
		writeLine(");");
		writeLine("if (" + this.bean.objectName + " == null) {");
		writeLine("throw new ObjectNotFoundException(" + CHAR_34 + bean.className + ".notFound" + CHAR_34 + ");");
		writeLine("} else {");
		writeLine("return " + this.bean.objectName + ";");
		writeLine("}");
		writeLine("}");
		skipLine();

		start = true;
		writeLine("/**");
		writeLine(" * exists object");
		writeLine(" */");
		writeLine("@Override");
		write("public boolean exists(");
		for (ViewProperty property:findPropertyList) {
			if (start) start = false; else write(", ");
			write(property.javaType + " " + property.name);
		}
		writeLine(") {");

		start = true;
		write("if (");
		for (ViewProperty property:findPropertyList) {
			if (start) start = false; else write(" && ");
			write(property.name + " == null");
		}
		writeLine(") {");

		writeLine("return false;");
		writeLine("}");

		start = true;
		write(this.bean.className + " " + this.bean.objectName + " = findOrNull(");
		for (ViewProperty property:findPropertyList) {
			if (start) start = false; else write(", ");
			write(property.name);
		}
		writeLine(");");
		writeLine("return " + this.bean.objectName + " != null;");
		writeLine("}");
		skipLine();
	}

	private void createSearch() {

		Property targetProperty = bean.selectionBehavior.targetProperty;

		writeLine("/**");
		writeLine(" * search");
		writeLine(" */");
		writeLine("@Override");
		writeLine("public List<" + this.bean.className + "> search(String arg) {");
		writeLine("Session session = this.sessionFactory.getCurrentSession();");
		writeLine("CriteriaBuilder builder = session.getCriteriaBuilder();");
		writeLine("CriteriaQuery<" + this.bean.className + "> criteria = builder.createQuery(" + this.bean.className + ".class);");
		skipLine();

		writeLine("Root<" + this.bean.className + "> root = criteria.from(" + this.bean.className + ".class);");
		skipLine();

		switch (targetProperty.textFilterType) {
			case CONTAINS:
				writeLine("Predicate predicate = getStringContainsRestriction(builder, root.get(" + bean.className + "_." + targetProperty.name + "), arg);");
				break;
			case CONTAINS_IGNORE_ACCENTS:
				writeLine("Predicate predicate = getUnaccentuatedStringContainsRestriction(builder, root.get(" + bean.className + "_." + targetProperty.name + "), arg);");
				break;
			case STARTS_WITH:
				writeLine("Predicate predicate = getStringStartsWithRestriction(builder, root.get(" + bean.className + "_." + targetProperty.name + "), arg);");
				break;
			default:
				break;
		}

		writeLine("if (predicate!=null){");
		writeLine("criteria.where(predicate);");
		writeLine("}");
		skipLine();

		writeLine("criteria.select(root);");
		skipLine();

		writeLine("Query<" + this.bean.className + "> query = session.createQuery(criteria);");
		writeLine("query.setMaxResults(20);");
		writeLine("return query.getResultList();");
		writeLine("}");
		skipLine();
	}

	private void createSaveComponent() {

		for (OneToManyComponent oneToManyComponent:bean.oneToManyComponentList){
			Bean currentBean = oneToManyComponent.referenceBean;
			writeLine("/**");
			writeLine(" * save one to many component " + currentBean.className);
			writeLine(" */");
			writeLine("@Override");
			writeLine("public void save" + currentBean.className + "(" + this.bean.className + " " + this.bean.objectName + ", " + currentBean.className + " " + currentBean.objectName + ") {");
			writeLine(currentBean.objectName + "." + oneToManyComponent.referenceProperty.setterName + "(" + bean.objectName + ");");
			writeLine("this.sessionFactory.getCurrentSession().save(" + currentBean.objectName + ");");
			writeLine("}");
			skipLine();
		}

		for (OneToOneComponent oneToOneComponent:bean.oneToOneComponentList){
			Bean currentBean = oneToOneComponent.referenceBean;
			writeLine("/**");
			writeLine(" * save one to one component " + currentBean.className);
			writeLine(" */");
			writeLine("@Override");
			writeLine("public void save" + currentBean.className + "(" + this.bean.className + " " + this.bean.objectName + ", " + currentBean.className + " " + currentBean.objectName + ") {");
			writeLine(currentBean.objectName + ".set" + bean.className + "(" + bean.objectName + ");");
			writeLine("this.sessionFactory.getCurrentSession().save(" + currentBean.objectName + ");");
			writeLine("}");
			skipLine();
		}
	}

	private void createDeleteComponent() {

		for (OneToManyComponent oneToManyComponent:bean.oneToManyComponentList){
			Bean currentBean = oneToManyComponent.referenceBean;
			writeLine("/**");
			writeLine(" * delete one to many component " + currentBean.className);
			writeLine(" */");
			writeLine("@Override");
			writeLine("public void delete" + currentBean.className + "(" + currentBean.className + " " + currentBean.objectName + ") {");
			writeLine(currentBean.objectName + "." + oneToManyComponent.referenceProperty.getterName + "().get" + currentBean.className + "Collection().remove(" + currentBean.objectName + ");");
			writeLine("this.sessionFactory.getCurrentSession().delete(" + currentBean.objectName + ");");
			writeLine("}");
			skipLine();
		}

		for (OneToOneComponent oneToOneComponent:bean.oneToOneComponentList){
			Bean currentBean = oneToOneComponent.referenceBean;
			writeLine("/**");
			writeLine(" * delete one to one component " + currentBean.className);
			writeLine(" */");
			writeLine("@Override");
			writeLine("public void delete" + currentBean.className + "(" + currentBean.className + " " + currentBean.objectName + ") {");

			writeLine(bean.className + " " +  bean.objectName + " = " + currentBean.objectName + ".get" + bean.className + "();");
			writeLine(bean.objectName + ".set" + currentBean.className + "(null);");
			writeLine("this.sessionFactory.getCurrentSession().delete(" + currentBean.objectName + ");");
			writeLine("}");
			skipLine();
		}
	}

	private class Alias {

		public String propertyName;
	    public String name;
	    public String parentName;
	    public String beanDataType;
	    public String parentBeanDataType;
	}

	private List<Alias> getAliases(Bean bean, int size, String parentName) {
		List<Alias> aliasList = new ArrayList<Alias>();

		for (int i = 0; i < size; i++) {
			Property currentProperty = bean.properties.get(i);
			if (currentProperty.visibility.isListVisible() && currentProperty.referenceBean != null && !currentProperty.relation.isComponentLink()) {
				Alias alias = new Alias();
				alias.propertyName = currentProperty.name;
				alias.parentName = StringUtils.isEmpty(parentName)?"root":parentName;
				alias.name = StringUtils.isEmpty(parentName)?currentProperty.name:parentName+JavaClassNaming.getClassNameFromObjectName(currentProperty.name);
				alias.parentBeanDataType = bean.className;
				alias.beanDataType = currentProperty.javaType;
				aliasList.add(alias);
				aliasList.addAll(getAliases(currentProperty, alias.name));
			}
		}

		return aliasList;
	}

	private List<Alias> getReferenceAliases(Bean bean, String parentName) {
		return getAliases(bean, bean.cardinality, parentName);
	}

	private List<Alias> getAllAliases(Bean bean, String parentName) {
		return getAliases(bean, bean.properties.size(), parentName);
	}

	private List<Alias> getAliases(Property property, String parentName) {
		if (property.embedded) {
			return getAllAliases(property.referenceBean, parentName);
		} else {
			return getReferenceAliases(property.referenceBean, parentName);
		}
	}

	private void writeRestriction(ViewProperty property) {

		switch (property.dataType) {
			case BOOLEAN :
				writeBooleanRestriction(property);
				return;
			case SHORT :
			case INTEGER :
			case LONG :
				writeLongRestriction(property);
				return;
			case DATE :
				writeDateRestriction(property);
				return;
			case DATETIME :
				writeDateTimeRestriction(property);
				return;
			case DOUBLE :
				writeDoubleRestriction(property);
				return;
			case BIG_DECIMAL :
				writeBigDecimalRestriction(property);
				return;
			case STRING :
			case TEXT :
				writeTextRestriction(property);
				return;
		}
	}

	private void writeTextRestriction(ViewProperty property) {
		String joinedAliasName = StringUtils.isEmpty(property.joinedAliasName)?"root":property.joinedAliasName;

		switch (property.textFilterType) {
			case CONTAINS:
				writeLine("addStringContainsRestriction(builder, predicates, " + joinedAliasName + ".get(" + property.lastParentBeanClassName + "_." + property.lastPropertyName + "), filter.get" + property.capName + "());");
				break;
			case CONTAINS_IGNORE_ACCENTS:
				writeLine("addUnaccentuatedStringContainsRestriction(builder, predicates, " + joinedAliasName + ".get(" + property.lastParentBeanClassName + "_." + property.lastPropertyName + "), filter.get" + property.capName + "());");
				break;
			case STARTS_WITH:
				writeLine("addStringStartsWithRestriction(builder, predicates, " + joinedAliasName + ".get(" + property.lastParentBeanClassName + "_." + property.lastPropertyName + "), filter.get" + property.capName + "());");
				break;
			default:
				break;
		}

	}

	private void writeBooleanRestriction(ViewProperty property) {
		String joinedAliasName = StringUtils.isEmpty(property.joinedAliasName)?"root":property.joinedAliasName;
		writeLine("addBooleanRestriction(builder, predicates, " + joinedAliasName + ".get(" + property.lastParentBeanClassName + "_." + property.lastPropertyName + "), filter.get" + property.capName + "());");
	}

	private void writeDoubleRestriction(ViewProperty property) {
		writeComparableRestriction(property);
	}

	private void writeBigDecimalRestriction(ViewProperty property) {
		writeComparableRestriction(property);
	}

	private void writeDateRestriction(ViewProperty property) {
		writeComparableRestriction(property);
	}

	private void writeDateTimeRestriction(ViewProperty property) {
		writeComparableRestriction(property);
	}

	private void writeLongRestriction(ViewProperty property) {
		writeComparableRestriction(property);
	}

	private void writeComparableRestriction(ViewProperty property) {
		String joinedAliasName = StringUtils.isEmpty(property.joinedAliasName)?"root":property.joinedAliasName;
		writeLine("addBetweenRestriction(builder, predicates, " + joinedAliasName + ".get(" + property.lastParentBeanClassName + "_." + property.lastPropertyName + "), filter.get" + property.capName + "MinValue(), filter.get" + property.capName + "MaxValue());");
	}

	private void writeEqualsRestriction(ViewProperty property) {
		String joinedAliasName = StringUtils.isEmpty(property.joinedAliasName)?"root":property.joinedAliasName;
		writeLine("addEqualsRestriction(builder, predicates, " + joinedAliasName + ".get(" + property.lastParentBeanClassName + "_." + property.lastPropertyName + "), " + property.name + ");");
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="com.yunstudio.entity.RepUser" table="rep_user" dynamic-insert="true" dynamic-update="true" batch-size="30">
		<id name="id" type="integer" column="id">
			<generator class="native" />
		</id>

		<property name="username" type="string" column="username">
		</property>
		<property name="password" type="string" column="password">
		</property>
		<property name="email" type="string" column="email">
		</property>
		<property name="islock" type="integer" column="islock">
		</property>
		<property name="ispassed" type="integer" column="ispassed">
		</property>
		<property name="notpassreason" type="string" column="notpassreason">
		</property>
		<property name="passtime" type="timestamp" column="passtime">
		</property>
		<property name="regtime" type="timestamp" column="regtime">
		</property>
		<property name="snumber" type="string" column="snumber">
		</property>
		<property name="realname" type="string" column="realname">
		</property>
		<property name="gender" type="integer" column="gender">
		</property>
		<property name="grade" type="string" column="grade">
		</property>
		<property name="school" type="string" column="school">
		</property>
		<property name="major" type="string" column="major">
		</property>
		<property name="birthday" type="timestamp" column="birthday">
		</property>
		<property name="qq" type="string" column="qq">
		</property>
		<property name="phone" type="string" column="phone">
		</property>
		<property name="lastloginip" type="string" column="lastloginip">
		</property>
		<property name="lastlogintime" type="timestamp" column="lastlogintime">
		</property>
		<property name="teacherorstu" type="integer" column="teacherorstu">
		</property>
		<property name="points" type="integer" column="points">
		</property>

		<!-- Associations -->

		<!--  双向一对多 RepMessage -->
		<set name="repMessages" table="rep_message">
			<key>
				<column name="userid" />
			</key>
			<one-to-many class="com.yunstudio.entity.RepMessage" />
		</set>

		<!--  双向一对多RepResource -->
		<set name="repResources" table="rep_resource">
			<key>
				<column name="userid" />
			</key>
			<one-to-many class="com.yunstudio.entity.RepResource" />
		</set>

		<!-- 双向一对多 RepComment -->
		<set name="repComments" table="rep_comment">
			<key>
				<column name="userid" />
			</key>
			<one-to-many class="com.yunstudio.entity.RepComment" />
		</set>

		<!-- 一对多 -->
		<set name="repFolders" table="rep_folder"
			cascade="delete-orphan">
			<key>
				<column name="userid" />
			</key>
			<one-to-many class="com.yunstudio.entity.RepFolder"/>
		</set>

		<!-- 一对多 -->
		<set name="repTopics" table="rep_topic">
			<key>
				<column name="userid" />
			</key>
			<one-to-many class="com.yunstudio.entity.RepTopic"/>
		</set>

	</class>
</hibernate-mapping>

redpajama_set_name: RedPajamaGithub


text:
$( function() {
  $('form#follow button[type=submit]').click(function(e) {
    $(this).find('i').removeClass('icon-heart').addClass('icon-refresh icon-spin')
  });
});


text:
import unittest

from webkitpy.common.system.executive import Executive, ScriptError
from webkitpy.common.system.executive_mock import MockExecutive
from webkitpy.common.system.filesystem import FileSystem
from webkitpy.common.system.filesystem_mock import MockFileSystem
from webkitpy.common.checkout.scm.git import Git

class GitTestWithRealFilesystemAndExecutive(unittest.TestCase):

    def setUp(self):
        self.executive = Executive()
        self.filesystem = FileSystem()
        self.original_cwd = self.filesystem.getcwd()

        # Set up fresh git repository with one commit.
        self.untracking_checkout_path = self._mkdtemp(suffix='-git_unittest_untracking')
        self._run(['git', 'init', self.untracking_checkout_path])
        self._chdir(self.untracking_checkout_path)
        self._write_text_file('foo_file', 'foo')
        self._run(['git', 'add', 'foo_file'])
        self._run(['git', 'commit', '-am', 'dummy commit'])
        self.untracking_scm = Git(cwd=self.untracking_checkout_path, filesystem=self.filesystem, executive=self.executive)

        # Then set up a second git repo that tracks the first one.
        self.tracking_git_checkout_path = self._mkdtemp(suffix='-git_unittest_tracking')
        self._run(['git', 'clone', '--quiet', self.untracking_checkout_path, self.tracking_git_checkout_path])
        self._chdir(self.tracking_git_checkout_path)
        self.tracking_scm = Git(cwd=self.tracking_git_checkout_path, filesystem=self.filesystem, executive=self.executive)

    def tearDown(self):
        self._chdir(self.original_cwd)
        self._run(['rm', '-rf', self.tracking_git_checkout_path])
        self._run(['rm', '-rf', self.untracking_checkout_path])

    def _join(self, *comps):
        return self.filesystem.join(*comps)

    def _chdir(self, path):
        self.filesystem.chdir(path)

    def _mkdir(self, path):
        assert not self.filesystem.exists(path)
        self.filesystem.maybe_make_directory(path)

    def _mkdtemp(self, **kwargs):
        return str(self.filesystem.mkdtemp(**kwargs))

    def _remove(self, path):
        self.filesystem.remove(path)

    def _run(self, *args, **kwargs):
        return self.executive.run_command(*args, **kwargs)

    def _run_silent(self, args, **kwargs):
        self.executive.run_command(args, **kwargs)

    def _write_text_file(self, path, contents):
        self.filesystem.write_text_file(path, contents)

    def _write_binary_file(self, path, contents):
        self.filesystem.write_binary_file(path, contents)

    def _make_diff(self, command, *args):
        # We use this wrapper to disable output decoding. diffs should be treated as
        # binary files since they may include text files of multiple different encodings.
        return self._run([command, 'diff'] + list(args), decode_output=False)

    def _git_diff(self, *args):
        return self._make_diff('git', *args)

    def test_add_list(self):
        self._chdir(self.untracking_checkout_path)
        git = self.untracking_scm
        self._mkdir('added_dir')
        self._write_text_file('added_dir/added_file', 'new stuff')
        print self._run(['ls', 'added_dir'])
        print self._run(['pwd'])
        print self._run(['cat', 'added_dir/added_file'])
        git.add_list(['added_dir/added_file'])
        self.assertIn('added_dir/added_file', git.added_files())

    def test_delete_recursively(self):
        self._chdir(self.untracking_checkout_path)
        git = self.untracking_scm
        self._mkdir('added_dir')
        self._write_text_file('added_dir/added_file', 'new stuff')
        git.add_list(['added_dir/added_file'])
        self.assertIn('added_dir/added_file', git.added_files())
        git.delete_list(['added_dir/added_file'])
        self.assertNotIn('added_dir', git.added_files())

    def test_delete_recursively_or_not(self):
        self._chdir(self.untracking_checkout_path)
        git = self.untracking_scm
        self._mkdir('added_dir')
        self._write_text_file('added_dir/added_file', 'new stuff')
        self._write_text_file('added_dir/another_added_file', 'more new stuff')
        git.add_list(['added_dir/added_file', 'added_dir/another_added_file'])
        self.assertIn('added_dir/added_file', git.added_files())
        self.assertIn('added_dir/another_added_file', git.added_files())
        git.delete_list(['added_dir/added_file'])
        self.assertIn('added_dir/another_added_file', git.added_files())

    def test_exists(self):
        self._chdir(self.untracking_checkout_path)
        git = self.untracking_scm
        self._chdir(git.checkout_root)
        self.assertFalse(git.exists('foo.txt'))
        self._write_text_file('foo.txt', 'some stuff')
        self.assertFalse(git.exists('foo.txt'))
        git.add_list(['foo.txt'])
        git.commit_locally_with_message('adding foo')
        self.assertTrue(git.exists('foo.txt'))
        git.delete_list(['foo.txt'])
        git.commit_locally_with_message('deleting foo')
        self.assertFalse(git.exists('foo.txt'))

    def test_move(self):
        self._chdir(self.untracking_checkout_path)
        git = self.untracking_scm
        self._write_text_file('added_file', 'new stuff')
        git.add_list(['added_file'])
        git.move('added_file', 'moved_file')
        self.assertIn('moved_file', git.added_files())

    def test_move_recursive(self):
        self._chdir(self.untracking_checkout_path)
        git = self.untracking_scm
        self._mkdir('added_dir')
        self._write_text_file('added_dir/added_file', 'new stuff')
        self._write_text_file('added_dir/another_added_file', 'more new stuff')
        git.add_list(['added_dir'])
        git.move('added_dir', 'moved_dir')
        self.assertIn('moved_dir/added_file', git.added_files())
        self.assertIn('moved_dir/another_added_file', git.added_files())

    def test_remote_branch_ref(self):
        # This tests a protected method. pylint: disable=protected-access
        self.assertEqual(self.tracking_scm._remote_branch_ref(), 'refs/remotes/origin/master')
        self._chdir(self.untracking_checkout_path)
        self.assertRaises(ScriptError, self.untracking_scm._remote_branch_ref)

    def test_create_patch(self):
        self._chdir(self.tracking_git_checkout_path)
        git = self.tracking_scm
        self._write_text_file('test_file_commit1', 'contents')
        self._run(['git', 'add', 'test_file_commit1'])
        git.commit_locally_with_message('message')
        git._patch_order = lambda: ''  # pylint: disable=protected-access
        patch = git.create_patch()
        self.assertNotRegexpMatches(patch, r'Subversion Revision:')

    def test_patches_have_filenames_with_prefixes(self):
        self._chdir(self.tracking_git_checkout_path)
        git = self.tracking_scm
        self._write_text_file('test_file_commit1', 'contents')
        self._run(['git', 'add', 'test_file_commit1'])
        git.commit_locally_with_message('message')

        # Even if diff.noprefix is enabled, create_patch() produces diffs with prefixes.
        self._run(['git', 'config', 'diff.noprefix', 'true'])
        git._patch_order = lambda: ''  # pylint: disable=protected-access
        patch = git.create_patch()
        self.assertRegexpMatches(patch, r'^diff --git a/test_file_commit1 b/test_file_commit1')

    def test_rename_files(self):
        self._chdir(self.tracking_git_checkout_path)
        git = self.tracking_scm
        git.move('foo_file', 'bar_file')
        git.commit_locally_with_message('message')

    def test_commit_position_from_git_log(self):
        # This tests a protected method. pylint: disable=protected-access
        git_log = """
commit 624c3081c0
Author: foobarbaz1 <foobarbaz1@chromium.org>
Date:   Mon Sep 28 19:10:30 2015 -0700

    Test foo bar baz qux 123.

    BUG=000000

    Review URL: https://codereview.chromium.org/999999999

    Cr-Commit-Position: refs/heads/master@{#1234567}
"""
        self._chdir(self.tracking_git_checkout_path)
        git = self.tracking_scm
        self.assertEqual(git._commit_position_from_git_log(git_log), 1234567)

    def test_timestamp_of_revision(self):
        # This tests a protected method. pylint: disable=protected-access
        self._chdir(self.tracking_git_checkout_path)
        git = self.tracking_scm
        position_regex = git._commit_position_regex_for_timestamp()
        git.most_recent_log_matching(position_regex, git.checkout_root)

class GitTestWithMock(unittest.TestCase):

    def make_scm(self):
        git = Git(cwd='.', executive=MockExecutive(), filesystem=MockFileSystem())
        git.read_git_config = lambda *args, **kw: 'MOCKKEY:MOCKVALUE'
        return git

    def _assert_timestamp_of_revision(self, canned_git_output, expected):
        git = self.make_scm()
        git.find_checkout_root = lambda path: ''
        # Modifying protected method. pylint: disable=protected-access
        git._run_git = lambda args: canned_git_output
        self.assertEqual(git.timestamp_of_revision('some-path', '12345'), expected)

    def test_timestamp_of_revision_utc(self):
        self._assert_timestamp_of_revision('Date: 2013-02-08 08:05:49 +0000', '2013-02-08T08:05:49Z')

    def test_timestamp_of_revision_positive_timezone(self):
        self._assert_timestamp_of_revision('Date: 2013-02-08 01:02:03 +0130', '2013-02-07T23:32:03Z')

    def test_timestamp_of_revision_pacific_timezone(self):
        self._assert_timestamp_of_revision('Date: 2013-02-08 01:55:21 -0800', '2013-02-08T09:55:21Z')

    def test_unstaged_files(self):
        scm = self.make_scm()
        status_lines = [
            ' M d/modified.txt',
            ' D d/deleted.txt',
            '?? d/untracked.txt',
            'D  d/deleted.txt',
            'M  d/modified-staged.txt',
            'A  d/added-staged.txt',
        ]
        # pylint: disable=protected-access
        scm._run_git = lambda args: '\x00'.join(status_lines) + '\x00'
        self.assertEqual(
            scm.unstaged_changes(),
            {
                'd/modified.txt': 'M',
                'd/deleted.txt': 'D',
                'd/untracked.txt': '?',
            })


text:
function instance_number_sort(filelist) {
    filelist.sort(function(a,b) {
        return a.InstanceNumber - b.InstanceNumber;
    });
}

function min_max_voi(file) {
    var min = Math.min.apply(this, file.PixelData);
    var max = Math.max.apply(this, file.PixelData);
    var center = min + (max-min)/2;
    var level = max-min;
    return [center, level];
}


text:
#pragma once
#include "cm_def.h"
#include "cm_array.h"
#include "cm_kernel.h"

class CmKernelData:public CmDynamicArray {
 public:

	static INT Create(CmKernel * pCmKernel, CmKernelData * &pKernelData);
	static INT Destroy(CmKernelData * &pKernelData);

	INT GetCmKernel(CmKernel * &pCmKernel);
	INT SetKernelDataSize(INT value);
	INT GetKernelDataSize();
	UINT Acquire(void);
	UINT SafeRelease(void);

	PCM_HAL_KERNEL_PARAM GetHalCmKernelData();
	UINT AcquireKernel(void);
	INT ReleaseKernel(void);
	BOOL IsInUse(void);
	UINT GetKernelCurbeSize(void);

 protected:

	 CmKernelData(CmKernel * pCmKernel);
	~CmKernelData(void);

	INT Initialize(void);

	UINT m_kerneldatasize;
	CmKernel *m_pCmKernel;
	UINT m_RefCount;
	CM_HAL_KERNEL_PARAM m_HalKernelParam;

	UINT m_KernelRef;

	BOOL m_IsInUse;

 private:
	 CmKernelData(const CmKernelData & other);
	 CmKernelData & operator=(const CmKernelData & other);
};


text:
Workbench
=========

The workbench package is a synthetic package that lets us use `pub` to pull in
some packages from `pub.dartlang.org` and some packages from within the source
tree. The workbench package is intended to reflect a typical environment for
developing a Sky application.


text:
layout: post
date: 2017-12-16
title: "Mia Solano Lace Slim A-line Wedding Dress - M1330Z Sleeveless Chapel Train Aline/Princess"
category: Mia Solano
tags: [Mia Solano,Aline/Princess ,V-neck,Chapel Train,Sleeveless]
---
### Mia Solano Lace Slim A-line Wedding Dress - M1330Z
Just **$389.99**
###   Sleeveless Chapel Train Aline/Princess

BRANDS	Mia Solano

Silhouette	Aline/Princess

Neckline	V-neck

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/mia-solano/46471-mia-solano-lace-slim-a-line-wedding-dress-m1330z.html](https://www.readybrides.com/en/mia-solano/46471-mia-solano-lace-slim-a-line-wedding-dress-m1330z.html)


text:
package org.wso2.carbon.apimgt.impl.dao.test;

import org.wso2.carbon.user.api.RealmConfiguration;
import org.wso2.carbon.user.api.TenantMgtConfiguration;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.user.core.config.multitenancy.MultiTenantRealmConfigBuilder;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager;

public class TestRealmService implements RealmService {

    public UserRealm getUserRealm(RealmConfiguration realmConfiguration) throws UserStoreException {
        return null;
    }

    public RealmConfiguration getBootstrapRealmConfiguration() {
        return null;
    }

    public UserRealm getBootstrapRealm() throws UserStoreException {
        return null;
    }

    public void setTenantManager(TenantManager tenantManager) throws UserStoreException {

    }

    public TenantManager getTenantManager() {
        return new TestTenantManager();
    }

    public MultiTenantRealmConfigBuilder getMultiTenantRealmConfigBuilder() throws UserStoreException {
        return null;
    }

    public UserRealm getCachedUserRealm(int i) throws UserStoreException {
        return null;
    }

    public void setTenantManager(org.wso2.carbon.user.api.TenantManager tenantManager) throws org.wso2.carbon.user.api.UserStoreException {

    }

    public org.wso2.carbon.user.api.UserRealm getTenantUserRealm(int i) throws org.wso2.carbon.user.api.UserStoreException {
        return null;
    }

    public TenantMgtConfiguration getTenantMgtConfiguration() {
        return null;
    }

    public void setBootstrapRealmConfiguration(RealmConfiguration realmConfiguration) {
        //TODO implement method
    }

	public void clearCachedUserRealm(int arg0) throws UserStoreException {

	}
}


text:
""" test_path.py - Test the path module.

This only runs on Posix and NT right now.  I would like to have more
tests.  You can help!  Just add appropriate pathnames for your
platform (os.name) in each place where the p() function is called.
Then send me the result.  If you can't get the test to run at all on
your platform, there's probably a bug in path.py -- please let me
know!

TempDirTestCase.testTouch() takes a while to run.  It sleeps a few
seconds to allow some time to pass between calls to check the modify
time on files.

URL:     http://www.jorendorff.com/articles/python/path
Author:  Jason Orendorff <jason@jorendorff.com>
Date:    7 Mar 2004

"""

import unittest
import codecs, os, random, shutil, tempfile, time, stat, sys
from scriptine._path import path, __version__ as path_version

# This should match the version of path.py being tested.
__version__ = '2.2'

if sys.platform in ('cygwin', 'win32'):
    is_windows = True
else:
    is_windows = False

def p(**choices):
    """ Choose a value from several possible values, based on os.name """
    return choices[os.name]

class BasicTestCase(unittest.TestCase):
    def testRelpath(self):
        root = path(p(nt='C:\\',
                      posix='/'))
        foo = root / 'foo'
        quux =        foo / 'quux'
        bar =         foo / 'bar'
        boz =                bar / 'Baz' / 'Boz'
        up = path(os.pardir)

        # basics
        self.assertEqual(root.relpathto(boz), path('foo')/'bar'/'Baz'/'Boz')
        self.assertEqual(bar.relpathto(boz), path('Baz')/'Boz')
        self.assertEqual(quux.relpathto(boz), up/'bar'/'Baz'/'Boz')
        self.assertEqual(boz.relpathto(quux), up/up/up/'quux')
        self.assertEqual(boz.relpathto(bar), up/up)

        # x.relpathto(x) == curdir
        self.assertEqual(root.relpathto(root), os.curdir)
        self.assertEqual(boz.relpathto(boz), os.curdir)
        # Make sure case is properly noted (or ignored)
        self.assertEqual(boz.relpathto(boz.normcase()), os.curdir)

        # relpath()
        cwd = path(os.getcwd())
        self.assertEqual(boz.relpath(), cwd.relpathto(boz))

        if os.name == 'nt':
            # Check relpath across drives.
            d = path('D:\\')
            self.assertEqual(d.relpathto(boz), boz)

    def testStringCompatibility(self):
        """ Test compatibility with ordinary strings. """
        x = path('xyzzy')
        self.assert_(x == 'xyzzy')
        self.assert_(x == 'xyzzy')

        # sorting
        items = [path('fhj'),
                 path('fgh'),
                 'E',
                 path('d'),
                 'A',
                 path('B'),
                 'c']
        items.sort()
        self.assert_(items == ['A', 'B', 'E', 'c', 'd', 'fgh', 'fhj'])

        # Test p1/p1.
        p1 = path("foo")
        p2 = path("bar")
        self.assertEqual(p1/p2, p(nt='foo\\bar', posix='foo/bar'))

    def testProperties(self):
        # Create sample path object.
        f = p(nt='C:\\Program Files\\Python\\Lib\\xyzzy.py',
              posix='/usr/local/python/lib/xyzzy.py')
        f = path(f)

        # .parent
        self.assertEqual(f.parent, p(nt='C:\\Program Files\\Python\\Lib',
                                     posix='/usr/local/python/lib'))

        # .name
        self.assertEqual(f.name, 'xyzzy.py')
        self.assertEqual(f.parent.name, p(nt='Lib', posix='lib'))

        # .ext
        self.assertEqual(f.ext, '.py')
        self.assertEqual(f.parent.ext, '')

        # .drive
        self.assertEqual(f.drive, p(nt='C:', posix=''))

    def testMethods(self):
        # .abspath()
        self.assertEqual(path(os.curdir).abspath(), os.getcwd())

        # .getcwd()
        cwd = path.cwd()
        self.assert_(isinstance(cwd, path))
        self.assertEqual(cwd, os.getcwd())

    def testUNC(self):
        if hasattr(os.path, 'splitunc'):
            p = path(r'\\python1\share1\dir1\file1.txt')
            self.assert_(p.uncshare == r'\\python1\share1')
            self.assert_(p.splitunc() == os.path.splitunc(str(p)))

class TempDirTestCase(unittest.TestCase):
    def setUp(self):
        # Create a temporary directory.
        f = tempfile.mktemp()
        system_tmp_dir = os.path.dirname(f)
        my_dir = 'testpath_tempdir_' + str(random.random())[2:]
        self.tempdir = os.path.join(system_tmp_dir, my_dir)
        os.mkdir(self.tempdir)

    def tearDown(self):
        shutil.rmtree(self.tempdir)

    def testTouch(self):
        # NOTE: This test takes a long time to run (~10 seconds).
        # It sleeps several seconds because on Windows, the resolution
        # of a file's mtime and ctime is about 2 seconds.
        #
        # atime isn't tested because on Windows the resolution of atime
        # is something like 24 hours.

        sleep_time = 2.0
        if is_windows:
            sleep_time = 5.0

        d = path(self.tempdir)
        f = d / 'test.txt'
        t0 = time.time() - sleep_time / 2
        f.touch()
        t1 = time.time() + sleep_time / 2
        try:
            self.assert_(f.exists())
            self.assert_(f.isfile())
            self.assertEqual(f.size(), 0)
            self.assert_(t0 <= f.mtime() <= t1)
            if hasattr(os.path, 'getctime'):
                ct = f.ctime()
                self.assert_(t0 <= ct <= t1)

            time.sleep(sleep_time)
            fobj = file(f, 'ab')
            fobj.write('some bytes')
            fobj.close()

            time.sleep(sleep_time)

            f_new = d / 'test_new.txt'
            f_new.touch()
            self.assert_(f_new.newer(f))
            t2 = time.time() - sleep_time / 2
            f.touch()
            t3 = time.time() + sleep_time / 2

            assert t0 <= t1 < t2 <= t3  # sanity check

            self.assert_(f.exists())
            self.assert_(f.isfile())
            self.assertEqual(f.size(), 10)
            self.assert_(t2 <= f.mtime() <= t3)
            if hasattr(os.path, 'getctime'):
                ct2 = f.ctime()
                if os.name == 'nt':
                    # On Windows, "ctime" is CREATION time
                    self.assertEqual(ct, ct2)
                    self.assert_(ct2 < t2)
                else:
                    # On other systems, it might be the CHANGE time
                    # (especially on Unix, time of inode changes)
                    self.failUnless(ct == ct2 or ct2 == f.mtime())
        finally:
            f.remove()

    def testListing(self):
        d = path(self.tempdir)
        self.assertEqual(d.listdir(), [])

        f = 'testfile.txt'
        af = d / f
        self.assertEqual(af, os.path.join(d, f))
        af.touch()
        try:
            self.assert_(af.exists())

            self.assertEqual(d.listdir(), [af])

            # .glob()
            self.assertEqual(d.glob('testfile.txt'), [af])
            self.assertEqual(d.glob('test*.txt'), [af])
            self.assertEqual(d.glob('*.txt'), [af])
            self.assertEqual(d.glob('*txt'), [af])
            self.assertEqual(d.glob('*'), [af])
            self.assertEqual(d.glob('*.html'), [])
            self.assertEqual(d.glob('testfile'), [])
        finally:
            af.remove()

        # Try a test with 20 files
        files = [d / ('%d.txt' % i) for i in range(20)]
        for f in files:
            fobj = file(f, 'w')
            fobj.write('some text\n')
            fobj.close()
        try:
            files2 = d.listdir()
            files.sort()
            files2.sort()
            self.assertEqual(files, files2)
        finally:
            for f in files:
                try:
                    f.remove()
                except:
                    pass

    def testMakeDirs(self):
        d = path(self.tempdir)

        # Placeholder file so that when removedirs() is called,
        # it doesn't remove the temporary directory itself.
        tempf = d / 'temp.txt'
        tempf.touch()
        try:
            foo = d / 'foo'
            boz =      foo / 'bar' / 'baz' / 'boz'
            boz.makedirs()
            try:
                self.assert_(boz.isdir())
            finally:
                boz.removedirs()
            self.failIf(foo.exists())
            self.assert_(d.exists())

            foo.mkdir(0o750)
            boz.makedirs(0o700)
            try:
                self.assert_(boz.isdir())
            finally:
                boz.removedirs()
            self.failIf(foo.exists())
            self.assert_(d.exists())
        finally:
            os.remove(tempf)

    def assertSetsEqual(self, a, b):
        ad = {}
        for i in a: ad[i] = None
        bd = {}
        for i in b: bd[i] = None
        self.assertEqual(ad, bd)

    def testShutil(self):
        # Note: This only tests the methods exist and do roughly what
        # they should, neglecting the details as they are shutil's
        # responsibility.

        d = path(self.tempdir)
        testDir = d / 'testdir'
        testFile = testDir / 'testfile.txt'
        testA = testDir / 'A'
        testCopy = testA / 'testcopy.txt'
        testLink = testA / 'testlink.txt'
        testInstall = testA / 'testinstall.txt'
        testB = testDir / 'B'
        testC = testB / 'C'
        testCopyOfLink = testC / testA.relpathto(testLink)

        # Create test dirs and a file
        testDir.mkdir()
        testA.mkdir()
        testB.mkdir()

        f = open(testFile, 'w')
        f.write('x' * 10000)
        f.close()

        # Test simple file copying.
        testFile.copyfile(testCopy)
        self.assert_(testCopy.isfile())
        self.assert_(testFile.bytes() == testCopy.bytes())

        # Test copying into a directory.
        testCopy2 = testA / testFile.name
        testFile.copy(testA)
        self.assert_(testCopy2.isfile())
        self.assert_(testFile.bytes() == testCopy2.bytes())

        # Test install file
        testFile.install(testInstall, chmod=0o740)
        stats = stat.S_IMODE(testInstall.stat().st_mode)

        self.assert_(stats ==
            stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP)
        testInstall.unlink()

        # Make a link for the next test to use.
        if hasattr(os, 'symlink'):
            testFile.symlink(testLink)
        else:
            testFile.copy(testLink)  # fallback

        # Test copying directory tree.
        testA.copytree(testC)
        self.assert_(testC.isdir())
        self.assertSetsEqual(
            testC.listdir(),
            [testC / testCopy.name,
             testC / testFile.name,
             testCopyOfLink])
        self.assert_(not testCopyOfLink.islink())

        # Clean up for another try.
        testC.rmtree()
        self.assert_(not testC.exists())

        # Copy again, preserving symlinks.
        testA.copytree(testC, True)
        self.assert_(testC.isdir())
        self.assertSetsEqual(
            testC.listdir(),
            [testC / testCopy.name,
             testC / testFile.name,
             testCopyOfLink])
        if hasattr(os, 'symlink'):
            self.assert_(testCopyOfLink.islink())
            self.assert_(testCopyOfLink.readlink() == testFile)

        # Clean up.
        testDir.rmtree()
        self.assert_(not testDir.exists())
        self.assertList(d.listdir(), [])

    def assertList(self, listing, expected):
        listing = list(listing)
        listing.sort()
        expected = list(expected)
        expected.sort()
        self.assertEqual(listing, expected)

    def testPatterns(self):
        d = path(self.tempdir)
        names = [ 'x.tmp', 'x.xtmp', 'x2g', 'x22', 'x.txt' ]
        dirs = [d, d/'xdir', d/'xdir.tmp', d/'xdir.tmp'/'xsubdir']

        for e in dirs:
            if not e.isdir():  e.makedirs()
            for name in names:
                (e/name).touch()
        self.assertList(d.listdir('*.tmp'), [d/'x.tmp', d/'xdir.tmp'])
        self.assertList(d.files('*.tmp'), [d/'x.tmp'])
        self.assertList(d.dirs('*.tmp'), [d/'xdir.tmp'])
        self.assertList(d.walk(), [e for e in dirs if e != d] + [e/n for e in dirs for n in names])
        self.assertList(d.walk('*.tmp'),
                        [e/'x.tmp' for e in dirs] + [d/'xdir.tmp'])
        self.assertList(d.walkfiles('*.tmp'), [e/'x.tmp' for e in dirs])
        self.assertList(d.walkdirs('*.tmp'), [d/'xdir.tmp'])

    def testUnicode(self):
        d = path(self.tempdir)
        p = d/'unicode.txt'

        def test(enc):
            """ Test that path works with the specified encoding,
            which must be capable of representing the entire range of
            Unicode codepoints.
            """

            given = ('Hello world\n'
                     '\u0d0a\u0a0d\u0d15\u0a15\r\n'
                     '\u0d0a\u0a0d\u0d15\u0a15\x85'
                     '\u0d0a\u0a0d\u0d15\u0a15\u2028'
                     '\r'
                     'hanging')
            clean = ('Hello world\n'
                     '\u0d0a\u0a0d\u0d15\u0a15\n'
                     '\u0d0a\u0a0d\u0d15\u0a15\n'
                     '\u0d0a\u0a0d\u0d15\u0a15\n'
                     '\n'
                     'hanging')
            givenLines = [
                'Hello world\n',
                '\u0d0a\u0a0d\u0d15\u0a15\r\n',
                '\u0d0a\u0a0d\u0d15\u0a15\x85',
                '\u0d0a\u0a0d\u0d15\u0a15\u2028',
                '\r',
                'hanging']
            expectedLines = [
                'Hello world\n',
                '\u0d0a\u0a0d\u0d15\u0a15\n',
                '\u0d0a\u0a0d\u0d15\u0a15\n',
                '\u0d0a\u0a0d\u0d15\u0a15\n',
                '\n',
                'hanging']
            expectedLines2 = [
                'Hello world',
                '\u0d0a\u0a0d\u0d15\u0a15',
                '\u0d0a\u0a0d\u0d15\u0a15',
                '\u0d0a\u0a0d\u0d15\u0a15',
                '',
                'hanging']

            # write bytes manually to file
            f = codecs.open(p, 'w', enc)
            f.write(given)
            f.close()

            # test all 3 path read-fully functions, including
            # path.lines() in unicode mode.
            self.assertEqual(p.bytes(), given.encode(enc))
            self.assertEqual(p.text(enc), clean)
            self.assertEqual(p.lines(enc), expectedLines)
            self.assertEqual(p.lines(enc, retain=False), expectedLines2)

            # If this is UTF-16, that's enough.
            # The rest of these will unfortunately fail because append=True mode
            # causes an extra BOM to be written in the middle of the file.
            # UTF-16 is the only encoding that has this problem.
            if enc == 'UTF-16':
                return

            # Write Unicode to file using path.write_text().
            cleanNoHanging = clean + '\n'  # This test doesn't work with a hanging line.
            p.write_text(cleanNoHanging, enc)
            p.write_text(cleanNoHanging, enc, append=True)
            # Check the result.
            expectedBytes = 2 * cleanNoHanging.replace('\n', os.linesep).encode(enc)
            expectedLinesNoHanging = expectedLines[:]
            expectedLinesNoHanging[-1] += '\n'
            self.assertEqual(p.bytes(), expectedBytes)
            self.assertEqual(p.text(enc), 2 * cleanNoHanging)
            self.assertEqual(p.lines(enc), 2 * expectedLinesNoHanging)
            self.assertEqual(p.lines(enc, retain=False), 2 * expectedLines2)

            # Write Unicode to file using path.write_lines().
            # The output in the file should be exactly the same as last time.
            p.write_lines(expectedLines, enc)
            p.write_lines(expectedLines2, enc, append=True)
            # Check the result.
            self.assertEqual(p.bytes(), expectedBytes)

            # Now: same test, but using various newline sequences.
            # If linesep is being properly applied, these will be converted
            # to the platform standard newline sequence.
            p.write_lines(givenLines, enc)
            p.write_lines(givenLines, enc, append=True)
            # Check the result.
            self.assertEqual(p.bytes(), expectedBytes)

            # Same test, using newline sequences that are different
            # from the platform default.
            def testLinesep(eol):
                p.write_lines(givenLines, enc, linesep=eol)
                p.write_lines(givenLines, enc, linesep=eol, append=True)
                expected = 2 * cleanNoHanging.replace('\n', eol).encode(enc)
                self.assertEqual(p.bytes(), expected)

            testLinesep('\n')
            testLinesep('\r')
            testLinesep('\r\n')
            testLinesep('\x0d\x85')

            # Again, but with linesep=None.
            p.write_lines(givenLines, enc, linesep=None)
            p.write_lines(givenLines, enc, linesep=None, append=True)
            # Check the result.
            expectedBytes = 2 * given.encode(enc)
            self.assertEqual(p.bytes(), expectedBytes)
            self.assertEqual(p.text(enc), 2 * clean)
            expectedResultLines = expectedLines[:]
            expectedResultLines[-1] += expectedLines[0]
            expectedResultLines += expectedLines[1:]
            self.assertEqual(p.lines(enc), expectedResultLines)

        test('UTF-8')
        test('UTF-16BE')
        test('UTF-16LE')
        test('UTF-16')

if __name__ == '__main__':
    if __version__ != path_version:
        print(("Version mismatch:  test_path.py version %s, path version %s" %
               (__version__, path_version)))
    unittest.main()


text:
SYNONYM

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

#### Published in
Leafl. of Philipp. Bot. 6(no. 103): 2218 (1914)

#### Original name
Phyllachora yapensis var. rhytismoides Rehm, 1914

### Remarks
null


text:
import Gaffer
import GafferImage

Gaffer.Metadata.registerNode(

	GafferImage.Constant,

	"description",
	"""
	Outputs an image of a constant flat colour.
	""",

	plugs = {

		"format" : [

			"description",
			"""
			The resolution and aspect ratio of the image.
			""",

		],

		"color" : [

			"description",
			"""
			The colour of the image.
			""",

		],

	}

)


text:
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;
using Nethereum.ABI.Decoders;
using Nethereum.Hex.HexTypes;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.RPC.Eth.Services;
using Nethereum.StandardTokenEIP20.ContractDefinition;
using Nethereum.StandardTokenEIP20.Events.DTO;
using Nethereum.XUnitEthereumClients;
using Xunit;
// ReSharper disable once ConsiderUsingConfigureAwait

namespace Nethereum.StandardTokenEIP20.IntegrationTests
{

    [Collection(EthereumClientIntegrationFixture.ETHEREUM_CLIENT_COLLECTION_DEFAULT)]
    public class Erc20TokenTester
    {
        private readonly EthereumClientIntegrationFixture _ethereumClientIntegrationFixture;

        public Erc20TokenTester(EthereumClientIntegrationFixture ethereumClientIntegrationFixture)
        {
            _ethereumClientIntegrationFixture = ethereumClientIntegrationFixture;
        }

        private static async Task<TransactionReceipt> GetTransactionReceiptAsync(
            EthApiTransactionsService transactionService, string transactionHash)
        {
            TransactionReceipt receipt = null;
            //wait for the contract to be mined to the address
            while (receipt == null)
            {
                await Task.Delay(1000).ConfigureAwait(false);
                receipt = await transactionService.GetTransactionReceipt.SendRequestAsync(transactionHash).ConfigureAwait(false);
            }
            return receipt;
        }

        [Fact]
        public async void ShouldGetTheDaiFromMainnet()
        {
            var web3 = _ethereumClientIntegrationFixture.GetInfuraWeb3(InfuraNetwork.Mainnet);
            var contractHandler = web3.Eth.GetContractHandler("0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359");
            var stringBytes32Decoder = new StringBytes32Decoder();
            var symbol = await contractHandler.QueryRawAsync<SymbolFunction, StringBytes32Decoder, string>().ConfigureAwait(false);
            var token = await contractHandler.QueryRawAsync<NameFunction, StringBytes32Decoder, string>().ConfigureAwait(false);

        }

        [Fact]
        public async void ShouldReturnData()
        {
            var web3 = _ethereumClientIntegrationFixture.GetWeb3();
            var deploymentHandler =  web3.Eth.GetContractDeploymentHandler<EIP20Deployment>();
            var receipt = await deploymentHandler.SendRequestAndWaitForReceiptAsync(new EIP20Deployment()
            {
                DecimalUnits = 18,
                InitialAmount = BigInteger.Parse("10000000000000000000000000"),
                TokenSymbol = "XST",
                TokenName = "XomeStandardToken"
            }).ConfigureAwait(false);

            var contractHandler = web3.Eth.GetContractHandler(receipt.ContractAddress);
            var symbol = await contractHandler.QueryRawAsync<SymbolFunction, StringBytes32Decoder, string>().ConfigureAwait(false);
            var token = await contractHandler.QueryRawAsync<NameFunction, StringBytes32Decoder, string>().ConfigureAwait(false);

            Assert.Equal("XST", symbol);
            Assert.Equal("XomeStandardToken", token);
        }

        [Fact]
        public async void Test()
        {
            var addressOwner = EthereumClientIntegrationFixture.AccountAddress;
            var web3 = _ethereumClientIntegrationFixture.GetWeb3();

            ulong totalSupply = 1000000;
            var newAddress = "0x12890d2cce102216644c59daE5baed380d84830e";

            var deploymentContract = new EIP20Deployment()
            {
                InitialAmount = totalSupply,
                TokenName = "TestToken",
                TokenSymbol = "TST"
            };

            var tokenService = await StandardTokenService.DeployContractAndGetServiceAsync(web3, deploymentContract).ConfigureAwait(false);

            var transfersEvent = tokenService.GetTransferEvent();

            var totalSupplyDeployed = await tokenService.TotalSupplyQueryAsync().ConfigureAwait(false);
            Assert.Equal(totalSupply, totalSupplyDeployed);

            var tokenName = await tokenService.NameQueryAsync().ConfigureAwait(false);
            Assert.Equal("TestToken", tokenName);

            var tokenSymbol = await tokenService.SymbolQueryAsync().ConfigureAwait(false);
            Assert.Equal("TST", tokenSymbol);

            var ownerBalance = await tokenService.BalanceOfQueryAsync(addressOwner).ConfigureAwait(false);
            Assert.Equal(totalSupply, ownerBalance);

            var transferReceipt =
                await tokenService.TransferRequestAndWaitForReceiptAsync(newAddress, 1000).ConfigureAwait(false);

            ownerBalance = await tokenService.BalanceOfQueryAsync(addressOwner).ConfigureAwait(false);
            Assert.Equal(totalSupply - 1000, ownerBalance);

            var newAddressBalance = await tokenService.BalanceOfQueryAsync(newAddress).ConfigureAwait(false);
            Assert.Equal(1000, newAddressBalance);

            var allTransfersFilter =
                await transfersEvent.CreateFilterAsync(new BlockParameter(transferReceipt.BlockNumber)).ConfigureAwait(false);
            var eventLogsAll = await transfersEvent.GetAllChangesAsync(allTransfersFilter).ConfigureAwait(false);
            Assert.Single(eventLogsAll);
            var transferLog = eventLogsAll.First();
            Assert.Equal(transferLog.Log.TransactionIndex.HexValue, transferReceipt.TransactionIndex.HexValue);
            Assert.Equal(transferLog.Log.BlockNumber.HexValue, transferReceipt.BlockNumber.HexValue);
            Assert.Equal(transferLog.Event.To.ToLower(), newAddress.ToLower());
            Assert.Equal(transferLog.Event.Value, (ulong) 1000);

            var approveTransactionReceipt = await tokenService.ApproveRequestAndWaitForReceiptAsync(newAddress, 1000).ConfigureAwait(false);
            var allowanceAmount = await tokenService.AllowanceQueryAsync(addressOwner, newAddress).ConfigureAwait(false);
            Assert.Equal(1000, allowanceAmount);
        }
    }
}


text:
package ru.asemenov.TestTask;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
 * Class TestTaskTest решение тестовой задачи.
 * @author asemenov
 * @version 1
 */
public class TestTaskTest {
    /**
     * Тест верное кол-во скобок.
     */
    @Test
    public final void trueTestTask() {
        TestTask test = new TestTask();
        String result = "()()()";
        assertThat(test.equal(result), is(true));
    }
    /**
     * Не верное кол-во скобок.
     */
    @Test
    public final void falseTestTask() {
        TestTask test = new TestTask();
        String result = "())";
        assertThat(test.equal(result), is(false));
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Code for America</title>
    <link rel="stylesheet" type="text/css" href="//cloud.typography.com/6304652/777902/css/fonts.css" />
    <link rel="stylesheet" href="/_style/css/main.css">
    <link rel="stylesheet" href="/_style/css/layout.css" media="all and (min-width: 40em)">
    <link href="/_style/css/prism.css" rel="stylesheet" />
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
    <link rel="apple-touch-icon-precomposed" href="/_style/favicons/60x60/flag-red.png"/>

Blog

Library

<form class="search-global" id="search-global">
    <input type="search" id="search-global-input" class="search-global-input" autocomplete="off" placeholder="Search" name="search-global" />

    <button class="search-global-submit" id="search-global-submit" value="Search" type="submit" name="search-global">Search</button>
</form>

Home

Blog

        Blogging [for America]

Menu

            		Who we are

                    Governments

                	Citizens

                	Apps

Donate

Home

Blog

Why I'm mentoring for America, by Zachary Townsend

                    <time class="post-date insulate text-whisper" datetime="2013-11-13 00:00:00 +0000">November 1st 2013</time>

I work with governments because, when operated well, they can improve the lives of so many people. I work with civic startups at the CfA Accelerator because, when operated well, they can improve the efficiency of so many governments. Every positive change I made working in government in Newark, N.J. might effect tens of thousands of families and every civic startup I mentor might affect hundreds of governments.

But let me take a step back: I started to care so much about government and their inner workings because local government changed the course of my life.

When I was ten years old, my mother and I were in a terrible car accident. Although I did not realize it then, the next few hours came to define my life. At the time I was confused. Now I vividly recall the kindness of the child welfare workers and their help in what was a scary situation for me. My conversations and their actions that day instilled in me a value that I will never forget: the power of a few individuals to profoundly affect a person in need.

It became clear that my mother was an alcoholic. My stepfather filed for divorce, and my parents (guided by child welfare) agreed that I would live with my dad. For years I did not understand what had happened, but in time I came to appreciate who the social workers were and the profound effect that a working and compassionate government can have on peoples lives. Or, in my case, just one life. Their careful and kind work made it so I could eventually go on to lead the life I've had.

I have spent most of my professional life working to understand and improve the efficiencies and effectiveness of governments. As a private consultant, I used my love of data and passion for technology to work with New York City Administration for Children's Services to improve services for children just like me, and many that were in much worse circumstances. From there, I worked in the Newark, N.J. Mayor's Office to leverage technology to improve city life and services.

Good city services are about basic fairness. As I wrote elsewhere:

Overall the quality of service provision in government offices remains low. The offices which provide services use outdated and ill-designed technology tools to facilitate rarely-updated business process. Services must be requested in person, lines can be long, multiple offices need to be visited, and forms that aren't filled out to exacting detail must be redone, creating an array of bureaucratic barriers. In essence, city services are a regressive tax on people's time.

Startups are the most powerful possibility I can find for helping to improve those services. A lack of procurement options is at the heart of the bad technology and the inefficient business processes of many cities.

So I spend my days working on making banking data and services more and accessible through a Y-Combinator backed startup called Standard Treasury. I use my nights and weekend to mentor Accelerator companies. I work to bridge my knowledge base running a fast-growing technology startup with my background and knowledge of governments. Together with some amazing entrepreneurs and the Code for America team, we can build great companies that empower great governments to do great things for citizens.

Written by

Zachary Townsend

I have spent most of my professional life working to understand and improve the efficiencies and effectiveness of governments.

Filed under

Accelerator

Commentary

Guest Post

Mentor

Previous

All articles

Next

Questions? Comments? Hit us up at @codeforamerica

<form class="search-global" id="search-global">
    <input type="search" id="search-global-input" class="search-global-input" autocomplete="off" placeholder="Search" name="search-global" />

    <button class="search-global-submit" id="search-global-submit" value="Search" type="submit" name="search-global">Search</button>
</form>

About

What we do

Annual report

Press

Supporters

Jobs

Contact

Who we are

Board

Team

Staff

City Partners

Brigade captains

Programs

Fellowship

Brigade

Startup

International

Peer Network

Donate

Financial Contributions

In-Kind Donations

Social

Facebook

Twitter

YouTube

GitHub

Tumblr

Flickr

RSS

            Code for America Labs, Inc is a non-partisan, non-political 501(c)(3) organization. Content is licensed through Creative Commons.


text:
//#define DoBooleanTest

using MatterHackers.Agg;
using MatterHackers.Agg.ImageProcessing;
using MatterHackers.Agg.PlatformAbstract;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.VectorMath;
using System;
using System.Collections.Generic;

namespace MatterHackers.MatterControl.PartPreviewWindow
{
	public partial class MirrorControls : FlowLayoutWidget
	{
		private CheckBox expandMirrorOptions;
		private FlowLayoutWidget mirrorOptionContainer;
		private View3DWidget view3DWidget;

		public MirrorControls(View3DWidget view3DWidget)
			: base(FlowDirection.TopToBottom)
		{
			this.view3DWidget = view3DWidget;

			// put in the mirror options
			{
				expandMirrorOptions = view3DWidget.ExpandMenuOptionFactory.GenerateCheckBoxButton(
					"Mirror".Localize().ToUpper(),
					View3DWidget.ArrowRight,
					View3DWidget.ArrowDown);
				expandMirrorOptions.Margin = new BorderDouble(bottom: 2);
				this.AddChild(expandMirrorOptions);

				mirrorOptionContainer = new FlowLayoutWidget(FlowDirection.TopToBottom);
				mirrorOptionContainer.HAnchor = HAnchor.ParentLeftRight;
				mirrorOptionContainer.Visible = false;
				this.AddChild(mirrorOptionContainer);

				AddMirrorControls(mirrorOptionContainer);
			}

			expandMirrorOptions.CheckedStateChanged += expandMirrorOptions_CheckedStateChanged;
		}

		private void AddMirrorControls(FlowLayoutWidget buttonPanel)
		{
			List<GuiWidget> mirrorControls = new List<GuiWidget>();

			double oldFixedWidth = view3DWidget.textImageButtonFactory.FixedWidth;
			view3DWidget.textImageButtonFactory.FixedWidth = view3DWidget.EditButtonHeight;

			FlowLayoutWidget buttonContainer = new FlowLayoutWidget(FlowDirection.LeftToRight);
			buttonContainer.HAnchor = HAnchor.ParentLeftRight;

			Button mirrorXButton = view3DWidget.textImageButtonFactory.Generate("X", centerText: true);
			buttonContainer.AddChild(mirrorXButton);
			mirrorControls.Add(mirrorXButton);
			mirrorXButton.Click += (s, e) =>
			{
				if (view3DWidget.SelectedMeshGroupIndex != -1)
				{
					view3DWidget.UndoBuffer.AddAndDo(new UndoRedoActions(() => MirrorOnAxis(0), () => MirrorOnAxis(0)));
				}
			};

			Button mirrorYButton = view3DWidget.textImageButtonFactory.Generate("Y", centerText: true);
			buttonContainer.AddChild(mirrorYButton);
			mirrorControls.Add(mirrorYButton);
			mirrorYButton.Click += (s, e) =>
			{
				if (view3DWidget.SelectedMeshGroupIndex != -1)
				{
					view3DWidget.UndoBuffer.AddAndDo(new UndoRedoActions(() => MirrorOnAxis(1), () => MirrorOnAxis(1)));
				}
			};

			Button mirrorZButton = view3DWidget.textImageButtonFactory.Generate("Z", centerText: true);
			buttonContainer.AddChild(mirrorZButton);
			mirrorControls.Add(mirrorZButton);
			mirrorZButton.Click += (s, e) =>
			{
				if (view3DWidget.SelectedMeshGroupIndex != -1)
				{
					view3DWidget.UndoBuffer.AddAndDo(new UndoRedoActions(() => MirrorOnAxis(2), () => MirrorOnAxis(2)));
				}
			};
			buttonPanel.AddChild(buttonContainer);
			buttonPanel.AddChild(view3DWidget.GenerateHorizontalRule());
			view3DWidget.textImageButtonFactory.FixedWidth = oldFixedWidth;
		}

		private void MirrorOnAxis(int axisIndex)
		{
			view3DWidget.SelectedMeshGroup.ReverseFaceEdges();
			Vector3 mirorAxis = Vector3.One;
			mirorAxis[axisIndex] = -1;
			view3DWidget.SelectedMeshGroupTransform = PlatingHelper.ApplyAtCenter(view3DWidget.SelectedMeshGroup, view3DWidget.SelectedMeshGroupTransform, Matrix4X4.CreateScale(mirorAxis));
			view3DWidget.PartHasBeenChanged();
			Invalidate();
		}

		private void expandMirrorOptions_CheckedStateChanged(object sender, EventArgs e)
		{
			if (mirrorOptionContainer.Visible != expandMirrorOptions.Checked)
			{
				mirrorOptionContainer.Visible = expandMirrorOptions.Checked;
			}
		}
	}
}


text:
<?php namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel {

	/**
	 * The application's global HTTP middleware stack.
	 *
	 * @var array
	 */
	protected $middleware = [
			\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
			\App\Http\Middleware\EncryptCookies::class,
			\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
			\Illuminate\Session\Middleware\StartSession::class,
			\Illuminate\View\Middleware\ShareErrorsFromSession::class,
			//\App\Http\Middleware\VerifyCsrfToken::class,,
			\App\Http\Middleware\Admin\TrimMiddleware::class,//http trim中间件
			\LucaDegasperi\OAuth2Server\Middleware\OAuthExceptionHandlerMiddleware::class,//OAuth
	];

	/**
	 * The application's route middleware.
	 *
	 * @var array
	 */
	protected $routeMiddleware = [
		'auth' 							=> \App\Http\Middleware\Authenticate::class,
		'auth.basic' 					=> \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
		'guest' 						=> \App\Http\Middleware\RedirectIfAuthenticated::class,
		'admin.base'					=> \App\Http\Middleware\Admin\BaseMiddleware::class,
		'oauth' 						=> \LucaDegasperi\OAuth2Server\Middleware\OAuthMiddleware::class,//OAuth
		'oauth-user'					=> \LucaDegasperi\OAuth2Server\Middleware\OAuthUserOwnerMiddleware::class,//OAuth
		'oauth-client' 					=> \LucaDegasperi\OAuth2Server\Middleware\OAuthClientOwnerMiddleware::class,//OAuth
		'check-authorization-params' 	=> \LucaDegasperi\OAuth2Server\Middleware\CheckAuthCodeRequestMiddleware::class,//OAuth
	];

}