text:
package com.dragon.codingol.repository.hibernate.base;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Column;
import javax.persistence.Table;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.transform.Transformers;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.dragon.codingol.common.IDCardValidate;
import com.dragon.codingol.common.SystemConfig;
import com.dragon.codingol.common.base.ReflectHelper;
import com.dragon.codingol.common.util.CriteriaUtil;
import com.dragon.codingol.domain.base.Valiform;

/**
 *
 * 类描述: DAO层泛型基类
 *
 * @author: dx
 * @date: 日期:2012-12-7 时间:上午10:16:48
 * @param <T>
 * @param <PK>
 * @version 1.0
 */
@Repository("genericCommonDao")
public class GenericCommonDao<T, PK extends Serializable> extends HibernateSessionFactory implements IGenericCommonDao {

	/**
	 * 根据实体名字获取唯一记录
	 *
	 * @param propertyName
	 * @param value
	 * @return
	 */
	public <T> T findUniqueByProperty(Class<T> entityClass, String propertyName, Object value) {
		Assert.hasText(propertyName);
		return (T) createCriteria(entityClass, Restrictions.eq(propertyName, value)).uniqueResult();
	}

	/**
	 * 按属性查找对象列表.
	 */
	public <T> List<T> findByProperty(Class<T> entityClass, String propertyName, Object value) {
		Assert.hasText(propertyName);
		return (List<T>) createCriteria(entityClass, Restrictions.eq(propertyName, value)).list();
	}

	/**
	 * 按属性查找 datastaus<>-1 对象列表.
	 */
	public <T> List<T> findEffectiveByProperty(Class<T> entityClass, String propertyName, Object value) {
		Criteria c = getSession().createCriteria(entityClass);
		c.add(Restrictions.eq(propertyName, value));
		c.add(Restrictions.ne(SystemConfig.getDatastatus(), -1));
		return (List<T>) c.list();
	}

	public <T> List<T> findEffectiveByPropertys(Class<T> entityClass, List<String> propertyName, List<Object> propertyValue) {
		Criteria c = getSession().createCriteria(entityClass);
		for (int i = 0; i < propertyName.size(); i++) {
			c.add(Restrictions.eq(propertyName.get(i), propertyValue.get(i)));
		}
		c.add(Restrictions.ne(SystemConfig.getDatastatus(), -1));
		return (List<T>) c.list();
	}

	/**
	 * 根据传入的实体持久化对象
	 *
	 * @throws Exception
	 */
	public <T> void save(T entity) throws Exception {
		try {
			valiform(entity);
			getSession().save(entity);
			getSession().flush();
		} catch (Exception e) {
			throw e;
		}

	}

	private void valiform(Object entity) throws Exception {
		Field[] fields = entity.getClass().getDeclaredFields();
		for (Field f : fields) {
			Valiform valiform = f.getAnnotation(Valiform.class);
			if (valiform != null) {
				// 拼写get方法名
				String str = f.getName();
				String firstChar = str.substring(0, 1).toUpperCase();
				String behindWord = str.substring(1, str.length());
				// 取得id值
				Method getId = entity.getClass().getMethod("getId");
				Object oId = getId.invoke(entity);
				String IdValue = (oId == null ? null : oId.toString());
				// 取得属性值
				Method getValue = entity.getClass().getMethod("get" + firstChar + behindWord);
				Object o = getValue.invoke(entity);
				String value = (o == null ? null : o.toString());

				if (valiform.notNull()) {
					if (StringUtils.isEmpty(value)) {
						throw new RuntimeException("\"" + valiform.title() + "\"不能为空!");
					}
				}

				if (valiform.idCard() && !StringUtils.isEmpty(value)) {
					IDCardValidate cc = new IDCardValidate();
					String validate = cc.IDCardValidate(value);
					if (!validate.equals("YES")) {
						throw new RuntimeException("\"" + valiform.title() + "\"格式不正确!");
					}

				}
				if (valiform.isUnique() && !StringUtils.isEmpty(value)) {
					List list = this.findEffectiveByProperty(entity.getClass(), f.getName(), value);
					if (list != null && list.size() > 0) {
						if (!StringUtils.isEmpty(IdValue)) { // id不为空,查检id是否相等
							Object s = list.get(0);
							Object sId = getId.invoke(s);
							String sIdValue = (sId == null ? null : sId.toString());
							if (!IdValue.equals(sIdValue)) {// id不相等,则重复;相等,则是修改,不是重复
								throw new RuntimeException("\"" + valiform.title() + "\"已经存在,请勿重复录入!");
							}
						} else {
							throw new RuntimeException("\"" + valiform.title() + "\"已经存在,请勿重复录入!");
						}
					}
				}

			}
		}
	}

	/**
	 * 批量保存数据
	 *
	 * @param <T>
	 * @param entitys
	 *            要持久化的临时实体对象集合
	 * @throws Exception
	 */
	public <T> void batchSave(List<T> entitys) throws Exception {
		for (int i = 0; i < entitys.size(); i++) {
			try {
				valiform(entitys.get(i));
				getSession().save(entitys.get(i));
				if (i % 20 == 0) {
					// 20个对象后才清理缓存,写入数据库
					getSession().flush();
					getSession().clear();
				}
			} catch (Exception e) {
				throw e;
			}
		}
	}

	/**
	 * 根据传入的实体添加或更新对象
	 *
	 * @param <T>
	 *
	 * @param entity
	 * @throws Exception
	 */

	public <T> void saveOrUpdate(T entity) throws RuntimeException {
		try {
			valiform(entity);
			getSession().saveOrUpdate(entity);
			getSession().flush();
		} catch (Exception e) {
			if(e.getCause()!=null && e.getCause().getMessage().equals("将截断字符串或二进制数据。")){
				throw new RuntimeException("更新失败。填写内容超过最大长度");
			}else{
				throw new RuntimeException(e.getMessage());
			}
		}
	}

	private <T> boolean isHaveDataStatus(T entity) {
		boolean isHave = false;
		ReflectHelper reflectHelper = new ReflectHelper(entity);
		Field[] field = entity.getClass().getDeclaredFields();
		for (Field f : field) {
			if (f.getName().equals("dataStatus")) {
				try {
					if (f.getType().equals(Integer.class)) {
						reflectHelper.setMethodValue(f.getName(), -1);
					} else
						reflectHelper.setMethodValue(f.getName(), (short) -1);
					isHave = true;
					break;
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		if (isHave) {
			try {
				this.saveOrUpdate(entity);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return isHave;
	}

	/**
	 * 根据传入的实体删除对象
	 *
	 * @throws Exception
	 */
	public <T> void delete(T entity) {
		try {
			if (!isHaveDataStatus(entity)) {
				getSession().delete(entity);
				getSession().flush();
			}

		} catch (RuntimeException e) {
			throw e;
		}
	}

	/**
	 * 根据主键删除指定的实体
	 *
	 * @param <T>
	 * @param pojo
	 * @throws Exception
	 */
	public <T> void deleteEntityById(Class<T> entityName, Serializable id) {
		Table table = entityName.getAnnotation(Table.class);
		if(table!=null &&  !StringUtils.isEmpty(table.name())){
			String sql  = "delete from " + table.name() + " where id  = ? ";
			List<Object> param = new ArrayList<Object>();
			param.add(id);
			this.executeSql(sql, param);
		}else{
			delete(get(entityName, id));
			getSession().flush();
		}
	}

	public <T> void deleteEntityByProperty(T entityName) throws Exception{
		Table table = entityName.getClass().getAnnotation(Table.class);
		if(table!=null &&  !StringUtils.isEmpty(table.name())){
			String sql  = "delete from " + table.name() + " where";
			Method method[] = entityName.getClass().getDeclaredMethods();
			List<Object> param = new ArrayList<Object>();

			for(Method m:method){
				if(m.getName().startsWith("get")){
					Column c = m.getAnnotation(Column.class);
					Object o = m.invoke(entityName, new Object[] {});
					if(StringUtils.isEmpty(o)){
						continue;
					}
					if(sql.endsWith("where")){
						sql += " "+ c.name().replace("[", "").replace("]", "")+ " = ? ";
						param.add(o);
					}else{
						sql += " and "+ c.name().replace("[", "").replace("]", "")+ " = ? ";
						param.add(o);
					}
				}
			}
			if(param.size() > 0)
				this.executeSql(sql, param);
		}
	}

	/**
	 * 根据主键删除指定的实体
	 *
	 * @param <T>
	 * @param pojo
	 * @throws Exception
	 */
	public <T> void deleteEntityByIds(Class<T> entityName, String ids){
		Table table = entityName.getAnnotation(Table.class);
		if(table!=null &&  !StringUtils.isEmpty(table.name())){
			String sql  = "delete from " + table.name() + " where 1=0 ";
			List<Object> param = new ArrayList<Object>();
			String id[] = ids.split(",");
			for(String i : id){
				sql += " or id = ? ";
				param.add(i);
			}
			this.executeSql(sql, param);
		}
	}

	/**
	 * 删除全部的实体
	 *
	 * @param <T>
	 *
	 * @param entitys
	 */
	public <T> void deleteAllEntitie(Collection<T> entitys) {
		for (Object entity : entitys) {
			if (!isHaveDataStatus(entity)) {
				getSession().delete(entity);
				getSession().flush();
			}
		}
	}

	/**
	 * 根据Id获取对象。
	 */
	public <T> T get(Class<T> entityClass, final Serializable id) {

		return (T) getSession().get(entityClass, id);

	}

	/**
	 * 根据主键获取实体并加锁。
	 *
	 * @param <T>
	 * @param entityName
	 * @param id
	 * @param lock
	 * @return
	 */
	public <T> T getEntity(Class<T> entityName, Serializable id) {

		T t = (T) getSession().get(entityName, id);
		if (t != null) {
			getSession().flush();
		}
		return t;
	}

	public <T> List<T> getEntitys(Class<T> entityName, String ids){
		Criteria criteria = getSession().createCriteria(entityName);
		String id[] = ids.split(",");
		for(String i :id){
			criteria.add(Restrictions.or(Restrictions.eq("id", i)));
		}
		return criteria.list();
	}

	/**
	 * 更新指定的实体
	 *
	 * @param <T>
	 * @param pojo
	 */
	public <T> void updateEntitie(T pojo) {
		getSession().update(pojo);
		getSession().flush();
	}

	/**
	 * 更新指定的实体
	 *
	 * @param <T>
	 * @param pojo
	 */
	public <T> void updateEntitie(String className, Object id) {
		getSession().update(className, id);
		getSession().flush();
	}

	/**
	 * 根据主键更新实体
	 */
	public <T> void updateEntityById(Class<T> entityName, Serializable id) {
		updateEntitie(get(entityName, id));
	}

	/**
	 * 通过hql 查询语句查找对象
	 *
	 * @param <T>
	 * @param query
	 * @return
	 */
	public List<T> findByQueryString(final String query) {

		Query queryObject = getSession().createQuery(query);
		List<T> list = queryObject.list();
		if (list.size() > 0) {
			getSession().flush();
		}
		return list;

	}

	/**
	 * 通过hql查询唯一对象
	 *
	 * @param <T>
	 * @param query
	 * @return
	 * @throws Exception
	 */
	public <T> T singleResult(String hql) throws Exception {
		T t = null;
		Query queryObject = getSession().createQuery(hql);
		List<T> list = queryObject.list();
		if (list.size() == 1) {
			getSession().flush();
			t = list.get(0);
		} else if (list.size() > 0) {
			throw new Exception("查询结果数:" + list.size() + "大于1");
		}
		return t;
	}

	/**
	 * 通过sql 查询语句查找HashMap对象
	 *
	 * @param <T>
	 * @param query
	 * @return
	 */
	public Map<Object, Object> getHashMapbyQuery(String sql, Object... param) {

		Query query = getSession().createSQLQuery(sql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				query.setParameter(i, param[i]);
			}
		}
		List list = query.list();
		Map<Object, Object> map = new HashMap<Object, Object>();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Object[] tm = (Object[]) iterator.next();
			map.put(tm[0].toString(), tm[1].toString());
		}
		return map;
	}

	/**
	 * 通过hql 查询语句查找HashMap对象
	 *
	 * @param <T>
	 * @param query
	 * @return
	 */
	public Map<Object, Object> getHashMapbyHqlQuery(String hql, Object... param) {

		Query query = getSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				query.setParameter(i, param[i]);
			}
		}
		List list = query.list();
		Map<Object, Object> map = new HashMap<Object, Object>();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Object[] tm = (Object[]) iterator.next();
			map.put(tm[0].toString(), tm[1].toString());
		}
		return map;

	}

