text:
package net.xby1993.common.dao;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.Transient;

import net.xby1993.common.util.ReflectionUtils;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.sql.JoinType;
import org.hibernate.transform.ResultTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.util.Assert;

@SuppressWarnings("unchecked")
public class HibernateServiceBi<T extends BaseEntity, PK extends Serializable> {
	private Logger log=LoggerFactory.getLogger(HibernateServiceBi.class);

	@Autowired
	private SessionFactory sessionFactory;
	@Autowired
	protected JdbcTemplate jdbcTemplate;

	private HibernateTemplate template;

	private Class<T> entityClass;

	public HibernateServiceBi() {
		ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
		entityClass = (Class<T>) type.getActualTypeArguments()[0];
	}

	protected Session getSession() {
		Session s=null;
		try {
			s=sessionFactory.getCurrentSession();
		} catch (HibernateException e) {
			s=sessionFactory.openSession();
		}
		return s;
	}
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public HibernateTemplate getTemplate(){
		if(template==null){
			synchronized(this){
				if(template==null){
					template=new HibernateTemplate(sessionFactory);
				}
			}
		}
		return template;
	}

	public void save(final T... entitys){
		Assert.notNull(entitys, "entity不能为空");
		getTemplate().executeWithNativeSession(new HibernateCallback<Void>() {
			@Override
			public Void doInHibernate(Session paramSession)
					throws HibernateException {
				for(T t:entitys){
					if(t.getInsertTime()==null)
					{
						t.setInsertTime(new Date());
						t.setUpdateTime(new Date());
					}
					else
					{
						t.setUpdateTime(new Date());
					}
					paramSession.saveOrUpdate(t);
				}
				return null;
			}
		});

	}

	public void delete(final T entity) {
		Assert.notNull(entity, "entity不能为空");
		getTemplate().delete(entity);
		log.debug("delete entity: {}", entity);
	}

	public void delete(final PK... ids) {
		Assert.notNull(ids, "ids不能为空");
		getTemplate().executeWithNativeSession(new HibernateCallback<Void>() {
			@Override
			public Void doInHibernate(Session paramSession)
					throws HibernateException {
				for (PK id : ids) {
					paramSession.delete(get(id));
				}
				return null;
			}
		});
		log.debug("delete entity {},id is {}", entityClass.getSimpleName(), ids);
	}

	/**
	 * 按id获取对象.
	 */
	public T load(final PK id) {
		Assert.notNull(id, "id不能为空");
		return (T) getTemplate().load(entityClass, id);
	}

	public T get(final PK id) {
		Assert.notNull(id, "id不能为空");
		return (T) getTemplate().get(entityClass, id);
	}
	public T loadInit(final PK id) {
		Assert.notNull(id, "id不能为空");
		T res=getTemplate().executeWithNativeSession(new HibernateCallback<T>() {
			@Override
			public T doInHibernate(Session paramSession)
					throws HibernateException {
				T t=(T) paramSession.load(entityClass, id);
				autoInit(t);
				return t;
			}

		});
		return res;
	}

	public T getInit(final PK id) {
		Assert.notNull(id, "id不能为空");
		T res=getTemplate().executeWithNativeSession(new HibernateCallback<T>() {
			@Override
			public T doInHibernate(Session paramSession)
					throws HibernateException {
				T t=(T) paramSession.get(entityClass, id);
				autoInit(t);
				return t;
			}

		});
		return res;
	}
	/**
	 *	获取全部对象.
	 */
	public List<T> getAll() {
		DetachedCriteria dc=DetachedCriteria.forClass(entityClass);
		return (List<T>) getTemplate().findByCriteria(dc);
	}
	/**
	 *	获取全部对象,支持排序.
	 */
	public List<T> getAll(String orderBy, boolean isAsc) {
		DetachedCriteria dc=DetachedCriteria.forClass(entityClass);
		if(isAsc)
		{
			dc.addOrder(Order.asc(orderBy));
		}
		else
		{
			dc.addOrder(Order.desc(orderBy));
		}
		return (List<T>) getTemplate().findByCriteria(dc);
	}

	/**
	 * 按属性查找对象列表,匹配方式为相等.
	 */
	public List<T> findBy(final String propertyName, final Object value) {
		Assert.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = Restrictions.eq(propertyName, value);
		DetachedCriteria dc=DetachedCriteria.forClass(entityClass);
		dc.add(criterion);
		return (List<T>) getTemplate().findByCriteria(dc);
	}
	public List<T> findByInit(final String propertyName, final Object value) {
		List<T> list=getTemplate().executeWithNativeSession(new HibernateCallback<List<T>>() {

			@Override
			public List<T> doInHibernate(Session paramSession)
					throws HibernateException {
				Criterion criterion = Restrictions.eq(propertyName, value);
				Criteria c=paramSession.createCriteria(entityClass).add(criterion);
				List<T> list=c.list();
				if(list!=null){
					for(T o:list){
						autoInit(o);
					}
				}
				return list;
			}
		});
		return list;
	}

	/**
	 * 按id列表获取对象.
	 */
	public List<T> findByIds(List<PK> ids) {
		DetachedCriteria dc=DetachedCriteria.forClass(entityClass).add(Restrictions.in(getIdName(), ids));
		return (List<T>) getTemplate().findByCriteria(dc);
	}

	/**
	 * 按HQL查询对象列表.
	 *
	 * @param values 数量可变的参数,按顺序绑定.
	 */
	public <X> List<X> find(final String hql, final Object... values) {
		return getTemplate().executeWithNativeSession(new HibernateCallback<List<X>>() {
			@Override
			public List<X> doInHibernate(Session paramSession)
					throws HibernateException {
				return createQuery(paramSession,hql, values).list();
			}
		});
	}

	/**
	 * 按HQL查询对象列表.
	 *
	 * @param values 命名参数,按名称绑定.
	 */
	public <X> List<X> find(final String hql, final Map<String, ?> values) {
		return getTemplate().executeWithNativeSession(new HibernateCallback<List<X>>() {
			@Override
			public List<X> doInHibernate(Session paramSession)
					throws HibernateException {
				return createQuery(paramSession,hql, values).list();
			}
		});
	}

	/**
	 * 执行HQL进行批量修改/删除操作.
	 */
	public int batchExecute(final String hql, final Object... values) {
		return getTemplate().executeWithNativeSession(new HibernateCallback<Integer>() {
			@Override
			public Integer doInHibernate(Session paramSession)
					throws HibernateException {
				return createQuery(paramSession,hql, values).executeUpdate();
			}
		});
	}

	/**
	 * 执行HQL进行批量修改/删除操作.
	 * @return 更新记录数.
	 */
	public int batchExecute(final String hql, final Map<String, ?> values) {
		return getTemplate().executeWithNativeSession(new HibernateCallback<Integer>() {
			@Override
			public Integer doInHibernate(Session paramSession)
					throws HibernateException {
				return createQuery(paramSession,hql, values).executeUpdate();
			}
		});
	}
	public void executeSql(final String sqlString, final Object... values) {
		getTemplate().executeWithNativeSession(new HibernateCallback<Void>() {

			@Override
			public Void doInHibernate(Session paramSession)
					throws HibernateException {
				Query query = paramSession.createSQLQuery(sqlString);
		        if (values != null)
		        {
		            for (int i = 0; i < values.length; i++)
		            {
		                query.setParameter(i, values[i]);
		            }
		        }
		        query.executeUpdate();
		        return null;
			}
		});

    }
	public List<T> findBySql(final String sqlString, final Object... values) {
		return getTemplate().executeWithNativeSession(new HibernateCallback<List<T>>() {
			@Override
			public List<T> doInHibernate(Session paramSession)
					throws HibernateException {
				SQLQuery query = paramSession.createSQLQuery(sqlString);
		        if (values != null)
		        {
		            for (int i = 0; i < values.length; i++)
		            {
		                query.setParameter(i, values[i]);
		            }
		        }
		        query.addEntity(entityClass);
		        return query.list();
			}
		});

	}