	public Map<Object, Object> getLinkedHashMapbyHqlQuery(String hql, Object... param) {

		Query query = getSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				query.setParameter(i, param[i]);
			}
		}
		List list = query.list();
		Map<Object, Object> map = new LinkedHashMap<Object, Object>();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Object[] tm = (Object[]) iterator.next();
			map.put(tm[0].toString(), tm[1].toString());
		}
		return map;

	}

	/**
	 * 通过sql更新记录
	 *
	 * @param <T>
	 * @param query
	 * @return
	 */
	public int updateBySqlString(final String query) {

		Query querys = getSession().createSQLQuery(query);
		return querys.executeUpdate();
	}

	public int updateBySqlString(final String query, List<Object> param) {

		Query querys = getSession().createSQLQuery(query);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				querys.setParameter(i, param.get(i));
			}
		}
		return querys.executeUpdate();
	}

	/**
	 * 通过sql查询语句查找对象
	 *
	 * @param <T>
	 * @param query
	 * @return
	 */
	public <T> List<T> findListbySql(String sql) {
		SQLQuery querys = getSession().createSQLQuery(sql);

		return querys.list();
	}

	public <T> List<T> findListbySql(Class<T> entityClass, String sql) {
		SQLQuery querys = getSession().createSQLQuery(sql);
		Field[] fields = entityClass.getFields();
		for (Field f : fields) {
			querys.addScalar(f.getName());
		}
		querys.setResultTransformer(Transformers.aliasToBean(entityClass));
		return querys.list();
	}

	/**
	 * 通过sql查询语句查找对象
	 *
	 * @param <T>
	 * @param query
	 * @return
	 */
	public <T> List<T> findListbySql(Class<T> entityClass, String sql, Object... param) {
		SQLQuery querys = getSession().createSQLQuery(sql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				querys.setParameter(i, param[i]);
			}
		}
		Field[] fields = entityClass.getFields();
		for (Field f : fields) {
			if (f.getName().equals("areaList")) {
				continue;
			}
			querys.addScalar(f.getName());
		}
		querys.setResultTransformer(Transformers.aliasToBean(entityClass));
		return querys.list();
	}

	public void queryCriteriaPage(CriteriaUtil criteriaUtil){

		Criteria criteria = criteriaUtil.getDetachedCriteria().getExecutableCriteria(getSession());
		CriteriaImpl impl = (CriteriaImpl) criteria;

		Projection projection = impl.getProjection();
		final int allCounts = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
		criteria.setProjection(projection);

		if (projection == null) {
			criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		} else {
			criteria.setResultTransformer(Transformers.aliasToBean(criteriaUtil.getTclass()));
		}

		criteria.setFirstResult((criteriaUtil.getPage() - 1 )*criteriaUtil.getLimit());
		criteria.setMaxResults(criteriaUtil.getLimit());

		if(!criteriaUtil.isIsorder()){
			addOrder(criteria, criteriaUtil.getTclass());
		}

		List list = criteria.list();

		criteriaUtil.getPager().setTotal(allCounts);
		criteriaUtil.getPager().setRows(list);
	}

	public Integer getCountBySql(String sql, Object... param) {
		SQLQuery countQuery = getSession().createSQLQuery(sql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				countQuery.setParameter(i, param[i]);
			}
		}
		return ((Number) countQuery.uniqueResult()).intValue();
	}

	public Integer getCountByHql(String hql, Object... param) {
		Query countQuery = getSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				countQuery.setParameter(i, param[i]);
			}
		}
		return ((Number) countQuery.uniqueResult()).intValue();
	}

	/**
	 * 创建Criteria对象,有排序功能。
	 *
	 * @param <T>
	 * @param entityClass
	 * @param orderBy
	 * @param isAsc
	 * @param criterions
	 * @return
	 */
	private <T> Criteria createCriteria(Class<T> entityClass, boolean isAsc, Criterion... criterions) {
		Criteria criteria = createCriteria(entityClass, criterions);
		if (isAsc) {
			criteria.addOrder(Order.asc("asc"));
		} else {
			criteria.addOrder(Order.desc("desc"));
		}
		return criteria;
	}

	/**
	 * 创建Criteria对象带属性比较
	 *
	 * @param <T>
	 * @param entityClass
	 * @param criterions
	 * @return
	 */
	private <T> Criteria createCriteria(Class<T> entityClass, Criterion... criterions) {
		Criteria criteria = getSession().createCriteria(entityClass);
		for (Criterion c : criterions) {
			criteria.add(c);
		}

		addOrder(criteria, entityClass);
		return criteria;
	}

	private void addOrder(Criteria criteria, Class entityClass){
		Field fields[] = entityClass.getDeclaredFields();
		for(Field f : fields){
			if(f.getName() == "order"){
				criteria.addOrder(Order.asc("order"));
			}
		}
	}

	public <T> List<T> loadAll(final Class<T> entityClass) {
		Criteria criteria = createCriteria(entityClass);
		return criteria.list();
	}

	/**
	 * 创建单一Criteria对象
	 *
	 * @param <T>
	 * @param entityClass
	 * @param criterions
	 * @return
	 */
	private <T> Criteria createCriteria(Class<T> entityClass) {
		Criteria criteria = getSession().createCriteria(entityClass);
		return criteria;
	}

	/**
	 * 根据属性名和属性值查询. 有排序
	 *
	 * @param <T>
	 * @param entityClass
	 * @param propertyName
	 * @param value
	 * @param orderBy
	 * @param isAsc
	 * @return
	 */
	public <T> List<T> findByPropertyisOrder(Class<T> entityClass, String propertyName, Object value, boolean isAsc) {
		Assert.hasText(propertyName);
		return createCriteria(entityClass, isAsc, Restrictions.eq(propertyName, value)).list();
	}

	/**
	 * 根据属性名和属性值 查询 且要求对象唯一.
	 *
	 * @return 符合条件的唯一对象.
	 */
	public <T> T findUniqueBy(Class<T> entityClass, String propertyName, Object value) {
		Assert.hasText(propertyName);
		return (T) createCriteria(entityClass, Restrictions.eq(propertyName, value)).uniqueResult();
	}

	/**
	 * 根据查询条件与参数列表创建Query对象
	 *
	 * @param session
	 *            Hibernate会话
	 * @param hql
	 *            HQL语句
	 * @param objects
	 *            参数列表
	 * @return Query对象
	 */
	public Query createQuery(Session session, String hql, Object... objects) {
		Query query = session.createQuery(hql);
		if (objects != null) {
			for (int i = 0; i < objects.length; i++) {
				query.setParameter(i, objects[i]);
			}
		}
		return query;
	}

	/**
	 * 批量插入实体
	 *
	 * @param clas
	 * @param values
	 * @return
	 * @throws Exception
	 */
	public <T> int batchInsertsEntitie(List<T> entityList) throws Exception {
		int num = 0;
		for (int i = 0; i < entityList.size(); i++) {
			save(entityList.get(i));
			num++;
		}
		return num;
	}

	/**
	 * 根据实体名返回全部对象
	 *
	 * @param <T>
	 * @param hql
	 * @param size
	 * @return
	 */
	public List<T> executeQuery(final String hql, final Object[] values) {
		Query query = getSession().createQuery(hql);
		for (int i = 0; values != null && i < values.length; i++) {
			query.setParameter(i, values[i]);
		}

		return query.list();

	}

	/**
	 * 根据实体模版查找
	 *
	 * @param entityName
	 * @param exampleEntity
	 * @return
	 */

	public List findByExample(final Object exampleEntity) {
		Criteria executableCriteria =  getSession().createCriteria(exampleEntity.getClass());
		executableCriteria.add(Example.create(exampleEntity));
		return executableCriteria.list();
	}

	/**
	 * 调用存储过程
	 */
	public void callableStatementByName(String proc) {
	}

	/**
	 * 查询指定实体的总记录数
	 *
	 * @param clazz
	 * @return
	 */
	public int getCount(Class<T> clazz) {

		int count = DataAccessUtils.intResult(getSession().createQuery("select count(*) from " + clazz.getName()).list());
		return count;
	}

	/**
	 * 通过hql 查询语句查找对象
	 *
	 * @param <T>
	 * @param query
	 * @return
	 */
	public <T> List<T> findHql(String hql, Object... param) {
		Query q = getSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.list();
	}

	/**
	 * 执行HQL语句操作更新
	 *
	 * @param hql
	 * @return
	 */

	public Integer executeHql(String hql) {
		Query q = getSession().createQuery(hql);
		return q.executeUpdate();
	}

	public Integer executeHql(String hql, Object... param) {
		Query q = getSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.executeUpdate();
	}

	@Override
	public Integer executeSql(String sql, List<Object> param) {
		Query q = getSession().createSQLQuery(sql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return q.executeUpdate();
	}

}


text:
package banking.reports;

import banking.domain.*;
import java.text.NumberFormat;

public class CustomerReport {

  public void generateReport() {
    NumberFormat currency_format = NumberFormat.getCurrencyInstance();

    Bank         bank = Bank.getBank();

    Customer     customer;

    System.out.println("\t\t\tCUSTOMERS REPORT");
    System.out.println("\t\t\t================");

    for ( int cust_idx = 0; cust_idx < bank.getNumOfCustomers(); cust_idx++ ) {
      customer = bank.getCustomer(cust_idx);

      System.out.println();
      System.out.println("Customer: "
			 + customer.getLastName() + ", "
			 + customer.getFirstName());

      for ( int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++ ) {
	Account account = customer.getAccount(acct_idx);
	String  account_type = "";

	// Determine the account type
	if ( account instanceof SavingsAccount ) {
	  account_type = "Savings Account";
	} else if ( account instanceof CheckingAccount ) {
	  account_type = "Checking Account";
	} else {
	  account_type = "Unknown Account Type";
	}

	// Print the current balance of the account
	System.out.println("    " + account_type + ": current balance is "
			 + currency_format.format(account.getBalance()));
      }
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef _SA_H_
#define _SA_H_

#define IPSEC_MAX_HDR_SIZE	64
#define IPSEC_MAX_IV_SIZE	16
#define IPSEC_MAX_IV_QWORD	(IPSEC_MAX_IV_SIZE / sizeof(uint64_t))
#define TUN_HDR_MSK (RTE_IPSEC_SATP_ECN_MASK | RTE_IPSEC_SATP_DSCP_MASK)

/* padding alignment for different algorithms */
enum {
	IPSEC_PAD_DEFAULT = 4,
	IPSEC_PAD_3DES_CBC = 8,
	IPSEC_PAD_AES_CBC = IPSEC_MAX_IV_SIZE,
	IPSEC_PAD_AES_CTR = IPSEC_PAD_DEFAULT,
	IPSEC_PAD_AES_GCM = IPSEC_PAD_DEFAULT,
	IPSEC_PAD_AES_CCM = IPSEC_PAD_DEFAULT,
	IPSEC_PAD_CHACHA20_POLY1305 = IPSEC_PAD_DEFAULT,
	IPSEC_PAD_NULL = IPSEC_PAD_DEFAULT,
	IPSEC_PAD_AES_GMAC = IPSEC_PAD_DEFAULT,
};

/* iv sizes for different algorithms */
enum {
	IPSEC_IV_SIZE_DEFAULT = IPSEC_MAX_IV_SIZE,
	IPSEC_AES_CTR_IV_SIZE = sizeof(uint64_t),
	/* TripleDES supports IV size of 32bits or 64bits but he library
	 * only supports 64bits.
	 */
	IPSEC_3DES_IV_SIZE = sizeof(uint64_t),
};

/* these definitions probably has to be in rte_crypto_sym.h */
union sym_op_ofslen {
	uint64_t raw;
	struct {
		uint32_t offset;
		uint32_t length;
	};
};

union sym_op_data {
#ifdef __SIZEOF_INT128__
	__uint128_t raw;
#endif
	struct {
		uint8_t *va;
		rte_iova_t pa;
	};
};

#define REPLAY_SQN_NUM		2
#define REPLAY_SQN_NEXT(n)	((n) ^ 1)

struct replay_sqn {
	rte_rwlock_t rwl;
	uint64_t sqn;
	__extension__ uint64_t window[0];
};

/*IPSEC SA supported algorithms */
enum sa_algo_type	{
	ALGO_TYPE_NULL = 0,
	ALGO_TYPE_3DES_CBC,
	ALGO_TYPE_AES_CBC,
	ALGO_TYPE_AES_CTR,
	ALGO_TYPE_AES_GCM,
	ALGO_TYPE_AES_CCM,
	ALGO_TYPE_CHACHA20_POLY1305,
	ALGO_TYPE_AES_GMAC,
	ALGO_TYPE_MAX
};

struct rte_ipsec_sa {

	uint64_t type;     /* type of given SA */
	uint64_t udata;    /* user defined */
	uint32_t size;     /* size of given sa object */
	uint32_t spi;
	/* sqn calculations related */
	uint64_t sqn_mask;
	struct {
		uint32_t win_sz;
		uint16_t nb_bucket;
		uint16_t bucket_index_mask;
	} replay;
	/* template for crypto op fields */
	struct {
		union sym_op_ofslen cipher;
		union sym_op_ofslen auth;
	} ctp;
	/* cpu-crypto offsets */
	union rte_crypto_sym_ofs cofs;
	/* tx_offload template for tunnel mbuf */
	struct {
		uint64_t msk;
		uint64_t val;
	} tx_offload;
	uint32_t salt;
	uint8_t algo_type;
	uint8_t proto;    /* next proto */
	uint8_t aad_len;
	uint8_t hdr_len;
	uint8_t hdr_l3_off;
	uint8_t icv_len;
	uint8_t sqh_len;
	uint8_t iv_ofs; /* offset for algo-specific IV inside crypto op */
	uint8_t iv_len;
	uint8_t pad_align;
	uint8_t tos_mask;

	/* template for tunnel header */
	uint8_t hdr[IPSEC_MAX_HDR_SIZE];

	/*
	 * sqn and replay window
	 * In case of SA handled by multiple threads *sqn* cacheline
	 * could be shared by multiple cores.
	 * To minimise performance impact, we try to locate in a separate
	 * place from other frequently accessed data.
	 */
	union {
		uint64_t outb;
		struct {
			uint32_t rdidx; /* read index */
			uint32_t wridx; /* write index */
			struct replay_sqn *rsn[REPLAY_SQN_NUM];
		} inb;
	} sqn;
	/* Statistics */
	struct {
		uint64_t count;
		uint64_t bytes;
		struct {
			uint64_t count;
			uint64_t authentication_failed;
		} errors;
	} statistics;

} __rte_cache_aligned;

int
ipsec_sa_pkt_func_select(const struct rte_ipsec_session *ss,
	const struct rte_ipsec_sa *sa, struct rte_ipsec_sa_pkt_func *pf);

/* inbound processing */

uint16_t
esp_inb_pkt_prepare(const struct rte_ipsec_session *ss, struct rte_mbuf *mb[],
	struct rte_crypto_op *cop[], uint16_t num);

uint16_t
esp_inb_tun_pkt_process(const struct rte_ipsec_session *ss,
	struct rte_mbuf *mb[], uint16_t num);

uint16_t
inline_inb_tun_pkt_process(const struct rte_ipsec_session *ss,
	struct rte_mbuf *mb[], uint16_t num);

uint16_t
esp_inb_trs_pkt_process(const struct rte_ipsec_session *ss,
	struct rte_mbuf *mb[], uint16_t num);

uint16_t
inline_inb_trs_pkt_process(const struct rte_ipsec_session *ss,
	struct rte_mbuf *mb[], uint16_t num);

uint16_t
cpu_inb_pkt_prepare(const struct rte_ipsec_session *ss,
		struct rte_mbuf *mb[], uint16_t num);

/* outbound processing */

uint16_t
esp_outb_tun_prepare(const struct rte_ipsec_session *ss, struct rte_mbuf *mb[],
	struct rte_crypto_op *cop[], uint16_t num);

uint16_t
esp_outb_trs_prepare(const struct rte_ipsec_session *ss, struct rte_mbuf *mb[],
	struct rte_crypto_op *cop[], uint16_t num);

uint16_t
esp_outb_sqh_process(const struct rte_ipsec_session *ss, struct rte_mbuf *mb[],
	uint16_t num);

uint16_t
pkt_flag_process(const struct rte_ipsec_session *ss,
	struct rte_mbuf *mb[], uint16_t num);

uint16_t
inline_outb_tun_pkt_process(const struct rte_ipsec_session *ss,
	struct rte_mbuf *mb[], uint16_t num);

uint16_t
inline_outb_trs_pkt_process(const struct rte_ipsec_session *ss,
	struct rte_mbuf *mb[], uint16_t num);

uint16_t
inline_proto_outb_pkt_process(const struct rte_ipsec_session *ss,
	struct rte_mbuf *mb[], uint16_t num);

uint16_t
cpu_outb_tun_pkt_prepare(const struct rte_ipsec_session *ss,
		struct rte_mbuf *mb[], uint16_t num);
uint16_t
cpu_outb_trs_pkt_prepare(const struct rte_ipsec_session *ss,
		struct rte_mbuf *mb[], uint16_t num);

#endif /* _SA_H_ */


text:
Interop with MassTransit (Routing RFC)
""""""""""""""""""""""""""""""""""""""

MassTransit's serializers do the main work of formatting the data that goes over the wire. Below is the message format that everything is mapped to/from:

.. sourcecode:: csharp

    string RequestId
    string ConversationId
    string CorrelationId
    string DestinationAddress
    DateTime? ExpirationTime
    string FaultAddress
    IDictionary<string, string> Headers
    object Message
    string MessageId
    IList<string> MessageType
    string Network
    string ResponseAddress
    int RetryCount
    string SourceAddress

This is a minimal message:

.. sourcecode:: javascript
	{
		"destinationAddress": "rabbitmq://isomorphism/MassTransit.Test.Receiver",
		"headers": {},
		"message": {
			"spoken": "Something wierd is going on!",
			"seqId": 2
		},
		"messageType": [
			"urn:message:MassTransit.Test.Messages:ChatMessage"
		],
		"retryCount": 0
	}

Which translates to these required properties:

 * message
 * messageType
 * destinationAddress

MessageType is a list of urns. See MessageUrnSpecs for the format. Informally, it's like this::

urn:message:NAMESPACE1.NAMESPACE2:TYPE

'retryCount', 'headers' will be defaulted.


text:
namespace Poco {
namespace RemotingNG {
namespace TCP {

class EventSubscription;

class RemotingNGTCP_API Listener: public Poco::RemotingNG::EventListener
	/// The RemotingNG Listener implementation for the TCP transport.
{
public:
	typedef Poco::AutoPtr<Listener> Ptr;

	Poco::BasicEvent<Connection::Ptr> connectionAccepted;
		/// Fired when a new client connection has been accepted.

	Listener(ConnectionManager& connectionManager = ConnectionManager::defaultManager());
		/// Creates a passive Event Listener.
		///
		/// This method is used to set up a passive Event Listener
		/// on the client. No TCPServer will be created.

	Listener(const std::string& endPoint, ConnectionManager& connectionManager = ConnectionManager::defaultManager());
		/// Creates a Listener for the given endpoint,
		/// which must be in <host>:<port> format.
		///
		/// This method will create a Poco::Net::ServerSocket,
		/// bind it to the given endpoint address, and set
		/// up a TCPServer instance for accepting incoming
		/// connections.

	Listener(const std::string& endPoint, Poco::Net::TCPServerParams::Ptr pParams, ConnectionManager& connectionManager = ConnectionManager::defaultManager());
		/// Creates a Listener for the given endpoint,
		/// which must be in <host>:<port> format.
		///
		/// This method will create a Poco::Net::ServerSocket,
		/// bind it to the given endpoint address, and set
		/// up a TCPServer instance (using the given params)
		/// for accepting incoming connections.

	Listener(const std::string& endPoint, const Poco::Net::ServerSocket& socket, Poco::Net::TCPServerParams::Ptr pParams, ConnectionManager& connectionManager = ConnectionManager::defaultManager());
		/// Creates a Listener for the given endpoint,
		/// which must be in <host>:<port> format.
		///
		/// This method will use the given server socket, and set
		/// up a TCPServer instance (using the given params)
		/// for accepting incoming connections.
		///
		/// Note that the given server socket can be a
		/// Poco::Net::SecureServerSocket in order to set up
		/// a secure connection.

	~Listener();
		/// Destroys the Listener.

	void setTimeout(Poco::Timespan timeout);
		/// Sets the receive timeout for connections.

	Poco::Timespan getTimeout() const;
		/// Returns the receive timeout for connections.

	void setEventSubscriptionTimeout(Poco::Timespan timeout);
		/// Sets the timeout for event subscriptions.

	Poco::Timespan getEventSubscriptionTimeout() const;
		/// Returns the timeout for event subscriptions.

	ConnectionManager& connectionManager();
		/// Returns the ConnectionManager used by the Listener.

	// Poco::RemotingNG::EventListener
	void subscribeToEvents(Poco::RemotingNG::EventSubscriber::Ptr pEventSubscriber);
	void unsubscribeFromEvents(Poco::RemotingNG::EventSubscriber::Ptr pEventSubscriber);

	// Poco::RemotingNG::Listener
	void start();
	void stop();
	const std::string& protocol() const;
	std::string createURI(const Poco::RemotingNG::Identifiable::TypeId& typeId, const Poco::RemotingNG::Identifiable::ObjectId& objectId);
	bool handlesURI(const std::string& uri);
	void registerObject(Poco::RemotingNG::RemoteObject::Ptr pRemoteObject, Poco::RemotingNG::Skeleton::Ptr pSkeleton);
	void unregisterObject(Poco::RemotingNG::RemoteObject::Ptr pRemoteObject);

	// internal
	Poco::RemotingNG::EventSubscriber::Ptr findEventSubscriber(const std::string& path) const;

private:
	enum
	{
		DEFAULT_TIMEOUT = 30,
		DEFAULT_EVENT_SUBSCR_TIMEOUT = 60
	};

	class RemotingNGTCP_API EventSubscription: public TimerTask
	{
	public:
		typedef Poco::AutoPtr<EventSubscription> Ptr;

		EventSubscription(Listener& listener, const std::string& uri, Poco::UInt32 id);
		void run();
		const std::string& path() const;

	private:
		Listener& _listener;
		Poco::URI _uri;
		std::string _suri;
		std::string _path;
	};

	typedef std::map<Poco::RemotingNG::EventSubscriber::Ptr, EventSubscription::Ptr> EventSubscriptionsMap;

	ConnectionManager& _connectionManager;
	Poco::Timespan _timeout;
	Poco::Timespan _eventSubscriptionTimeout;
	bool _secure;
	Poco::SharedPtr<Poco::Net::TCPServer> _pTCPServer;
	EventSubscriptionsMap _eventSubscriptions;
	Poco::UInt32 _nextSubscriberId;
	Timer _timer;
	mutable Poco::FastMutex _mutex;
};

} } } // namespace Poco::RemotingNG::TCP

#endif // RemotingNG_TCP_Listener_INCLUDED


text:
var events = require('events');
var stopMediaStream = require('stop-media-stream');

var EventEmitter = events.EventEmitter;
var VIDEO_TYPE = 'video/webm';

function Recorder(UserMedia, constraints) {
  var recorder = new EventEmitter();
  var chunks = [];

  UserMedia.getCorrectDevice(/video/, 'Kinect')
    .then(function (device) {
      if (device) {
        constraints.video = { deviceId: { exact: device.deviceId }};
      }
      return UserMedia.get(constraints);
    })
    .then(_handleMediaStream)
    .catch(recorder.emit.bind(recorder, 'error'));

  return recorder;

  function _handleMediaStream(mediaStream) {
    var mediaRecorder = _createMediaRecorder(mediaStream);
    _setupRecorder(mediaRecorder);
    recorder.emit('stream', mediaStream);
  }

  function _createMediaRecorder(mediaStream) {
    var recorderOptions = { mimeType: VIDEO_TYPE };
    var mediaRecorder = new MediaRecorder(mediaStream, recorderOptions);
    mediaRecorder.ondataavailable = addChunk;
    return mediaRecorder;
  }

  function addChunk(event) {
    if(event.data && event.data.size > 0){
      chunks.push(event.data);
    }
  }

  function _setupRecorder(mediaRecorder) {
    recorder.start = mediaRecorder.start.bind(mediaRecorder);
    recorder.stop = _stopRecording.bind(null, mediaRecorder);
    recorder.getBlob = getRecorderBlob;
  }

  function _stopRecording(mediaRecorder) {
    var stream = mediaRecorder.stream;
    mediaRecorder.stop();
    stopMediaStream(stream);
  }

  function getRecorderBlob() {
    return new Blob(chunks, { type: VIDEO_TYPE });
  }
}

Recorder.isPresent = (window.MediaRecorder !== undefined);

module.exports = Recorder;


text:
<!--
Copyright 2013 The Polymer Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<!--
/**
 * @module Polymer Elements
 */
/**
 * polymer-media-query can be used to data bind to a CSS media query.
 * The "query" property is a bare CSS media query.
 * The "queryMatches" property will be a boolean representing if the page matches that media query.
 *
 * polymer-media-query uses media query listeners to dynamically update the "queryMatches" property.
 * A "polymer-mediachange" event also fires when queryMatches changes.
 *
 * Example:
 *
 *      <polymer-media-query query="max-width: 640px" queryMatches="{{phoneScreen}}"></polymer-media-query>
 *
 * @class polymer-media-query
 */
-->
<link rel="import" href="../polymer/polymer.html">

<polymer-element name="polymer-media-query" attributes="query queryMatches">
  <template>
    <style>
      :host {
        display: none;
      }
    </style>
  </template>
  <script>

    Polymer('polymer-media-query', {
      /**
       * The Boolean return value of the media query
       * @attribute queryMatches
       * @type Boolean
       * @default false
       */
      queryMatches: false,
      /**
       * The CSS media query to evaulate
       * @attribute query
       * @type string
       * @default ''
       */
      query: '',
      ready: function() {
        this._mqHandler = this.queryHandler.bind(this);
        this._mq = null;
      },
      queryChanged: function() {
        if (this._mq) {
          this._mq.removeListener(this._mqHandler);
        }
        var query = this.query;
        if (query[0] !== '(') {
          query = '(' + this.query + ')';
        }
        this._mq = window.matchMedia(query);
        this._mq.addListener(this._mqHandler);
        this.queryHandler(this._mq);
      },
      queryHandler: function(mq) {
        this.queryMatches = mq.matches;
        this.asyncFire('polymer-mediachange', mq);
      }
    });
  </script>
</polymer-element>


text:
layout: headerfooter
tagName: Unsolicited Opinions
tagDescription: Stuff no one asked me to, or really probably wants me to, write about
---
{% include tagged_post_list.html tagDescription=page.tagDescription  tag=page.tagName %}


text:
id: bad87fee1348bd9aedf08828
title: Crea una lista ordenada
challengeType: 0
videoUrl: 'https://scrimba.com/p/pVMPUv/cQ3B8TM'
forumTopicId: 16824
dashedName: create-an-ordered-list
---

# --description--

HTML tiene otro elemento especial para crear <dfn>listas ordenadas</dfn>, o listas numeradas.

Las listas ordenadas comienzan con un elemento de apertura `<ol>`, seguido de cualquier número de elementos `<li>`. Por último, las listas ordenadas se cierran con la etiqueta `</ol>`.

Por ejemplo:

```html
<ol>
  <li>Garfield</li>
  <li>Sylvester</li>
</ol>
```

crearía una lista numerada de `Garfield` y `Sylvester`.

# --instructions--

Crea una lista ordenada de las 3 cosas que los gatos odian (Top 3 things cats hate) más.

# --hints--

Debes tener una lista ordenada para `Top 3 things cats hate:`

```js
assert(/Top 3 things cats hate:/i.test($('ol').prev().text()));
```

Debes tener una lista no ordenada para `Things cats love:`

```js
assert(/Things cats love:/i.test($('ul').prev().text()));
```

Solo debes tener un elemento `ul`.

```js
assert.equal($('ul').length, 1);
```

Solo debes tener un elemento `ol`.

```js
assert.equal($('ol').length, 1);
```

Debes tener tres elementos `li` dentro de tu elemento `ul`.

```js
assert.equal($('ul li').length, 3);
```

Debes tener tres elementos `li` dentro de tu elemento `ol`.

```js
assert.equal($('ol li').length, 3);
```

Tu elemento `ul` debe tener una etiqueta de cierre.

```js
assert(
  code.match(/<\/ul>/g) &&
    code.match(/<\/ul>/g).length === code.match(/<ul>/g).length
);
```

Tu elemento `ol` debe tener una etiqueta de cierre.

```js
assert(
  code.match(/<\/ol>/g) &&
    code.match(/<\/ol>/g).length === code.match(/<ol>/g).length
);
```

Tu elemento `li` debe tener una etiqueta de cierre.

```js
assert(
  code.match(/<\/li>/g) &&
    code.match(/<li>/g) &&
    code.match(/<\/li>/g).length === code.match(/<li>/g).length
);
```

Los elementos `li` de tu lista no ordenada no deben estar vacíos.

```js
$('ul li').each((i, val) =>
  assert(__helpers.removeWhiteSpace(val.textContent))
);
```

Los elementos `li` de tu lista ordenada no deben estar vacíos.

```js
$('ol li').each((i, val) =>
  assert(!!__helpers.removeWhiteSpace(val.textContent))
);
```

# --seed--

## --seed-contents--

```html
<h2>CatPhotoApp</h2>
<main>
  <p>Click here to view more <a href="#">cat photos</a>.</p>

  <a href="#"><img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a>

  <p>Things cats love:</p>
  <ul>
    <li>cat nip</li>
    <li>laser pointers</li>
    <li>lasagna</li>
  </ul>
  <p>Top 3 things cats hate:</p>

</main>
```

# --solutions--

```html
<h2>CatPhotoApp</h2>
<main>
  <p>Click here to view more <a href="#">cat photos</a>.</p>

  <a href="#"><img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a>

  <p>Things cats love:</p>
  <ul>
    <li>cat nip</li>
    <li>laser pointers</li>
    <li>lasagna</li>
  </ul>
  <p>Top 3 things cats hate:</p>
  <ol>
    <li>hate 1</li>
    <li>hate 2</li>
    <li>hate 3</li>
  </ol>
</main>
```


text: .string-list-input{margin-left:5%}.string-list-input label{cursor:move}


text:
package com.intellij.ide.todo;

import com.intellij.openapi.project.Project;

import javax.swing.*;

/**
 * @author irengrig
 */
public interface TodoTreeBuilderFactory {
  TodoTreeBuilder createTreeBuilder(JTree tree,Project project);
}


text:
layout: post
title: "Wednesday 05.23.18 -  CrossFit"
teaser: "A.  Front Squat 5 x 3
 B.  Muscle Snatch 5 x 2
 C.  For Time: Front Squats and Bar Muscle-Ups"
date: 2018-05-23 00:00:00
categories: wodup
tags: wods wednesday
header: no
---

A.  Front Squat 5 x 3

Every 2 minutes, for 10 minutes (5 sets):
3 Front Squats

B.  Muscle Snatch 5 x 2

Every 2 minutes, for 10 minutes (5 sets):
2 Muscle Snatches

C.  For Time: Front Squats and Bar Muscle-Ups

For Time:
– 20 Front Squats @ 90/60 kg
– 15 Bar Muscle-Ups
– 10 Front Squats @ 90/60 kg
– 5 Bar Muscle-Ups

Bar needs to be taken from the floor.  Choose a weight that is heavy but not soul crushing.
View on WodUp

#### Compare to other Wednesdays
{: .t60 }

{% include list-posts tag='wednesday' %}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" tools:context=".TCL">
        <item
        android:id="@+id/menu_item_share"
        android:title="@string/share_settings"
        android:icon="@drawable/ic_share_white"
        android:actionProviderClass="android.widget.ShareActionProvider"
        app:showAsAction="always|withText"/>
        <item
            android:id="@+id/action_settings"
            android:title="@string/powered_settings"
            android:icon="@drawable/ic_mlstuff"
            android:orderInCategory="100"
            app:showAsAction="always|withText" />
</menu>
<!-- From: file:/C:/Users/Sebastian/AndroidStudioProjects/TCL/app/src/main/res/menu/menu_tcl.xml -->


text:
Here you can find scripts for different deployment scenarios using Azure AKS platform:

- [**monolith**](/docs/user-guide/install/{{docsPrefix}}cluster/azure-monolith-setup/) - simplistic deployment of ThingsBoard with only one service and
  Azure Database for PostgreSQL;
- [**microservices**](/docs/user-guide/install/{{docsPrefix}}cluster/azure-microservices-setup/) (recommended) - deployment of ThingsBoard in a microservices mode
  with Azure Database for PostgreSQL and Azure Cache for Redis;


text:
package main

import (
	"github.com/solidworx/proj/cmd"
)

func main() {
	cmd.Execute()
}


text:
import simplejson as json
import cherrypy, sys, os, binascii
from pprint import pprint

from sourcelyzer.httpapi.utils.json import json_error_output
from sourcelyzer.httpapi.v1.commands import LoginCommand, SessionCommand
from sourcelyzer.httpapi.tools.sqlalchemy import SATool
from sourcelyzer.utils.hashing import gen_passwd_hash, gen_auth_token

from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sourcelyzer.dao.base import Base

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

from cherrypy.test import helper
from cherrypy.lib.sessions import RamSession

import mock

def custom_urandom(length):
    s = 'f' * length;
    return s.encode('utf-8')

class UserDao(Base):
    __tablename__ = 'test_users'

    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String)
    password = Column(String)

def setup_db():
    dbfile = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test.db')

    if os.path.exists(dbfile):
        os.remove(dbfile)

    engine = create_engine('sqlite:///%s' % dbfile)

    Base.metadata.create_all(engine)

    SessionMaker = sessionmaker(bind=engine)
    session = SessionMaker()

    test_user_one = UserDao(username='test1', password=gen_passwd_hash('test1pw'))
    test_user_two = UserDao(username='test2', password=gen_passwd_hash('test2pw'))

    session.add(test_user_one)
    session.add(test_user_two)

    session.commit()
    session.flush()
    session.close()

    engine.dispose()
    engine = None

class LoginCommandTest(helper.CPWebCase):

    interactive = False

    def setUp(self):
        setup_db()

    def tearDown(self):
        dbfile = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test.db')
        os.remove(dbfile)

    def setup_server():

        dbfile = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test.db')

        satool = SATool(dburi='sqlite:///%s' % dbfile)
        cherrypy.tools.db = satool

        cherrypy.config.update({
            'error_page.default': json_error_output,
            'environment': 'test_suite',
            'tools.db.on': True,
            'tools.sessions.on': True,
            'server.thread_pool': 1
        })

        cherrypy.tree.mount(LoginCommand(UserDao), '/login')
        cherrypy.tree.mount(SessionCommand(UserDao), '/session')

    def test_good_login(self):

        body = json.dumps({'username': 'test1', 'password': 'test1pw'})

        headers = [
            ('Content-Type', 'application/json'),
            ('Content-Length', str(len(body)))
        ]

        cherrypy.session = RamSession()

        self.getPage('/login', method='POST', body=body, headers=headers)
        pprint(json.loads(self.body))
        self.assertStatus(200)

        body = json.loads(self.body.decode('utf-8'))

        assert body['session'] == cherrypy.session.id

        assert cherrypy.session['user']['id'] == 1
        assert cherrypy.session['user']['username'] == 'test1'
        assert cherrypy.session['user']['auth'] == True
        assert cherrypy.session['user']['token'] == body['token']

        del cherrypy.session

    @mock.patch('os.urandom', side_effect=custom_urandom)
    def test_good_session(self,mock):

        cherrypy.session = RamSession()

        user = cherrypy.tools.db.session.query(UserDao).filter(UserDao.id == 2).first()

        token = gen_auth_token('test2', user.password, 2, cherrypy.session.id)
        cherrypy.session['user'] = {}
        cherrypy.session['user']['id'] = 2
        cherrypy.session['user']['username'] = 'test2'
        cherrypy.session['user']['auth'] = True
        cherrypy.session['user']['token'] = token

        self.getPage('/session', method='POST', headers=[('Authorization', token)])
        print('GOOD SESSION: %s' % self.body)
        self.assertStatus(204)

        del cherrypy.session

    def test_bad_password(self):
        body = json.dumps({'username': 'test1', 'password': 'bad_pw'})

        headers = [
            ('Content-Type', 'application/json'),
            ('Content-Length', str(len(body)))
        ]

        self.getPage('/login', method='POST', body=body, headers=headers)
        pprint(json.loads(self.body))
        self.assertStatus(401)

    def test_bad_username(self):
        body = json.dumps({'username': 'bad_user', 'password': 'test1pw'})

        headers = [
            ('Content-Type', 'application/json'),
            ('Content-Length', str(len(body)))
        ]

        self.getPage('/login', method='POST', body=body, headers=headers)
        self.assertStatus(401)


text:
<!--
The MIT License (MIT)
Copyright (c) 2014 Leap Motion Inc
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
//-->

<html>
<body>

<script src = "https://js.leapmotion.com/leap-0.6.2.min.js" ></script>
<script src = "lib/three.min.js"                                  ></script>
<script src = "lib/stats.min.js"                                  ></script>
<script src = "lib/ConnectedHand.js"                              ></script>

<script>

  // Global Variables for THREE.JS
  var container , camera, scene, renderer , stats;

  // Global variable for leap
  var frame, controller;

  // Setting up how big we want the scene to be
  var sceneSize = 100;

  var leftHand , rightHand;

  // Get everything set up
  init();

  // Start the frames rolling
  animate();

  function init(){

    controller = new Leap.Controller();

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(
      50 ,
      window.innerWidth / window.innerHeight,
      sceneSize / 100 ,
      sceneSize * 4
    );

    // placing our camera position so it can see everything
    camera.position.z = sceneSize;

    // Getting the container in the right location
    container = document.createElement( 'div' );

    container.style.width      = '100%';
    container.style.height     = '100%';
    container.style.position   = 'absolute';
    container.style.top        = '0px';
    container.style.left       = '0px';
    container.style.background = '#000';

    document.body.appendChild( container );

    // Getting the stats in the right position
    stats = new Stats();

    stats.domElement.style.position  = 'absolute';
    stats.domElement.style.bottom    = '0px';
    stats.domElement.style.right     = '0px';
    stats.domElement.style.zIndex    = '999';

    document.body.appendChild( stats.domElement );

    // Setting up our Renderer
    renderer = new THREE.WebGLRenderer();

    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );

    // Making sure our renderer is always the right size
    window.addEventListener( 'resize', onWindowResize , false );

    leftHand = new ConnectedHand( controller );
    leftHand.addToScene( scene );

    rightHand = new ConnectedHand( controller );
    rightHand.addToScene( scene );

    var geo = new THREE.CubeGeometry( 1 , 1 , 1 );
    var mat = new THREE.MeshBasicMaterial({color:0xc0ffee, transparent:true,opacity:.5 });
    var jointMesh = new THREE.Mesh( geo , mat );

    var connectionMesh = new THREE.Mesh( geo , mat );

    var centerMesh = new THREE.Mesh( geo , mat );
    centerMesh.scale.x = 10;
    centerMesh.scale.z = 10;

    leftHand.createFingers( jointMesh , connectionMesh );
    leftHand.createPalm( jointMesh , connectionMesh , centerMesh );

    controller.connect();

  }