	/**
	 * 根据查询HQL与参数列表创建Query对象.
	 *
	 * 本类封装的find()函数全部默认返回对象类型为T,当不为T时使用本函数.
	 *
	 * @param values 数量可变的参数,按顺序绑定.
	 */
	private Query createQuery(Session session, final String queryString, final Object... values) {
		Assert.hasText(queryString, "queryString不能为空");
		Query query = session.createQuery(queryString);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}
		return query;
	}

	/**
	 * 根据查询HQL与参数列表创建Query对象.
	 *
	 * @param values 命名参数,按名称绑定.
	 */
	private Query createQuery(Session session, final String queryString, final Map<String, ?> values) {
		Assert.hasText(queryString, "queryString不能为空");
		Query query = session.createQuery(queryString);
		if (values != null) {
			query.setProperties(values);
		}
		return query;
	}

	/**
	 * 按Criteria查询对象列表.
	 *
	 * @param criterions 数量可变的Criterion.
	 */
	public List<T> find(final List<Criterion> criterions,final String[] aliasNames,final List<Order> orders) {

		return getTemplate().executeWithNativeSession(new HibernateCallback<List<T>>() {
			@Override
			public List<T> doInHibernate(Session paramSession)
					throws HibernateException {
				return createCriteria(paramSession,criterions,orders,aliasNames).list();
			}
		});
	}
	public List<T> findInit(final List<Criterion> criterions,final String[] aliasNames,final List<Order> orders) {
		return getTemplate().executeWithNativeSession(new HibernateCallback<List<T>>() {
			@Override
			public List<T> doInHibernate(Session paramSession)
					throws HibernateException {
				List<T> list= createCriteria(paramSession,criterions,orders,aliasNames).list();
				if(list!=null){
					for(T t:list){
						autoInit(t);
					}
				}
				return list;
			}
		});
	}
	public List<T> find(DetachedCriteria dc){
		return (List<T>) getTemplate().findByCriteria(dc);
	}

	/**
	 * 分组查询///
	 */
	public List<Object> find(final List<Criterion> criterions,final String[] aliasNames,final List<Order> orders,	final ProjectionList pList) {

		//pList.add(Projections.property("firm.name"));
		//pList.add(Projections.groupProperty(group));
		return getTemplate().executeWithNativeSession(new HibernateCallback<List<Object>>() {
			@Override
			public List<Object> doInHibernate(Session paramSession)
					throws HibernateException {
				return createCriteria(paramSession,criterions,orders,aliasNames).setProjection(pList).list();
			}
		});
	}

	/**
	 * 按Criteria查询唯一对象.
	 *
	 * @param criterions 数量可变的Criterion.
	 */
	public T findUnique(final List<Criterion> criterions,final String[] aliasNames) {
		return getTemplate().executeWithNativeSession(new HibernateCallback<T>() {
			@Override
			public T doInHibernate(Session paramSession)
					throws HibernateException {
				return (T) createCriteria(paramSession,criterions,null,aliasNames).uniqueResult();
			}
		});
	}
	public T findUniqueInit(final List<Criterion> criterions,final String[] aliasNames) {
		return getTemplate().executeWithNativeSession(new HibernateCallback<T>() {
			@Override
			public T doInHibernate(Session paramSession)
					throws HibernateException {
				T tt=(T) createCriteria(paramSession,criterions,null,aliasNames).uniqueResult();
				autoInit(tt);
				return tt;
			}
		});
	}
	/**
	 * 根据Criterion条件创建Criteria.
	 *
	 * 本类封装的find()函数全部默认返回对象类型为T,当不为T时使用本函数.
	 *
	 * @param criterions 数量可变的Criterion.
	 */
	public Criteria createCriteria(Session session,final List<Criterion> criterions,final List<Order> orders,final String[] aliasNames) {
		Criteria criteria = session.createCriteria(entityClass);

		if(criterions!=null)
		{
			for (Criterion c : criterions) {
				criteria.add(c);
			}
		}
		if(aliasNames!=null)
		{
			for (String alias : aliasNames)
			{
				String alias2 = alias;
				if(alias.indexOf(".")>0)
				{
					int size = alias.split("\\.").length;
					alias2 = alias.split("\\.")[size-1];

				}

				criteria.createAlias(alias, alias2,JoinType.LEFT_OUTER_JOIN);

			}
		}
		if(orders!=null)
		{
			for (Order order : orders)
			{
				criteria.addOrder(order);
			}
		}
		else
		{
			criteria.addOrder(Order.desc("insertTime"));
		}

		return criteria;
	}

	/**
	 * 初始化对象.
	 * 只初始化entity的直接属性,但不会初始化延迟加载的关联集合和属性.
	 * 如需初始化关联属性,可实现新的函数,执行:
	 * Hibernate.initialize(user.getRoles()),初始化User的直接属性和关联集合.
	 * Hibernate.initialize(user.getDescription()),初始化User的直接属性和延迟加载的Description属性.
	 */
	public void initEntity(T... entityList) {
		for (T entity : entityList) {
			Hibernate.initialize(entity);
		}
	}

	/**
	 * Flush当前Session.
	 */
	public void flush() {
		getSession().flush();
	}

	/**
	 * 取得对象的主键名.
	 */
	public String getIdName() {
		ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
		return meta.getIdentifierPropertyName();
	}

	/**
	 * 按HQL分页查询.
	 *
	 * @param page 分页参数.不支持其中的orderBy参数.
	 * @param hql hql语句.
	 * @param pageNo 当前页数.
	 * @param pageSize 总页数.
	 * @param values 数量可变的查询参数,按顺序绑定.
	 * @return 分页查询结果, 附带结果列表及所有查询时的参数.
	 */
	@SuppressWarnings("unchecked")
	public Page<T> findPage(final String hql,final int pageNo,final int pageSize, final Object... values) {

		return getTemplate().executeWithNativeSession(new HibernateCallback<Page<T>>() {
			@Override
			public Page<T> doInHibernate(Session paramSession)
					throws HibernateException {
				Query q = createQuery(paramSession,hql, values);

				Page<T> page = new Page<T>();

				page.setPageNo(pageNo);
				page.setPageSize(pageSize);

				long totalCount = countHqlResult(hql, values);
				page.setTotalCount((int)totalCount);

				int start = ((pageNo - 1) * pageSize);
				q.setFirstResult(start);
				q.setMaxResults(pageSize);

				List result = q.list();
				page.setResult(result);
				return page;
			}
		});
	}

	/**
	 * 按HQL分页查询.
	 *
	 * @param page 分页参数.
	 * @param hql hql语句.
	 * @param values 命名参数,按名称绑定.
	 * @param pageNo 当前页数.
	 * @param pageSize 总页数.
	 * @return 分页查询结果, 附带结果列表及所有查询时的参数.
	 */
	@SuppressWarnings("unchecked")
	public Page<T> findPage(final String hql,final int pageNo,final int pageSize, final Map<String, ?> values) {

		return getTemplate().executeWithNativeSession(new HibernateCallback<Page<T>>() {
			@Override
			public Page<T> doInHibernate(Session paramSession)
					throws HibernateException {
				Query q = createQuery(paramSession,hql, values);
				Page<T> page = new Page<T>();

				page.setPageNo(pageNo);
				page.setPageSize(pageSize);
				long totalCount = countHqlResult(hql, values);
				page.setTotalCount((int)totalCount);

				int start = ((pageNo - 1) * pageSize);
				q.setFirstResult(start);
				q.setMaxResults(pageSize);

				List result = q.list();
				page.setResult(result);
				return page;
			}
		});
	}

	/**
	 * @param criterions 数量可变的Criterion
	 * @param orders 数量可变的Order
	 * @param pageNo 当前页数
	 * @param pageSize 总页数
	 * @param aliasNames 别名,用于多表关联查询
	 * @return 分页查询结果.附带结果列表及所有查询时的参数.
	 */
	public Page<T> findPage( final List<Criterion> criterions,final List<Order> orders, final int pageNo,final int pageSize,final String[] aliasNames) {
		return getTemplate().executeWithNativeSession(new HibernateCallback<Page<T>>() {
			@Override
			public Page<T> doInHibernate(Session paramSession)
					throws HibernateException {
				Criteria c = createCriteria(paramSession,criterions,orders,aliasNames);
				return findPage(c,pageNo,pageSize);
			}
		});
	}
	public Page<T> findPageInit( final List<Criterion> criterions,final List<Order> orders, final int pageNo,final int pageSize,final String[] aliasNames) {
		return getTemplate().executeWithNativeSession(new HibernateCallback<Page<T>>() {
			@Override
			public Page<T> doInHibernate(Session paramSession)
					throws HibernateException {
				Criteria c = createCriteria(paramSession,criterions,orders,aliasNames);
				Page<T> page= findPage(c,pageNo,pageSize);
				if(page.getResult()!=null){
					for(T t:page.getResult()){
						autoInit(t);
					}
				}
				return page;
			}
		});
	}
	public Page<T> findPage(final DetachedCriteria dc,final int pageNo,final int pageSize){
		return getTemplate().executeWithNativeSession(new HibernateCallback<Page<T>>() {
			@Override
			public Page<T> doInHibernate(Session paramSession)
					throws HibernateException {
				Criteria c=dc.getExecutableCriteria(paramSession);
				return findPage(c, pageNo, pageSize);
			}
		});
	}
	protected Page<T> findPage(Criteria c,int pageNo,int pageSize ){
		Page<T> page = new Page<T>();

		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		int totalCount = countCriteriaResult(c);
		page.setTotalCount(totalCount);

		int start = ((pageNo - 1) * pageSize);
		c.setFirstResult(start);
		c.setMaxResults(pageSize);

		List result = c.list();
		page.setResult(result);
		return page;
	}

	/**
	 * 根据搜索条件查询前几条记录
	 * @param criterions 数量可变的Criterion
	 * @param orders 数量可变的Order
	 * @param topCount 前几条记录
	 * @param aliasNames 别名,用于多表关联查询
	 * @return 列表集合
	 */
	public List<T> findTopList(final List<Criterion> criterions,final String[] aliasNames,final List<Order> orders, final int topCount)
	{

		return getTemplate().executeWithNativeSession(new HibernateCallback<List<T>>() {
			@Override
			public List<T> doInHibernate(Session paramSession)
					throws HibernateException {
				Criteria c = createCriteria(paramSession,criterions,orders,aliasNames);
				c.setFirstResult(0);
				c.setMaxResults(topCount);

				List<T> result = c.list();
				return result;
			}
		});
	}
	public List<T> findTopListInit(final List<Criterion> criterions,final String[] aliasNames,final List<Order> orders, final int topCount)
	{
		return getTemplate().executeWithNativeSession(new HibernateCallback<List<T>>() {
			@Override
			public List<T> doInHibernate(Session paramSession)
					throws HibernateException {
				Criteria c = createCriteria(paramSession,criterions,orders,aliasNames);
				c.setFirstResult(0);
				c.setMaxResults(topCount);

				List<T> result = c.list();
				if(result!=null){
					for(T t:result){
						autoInit(t);
					}
				}
				return result;
			}
		});
	}

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 *
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 */
	public long countHqlResult(final String hql, final Object... values) {
		String fromHql = hql;
		//select子句与order by子句会影响count查询,进行简单的排除.
		fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
		fromHql = StringUtils.substringBefore(fromHql, "order by");

		String countHql = "select count(*) " + fromHql;

		try {
			Long count = (Long) find(countHql, values).get(0);
			return count;
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
		}
	}

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 *
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 */
	public long countHqlResult(final String hql, final Map<String, ?> values) {
		String fromHql = hql;
		//select子句与order by子句会影响count查询,进行简单的排除.
		fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
		fromHql = StringUtils.substringBefore(fromHql, "order by");

		String countHql = "select count(*) " + fromHql;

		try {
			Long count = (Long) find(countHql, values).get(0);
			return count;
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
		}
	}

	/**
	 * 执行count查询获得本次Criteria查询所能获得的对象总数.
	 */
	@SuppressWarnings("unchecked")
	protected int countCriteriaResult(final Criteria c) {
		CriteriaImpl impl = (CriteriaImpl) c;

		// 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
		Projection projection = impl.getProjection();
		ResultTransformer transformer = impl.getResultTransformer();

		List<CriteriaImpl.OrderEntry> orderEntries = null;
		try {
			orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries");
			ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());
		} catch (Exception e) {
			log.error("不可能抛出的异常:{}", e.getMessage());
		}

		// 执行Count查询
		Object tmp = c.setProjection(Projections.count("id")).uniqueResult();
		int totalCount = Integer.valueOf(tmp == null ? "-1" : tmp.toString());

		// 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
		c.setProjection(projection);

		if (projection == null) {
			c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		}
		if (transformer != null) {
			c.setResultTransformer(transformer);
		}
		try {
			ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
		} catch (Exception e) {
			log.error("不可能抛出的异常:{}", e.getMessage());
		}

		return totalCount;
	}

  public Integer getCount(final List<Criterion> criterions,final String[] aliasNames){

	  return getTemplate().executeWithNativeSession(new HibernateCallback<Integer>() {

		@Override
		public Integer doInHibernate(Session paramSession)
				throws HibernateException {
			Criteria c = createCriteria(paramSession,criterions,null,aliasNames);
			return countCriteriaResult(c);
		}
	});
  }

  public Integer getCount(final DetachedCriteria detachedCriteria) {
      // 设置记录数投影
      detachedCriteria.setProjection(Projections.rowCount());
      List<Long> list = (List<Long>) this.getTemplate().findByCriteria(detachedCriteria);
      // 将投影置为空
      detachedCriteria.setProjection(null);
      if (list.size() > 0) {
          return list.get(0).intValue();
      }
      return -1;
  }

	public boolean isPropertyExists(final String propertyName, final Object newValue) {
		List<T> list = findBy(propertyName, newValue);
		return (list != null && list.size()>0);
	}

	public void autoInit(T entity){
		if(entity==null){
			return;
		}
		Hibernate.initialize(entity);

		Class<?> clazz=entity.getClass();
		List<Field> fslist=new ArrayList<Field>();
		for(Class superClass=clazz;superClass!=Object.class;superClass=superClass.getSuperclass()){
			Field[] fs=superClass.getDeclaredFields();
			for(Field f:fs){
				fslist.add(f);
			}
		}
		for(Field f:fslist){
			if(f.isSynthetic()){
				continue;
			}
			Class<?> clz = f.getType();
			String name = f.getName();
			if (clz.isPrimitive() || (!BaseEntity.class.isAssignableFrom(clz))) {
				continue;
			}
			try {
				Method m = clazz.getMethod("get" + StringUtils.capitalize(name));
				Transient t1=m.getAnnotation(Transient.class);
				if(t1==null){
					Object obj = m.invoke(entity);
					Hibernate.initialize(obj);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}


text:
package com.franmontiel.localechanger.utils;

import android.os.Build;
import android.os.LocaleList;
import androidx.annotation.RequiresApi;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

/**
 * A class useful to retrieve the system configured Locales.
 */
public class SystemLocaleRetriever {

    private SystemLocaleRetriever() {
    }

    public static List<Locale> retrieve() {
        List<Locale> systemLocales;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            systemLocales = mapToListOfLocales(LocaleList.getDefault());
        } else {
            systemLocales = Collections.singletonList(Locale.getDefault());
        }
        return systemLocales;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private static List<Locale> mapToListOfLocales(LocaleList localeList) {
        List<Locale> locales = new ArrayList<>();
        for (int i = 0; i < localeList.size(); i++) {
            locales.add(localeList.get(i));
        }
        return locales;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import {Component, Inject, OnInit} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material';

@Component({
  selector: 'app-user-quiz-hint-popup',
  templateUrl: './quiz-hint-popup.component.html',
  styleUrls: ['./quiz-hint-popup.component.css']
})
export class UserQuizHintPopupComponent implements OnInit {

  constructor(public dialogRef: MatDialogRef<UserQuizHintPopupComponent>,@Inject(MAT_DIALOG_DATA) public data: any) { }

  ngOnInit() {
  }

}


text:
package nl.hanze.t23i.gamemodule.extern.tictactoe;

public enum PlayerType {
    NONE(' '), PLAYER_ONE('X'), PLAYER_TWO('O');

    public final char symbol;

    PlayerType(char symbol) {
        this.symbol = symbol;
    }
}


text:
namespace dvu
{
	enum class depth_func : unsigned int
	{
		never,
		less,
		equal,
		less_equal,
		greater,
		not_equal,
		greater_equal,
		always
	};

	class render_device
	{
	public:
		virtual void swap() const = 0;
		virtual void clear(bool color, bool depth, bool stencil) const = 0;
		virtual void draw_triangles(int offset, int count) const = 0;

		virtual void set_depth_test(bool enabled) const = 0;
		virtual void set_blending(bool enabled) const = 0;
		virtual void set_clear_color(color_rgba color) const = 0;
		virtual void set_depth_func(depth_func func) const = 0;
		virtual const window* get_window() const = 0;
		virtual void set_pixel_unpack_alignment(int alignment) const = 0;
	};
};


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="GameScreen">
        <attr name="screenIsRectangle" format="boolean" />
    </declare-styleable>
</resources>


text:
#region Licence
// The MIT License (MIT)
//
// Copyright (c) 2013 Eric Ruan
//
// 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.
#endregion

using System;

namespace cmstar.Serialization.Json
{
    public static class JsonContractErrors
    {
        public static JsonContractException UnexpectedToken(JsonToken expected, JsonToken actual)
        {
            var msg = string.Format(
                "Unexpected token, {0} expected, but was {1}.",
                expected, actual);
            return new JsonContractException(msg);
        }

        public static JsonContractException UnexpectedToken(JsonToken actual)
        {
            var msg = string.Format("Unexpected token: {0}.", actual);
            return new JsonContractException(msg);
        }

        public static JsonContractException CannotCreateInstance(Type type, Exception innerException)
        {
            var msg = string.Format("Cannot create an instance of type {0}", type);
            return new JsonContractException(msg, innerException);
        }

        public static JsonContractException NullValueNotSupported()
        {
            var msg = "Null values are not supported in the contract.";
            return new JsonContractException(msg);
        }

        public static JsonContractException TypeNotSupported(Type type)
        {
            var msg = string.Format("The type {0} is not supported by the contract.", type);
            return new JsonContractException(msg);
        }

        public static JsonContractException CannotConverType(object value, Type targetType, Exception innException)
        {
            string valueDescription;
            if (value == null)
            {
                valueDescription = "<null>";
            }
            else
            {
                var type = value.GetType();
                var typeCode = Type.GetTypeCode(type);
                switch (typeCode)
                {
                    case TypeCode.String:
                        valueDescription = string.Concat("'", (string)value, "'");
                        break;

                    case TypeCode.Double:
                        valueDescription = "number " + value;
                        break;

                    case TypeCode.Object:
                        valueDescription = "<object>";
                        break;

                    default:
                        valueDescription = string.Format("{0} ({1})", value, type);
                        break;
                }
            }

            var msg = string.Format("Can not cast {0} to type {1}.", valueDescription, targetType);
            return new JsonContractException(msg, innException);
        }
    }
}


text:
set -e
REPO_ROOT=$(git rev-parse --show-toplevel)

rm -rf /tmp/tests
mkdir /tmp/tests

cp -r $REPO_ROOT/invoker/conformance /tmp/tests

cd $REPO_ROOT/invoker
mvn versions:set -DnewVersion=0.0.0-SNAPSHOT -DprocessAllModules=true
mvn install -Dmaven.repo.local=/tmp/tests/conformance/artifacts

cd $REPO_ROOT/functions-framework-api
mvn versions:set -DnewVersion=0.0.0-SNAPSHOT -DprocessAllModules=true
mvn install -Dmaven.repo.local=/tmp/tests/conformance/artifacts

rm /tmp/tests/conformance/pom.xml
mv /tmp/tests/conformance/buildpack_pom.xml /tmp/tests/conformance/pom.xml


text:
package com.epimorphics.server.webapi.dsapi;

import static com.epimorphics.server.webapi.dsapi.JSONConstants.*;

import com.epimorphics.rdfutil.RDFUtil;
import com.epimorphics.server.general.PrefixService;
import com.epimorphics.server.webapi.marshalling.JSFullWriter;
import com.hp.hpl.jena.rdf.model.Resource;

/**
 * Range used to report hierarchical values. Points to an API
 * which through which the scheme or collection can be browsed.
 *
 * @author Dave Reynolds
 */

// TODO this example shows that range reporting and range filtering out to be separated

public class RangeHierarchyTop extends Range {
    protected String id;
    protected String label;
    protected String description;
    protected String api;

    public RangeHierarchyTop(Resource codelist, DSAPI dsapi) {
        this.id = PrefixService.get().getResourceID(codelist);
        this.label = RDFUtil.getLabel(codelist);
        this.description = RDFUtil.getDescription(codelist);
        api = dsapi.getMan().getApiBase() + "/codelist/" + id;
    }

    @Override
    public void writeTo(JSFullWriter out) {
        out.startObject();
        out.pair(ID, id);
        out.pair(LABEL, label);
        out.pair(DESCRIPTION, description);
        out.pair(API, api);
        out.finishObject();
    }

}


text:
package com.woorea.openstack.examples.compute;

import com.woorea.openstack.examples.ExamplesConfiguration;
import com.woorea.openstack.keystone.Keystone;
import com.woorea.openstack.keystone.model.Access;
import com.woorea.openstack.keystone.model.Tenants;
import com.woorea.openstack.keystone.model.authentication.TokenAuthentication;
import com.woorea.openstack.keystone.model.authentication.UsernamePassword;
import com.woorea.openstack.nova.Nova;
import com.woorea.openstack.nova.model.Flavor;
import com.woorea.openstack.nova.model.Flavors;

public class NovaListFlavors {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Keystone keystone = new Keystone(ExamplesConfiguration.KEYSTONE_AUTH_URL);
		Access access = keystone.tokens().authenticate(
				new UsernamePassword(ExamplesConfiguration.KEYSTONE_USERNAME, ExamplesConfiguration.KEYSTONE_PASSWORD))
				.execute();

		//use the token in the following requests
		keystone.token(access.getToken().getId());

		Tenants tenants = keystone.tenants().list().execute();

		//try to exchange token using the first tenant
		if(tenants.getList().size() > 0) {

			access = keystone.tokens().authenticate(new TokenAuthentication(access.getToken().getId())).withTenantId(tenants.getList().get(0).getId()).execute();

			//NovaClient novaClient = new NovaClient(KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "compute", null, "public"), access.getToken().getId());
			Nova novaClient = new Nova(ExamplesConfiguration.NOVA_ENDPOINT.concat("/").concat(tenants.getList().get(0).getId()));
			novaClient.token(access.getToken().getId());
			//novaClient.enableLogging(Logger.getLogger("nova"), 100 * 1024);

			Flavors flavors = novaClient.flavors().list(true).execute();
			for(Flavor flavor : flavors) {
				System.out.println(flavor);
			}

		} else {
			System.out.println("No tenants found!");
		}

	}

}


text:
  background: #ffffff;
}

#toolbar {
  display:none;
}

#welcome {
  background: url('/logo.png') no-repeat right top;
  margin-right: 50px;
}


text:
#ifndef ALIGENMUONCOCKTAILPP_H
#define ALIGENMUONCOCKTAILPP_H

//
// Class to create the coktail for physics with muons for pp collisions
// using the The followoing sources:
// jpsi, psiP, upsilon, upsilonP, upsilonPP, open charm and open beauty
//

#include "AliGenCocktail.h"
#include "AliDecayer.h"

class AliGenCocktailEntry;
class AliGenParam;

class AliGenMUONCocktailpp : public AliGenCocktail
{
 public:

    AliGenMUONCocktailpp();
    enum CMSEnergyCode { kCMS07TeV, kCMS10TeV, kCMS14TeV, kCMS03TeVpPb, kCMS03TeVPbp, kCMS04TeVpPb, kCMS04TeVPbp, kCMS05TeVpPb, kCMS05TeVPbp, kCMS09TeVpPb, kCMS09TeVPbp, kCMS03TeVPbPb, kNCMSEs };

    virtual ~AliGenMUONCocktailpp();
    virtual void Init();
    virtual void CreateCocktail();
    virtual void Generate();
    Int_t   GetNSucceded()         const {return fNSucceded;}
    Int_t   GetNGenerated()        const {return fNGenerated;}
    Int_t   GetCentralityBin()     const {return fCentralityBin;}
    Int_t   GetMuonMultiplicity()  const {return fMuonMultiplicity;}
    Float_t GetMuonPtCut()         const {return fMuonPtCut;}
    Float_t GetMuonPCut()          const {return fMuonPCut;}
    Float_t GetMuonThetaMin()      const {return fMuonThetaMinCut;}
    Float_t GetMuonThetaMax()      const {return fMuonThetaMaxCut;}
    Float_t GetMuonOriginCut()     const {return fMuonOriginCut;}
    Float_t GetDecayModeResonance()const {return fDecayModeResonance;}
    Float_t GetDecayModePythia()   const {return fDecayModePythia;}

    void    SetCentralityBin(Int_t bin) { fCentralityBin = bin;}
    void    SetMuonMultiplicity(Int_t MuonMultiplicity) { fMuonMultiplicity = MuonMultiplicity;}
    void    SetMuonPtCut(Float_t PtCut) { fMuonPtCut = PtCut;}
    void    SetMuonPCut(Float_t PCut) { fMuonPCut = PCut;}
    void    SetMuonOriginCut(Float_t originCut) { fMuonOriginCut = originCut;}
    void    SetMuonThetaRange(Float_t ThetaMin, Float_t ThetaMax){
	fMuonThetaMinCut=ThetaMin;
	fMuonThetaMaxCut=ThetaMax; }
    void    SetDecayer(AliDecayer* const decayer){fDecayer = decayer;}
    void    SetDecayModeResonance(Decay_t decay){ fDecayModeResonance = decay;}
    void    SetDecayModePythia(Decay_t decay){ fDecayModePythia = decay;}
    void    SetResPolarization(Double_t JpsiPol, Double_t PsiPPol, Double_t UpsPol,
    				Double_t UpsPPol, Double_t UpsPPPol, char *PolFrame);

    void    SetCMSEnergy(CMSEnergyCode cmsEnergy);
    void    SetSigmaSilent() { fSigmaSilent = kTRUE; }

    void    ScaleJPsi(Double_t sc) { fScaleJPsi = sc;}
    void    ScaleCharmonia(Double_t sc) { fScaleCharmonia = sc;}
    void    ScaleBottomonia(Double_t sc) { fScaleBottomonia = sc;}
    void    ScaleCCbar(Double_t sc) { fScaleCCbar = sc;}
    void    ScaleBBbar(Double_t sc) { fScaleBBbar = sc;}

 protected:

    //
 private:
    AliGenMUONCocktailpp(const AliGenMUONCocktailpp &cocktail);
    AliGenMUONCocktailpp & operator=(const AliGenMUONCocktailpp &cocktail);

    void AddReso2Generator(Char_t *nameReso, AliGenParam* const genReso, Double_t sigmaReso, Double_t polReso);

    AliDecayer* fDecayer; // External decayer
    Decay_t fDecayModeResonance; //decay mode in which resonances are forced to decay, default: kAll
    Decay_t fDecayModePythia; //decay mode in which particles in Pythia are forced to decay, default: kAll
    Int_t   fMuonMultiplicity; // Muon multiplicity for the primordial trigger
    Float_t fMuonPtCut;// Transverse momentum cut for muons
    Float_t fMuonPCut;// Momentum cut for muons
    Float_t fMuonThetaMinCut;// Minimum theta cut for muons
    Float_t fMuonThetaMaxCut; // Maximum theta cut for muons
    Float_t fMuonOriginCut; //use only muons whose "part->Vz()" value is larger than fMuonOrigin
    Int_t   fNSucceded;// Number of Succes in the (di)-muon generation in the acceptance
    Int_t   fNGenerated;// Number of generated cocktails
    Int_t   fCentralityBin;                 // Collision centrality bin number
    Double_t fScaleJPsi;                    // xsec scale factors for onia and HF
    Double_t fScaleCharmonia;
    Double_t fScaleBottomonia;
    Double_t fScaleCCbar;
    Double_t fScaleBBbar;
    Double_t fJpsiPol, fChic1Pol, fChic2Pol, fPsiPPol, fUpsPol, fUpsPPol, fUpsPPPol;//Resonances polarization parameters
    Int_t    fPolFrame;//Resonances polarization frame (Collins-Soper / Helicity)
//    Int_t fCMSEnergy; // CMS beam energy

    Double_t fCMSEnergyTeV;                 // energy
    Double_t fCMSEnergyTeVArray[kNCMSEs];   //!
    Double_t fSigmaReaction;                // xsec pp
    Double_t fSigmaReactionArray[kNCMSEs];  //!
    Double_t fSigmaJPsi;                    // xsec JPsi
    Double_t fSigmaJPsiArray[kNCMSEs];      //!
    Double_t fSigmaChic1;                   // xsec Chic1
    Double_t fSigmaChic1Array[kNCMSEs];     //!
    Double_t fSigmaChic2;                   // xsec Chic2
    Double_t fSigmaChic2Array[kNCMSEs];     //!
    Double_t fSigmaPsiP;                    // xsec Psi-prime
    Double_t fSigmaPsiPArray[kNCMSEs];      //!
    Double_t fSigmaUpsilon;                 // xsec Upsilon
    Double_t fSigmaUpsilonArray[kNCMSEs];   //!
    Double_t fSigmaUpsilonP;                // xsec Upsilon-prime
    Double_t fSigmaUpsilonPArray[kNCMSEs];  //!
    Double_t fSigmaUpsilonPP;               // xsec Upsilon-double-prime
    Double_t fSigmaUpsilonPPArray[kNCMSEs]; //!
    Double_t fSigmaCCbar;                   // xsec correlated charm
    Double_t fSigmaCCbarArray[kNCMSEs];     //!
    Double_t fSigmaBBbar;                   // xsec correlated beauty
    Double_t fSigmaBBbarArray[kNCMSEs];     //!

    Bool_t   fSigmaSilent;    // hide values of cross-sections in output

    ClassDef(AliGenMUONCocktailpp,5)  //  cocktail for physics in the Alice
};

#endif


text:
#include "Core/FixedArray.hpp"
#include "Core/Pair.hpp"

#include "Engine/Entity.hpp"

#include "Graphics/Scene.hpp"

#include "EditorWindow.hpp"

class World;

struct SceneObjectId;
struct EditorContext;

namespace kokko
{
namespace editor
{

class EntityListView : public EditorWindow
{
private:
	Entity requestScrollToEntity;

	// First one is the object that is moved, the second one is the parent
	Pair<SceneObjectId, SceneObjectId> requestSetSceneObjectParent;

	void DrawEntityListButtons(World* world);
	void DrawEntityNode(EditorContext& context, World* world, Entity entity, SceneObjectId sceneObj);

	static void ProcessSceneDragDropSource(SceneObjectId sceneObj, const char* entityName);
	void ProcessSceneDragDropTarget(SceneObjectId parent);

public:
	EntityListView();

	virtual void Update(EditorContext& context) override;
};

}
}


text:
try:
    from setuptools import setup
except:
    from distutils.core import setup

config = {
    'description': "Compute entropy, Shannon's information and several related quantities",
    'author': 'Pablo Jadzinsky and Lane McIntosh',
    'url': 'no url yet',
    'download_url': 'git@github.com:baccuslab/shannon.git',
    'author_email': 'pjadzinsky@gmail.com;lmcintosh@stanford.edu',
    'version': '0.1',
    'install_requires': ['nose', 'numpy', 'scipy'],
    'packages': ['shannon'],
    'scripts': [],
    'name': 'shannon'
}

setup(**config)


text:
"""
sentry.interfaces.user
~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

__all__ = ('User',)

import six

from sentry.interfaces.base import Interface, InterfaceValidationError
from sentry.utils.safe import trim, trim_dict
from sentry.web.helpers import render_to_string
from sentry.utils.validators import validate_ip
from sentry.constants import MAX_EMAIL_FIELD_LENGTH

def validate_email(value, required=True):
    if not required and not value:
        return

    if not isinstance(value, six.string_types):
        raise ValueError('object of type %r is not an email address' % type(value).__name__)

    # safe to assume an email address at least has a @ in it.
    if '@' not in value:
        raise ValueError('malformed email address')
    return value

class User(Interface):
    """
    An interface which describes the authenticated User for a request.

    You should provide **at least** either an `id` (a unique identifier for
    an authenticated user) or `ip_address` (their IP address).

    All other attributes are optional.

    >>> {
    >>>     "id": "unique_id",
    >>>     "username": "my_user",
    >>>     "email": "foo@example.com"
    >>>     "ip_address": "127.0.0.1",
    >>>     "optional": "value"
    >>> }
    """
    @classmethod
    def to_python(cls, data):
        data = data.copy()

        extra_data = data.pop('data', data)
        if not isinstance(extra_data, dict):
            extra_data = {}

        ident = trim(data.pop('id', None), 128)
        if ident:
            ident = six.text_type(ident)
        try:
            email = trim(validate_email(data.pop('email', None), False), MAX_EMAIL_FIELD_LENGTH)
        except ValueError:
            raise InterfaceValidationError("Invalid value for 'email'")
        username = trim(data.pop('username', None), 128)
        if username:
            username = six.text_type(username)

        try:
            ip_address = validate_ip(data.pop('ip_address', None), False)
        except ValueError:
            raise InterfaceValidationError("Invalid value for 'ip_address'")

        # TODO(dcramer): patch in fix to deal w/ old data but not allow new
        # if not (ident or email or username or ip_address):
        #     raise ValueError('No identifying value')

        kwargs = {
            'id': ident,
            'email': email,
            'username': username,
            'ip_address': ip_address,
        }

        kwargs['data'] = trim_dict(extra_data)
        return cls(**kwargs)

    def get_api_context(self, is_public=False):
        return {
            'id': self.id,
            'email': self.email,
            'username': self.username,
            'ipAddress': self.ip_address,
            'data': self.data,
        }

    def get_path(self):
        return 'sentry.interfaces.User'

    def get_hash(self):
        return []

    def get_display_name(self):
        return self.email or self.username

    def get_label(self):
        return self.email or self.username or self.id or self.ip_address

    def to_email_html(self, event, **kwargs):
        context = {
            'user_id': self.id,
            'user_email': self.email,
            'user_username': self.username,
            'user_ip_address': self.ip_address,
            'user_data': self.data,
            'user': self,
        }
        return render_to_string('sentry/partial/interfaces/user_email.html', context)


text:
package laddercontroller

import (
	"encoding/json"
	"fmt"
	"sort"

	"k8s.io/api/core/v1"

	"github.com/kubernetes-incubator/cluster-proportional-autoscaler/pkg/autoscaler/controller"
	"github.com/kubernetes-incubator/cluster-proportional-autoscaler/pkg/autoscaler/k8sclient"

	"github.com/golang/glog"
)

var _ = controller.Controller(&LadderController{})

const (
	// ControllerType defines the controller type string
	ControllerType = "ladder"
)

// LadderController uses ladder control pattern
type LadderController struct {
	params  *ladderParams
	version string
}

// NewLadderController returns a new ladder controller
func NewLadderController() controller.Controller {
	return &LadderController{}
}

type paramEntry [2]int

type paramEntries []paramEntry

func (entries paramEntries) Len() int {
	return len(entries)
}

func (entries paramEntries) Less(i, j int) bool {
	return entries[i][0] < entries[j][0]
}

func (entries paramEntries) Swap(i, j int) {
	entries[i], entries[j] = entries[j], entries[i]
}

type ladderParams struct {
	CoresToReplicas paramEntries `json:"coresToReplicas"`
	NodesToReplicas paramEntries `json:"nodesToReplicas"`
}

func (c *LadderController) SyncConfig(configMap *v1.ConfigMap) error {
	glog.V(0).Infof("Detected ConfigMap version change (old: %s new: %s) - rebuilding lookup entries", c.version, configMap.ObjectMeta.ResourceVersion)
	glog.V(2).Infof("Params from apiserver: \n%v", configMap.Data[ControllerType])
	params, err := parseParams([]byte(configMap.Data[ControllerType]))
	if err != nil {
		return fmt.Errorf("error parsing ladder params: %s", err)
	}
	sort.Sort(params.CoresToReplicas)
	sort.Sort(params.NodesToReplicas)
	c.params = params
	c.version = configMap.ObjectMeta.ResourceVersion
	return nil
}

// parseParams Parse the params from JSON string
func parseParams(data []byte) (*ladderParams, error) {
	var p ladderParams
	if err := json.Unmarshal(data, &p); err != nil {
		return nil, fmt.Errorf("could not parse parameters (%s)", err)
	}
	for _, e := range p.CoresToReplicas {
		if len(e) != 2 {
			return nil, fmt.Errorf("invalid element %v in cores_to_replicas_map", e)
		}
		if e[0] < 0 || e[1] < 0 {
			return nil, fmt.Errorf("invalid negative values in entry %v in cores_to_replicas_map", e)
		}
	}
	for _, e := range p.NodesToReplicas {
		if len(e) != 2 {
			return nil, fmt.Errorf("invalid element %b in nodes_to_replicas_map", e)
		}
		if e[0] < 0 || e[1] < 0 {
			return nil, fmt.Errorf("invalid negative values in entry %v in nodes_to_replicas_map", e)
		}
	}
	return &p, nil
}

func (c *LadderController) GetParamsVersion() string {
	return c.version
}

func (c *LadderController) GetExpectedReplicas(status *k8sclient.ClusterStatus) (int32, error) {
	// Get the expected replicas for the currently schedulable nodes and cores
	expReplicas := int32(c.getExpectedReplicasFromParams(int(status.SchedulableNodes), int(status.SchedulableCores)))

	return expReplicas, nil
}

func (c *LadderController) getExpectedReplicasFromParams(schedulableNodes, schedulableCores int) int {
	replicasFromCore := getExpectedReplicasFromEntries(schedulableCores, c.params.CoresToReplicas)
	replicasFromNode := getExpectedReplicasFromEntries(schedulableNodes, c.params.NodesToReplicas)

	// Returns the results which yields the most replicas
	if replicasFromCore > replicasFromNode {
		return replicasFromCore
	}
	return replicasFromNode
}

func getExpectedReplicasFromEntries(schedulableResources int, entries []paramEntry) int {
	if len(entries) == 0 {
		return 1
	}
	// Binary search for the corresponding replicas number
	pos := sort.Search(
		len(entries),
		func(i int) bool {
			return schedulableResources < entries[i][0]
		})
	if pos > 0 {
		pos = pos - 1
	}
	return entries[pos][1]
}

func (c *LadderController) GetControllerType() string {
	return ControllerType
}


text:
package com.intellij.psi.tree;

import com.intellij.lang.LighterASTNode;
import com.intellij.lang.LighterLazyParseableNode;
import com.intellij.util.diff.FlyweightCapableTreeStructure;

/**
 * Provides more flexible parsing capabilities for ILazyParseableElementType.
 * todo: merge with ILazyParseableElementType
 */
public interface ILightLazyParseableElementType {
  /**
   * Parses the contents of the specified chameleon node and returns the lightweight tree
   * representing the parsed contents.
   *
   * @param chameleon the node to parse.
   * @return the parsed contents of the node.
   */
  FlyweightCapableTreeStructure<LighterASTNode> parseContents(final LighterLazyParseableNode chameleon);
}


text:
namespace suic
{

class IGeneratorHost
{
public:

	virtual ~IGeneratorHost() {}

	virtual void SetIsGrouping(bool isGrouping) = 0;
	virtual bool IsItemItsOwnContainer(Object* item) = 0;
	virtual DpObject* GetContainerForItem(Object* item) = 0;
	virtual bool IsHostForItemContainer(DpObject* container) = 0;

	virtual void PrepareItemContainer(DpObject* container, Object* item) = 0;
    virtual void ClearContainerForItem(DpObject* container, Object* item) = 0;
    virtual GroupStyle* GetGroupStyle(CollectionViewGroup* group, int level) = 0;

    virtual int GetAlternationCount() = 0;
    virtual ItemCollectionEx* GetView() = 0;
};

}

#endif


text:
package org.vizzini.illyriad;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

import java.util.List;

import org.junit.Test;

/**
 * Provides tests for the City class.
 */
public final class CityTest
{
    /**
     * Test the computeDistance() method.
     */
    @Test
    public void computeDistance()
    {
        final double result = City.LOCKSTONE.computeDistance(City.LOCKSLEY);
        assertThat(String.format("%10.1f", result).trim(), is("495.5"));
    }

    /**
     * Test the getOtherCitiesByDistance() method.
     */
    @Test
    public void getOtherCitiesByDistance()
    {
        final List<City> result = City.LOCKSTONE.getOtherCitiesByDistance();
        assertNotNull(result);
        assertFalse(result.isEmpty());
        assertThat(result.size(), is(8));

        int i = 0;

        assertThat(result.get(i++), is(City.LOCKS_HEATH));
        assertThat(result.get(i++), is(City.LOCKSTAR));
        assertThat(result.get(i++), is(City.LOCK_HAVEN));
        assertThat(result.get(i++), is(City.LOCKAND_KEY));
        assertThat(result.get(i++), is(City.LOCK_STEPPE));
        assertThat(result.get(i++), is(City.LOCK_DOWNS));
        assertThat(result.get(i++), is(City.LOCKSLEY));
        assertThat(result.get(i++), is(City.LOCKMOOR));
    }

    /**
     * Test the toString() method.
     */
    @Test
    public void testToString()
    {
        assertThat(City.LOCKSTONE.toString(), is("Lockstone"));
    }
}


text:
class SILENCE_EXPORT PathException : public std::exception
{
    std::string message;
public:
    explicit PathException(std::string);
    ~PathException() throw();

    const char * what() const throw() override;
};


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="3d_playground" type="K2JSConfigurationType" factoryName="Kotlin (JavaScript)">
    <K2JSConfigurationSettings>
      <option name="browserFamily" value="Chrome" />
      <option name="generatedFilePath" value="$PROJECT_DIR$/build/classes/kotlin/main" />
      <option name="pageToOpenFilePath" value="$PROJECT_DIR$/build/classes/kotlin/main/index.html" />
      <option name="shouldOpenInBrowserAfterTranslation" value="true" />
    </K2JSConfigurationSettings>
    <method />
  </configuration>
</component>


text:
module Spree
  class Zone < Spree::Base
    has_many :zone_members, dependent: :destroy, class_name: "Spree::ZoneMember", inverse_of: :zone
    has_many :tax_rates, dependent: :destroy, inverse_of: :zone

    with_options through: :zone_members, source: :zoneable do
      has_many :countries, source_type: "Spree::Country"
      has_many :states, source_type: "Spree::State"
    end

    has_many :shipping_method_zones
    has_many :shipping_methods, through: :shipping_method_zones

    validates :name, presence: true, uniqueness: { allow_blank: true }
    after_save :remove_defunct_members
    after_save :remove_previous_default

    scope :with_member_ids, ->(state_ids, country_ids) do
      return none if !state_ids.present? && !country_ids.present?

      spree_zone_members_table = Spree::ZoneMember.arel_table
      matching_state =
        spree_zone_members_table[:zoneable_type].eq("Spree::State").
        and(spree_zone_members_table[:zoneable_id].in(state_ids))
      matching_country =
        spree_zone_members_table[:zoneable_type].eq("Spree::Country").
        and(spree_zone_members_table[:zoneable_id].in(country_ids))
      joins(:zone_members).where(matching_state.or(matching_country)).distinct
    end

    scope :for_address, ->(address) do
      if address
        with_member_ids(address.state_id, address.country_id)
      else
        none
      end
    end

    alias :members :zone_members
    accepts_nested_attributes_for :zone_members, allow_destroy: true, reject_if: proc { |a| a['zoneable_id'].blank? }

    self.whitelisted_ransackable_attributes = ['description']

    def self.default_tax
      where(default_tax: true).first
    end

    # Returns the most specific matching zone for an address. Specific means:
    # A State zone wins over a country zone, and a zone with few members wins
    # over one with many members. If there is no match, returns nil.
    def self.match(address)
      return unless address && (matches =
                                  with_member_ids(address.state_id, address.country_id).
                                  order(:zone_members_count, :created_at, :id).
                                  references(:zones))

      ['state', 'country'].each do |zone_kind|
        if match = matches.detect { |zone| zone_kind == zone.kind }
          return match
        end
      end
      matches.first
    end

    # Returns all zones that contain any of the zone members of the zone passed
    # in. This also includes any country zones that contain the state of the
    # current zone, if it's a state zone. If the passed-in zone has members, it
    # will also be in the result set.
    def self.with_shared_members(zone)
      return none unless zone

      states_and_state_country_ids = zone.states.pluck(:id, :country_id).to_a
      state_ids = states_and_state_country_ids.map(&:first)
      state_country_ids = states_and_state_country_ids.map(&:second)
      country_ids = zone.countries.pluck(:id).to_a

      with_member_ids(state_ids, country_ids + state_country_ids).distinct
    end

    def kind
      if members.any? && !members.any? { |member| member.try(:zoneable_type).nil? }
        members.last.zoneable_type.demodulize.underscore
      end
    end

    def kind=(value)
      # do nothing - just here to satisfy the form
    end

    def include?(address)
      return false unless address

      members.any? do |zone_member|
        case zone_member.zoneable_type
        when 'Spree::Country'
          zone_member.zoneable_id == address.country_id
        when 'Spree::State'
          zone_member.zoneable_id == address.state_id
        else
          false
        end
      end
    end

    # convenience method for returning the countries contained within a zone
    def country_list
      @countries ||= case kind
                     when 'country' then zoneables
                     when 'state' then zoneables.collect(&:country)
                     else []
                     end.flatten.compact.uniq
    end

    def <=>(other)
      name <=> other.name
    end

    # All zoneables belonging to the zone members.  Will be a collection of either
    # countries or states depending on the zone type.
    def zoneables
      members.includes(:zoneable).collect(&:zoneable)
    end

    def country_ids
      if kind == 'country'
        members.pluck(:zoneable_id)
      else
        []
      end
    end

    def state_ids
      if kind == 'state'
        members.pluck(:zoneable_id)
      else
        []
      end
    end

    def country_ids=(ids)
      set_zone_members(ids, 'Spree::Country')
    end

    def state_ids=(ids)
      set_zone_members(ids, 'Spree::State')
    end

    # Indicates whether the specified zone falls entirely within the zone performing
    # the check.
    def contains?(target)
      return true if self == target
      return false if kind == 'state' && target.kind == 'country'
      return false if zone_members.empty? || target.zone_members.empty?

      if kind == target.kind
        (target.zoneables.collect(&:id) - zoneables.collect(&:id)).empty?
      else
        (target.zoneables.collect(&:country).collect(&:id) - zoneables.collect(&:id)).empty?
      end
    end

    private

    def remove_defunct_members
      if zone_members.any?
        zone_members.where('zoneable_id IS NULL OR zoneable_type != ?', "Spree::#{kind.classify}").destroy_all
      end
    end

    def remove_previous_default
      Spree::Zone.where('id != ?', id).update_all(default_tax: false) if default_tax
    end

    def set_zone_members(ids, type)
      zone_members.destroy_all
      ids.reject(&:blank?).map do |id|
        member = ZoneMember.new
        member.zoneable_type = type
        member.zoneable_id = id
        members << member
      end
    end
  end
end


text:
(function() {
  var PreviousMap, base64js, fs, mozilla, path;

  base64js = require('base64-js');

  mozilla = require('source-map');

  path = require('path');

  fs = require('fs');

  PreviousMap = (function() {
    function PreviousMap(root, opts) {
      var text, _ref;
      this.file = opts.from;
      this.loadAnnotation(root);
      this.inline = this.startWith(this.annotation, '# sourceMappingURL=data:');
      text = this.loadMap((_ref = opts.map) != null ? _ref.prev : void 0);
      if (text) {
        this.text = text;
      }
    }

    PreviousMap.prototype.consumer = function() {
      return this.consumerCache || (this.consumerCache = new mozilla.SourceMapConsumer(this.text));
    };

    PreviousMap.prototype.withContent = function() {
      var _ref;
      return ((_ref = this.consumer().sourcesContent) != null ? _ref.length : void 0) > 0;
    };

    PreviousMap.prototype.startWith = function(string, start) {
      if (!string) {
        return false;
      }
      return string.slice(0, +(start.length - 1) + 1 || 9e9) === start;
    };

    PreviousMap.prototype.loadAnnotation = function(root) {
      var last;
      last = root.last;
      if (!last) {
        return;
      }
      if (last.type === 'comment' && this.startWith(last.text, '# sourceMappingURL=')) {
        return this.annotation = last.text;
      }
    };

    PreviousMap.prototype.decodeInline = function(text) {
      var base64, byte, bytes, encoding, uri, _ref;
      uri = '# sourceMappingURL=data:application/json,';
      base64 = '# sourceMappingURL=data:application/json;base64,';
      if (this.startWith(text, uri)) {
        return decodeURIComponent(text.slice(uri.length));
      } else if (this.startWith(text, base64)) {
        text = text.slice(base64.length);
        bytes = base64js.toByteArray(text);
        return ((function() {
          var _i, _len, _results;
          _results = [];
          for (_i = 0, _len = bytes.length; _i < _len; _i++) {
            byte = bytes[_i];
            _results.push(String.fromCharCode(byte));
          }
          return _results;
        })()).join('');
      } else {
        encoding = (_ref = text.match(/ata:application\/json;([^,]+),/)) != null ? _ref[1] : void 0;
        throw new Error("Unsupported source map encoding " + encoding);
      }
    };

    PreviousMap.prototype.loadMap = function(prev) {
      var map;
      if (prev === false) {
        return;
      }
      if (prev) {
        if (typeof prev === 'string') {
          return prev;
        } else if (prev instanceof mozilla.SourceMapConsumer) {
          return mozilla.SourceMapGenerator.fromSourceMap(prev).toString();
        } else if (prev instanceof mozilla.SourceMapGenerator) {
          return prev.toString();
        } else if (typeof prev === 'object' && (prev.mappings != null)) {
          return JSON.stringify(prev);
        } else {
          throw new Error("Unsupported previous source map format: " + prev);
        }
      } else if (this.inline) {
        return this.decodeInline(this.annotation);
      } else if (this.annotation) {
        map = this.annotation.replace('# sourceMappingURL=', '');
        if (this.file) {
          map = path.join(path.dirname(this.file), map);
        }
        this.root = path.dirname(map);
        if (typeof fs.existsSync === "function" ? fs.existsSync(map) : void 0) {
          return fs.readFileSync(map).toString();
        }
      }
    };

    return PreviousMap;

  })();

  module.exports = PreviousMap;

}).call(this);


text:
package org.apache.camel.itest.karaf;

import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;

@RunWith(JUnit4TestRunner.class)
@Ignore("Requires Spring 3.1")
public class CamelTestSpringTest extends AbstractFeatureTest {

    public static final String COMPONENT = "test-spring";

    @Test
    public void test() throws Exception {
        // noop
    }

    @Configuration
    public static Option[] configure() {
        return configure(COMPONENT);
    }

}


text:
local M = {}

M.setup = function(servers)
    local lsp_installer_ok, lsp_installer = pcall(require, "nvim-lsp-installer")
    if not lsp_installer_ok then
        return
    end

    local installer_settings = {
        automatic_installation = true,
        ensure_installed = servers,
        ui = {
            icons = {
                server_installed = "✓",
                server_pending = "➜",
                server_uninstalled = "✗",
            },
        },
    }

    lsp_installer.setup(installer_settings)
end

return M


text:
(function () {
	"use strict";
	// llevar fuera la configuración
	var config = require('./express.js');

	// iniciar la aplicación
	var app =config.initApp();
	// y el router
	var router = config.initRouter(app);

	var root = router.route('/');
	var rootSimple = router.route('/simple');

	root.get(function (peticion, respuesta) {
		respuesta.send('Hola Express!');
	});
	rootSimple.get(function (peticion, respuesta) {
		respuesta.render('simple',{title:"Soy muy simple"});
	});

	require('./rutas/api.js').enrutar(router);
	require('./rutas/cuentas.js').enrutar(router);

	app.listen(3000);
}());


text:
SYNONYM

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

#### Published in
Ann. Rep. N. Y. St. Mus. 49: 115 (1897)

#### Original name
Phyllosticta limitata Peck, 1897

### Remarks
null


text:
EDITOR='vim'

autoload zmv

if [ $MAC -ne 0 ]
then
  setxkbmap -option caps:escape
  setxkbmap -option compose:ralt
fi


text:
package edu.berkeley.ground.api.models.postgres;

import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.berkeley.ground.api.PostgresTest;
import edu.berkeley.ground.api.models.NodeVersion;
import edu.berkeley.ground.api.models.Tag;
import edu.berkeley.ground.api.versions.GroundType;
import edu.berkeley.ground.exceptions.GroundException;

import static org.junit.Assert.*;

public class PostgresNodeVersionFactoryTest extends PostgresTest {

  public PostgresNodeVersionFactoryTest() throws GroundException {
    super();
  }

  @Test
  public void testNodeVersionCreation() throws GroundException {
    String nodeName = "testNode";
    long nodeId = super.factories.getNodeFactory().create(nodeName, new HashMap<>()).getId();

    String structureName = "testStructure";
    long structureId = super.factories.getStructureFactory().create(structureName, new HashMap<>()).getId();

    Map<String, GroundType> structureVersionAttributes = new HashMap<>();
    structureVersionAttributes.put("intfield", GroundType.INTEGER);
    structureVersionAttributes.put("boolfield", GroundType.BOOLEAN);
    structureVersionAttributes.put("strfield", GroundType.STRING);

    long structureVersionId = super.factories.getStructureVersionFactory().create(
        structureId, structureVersionAttributes, new ArrayList<>()).getId();

    Map<String, Tag> tags = new HashMap<>();
    tags.put("intfield", new Tag(-1, "intfield", 1, GroundType.INTEGER));
    tags.put("strfield", new Tag(-1, "strfield", "1", GroundType.STRING));
    tags.put("boolfield", new Tag(-1, "boolfield", true, GroundType.BOOLEAN));

    String testReference = "http://www.google.com";
    Map<String, String> parameters = new HashMap<>();
    parameters.put("http", "GET");

    long nodeVersionId = super.factories.getNodeVersionFactory().create(tags,
        structureVersionId, testReference, parameters, nodeId, new ArrayList<>()).getId();

    NodeVersion retrieved = super.factories.getNodeVersionFactory().retrieveFromDatabase(nodeVersionId);

    assertEquals(nodeId, retrieved.getNodeId());
    assertEquals(structureVersionId, retrieved.getStructureVersionId());
    assertEquals(testReference, retrieved.getReference());

    assertEquals(parameters.size(), retrieved.getParameters().size());
    assertEquals(tags.size(), retrieved.getTags().size());

    Map<String, String> retrievedParameters = retrieved.getParameters();
    Map<String, Tag> retrievedTags = retrieved.getTags();

    for (String key : parameters.keySet()) {
      assert (retrievedParameters).containsKey(key);
      assertEquals(parameters.get(key), retrievedParameters.get(key));
    }

    for (String key : tags.keySet()) {
      assert (retrievedTags).containsKey(key);
      assertEquals(tags.get(key), retrievedTags.get(key));
    }

    List<Long> leaves = super.factories.getNodeFactory().getLeaves(nodeName);

    assertTrue(leaves.contains(nodeVersionId));
    assertTrue(1 == leaves.size());
  }

  @Test
  public void testTransitiveClosure() throws GroundException {
    String nodeName = "testNode1";
    long nodeId = super.factories.getNodeFactory().create(nodeName, new HashMap<>()).getId();

    long nodeVersionId = super.factories.getNodeVersionFactory().create(new HashMap<>(),
        -1, null, new HashMap<>(), nodeId, new ArrayList<>()).getId();

    nodeName = "testNode2";
    nodeId = super.factories.getNodeFactory().create(nodeName, new HashMap<>()).getId();

    long secondNVId = super.factories.getNodeVersionFactory().create(new HashMap<>(), -1,
        null, new HashMap<>(), nodeId, new ArrayList<>()).getId();

    String edgeName = "testEdge1";
    long edgeId = super.factories.getEdgeFactory()
        .create(edgeName, new HashMap<>()).getId();

    super.factories.getEdgeVersionFactory().create(new HashMap<>(), -1, null, new
        HashMap<>(), edgeId, secondNVId, nodeVersionId, new ArrayList<>()).getId();

    nodeName = "testNode3";
    nodeId = super.factories.getNodeFactory().create(nodeName, new HashMap<>()).getId();

    long thirdNVId = super.factories.getNodeVersionFactory().create(new HashMap<>(), -1,
        null, new HashMap<>(), nodeId, new ArrayList<>()).getId();

    edgeName = "testEdge3";
    edgeId = super.factories.getEdgeFactory().create(edgeName, new HashMap<>()).getId();

    super.factories.getEdgeVersionFactory().create(new HashMap<>(), -1, null, new
        HashMap<>(), edgeId, thirdNVId, secondNVId, new ArrayList<>()).getId();

    List<Long> reachable = super.factories.getNodeVersionFactory()
        .getTransitiveClosure(thirdNVId);

    assertTrue(reachable.contains(nodeVersionId));
    assertTrue(reachable.contains(secondNVId));
  }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <base href="/">
    <title>angular-iconic</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/yeti/bootstrap.min.css" rel="stylesheet" integrity="sha256-gJ9rCvTS5xodBImuaUYf1WfbdDKq54HCPz9wk8spvGs= sha512-weqt+X3kGDDAW9V32W7bWc6aSNCMGNQsdOpfJJz/qD/Yhp+kNeR+YyvvWojJ+afETB31L0C4eO0pcygxfTgjgw==" crossorigin="anonymous">
    <link href="bower_components/prism/themes/prism.css" rel="stylesheet">
    <link href="bower_components/angular-snippets/dist/themes/bootstrap-tabs/style.css" rel="stylesheet">
    <link href="/app.css" rel="stylesheet">

          <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#bs-navbar" aria-controls="bs-navbar" aria-expanded="false">
            Toggle navigation

          </button>
          angular-iconic

              Examples

GitHub

angular-iconic Examples

These are just some basic examples based on Open Iconic. Mostly just for development purposes.

Also be sure to take a look at the source code of this page for more examples.

And also check out the GitHub Project.

data-src as regular svg file

Basic usage with some minimal styling.

      <snippets path="snippets/as-svg" files="['as-svg.html', 'app.js', 'app.css']">
        <snippets-pane snippet="{name: 'run', cls: 'pull-right'}">

        </snippets-pane>
      </snippets>

data-src as expression

Using the Directive with AngularJS expressions.

      <snippets path="snippets/as-expression" files="['as-expression.html', 'app.js']">
        <snippets-pane snippet="{name: 'run', cls: 'pull-right'}">

        </snippets-pane>
      </snippets>


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="news_admin" extends="news-default" namespace="/news/admin">
		<action name="*" method="{1}" class="com.abbcc.news.action.admin.AdminAction">
			<result name="input">/admin/login.htm</result>
			<result name="enter" type="redirect">/news/admin/index</result>
			<result name="index">/admin/index.htm</result>
		</action>
	</package>
</struts>


text:
if [ "$#" -ne 4 ]; then
    echo "Expected 4 arguments"
    echo "Syntax: ./merge_pr.sh <PR_NUMBER> <HASH_PR_HEAD> <HASH_BASE_HEAD> <SSH Key Path>"
    echo "Use PR_NUMBER=0 if not a PR"
    exit 1
fi

# Fetching merged head
if [ "$1" != "0" ]; then
    PR_NUMBER=$1
    HASH_PR_HEAD=$2
    HASH_BASE_HEAD=$3
    SSH_KEY_PATH=$4

    # Copying SSH key
    mkdir -p $HOME/.ssh
    sudo cp $SSH_KEY_PATH $HOME/.ssh/id_rsa
    sudo chown $USER:$USER $HOME/.ssh/id_rsa
    sudo chmod 400 $HOME/.ssh/id_rsa

    # Setting identity
    git config --global user.email "jenkins@diplomacy.ai"
    git config --global user.name "Jenkins (diplomacy.ai)"

    # Displaying hashes
    echo "PR Head: $HASH_PR_HEAD"
    echo "Base Head: $HASH_BASE_HEAD"
    echo "PR #${PR_NUMBER} - Merging ${HASH_PR_HEAD::7} into ${HASH_BASE_HEAD::7}"

    # Fetching and merging
    git fetch origin +refs/pull/*:refs/remotes/origin/pr/* +refs/heads/*:refs/remotes/origin/*
    git checkout -qf $HASH_BASE_HEAD
    git merge --no-ff $HASH_PR_HEAD -m "PR #${PR_NUMBER} - Merge ${HASH_PR_HEAD::7} into ${HASH_BASE_HEAD::7}"
fi


text:
using System;
using System.Collections.Generic;

namespace Public.NeuralNetworks.MiniBatch
{
    [Serializable]
    public class MiniBatchSet
    {
        private List<int[]> ShuffledIndexSets;

        public int NumberOfSets
        {
            get
            {
                int output = this.ShuffledIndexSets.Count;
                return output;
            }
        }
        public int NumberOfItemsInSet { get; private set; }
        public int[] this[int setIndex]
        {
            get
            {
                int[] output = this.ShuffledIndexSets[setIndex];
                return output;
            }
            set
            {
                this.CheckSetSize(value);

                this.ShuffledIndexSets[setIndex] = value;
            }
        }

        private MiniBatchSet()
        {
            this.ShuffledIndexSets = new List<int[]>();
        }

        public MiniBatchSet(int numberOfItemsInSet)
            : this()
        {
            this.NumberOfItemsInSet = numberOfItemsInSet;
        }

        private void CheckSetSize(int[] set)
        {
            if (set.Length != this.NumberOfItemsInSet)
            {
                string message = String.Format(@"Unallowed set size. Allows sets of size: {0}, found: {0}.", this.NumberOfItemsInSet, set.Length);
                throw new ArgumentException(message);
            }
        }

        public void AddSet(int[] set)
        {
            this.CheckSetSize(set);

            this.ShuffledIndexSets.Add(set);
        }
    }
}


text:
<?php

namespace BenGorUser\UserBundle\Form\Type;

use BenGorUser\User\Application\Command\Remove\RemoveUserCommand;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * Remove user form type.
 *
 * @author Beñat Espiña <benatespina@gmail.com>
 */
class RemoveType extends AbstractType
{
    /**
     * The current logged user.
     *
     * @var UserInterface|null
     */
    private $currentUser;

    /**
     * Constructor.
     *
     * @param TokenStorageInterface $aTokenStorage The token storage
     */
    public function __construct(TokenStorageInterface $aTokenStorage)
    {
        if ($aTokenStorage->getToken() instanceof TokenInterface) {
            $this->currentUser = $aTokenStorage->getToken()->getUser();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('submit', SubmitType::class, [
            'label'              => 'remove.form_submit_button',
            'translation_domain' => 'BenGorUser',
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => RemoveUserCommand::class,
            'empty_data' => function (FormInterface $form) {
                return new RemoveUserCommand(
                    $this->currentUser->id
                );
            },
        ]);
    }
}


text:
using System;
using System.Collections;
using Alachisoft.NCache.Caching;
using Alachisoft.NCache.SocketServer.Util;
using System.Collections.Generic;

namespace Alachisoft.NCache.SocketServer.EventTask
{
    /// <summary>
    /// This event is fired when cache is cleared
    /// </summary>
    internal sealed class CacheClearedEvent : IEventTask
    {
        private string _cacheId;
        private string _clientId;
        private EventContext _eventContext;

        internal CacheClearedEvent(string cacheId, string clientId, EventContext eventContext)
        {
            _cacheId = cacheId;
            _clientId = clientId;
            _eventContext = eventContext;
        }

        public void Process()
        {
            ClientManager clientManager = null;

            lock (ConnectionManager.ConnectionTable) clientManager = (ClientManager)ConnectionManager.ConnectionTable[_clientId];

            if (clientManager != null)
            {
                Alachisoft.NCache.Common.Protobuf.Response response = new Alachisoft.NCache.Common.Protobuf.Response();

                response.cacheCleared = EventHelper.GetCacheClearedResponse(_eventContext);
                response.responseType = Alachisoft.NCache.Common.Protobuf.Response.Type.CACHE_CLEARED_EVENT;

                IList serializedResponse = Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response,Common.Protobuf.Response.Type.CACHE_CLEARED_EVENT);

                ConnectionManager.AssureSend(clientManager, serializedResponse, false);
            }
        }
    }
}


text:
class CodeRunner
module LoadLeveler

	def queue_status
		if ((prefix = ENV['CODE_RUNNER_LAUNCHER']).size > 0 rescue false)
			%x[cat #{ENV['HOME']}/.coderunner_to_launch_#{prefix}/queue_status.txt]  +
			%x[cat #{ENV['HOME']}/.coderunner_to_launch_#{prefix}/queue_status2.txt]
		else
			%x[llq -WX all | grep $USER].gsub(/^bglogin\d\./, '')
		end
	end

	#def mpi_prog
		#"aprun -n #{nprocstot} -N #{ppn}"
	#end

	def nodes
			nodes, ppn = @nprocs.split(/x/)
			nodes
	end
	def ppn
			nodes, ppn = @nprocs.split(/x/)
			ppn
	end
	def nprocstot
			nodes, ppn = @nprocs.split(/x/)
			nprocstot = nodes.to_i * ppn.to_i
	end
	def run_command
# 		"qsub #{batch_script_file}"
		if (ENV['CODE_RUNNER_LAUNCHER'].size > 0 rescue false)
			return %[mpiexec -np #{@nprocs} #{executable_location}/#{executable_name} #{parameter_string} > #{output_file} 2> #{error_file}]
		else
			#nodes, ppn = @nprocs.split(/x/)
			#nprocstot = nodes.to_i * ppn.to_i
			"runjob --env-all --exe #{executable_location}/#{executable_name} --np #{nprocstot} --ranks-per-node #{ppn} --args \"#{parameter_string}\""
		end
	end

	def execute
		if ((prefix = ENV['CODE_RUNNER_LAUNCHER']).size > 0 rescue false)
			launch_id = "#{Time.now.to_i}#{$$}"
			fname = ENV['HOME'] + "/.coderunner_to_launch_#{prefix}/#{launch_id}"
			File.open(fname + '.start', 'w'){|file| file.puts "cd #{Dir.pwd};#{run_command}"}
			sleep 1 until FileTest.exist? fname + '.pid'
			pid = File.read(fname + '.pid').to_i
			FileUtils.rm fname + '.pid'
			return pid
		else
			File.open(batch_script_file, 'w'){|file| file.puts batch_script + "\n" + run_command + "\n"}
			%x[llsubmit #{batch_script_file}].to_i
			return nil
		end
	end

	def batch_script_file
		"#{executable_name}_#{job_identifier}.sh"
	end

	def max_ppn
		raise "Please define max_ppn for your system"
	end

	def batch_script

		nodes, ppn = @nprocs.split(/x/)
		eputs "Warning: You must use 128 nodes or greater on a BlueGene Q: This may fail." if  nodes.to_i < 128
		eputs "Warning: Underuse of nodes (#{ppn} cores per node instead of #{max_ppn})" if ppn.to_i < max_ppn
		eputs "Warning: processes per node excedes cores per node: #{max_ppn}" if ppn.to_i > max_ppn
		ppn ||= max_ppn
		if @wall_mins
			ep @wall_mins
			hours = (@wall_mins / 60).floor
			mins = @wall_mins.to_i % 60
			secs = ((@wall_mins - @wall_mins.to_i) * 60).to_i
			eputs "Allotted wall time is " + sprintf("%02d:%02d:%02d", hours, mins, secs)
		else
			raise "Error: no wall clock time specified."
		end

		return <<EOF
#!/bin/bash

## job requirements for load leveler
######################################################################
\#@bg_size=#{nodes}
\#@job_type=bluegene
\#@class=prod
\#@executable=#{batch_script_file}
\#@environment=COPY_ALL
\#@output=#{executable_name}.#{job_identifier}.$(jobid).output.txt
\#@error=#{executable_name}.#{job_identifier}.$(jobid).error.txt
\#@wall_clock_limit=#{sprintf("%02d:%02d:%02d", hours, mins, secs)}
\#@notification=complete
\#@queue

## commands to be executed
######################################################################
## This is any custom configuration required for the code:
#{code_run_environment}
printenv
echo "Submitting #{nodes}x#{ppn} job on #{CodeRunner::SYS} for project (#@project)..."

EOF

	end

	def cancel_job
		if ((prefix = ENV['CODE_RUNNER_LAUNCHER']).size > 0 rescue false)
			 fname = ENV['HOME'] + "/.coderunner_to_launch_#{prefix}/#{$$}.stop"
			 File.open(fname, 'w'){|file| file.puts "\n"}
		else
			`llcancel #{@job_no}`
		end
	end

	def error_file
		return "#{executable_name}.#{job_identifier}.#@job_no.error.txt"
	end

	def output_file
		return "#{executable_name}.#{job_identifier}.#@job_no.output.txt"
	end

def get_run_status(job_no, current_status)
	if ((prefix = ENV['CODE_RUNNER_LAUNCHER']).size > 0 rescue false)
		return :Unknown
	end
	line = current_status.split(/\n/).grep(Regexp.new(job_no.to_s))[0]
	unless line
		return :Unknown
	else
		if line =~ /\sS|H\s/
			return :Held
		elsif line =~ /\sI\s/
			return :Queueing
		elsif line =~ /\sR\s/
			return :Running
		else
			ep 'line', line
			raise 'Could not get run status'
		end
	end
end

 	# It takes a long time for the job to appear in the queue
  # Each attempt to wait for it to appear takes 0.2 seconds
	# Here we therefore wait 40 seconds!
	def queue_wait_attempts
		200
	end
	end
end


text:
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
  DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"

classpath=$(${DIR}/classpath.sh tools/format)
if [ $? -ne 0 ]; then
  echo "${classpath}"
  exit
fi

java \
-Dfile.encoding=UTF-8 \
-classpath ${classpath} \
io.lumify.tools.format.FormatLumify


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.test</groupId>
	<artifactId>consumer</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>consumer</name>
	<description>consumes a simple api</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.2.5.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
		<start-class>consumer.ConsumerApplication</start-class>
	</properties>

	<dependencies>
		<!-- Spring -->

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-rest</artifactId>
		</dependency>

		<!-- Misc -->

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.4</version>
		</dependency>
		<!-- Test -->

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


text:
#include "stdafx.h"
#include "Log.h"

CLog *CLog::m_Instance = 0;

/******************************************************************************
Create a new log
******************************************************************************/
CLog::CLog()
{
	SetDirectory();
}

/******************************************************************************
Delete log
******************************************************************************/
CLog::~CLog()
{
	if(this == m_Instance)
		m_Instance = 0;
}

/******************************************************************************
Adds a Log Entry to the log file
******************************************************************************/
void CLog::AddLog(const CString fmt, ...)
{
	CString temp;
	va_list va_alist;
	struct tm* current_tm = new tm();
	time_t current_time;

	time(&current_time);
	localtime_s(current_tm, &current_time);
	temp.Format(L"%02d:%02d:%02d-> ", current_tm->tm_hour, current_tm->tm_min, current_tm->tm_sec);

	va_start(va_alist, fmt);
	temp.AppendFormatV(fmt, va_alist);
	va_end(va_alist);
	temp.AppendFormat(L"\r\n");

	CFile logFile(m_FullPath, CFile::modeCreate | CFile::modeWrite);
	logFile.SeekToEnd();
	logFile.Write(temp, temp.GetLength());
	logFile.Close();
}

/******************************************************************************
Set location and name of log file
******************************************************************************/
void CLog::SetDirectory(const CString dir)
{
	m_Directory = dir;
	m_FullPath.Format(L"%sUpdater Log.txt", m_Directory);
}

/******************************************************************************
Get the log class instance or create one
******************************************************************************/
CLog* CLog::Instance()
{
	if(!m_Instance)
	{
		m_Instance = new CLog();
	}
	return m_Instance;
}

/******************************************************************************
Delete the singleton log object if it exists
******************************************************************************/
void CLog::Dispose()
{
	delete m_Instance;
}