  function animate(){

    // Tells us which hand to update with
    leftHand.update( 'left' );
    rightHand.update( 'right' );

    stats.update();

    renderer.render( scene , camera );

    requestAnimationFrame( animate );

  }

  // Resets the renderer to be the proper size
  function onWindowResize(){

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

  }

</script>

</body>
</html>


text:
// Type definitions for gulp-sort
// Project: https://github.com/pgilad/gulp-sort
// Definitions by: Joe Skeen <http://github.com/joeskeen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

/// <reference path="../node/node.d.ts" />
/// <reference path="../gulp-util/gulp-util.d.ts" />

/** Sort files in stream by path or any custom sort comparator */
declare module 'gulp-sort' {

	import gulpUtil = require('gulp-util');

	interface IOptions {
		/**
		 * A function to compare two files.
		 * Returns:
		 * -1 if file1 should be before file2,
		 * 0 if file1 is equivalent to file2, and
		 * 1 if file1 should be after file2
		 */
		comparator?: IComparatorFunction;
		/** Whether to sort in ascending order, default is true */
		asc?: boolean;
	}

	interface IComparatorFunction {
		/**
		 * A function to compare two files.
		 * Returns:
		 * -1 if file1 should be before file2,
		 * 0 if file1 is equivalent to file2, and
		 * 1 if file1 should be after file2
		 */
		(file1: gulpUtil.File, file2: gulpUtil.File): number;
	}

	/** Sort files in stream by path or any custom sort comparator */
	function gulpSort(): NodeJS.ReadWriteStream;
	function gulpSort(comparator: IComparatorFunction): NodeJS.ReadWriteStream;
	function gulpSort(options: IOptions): NodeJS.ReadWriteStream;

	namespace gulpSort {}

	export = gulpSort;
}


text:
def laudRandomly(host, laudcount):
    import json, httplib
    conn = httplib.HTTPConnection(host)

    for i in range(laudcount):

        ## Get a random poem ID
        conn.request("GET", "/api/v2/poems/random")
        random_poem = conn.getresponse().read()
        random_poem_json = json.loads(random_poem)
        random_poem_id = random_poem_json['id']

        ## Laud it
        conn.request("POST", "/api/v2/poems/{}/lauds".format(random_poem_id))
        conn.getresponse().read()

    conn.close()


text:
package uk.ac.ebi.pride.archive.repo.services.file;

import uk.ac.ebi.pride.archive.dataprovider.file.ProjectFileProvider;
import uk.ac.ebi.pride.archive.dataprovider.file.ProjectFileSource;
import uk.ac.ebi.pride.archive.dataprovider.file.ProjectFileType;

/**
 * @author Jose A. Dianes
 * @version $Id$
 */
public class FileSummary implements ProjectFileProvider {

  private Long projectId;
  private Long assayId;
  private ProjectFileType fileType;
  private long fileSize;
  private ProjectFileSource fileSource;
  @Deprecated private String filePath;
  private String fileName;
  private Long id;

  public Long getProjectId() {
    return projectId;
  }

  public void setProjectId(Long projectId) {
    this.projectId = projectId;
  }

  public Long getAssayId() {
    return assayId;
  }

  public void setAssayId(Long assayId) {
    this.assayId = assayId;
  }

  public ProjectFileType getFileType() {
    return fileType;
  }

  public void setFileType(ProjectFileType fileType) {
    this.fileType = fileType;
  }

  public ProjectFileSource getFileSource() {
    return fileSource;
  }

  public void setFileSource(ProjectFileSource fileSource) {
    this.fileSource = fileSource;
  }

  public long getFileSize() {
    return fileSize;
  }

  public void setFileSize(long fileSize) {
    this.fileSize = fileSize;
  }

  @Deprecated
  public String getFilePath() {
    return filePath;
  }

  @Deprecated
  public void setFilePath(String filePath) {
    this.filePath = filePath;
  }

  public String getFileName() {
    return fileName;
  }

  public void setFileName(String fileName) {
    this.fileName = fileName;
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }
}


text:
            <button type="button" class="btn btn-default" ng-click="createProcess()" translate>
                PROCESS-LIST.ACTION.CREATE
            </button>
            <button type="button" class="btn btn-default" ng-click="importProcess()" translate>
                PROCESS-LIST.ACTION.IMPORT
            </button>

{{'PROCESS-LIST.TITLE' | translate}}

				 <input type="text" ng-model="model.pendingFilterText" class="form-control"
                               ng-change="filterDelayed()"
                               placeholder="{{'PROCESS-LIST.SEARCH-PLACEHOLDER' | translate}}">

                {{'PROCESS-LIST.FILTER.' + filter.labelKey | translate}}

                <button type="button" class="btn btn-default dropdown-toggle"
                        data-toggle="dropdown">{{'PROCESS-LIST.SORT.' + model.activeSort.labelKey | translate}} </button>

                        {{'PROCESS-LIST.SORT.' + sort.labelKey | translate}}

                 1">{{'PROCESS-LIST.FILTER.' + model.activeFilter.labelKey + '-COUNT' | translate:model.processes}}
                {{'PROCESS-LIST.FILTER.' + model.activeFilter.labelKey + '-ONE' | translate}}
                 0 && model.filterText !='' && model.filterText !== undefined">{{'PROCESS-LIST.FILTER.FILTER-TEXT' | translate:model}}
                {{'PROCESS-LIST.FILTER.FILTER-TEXT-EMPTY' | translate:model}}

                        {{'PROCESS-LIST.FILTER.PROCESSES-EMPTY' | translate}}

                    v{{process.version}}

                        <button id="detailsButton" type="button"
                                ng-click="showProcessDetails(process); $event.stopPropagation();"
                                class="btn btn-default" title="{{'PROCESS.ACTION.DETAILS' | translate}}">

                        </button>
                        <button id="editButton" type="button"
                                ng-click="editProcessDetails(process); $event.stopPropagation();"
                                class="btn btn-default" title="{{'PROCESS.ACTION.OPEN-IN-EDITOR' | translate}}">

                        </button>

                        {{process.name}}

                         {{process.createdBy}}  {{process.lastUpdated | dateformat}}

{{process.description}}

        <div class="show-more" ng-if="model.processes.data.length < model.processes.total">
            {{'PROCESSES-LIST.ACTION.SHOW-MORE' | translate}}


text:
__declspec(dllexport)
#endif
int bang();


text:
#pragma once
#include <aws/waf-regional/WAFRegional_EXPORTS.h>
#include <aws/waf-regional/WAFRegionalRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace WAFRegional
{
namespace Model
{

  /**
   */
  class AWS_WAFREGIONAL_API GetGeoMatchSetRequest : public WAFRegionalRequest
  {
  public:
    GetGeoMatchSetRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "GetGeoMatchSet"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The GeoMatchSetId of the GeoMatchSet that you want to
     * get. GeoMatchSetId is returned by CreateGeoMatchSet and by
     * ListGeoMatchSets.

     */
    inline const Aws::String& GetGeoMatchSetId() const{ return m_geoMatchSetId; }

    /**
     *
The GeoMatchSetId of the GeoMatchSet that you want to
     * get. GeoMatchSetId is returned by CreateGeoMatchSet and by
     * ListGeoMatchSets.

     */
    inline bool GeoMatchSetIdHasBeenSet() const { return m_geoMatchSetIdHasBeenSet; }

    /**
     *
The GeoMatchSetId of the GeoMatchSet that you want to
     * get. GeoMatchSetId is returned by CreateGeoMatchSet and by
     * ListGeoMatchSets.

     */
    inline void SetGeoMatchSetId(const Aws::String& value) { m_geoMatchSetIdHasBeenSet = true; m_geoMatchSetId = value; }

    /**
     *
The GeoMatchSetId of the GeoMatchSet that you want to
     * get. GeoMatchSetId is returned by CreateGeoMatchSet and by
     * ListGeoMatchSets.

     */
    inline void SetGeoMatchSetId(Aws::String&& value) { m_geoMatchSetIdHasBeenSet = true; m_geoMatchSetId = std::move(value); }

    /**
     *
The GeoMatchSetId of the GeoMatchSet that you want to
     * get. GeoMatchSetId is returned by CreateGeoMatchSet and by
     * ListGeoMatchSets.

     */
    inline void SetGeoMatchSetId(const char* value) { m_geoMatchSetIdHasBeenSet = true; m_geoMatchSetId.assign(value); }

    /**
     *
The GeoMatchSetId of the GeoMatchSet that you want to
     * get. GeoMatchSetId is returned by CreateGeoMatchSet and by
     * ListGeoMatchSets.

     */
    inline GetGeoMatchSetRequest& WithGeoMatchSetId(const Aws::String& value) { SetGeoMatchSetId(value); return *this;}

    /**
     *
The GeoMatchSetId of the GeoMatchSet that you want to
     * get. GeoMatchSetId is returned by CreateGeoMatchSet and by
     * ListGeoMatchSets.

     */
    inline GetGeoMatchSetRequest& WithGeoMatchSetId(Aws::String&& value) { SetGeoMatchSetId(std::move(value)); return *this;}

    /**
     *
The GeoMatchSetId of the GeoMatchSet that you want to
     * get. GeoMatchSetId is returned by CreateGeoMatchSet and by
     * ListGeoMatchSets.

     */
    inline GetGeoMatchSetRequest& WithGeoMatchSetId(const char* value) { SetGeoMatchSetId(value); return *this;}

  private:

    Aws::String m_geoMatchSetId;
    bool m_geoMatchSetIdHasBeenSet;
  };

} // namespace Model
} // namespace WAFRegional
} // namespace Aws


text: This class mostly adds some constants that are used in the Richards benchmarks.


text:
/*
    This file is part of web3.js.

    web3.js is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    web3.js is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with web3.js.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @file index.js
 * @author Fabian Vogelsteller <fabian@ethereum.org>
 * @date 2017
 */

"use strict";

var core = require('web3-core');
var Method = require('web3-core-method');
var utils = require('web3-utils');
var Net = require('web3-net');

var formatters = require('web3-core-helpers').formatters;

var Personal = function Personal() {
    var _this = this;

    // sets _requestmanager
    core.packageInit(this, arguments);

    this.net = new Net(this.currentProvider);

    var defaultAccount = null;
    var defaultBlock = 'latest';

    Object.defineProperty(this, 'defaultAccount', {
        get: function () {
            return defaultAccount;
        },
        set: function (val) {
            if(val) {
                defaultAccount = utils.toChecksumAddress(formatters.inputAddressFormatter(val));
            }

            // update defaultBlock
            methods.forEach(function(method) {
                method.defaultAccount = defaultAccount;
            });

            return val;
        },
        enumerable: true
    });
    Object.defineProperty(this, 'defaultBlock', {
        get: function () {
            return defaultBlock;
        },
        set: function (val) {
            defaultBlock = val;

            // update defaultBlock
            methods.forEach(function(method) {
                method.defaultBlock = defaultBlock;
            });

            return val;
        },
        enumerable: true
    });

    var methods = [
        new Method({
            name: 'getAccounts',
            call: 'personal_listAccounts',
            params: 0,
            outputFormatter: utils.toChecksumAddress
        }),
        new Method({
            name: 'newAccount',
            call: 'personal_newAccount',
            params: 1,
            inputFormatter: [null],
            outputFormatter: utils.toChecksumAddress
        }),
        new Method({
            name: 'unlockAccount',
            call: 'personal_unlockAccount',
            params: 3,
            inputFormatter: [formatters.inputAddressFormatter, null, null]
        }),
        new Method({
            name: 'lockAccount',
            call: 'personal_lockAccount',
            params: 1,
            inputFormatter: [formatters.inputAddressFormatter]
        }),
        new Method({
            name: 'importRawKey',
            call: 'personal_importRawKey',
            params: 2
        }),
        new Method({
            name: 'sendTransaction',
            call: 'personal_sendTransaction',
            params: 2,
            inputFormatter: [formatters.inputTransactionFormatter, null]
        }),
        new Method({
            name: 'sign',
            call: 'personal_sign',
            params: 3,
            inputFormatter: [formatters.inputSignFormatter, formatters.inputAddressFormatter, null]
        }),
        new Method({
            name: 'ecRecover',
            call: 'personal_ecRecover',
            params: 2,
            inputFormatter: [formatters.inputSignFormatter, null]
        })
    ];
    methods.forEach(function(method) {
        method.attachToObject(_this);
        method.setRequestManager(_this._requestManager);
        method.defaultBlock = _this.defaultBlock;
        method.defaultAccount = _this.defaultAccount;
    });
};

core.addProviders(Personal);

module.exports = Personal;


text:
This repository has some PHPunit tests embedded.
U simply can run it with the terminal commando `phpunit` if phpunit is gobally installed.

## Installing PHPunit.

They distribute a PHP Archieve (PHAR) that has all required (as well as some optional) dependencies of PHPunit
bundled in a single file.

```bash
$ wget https://phar.phpunit.de/phpunit.phar

$ chmod +x phpunit.phar

$ mv phpunit.phar /usr/local/bin/phpunit
```

You can also immediately use the PHAR after you have download it, of course:

```bash
php phpunit.phar
```

## Testing groups.

You can also test everything with specif groups.

### Example command:

```bash
$ php phpunit.phar

$ phpunit --group {group name}
```

### Groups and ther description.

| Group:              | Description:                              |
| :------------------ | :---------------------------------------- |
| `all`               | Run all the tests.                        |
| `rental`            | Run all the tests for the rental system.  |
| `backend`           | Run all the tests for the backend system. |
| `database`          | Run all the database tests.               |


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MVCFramework45.FunctionalTests.Data;
using MVCFramework45.FunctionalTests.Models;
using MVCFramework45.FunctionalTests.Services;
using FunctionalTestUtils;
using Microsoft.ApplicationInsights.Channel;

namespace MVCFramework45.FunctionalTests
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            // Set up configuration sources.
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; set; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<ITelemetryChannel>(new BackTelemetryChannel());
            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");

                // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
                try
                {
                    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                        .CreateScope())
                    {
                        serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
                             .Database.Migrate();
                    }
                }
                catch { }
            }

            app.UseStaticFiles();

            app.UseIdentity();

            // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}


text:
package opsmanager_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/pivotalservices/cfbackup/tileregistry"
	. "github.com/pivotalservices/cfbackup/tiles/opsmanager"
)

var _ = Describe("OpsManagerBuilder", func() {
	Describe("given a New() method", func() {
		Context("when called with invalid tileSpec connection credentials", func() {
			var controlTileSpec tileregistry.TileSpec
			BeforeEach(func() {
				controlTileSpec = tileregistry.TileSpec{}
			})

			It("then it should lazy load dial and NOT error", func() {
				_, err := new(OpsManagerBuilder).New(controlTileSpec)
				Ω(err).ShouldNot(HaveOccurred())
			})
		})
	})
})


text:
package org.eurekaj.manager.server.handlers;

import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.Set;

import org.apache.log4j.Logger;
import org.eurekaj.api.datatypes.AccessToken;
import org.eurekaj.api.datatypes.Session;
import org.eurekaj.api.datatypes.User;
import org.eurekaj.manager.service.*;
import org.eurekaj.manager.util.UriUtil;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.Cookie;
import org.jboss.netty.handler.codec.http.CookieDecoder;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.QueryStringDecoder;
import org.jboss.netty.util.CharsetUtil;
import org.json.JSONException;
import org.json.JSONObject;

public class EurekaJGenericChannelHandler extends SimpleChannelUpstreamHandler {
	private static Logger logger = Logger.getLogger(EurekaJGenericChannelHandler.class.getName());
	private TreeMenuService berkeleyTreeMenuService;
    private AdministrationService administrationService;
    private AccountService accountService;
    private String rootUser;

	public AdministrationService getAdministrationService() {
        if (administrationService == null) {
            administrationService = new AdministrationServiceImpl();
        }
        return administrationService;
    }

    public TreeMenuService getBerkeleyTreeMenuService() {
        if (berkeleyTreeMenuService == null) {
            berkeleyTreeMenuService = new TreeMenuServiceImpl();
        }
        return berkeleyTreeMenuService;
    }

    public AccountService getAccountService() {
        if (accountService == null) {
            accountService = new ManagerAccountService();
        }

        return accountService;
    }

    public String getRootUser() {
		if (rootUser == null) {
			rootUser = System.getProperty("montric.rootUser");
		}

		return rootUser;
	}

    public String getUri(MessageEvent e) {
    	HttpRequest request = (HttpRequest) e.getMessage();
        return request.getUri();
    }

    public String getCookieValue(MessageEvent e, String cookieName) {
    	String cookieValue = null;

    	HttpRequest request = (HttpRequest) e.getMessage();
		String value = request.getHeader("Cookie");
		logger.info("cookie header: \n" + value);
		if (value != null) {
			Set<Cookie> cookies = new CookieDecoder().decode(value);
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(cookieName)) {
					cookieValue = cookie.getValue();
					break;
				}
			}
		}

    	return cookieValue;
    }

    protected User getLoggedInUser(String cookieUuidToken) {
		User loggedInUser = null;
        Session session = getAccountService().getSession(cookieUuidToken);
        if (session != null) {
        	loggedInUser = getAccountService().getUser(session.getEmail(), session.getAccountName());
        }

        return loggedInUser;
	}

    protected boolean isUser(User user) {
    	return (user != null && (user.getUserRole().equals("user") || user.getUserRole().equals("admin")));
    }

    protected boolean isAdmin(User user) {
    	return (user != null && (user.getUserRole().equals("admin")));
    }

    protected boolean isRoot(Session session) {
    	return getRootUser() != null && session != null && session.getEmail().equals(getRootUser());
    }

    protected String getUrlId(MessageEvent e, String urlToken) {
    	HttpRequest request = (HttpRequest)e.getMessage();
    	String uri = request.getUri();
        String id = UriUtil.getIdFromUri(uri, urlToken);

        if (id != null) {
            id = id.replaceAll("\\%20", " ");
        }

        return id;
    }

    public boolean isPut(MessageEvent e) {
    	HttpRequest request = (HttpRequest) e.getMessage();
		HttpMethod method = request.getMethod();
		return method == HttpMethod.PUT;
    }

    public boolean isPost(MessageEvent e) {
    	HttpRequest request = (HttpRequest) e.getMessage();
		HttpMethod method = request.getMethod();
		return method == HttpMethod.POST;
    }

    public boolean isGet(MessageEvent e) {
    	HttpRequest request = (HttpRequest) e.getMessage();
		HttpMethod method = request.getMethod();
		return method == HttpMethod.GET;
    }

    public boolean isDelete(MessageEvent e) {
    	HttpRequest request = (HttpRequest) e.getMessage();
		HttpMethod method = request.getMethod();
		return method == HttpMethod.DELETE;
    }

    public String getHttpMessageContent(MessageEvent e) {
		String requestContent = null;
		HttpRequest request = (HttpRequest) e.getMessage();
		ChannelBuffer content = request.getContent();
        if (content.readable()) {
        	requestContent = content.toString(CharsetUtil.UTF_8);
        	logger.debug("InstrumentationMenu: \n" + requestContent);
        }
		return requestContent;
	}

    public void writeContentsToBuffer(ChannelHandlerContext ctx, String responseText, String contentType) {
		HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        response.setHeader(CONTENT_TYPE, contentType + "; charset=UTF-8");
        response.setContent(ChannelBuffers.copiedBuffer(responseText + "\r\n", CharsetUtil.UTF_8));

        // Close the connection as soon as the error message is sent.
        ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
	}

    public void write401ToBuffer(ChannelHandlerContext ctx) {
    	HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
    	ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
    }

    protected void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
        response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
        response.setContent(ChannelBuffers.copiedBuffer(
                "Failure: " + status.toString() + "\r\n",
                CharsetUtil.UTF_8));

        // Close the connection as soon as the error message is sent.
        ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
    }

    protected ChannelBuffer getFileContent(String rootPath, String path) {
        InputStream is;
        try {
            is = new FileInputStream(rootPath + path);

            if (is == null) {
                return null;
            }

            final int maxSize = 512 * 1024;
            ByteArrayOutputStream out = new ByteArrayOutputStream(maxSize);
            byte[] bytes = new byte[maxSize];

            while (true) {
                int r = is.read(bytes);
                if (r == -1) break;

                out.write(bytes, 0, r);
            }

            ChannelBuffer cb = ChannelBuffers.copiedBuffer(out.toByteArray());
            out.close();
            is.close();
            return cb;
        } catch (IOException e) {
            return null;
        }
    }

    protected String sanitizeUri(String uri) throws URISyntaxException {
        // Decode the path.
        try {
            uri = URLDecoder.decode(uri, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            try {
                uri = URLDecoder.decode(uri, "ISO-8859-1");
            } catch (UnsupportedEncodingException e1) {
                throw new Error();
            }
        }

        // Convert file separators.
        uri = uri.replace(File.separatorChar, '/');

        // Simplistic dumb security check.
        // You will have to do something serious in the production environment.
        if (uri.contains(File.separator + ".") ||
            uri.contains("." + File.separator) ||
            uri.startsWith(".") || uri.endsWith(".")) {
            return null;
        }

        QueryStringDecoder decoder = new QueryStringDecoder(uri);
        uri = decoder.getPath();

        if (uri.endsWith("/")) {
            uri += "index.html";
        }

        return uri;
    }

    public String getAccountForAccessToken(JSONObject jsonObject) throws JSONException {
    	String accountName = null;
    	String key = "accessToken";

    	//Backwards compatibility to pre-1.0
    	if (jsonObject.has("liveStatisticsToken")) {
    		key = "liveStatisticsToken";
    	}

        if (jsonObject.has(key) && jsonObject.getString(key).length() >= 16) {
        	AccessToken accessToken = getAccountService().getAccessToken(jsonObject.getString(key));
        	if (accessToken != null) {
        		accountName = accessToken.getAccountName();
        	}
        }

        return accountName;
    }
}


text:
module.exports = {
	start: function (houston, logs, port, ip) {
		var server = require("net").createServer();

		server.listen(port, ip);
		server.on("connection", function (client) {
			createContext(houston, logs, client, require("repl").start("houston> ", client).context);
		});
	}
};

function createContext(houston, logs, client, ctx) {
	for (k in houston) {
		ctx[k] = houston[k];
	}
	ctx.logs = function () {
		return Object.keys(logs);
	};
	ctx.log = function (uid) {
		return houston(uid);
	};
	ctx.exit = function () {
		client.end();
	};
}


text:
package net.iovar.web.bin.shell.task;

// local imports:
import net.iovar.parse.*;
import net.iovar.web.*;
import net.iovar.web.dev.*;
import net.iovar.web.lib.*;
import net.iovar.web.proc.*;

// java imports:
import java.io.*;
import javax.servlet.*;

// 3rd-party imports:

/**
 * Do something one or more times, conditionally.
 *
 * @author  shawn@lannocc.com
 */
public class DoWhile implements Graph, Task
{
    Task todo;
    Task condition;

    public boolean assemble (final GraphReader in) throws IOException, GraphException
    {
        if ('d' != in.peek (1)) return false;
        if ('o' != in.peek (2)) return false;

        // FIXME: would like to use Whitespace class here (add support to GraphReader?)
        if (' ' != in.peek (3) && '\t' != in.peek (3)) return false;
        in.discard (3);

        Whitespace white = new Whitespace ();
        Block block = new Block ();
        Operation op = new Operation ();

        white.assemble (in);

        if (block.assemble (in))
        {
            todo = block;
            block = new Block ();
        }
        else if (op.assemble (in))
        {
            todo = op;
            op = new Operation ();
        }
        else
        {
            throw new GraphException ("expecting block or operation to follow 'do'");
        }

        white.assemble (in);

        if ('w' != in.pop ()) throw new GraphException ("expecting 'while' to follow block or operation after 'do'");
        if ('h' != in.pop ()) throw new GraphException ("expecting 'while' to follow block or operation after 'do'");
        if ('i' != in.pop ()) throw new GraphException ("expecting 'while' to follow block or operation after 'do'");
        if ('l' != in.pop ()) throw new GraphException ("expecting 'while' to follow block or operation after 'do'");
        if ('e' != in.pop ()) throw new GraphException ("expecting 'while' to follow block or operation after 'do'");
        if (! white.assemble (in)) throw new GraphException ("expecting 'while' to follow block or operation after 'do'");

        if (block.assemble (in))
        {
            condition = block;
        }
        else if (op.assemble (in))
        {
            condition = op;
        }
        else
        {
            throw new GraphException ("expecting block or operation to follow 'while'");
        }

        return true;
    }

    public Return exec (final TaskData task) throws IOException, ServletException
    {
        // NOTE: this logic mostly copied from Group.

        final ByteArrayOutputStream out = new ByteArrayOutputStream ();
        Return r = null;

        Session shell = task.shell;

        // FIXME: does it really make sense to allow input piping here?
        InputStream in = task.in;

        do
        {
            //final Writer out2 = new OutputStreamWriter (out);
            //out2.write (shell.toString ()+'\n');
            //out2.write (shell.getEnvironment ().toString ()+'\n');
            //out2.flush ();

            Return r_old = r;

            r = todo.exec (new TaskData (shell, task.context, task.user, task.htsession, in, task.contentType, task.disposition, task.allowOrigin));
            Log.debug ("todo exec returned: "+r);
            if (r==null) r = r_old; // may be null if operation was simply variable assignment
            if (r!=null) Utils.pipe (r.data, out);

            // session may have changed after exec
            // FIXME: re-evaluate
            Log.debug ("reloading session: "+shell);
            shell = Sessions.load (task.context, task.htsession, shell.getPath ());

            in = null;
            r_old = r;

            //out2.write ("pre-condition: "+shell.toString ()+'\n');
            //out2.write (shell.getEnvironment ().toString ()+'\n');
            //out2.flush ();

            r = condition.exec (new TaskData (shell, task.context, task.user, task.htsession, in, task.contentType, task.disposition, task.allowOrigin));
            Log.debug ("condition exec returned: "+r);
            if (r==null) r = r_old; // may be null if operation was simply variable assignment
            if (r!=null) Utils.pipe (r.data, out);

            // session may have changed after exec
            // FIXME: re-evaluate
            Log.debug ("reloading session: "+shell);
            shell = Sessions.load (task.context, task.htsession, shell.getPath ());

            //out2.write ("post-condition: "+shell.toString ()+'\n');
            //out2.write (shell.getEnvironment ().toString ()+'\n');
            //out2.flush ();
        }
        while (r.status.affirmative () && shell.getExit () == 0);

        // FIXME: return the last condition's type and status (as we are), or something else instead?
        return new Return (r.type, r.disposition, r.allowOrigin, new ByteArrayInputStream (out.toByteArray()), r.status);
    }
}


text:
if [ "$1" == "purge" ]; then
    /etc/init.d/slapd stop
    apt-get purge slapd
    rm /var/lib/ldap/*
    apt-get install slapd
fi

echo =========================
echo Adding base setup schemas
echo =========================
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/ldap/schema/cosine.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/ldap/schema/inetorgperson.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/ldap/schema/nis.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f db.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f migrated-base.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f base.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f config.ldif
# This final step requires re-entry of the password specified previously.
echo Adding access control, password needed
ldapmodify -x -D cn=admin,cn=config -W -f acl.ldif

echo =========================
echo Creating a CA, and making
echo self-signed certificates
echo Passwords/phrases required
echo =========================
./makeCA.sh
./makeCertKey.sh
./copyCert.sh
ldapmodify -x -D cn=admin,cn=config -W -f certs.ldif

echo =========================
echo Configuring Samba/LDAP
echo =========================
/etc/init.d/slapd restart
echo Adding Samba schema
ldapadd -x -D cn=admin,cn=config -W -f /root/cn\=samba.ldif
./ldapconfigmodify.sh samba_indexes.ldif

echo =========================
echo Configuring smbldap-tools
echo =========================
perl /usr/share/doc/smbldap-tools/configure.pl

slapcat -l backup.ldif
echo Populating database
smbldap-populate
echo Adding admin user
smbpasswd -w %{PASSWORD}
smbpasswd -s -a admiral <<END
%{PASSWORD}
%{PASSWORD}
END
/etc/init.d/samba restart
echo Adding test_admiral user
smbldap-useradd -a -P -m test_admiral
/etc/init.d/samba restart
echo ====================================
echo Need to delete and re-add first LDAP
echo user added, as UID detection fails
echo first time round
echo ====================================
smbldap-userdel -r test_admiral
echo User test_admiral deleted

echo =========================
echo Configuring PAM/LDAP
echo =========================
auth-client-config -t nss -p lac_ldap
pam-auth-update
echo =========================================
echo pam-auth-update puts the unix and LDAP
echo lines in common-auth the wrong way round!
echo =========================================
cp common-auth /etc/pam.d/common-auth
cp etcldap.conf /etc/ldap.conf
echo "/etc/pam.d/common-auth and /etc/ldap.conf updated"

/etc/init.d/samba restart


text:
ActiveRecord::Schema.define(version: 20140530053214) do

  create_table "activities", force: true do |t|
    t.text     "note"
    t.integer  "ticket_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "duration"
    t.integer  "user_id"
    t.integer  "type_id"
  end

  add_index "activities", ["ticket_id"], name: "index_activities_on_ticket_id"
  add_index "activities", ["type_id"], name: "index_activities_on_type_id"

  create_table "activity_types", force: true do |t|
    t.string   "typename"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "states", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "tickets", force: true do |t|
    t.string   "subject"
    t.text     "description"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "owner_id"
    t.integer  "urgency"
    t.integer  "type_id"
    t.integer  "user_id"
    t.integer  "state_id"
  end

  add_index "tickets", ["owner_id"], name: "index_tickets_on_owner_id"
  add_index "tickets", ["state_id"], name: "index_tickets_on_state_id"
  add_index "tickets", ["type_id"], name: "index_tickets_on_type_id"
  add_index "tickets", ["user_id"], name: "index_tickets_on_user_id"

  create_table "types", force: true do |t|
    t.string   "typename"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "username"
    t.string   "short_name"
    t.integer  "access_level"
    t.string   "first_name"
    t.string   "last_name"
    t.string   "phone"
    t.text     "comments"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end


text:
module InstanceValue

  class << self

    private

    def included(mod)
      mod.extend ClassMethods
    end

  end

end