text:
package com.salesforce.dva.argus.service;

import com.fasterxml.jackson.databind.JavaType;
import java.io.Serializable;
import java.util.List;

/**
 * Provides methods to synchronously queue and dequeue point to point text based messages.
 *
 * @author  Tom Valine (tvaline@salesforce.com)
 */
public interface MQService extends Service {

    //~ Methods **************************************************************************************************************************************

    /**
     * Enqueues an message. If the object is a <tt>String</tt> then a text message shall be enqueued, otherwise an object message shall be enqueued.
     * This method blocks until initialization is complete and the queue is available.
     *
     * @param  <T>        The serializable type of the object.
     * @param  queueName  The queue name to use. Cannot be null or empty.
     * @param  object     The serializable object to enqueue. Cannot be null or empty.
     */
    <T extends Serializable> void enqueue(String queueName, T object);

    /**
     * Enqueues messages. If the objects are of type <tt>String</tt> then text messages shall be enqueued, otherwise object messages shall be
     * enqueued. This method blocks until initialization is complete and the queue is available.
     *
     * @param  <T>        The serializable type of the objects.
     * @param  queueName  The queue name to use. Cannot be null or empty.
     * @param  objects    The serializable objects to enqueue. Cannot be null or empty.
     */
    <T extends Serializable> void enqueue(String queueName, List<T> objects);

    /**
     * Dequeues a message.
     *
     * @param   queueName  The queue name to use. Cannot be null or empty.
     * @param   timeout    If <0 the call will block until a message becomes available. If 0, will return immediately even if no message is
     *                     available to dequeue. If >0, the call will wait for the number of milliseconds before attempting to dequeue the message.
     *
     * @return  The text based object dequeued.
     */
    String dequeue(String queueName, int timeout);

    /**
     * Dequeues a message. If the return type is <tt>String</tt> then a text based message is assumed.
     *
     * @param   <T>        The serializable type of the object being dequeued.
     * @param   queueName  The queue name to use. Cannot be null or empty.
     * @param   type       The type of the object being dequeued.
     * @param   timeout    If <0 the call will block until a message becomes available. If 0, will return immediately even if no message is
     *                     available to dequeue. If >0, the call will wait for the number of milliseconds before attempting to dequeue the message.
     *
     * @return  The dequeued object.
     */
    <T extends Serializable> T dequeue(String queueName, Class<T> type, int timeout);

    /**
     * Dequeues a message. If the return type is <tt>String</tt> then a text based message is assumed.
     *
     * @param   <T>        The serializable type of the object being dequeued.
     * @param   queueName  The queue name to use. Cannot be null or empty.
     * @param   type       The type of the object being dequeued.
     * @param   timeout    If <0 the call will block until a message becomes available. If 0, will return immediately even if no message is
     *                     available to dequeue. If >0, the call will wait for the number of milliseconds before attempting to dequeue the message.
     *
     * @return  The dequeued object.
     */
    <T extends Serializable> T dequeue(String queueName, JavaType type, int timeout);

    /**
     * Dequeues messages.
     *
     * @param   queueName  The queue name to use. Cannot be null or empty.
     * @param   timeout    If <0 the call will block until a message becomes available. If 0, will return immediately even if no message is
     *                     available to dequeue. If >0, the call will wait for the number of milliseconds before attempting to dequeue the message.
     * @param   limit      The maximum number of messages to retrieve. Must be non-negative.
     *
     * @return  The text based object dequeued.
     */
    List<String> dequeue(String queueName, int timeout, int limit);

    /**
     * Dequeues messages. If the return type is <tt>String</tt> then text based messages is assumed.
     *
     * @param   <T>        The serializable type of the object being dequeued.
     * @param   queueName  The queue name to use. Cannot be null or empty.
     * @param   type       The type of the object being dequeued.
     * @param   timeout    If <0 the call will block until a message becomes available. If 0, will return immediately even if no message is
     *                     available to dequeue. If >0, the call will wait for the number of milliseconds before attempting to dequeue the message.
     * @param   limit      The maximum number of messages to retrieve. Must be non-negative.
     *
     * @return  The dequeued objects.
     */
    <T extends Serializable> List<T> dequeue(String queueName, Class<T> type, int timeout, int limit);

    /**
     * Dequeues messages. If the return type is <tt>String</tt> then text based messages is assumed.
     *
     * @param   <T>        The serializable type of the object being dequeued.
     * @param   queueName  The queue name to use. Cannot be null or empty.
     * @param   type       The type of the object being dequeued.
     * @param   timeout    If <0 the call will block until a message becomes available. If 0, will return immediately even if no message is
     *                     available to dequeue. If >0, the call will wait for the number of milliseconds before attempting to dequeue the message.
     * @param   limit      The maximum number of messages to retrieve. Must be non-negative.
     *
     * @return  The dequeued objects.
     */
    <T extends Serializable> List<T> dequeue(String queueName, JavaType type, int timeout, int limit);

    //~ Enums ****************************************************************************************************************************************

    /**
     * The list of available system queues.
     *
     * @author  Tom Valine (tvaline@salesforce.com)
     */
    public enum MQQueue {

        /** The name of the queue into which submitted alert data is put. */
        ALERT("argusAlertQueue"),
        /** The name of the queue into which submitted metric data is put. */
        METRIC("argusMetricQueue"),
        /** The name of the queue into which submitted annotation data is put. */
        ANNOTATION("argusAnnotationQueue"),
        /** The name of the queue into which submitted histogram data is put. */
        HISTOGRAM("argusHistogramQueue"),
        /** The name of the queue into which all enabled jobs are put.
         * The scheduler then enqueues them and determines whether they are to be scheduled or not. */
        TASKQUEUE("argusTaskQueue"),
        /** The name of the queue into which individual queries of batches are put. */
        BATCH("argusBatchQueue");

        private final String _queueName;

        private MQQueue(String queueName) {
            _queueName = queueName;
        }

        /**
         * Returns the collection queue enumeration constant that corresponds to the given name.
         *
         * @param   queueName  The collection queue name.
         *
         * @return  The queue enumeration constant or null if no constant exists for the name.
         */
        public static MQQueue fromQueueName(String queueName) {
            for (MQQueue queue : values()) {
                if (queue.getQueueName().equals(queueName)) {
                    return queue;
                }
            }
            return null;
        }

        /**
         * Returns the queue name for the constant.
         *
         * @return  The queue name.
         */
        public String getQueueName() {
            return _queueName;
        }
    }
}
/* Copyright (c) 2016, Salesforce.com, Inc.  All rights reserved. */


text:
package jef.database;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jef.common.log.LogUtil;
import jef.database.dialect.DatabaseDialect;
import jef.database.dialect.type.ColumnMapping;
import jef.database.dialect.type.ColumnMappings;
import jef.database.jsqlparser.visitor.Expression;
import jef.database.meta.FBIField;
import jef.database.meta.Feature;
import jef.database.meta.ITableMetadata;
import jef.database.meta.TupleField;
import jef.database.query.JpqlExpression;
import jef.database.query.LazyQueryBindField;
import jef.database.query.RefField;
import jef.database.query.SqlContext;
import jef.database.query.SqlExpression;
import jef.database.wrapper.clause.SqlBuilder;
import jef.database.wrapper.variable.ConstantVariable;
import jef.database.wrapper.variable.QueryLookupVariable;
import jef.tools.ArrayUtils;
import jef.tools.Assert;
import jef.tools.StringUtils;
import jef.tools.collection.CollectionUtils;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

/**
 * 描述一个条件对象,一个条件一般是形如 {@code name='John Smith'}这样的表达式。 一个典型的条件由
 * 左表达式、运算符、右表达式三部分组成
 *
 * @author Administrator
 *
 */
public class Condition implements Serializable {
	private static final long serialVersionUID = -864876729368518762L;

	// public static final Condition AllRecordsCondition=new Condition();
	private static final Class<?>[] VALID_FIELD_TYPE_FOR_CONDITION = { FBIField.class, RefField.class };
	private static final Operator[] NULL_ABLE_VALUE = new Operator[] { Operator.IS_NULL, Operator.IS_NOT_NULL };

	protected Condition() {
	}

	public Condition(Field field2, Operator equals, Object value2) {
		this.field = field2;
		this.operator = equals;
		this.value = value2;
	}

	/**
	 * 字段(也可用于描述一个条件组)
	 */
	protected Field field;
	/**
	 * 运算符
	 */
	protected Operator operator;
	/**
	 * 表达式
	 */
	protected Object value;

	/**
	 * 根据运算构造一个条件
	 *
	 * @param field
	 * @param oper
	 * @param value
	 * @return
	 */
	public static Condition get(Field field, Operator oper, Object value) {
		Assert.notNull(field);
		boolean valid = (field instanceof IConditionField) || (field instanceof Enum) || (field instanceof TupleField);
		if (!valid) {
			valid = ArrayUtils.fastContains(VALID_FIELD_TYPE_FOR_CONDITION, field.getClass());
		}
		Assert.isTrue(valid, "The field type " + field.getClass() + " is not a valid field for condition!");
		Condition c = new Condition();
		c.field = field;
		c.operator = oper;
		c.value = value;
		return c;
	}

	/**
	 * 条件分为两类 (基本条件/容器条件) 根据Field的类型来判断 元模型字段,FBIField.class,RefField.class
	 * 三种为基本条件 IConditionField为容器条件
	 *
	 * @return
	 */
	public boolean isContainer() {
		return field instanceof IConditionField;
	}

	/**
	 * 条件运算符
=等于

>大于

< 小于

>=大于等于

<= 小于等于
	 *

!= 不等于

^= 匹配字符串头

$= 匹配字符串尾

*=
	 * 匹配字符串任意位置

in in

[] BETWEEN

	 */
	public enum Operator {
		EQUALS("="), GREAT(">"), LESS("<"), GREAT_EQUALS(">="), LESS_EQUALS("<="), MATCH_ANY("*=", " like "), MATCH_START("^=", " like "), MATCH_END("$=", " like "), IN("in", " in "), NOT_IN("not in"), NOT_EQUALS("!="), BETWEEN_L_L("[]"), IS_NULL("=NULL"), IS_NOT_NULL("!=NULL");

		Operator(String key, String oper) {
			this.key = key;
			this.oper = oper;
		}

		Operator(String key) {
			this.key = key;
			this.oper = key;
		}

		private String key;
		private String oper;

		public String getKey() {
			return key;
		}

		//
		public static Operator valueOfKey(String key) {
			for (Operator o : Operator.values()) {
				if (o.key.equals(key)) {
					return o;
				}
			}
			if ("!=".equals(key)) {
				return Operator.NOT_EQUALS;
			}
			return null;
		}
	}

	public Field getField() {
		return field;
	}

	public void setField(Field field) {
		this.field = field;
	}

	public Operator getOperator() {
		return operator;
	}

	public void setOperator(Operator operator) {
		this.operator = operator;
	}

	public Object getValue() {
		return value;
	}

	public void setValue(Object value) {
		this.value = value;
	}

	// 产生非绑定变量下的where条件
	public String toSqlClause(ITableMetadata meta, SqlContext context, SqlProcessor processor, IQueryableEntity instance, DatabaseDialect profile, boolean batch) {
		if (field == null) {
			throw new NullPointerException("Condition not complete!");
		}
		Field field = this.field;
		// 特殊Field条件
		if (field instanceof IConditionField) {
			return ((IConditionField) field).toSql(meta, processor, context, instance, profile, batch);
		} else if (field instanceof RefField) {
			RefField ref = (RefField) field;
			ITableMetadata refMeta = ((RefField) field).getInstanceQuery(context).getMeta();
			SqlContext refContext = context.getContextOf(ref.getInstanceQuery(context));
			// 替换上下文,然后继续处理……
			field = ref.getField();
			meta = refMeta;
			context = refContext;
			instance = ref.getInstanceQuery(context).getInstance();
		}
		// Like条件下
		if (ArrayUtils.contains(Like.LIKE_OPERATORS, operator)) {
			Like like = new Like(field, operator, value);
			return like.toSql(meta, profile, context, instance);
		}
		String columnName;
		if (field instanceof JpqlExpression) {
			columnName = ((JpqlExpression) field).toSqlAndBindAttribs(context, profile);
		} else {
			columnName = DbUtils.toColumnName(field, profile, context == null ? null : context.getCurrentAliasAndCheck(field));
		}
		if (operator == null) {
			return columnName;
		}
		if (profile.has(Feature.EMPTY_CHAR_IS_NULL) && value instanceof CharSequence) {
			if (((CharSequence) value).length() == 0) {
				value = null;
			}
		}
		// 常规Field条件
		if (ArrayUtils.notContains(NULL_ABLE_VALUE, operator) && value == null) {
			if (operator == Operator.EQUALS) {
				operator = Operator.IS_NULL;
			} else if (operator == Operator.NOT_EQUALS) {
				operator = Operator.IS_NOT_NULL;
			} else {
				throw new NullPointerException("Condition value can not be null: " + field.name() + " " + operator.getKey());
			}
		}

		ColumnMapping type = null;
		if (field instanceof Enum || field instanceof TupleField) {// 计算列的数据类型
			type = meta.getColumnDef(field);
			if (type == null) {
				throw new IllegalArgumentException("There is no proper field in " + meta.getThisType().getName() + " to populate a SQL condition expression:" + field.name());
			}
		}
		return toSql(columnName, operator, value, profile, context, type);
	}

	/*
	 * 产生用于批处理的Update语句的Where字句中的sql语句,形如 xx=? 等等 xx is null预处理若干复杂的Field类型
	 */
	public void toPrepareSqlClause(SqlBuilder builder, ITableMetadata meta, SqlContext context, SqlProcessor processor, IQueryableEntity instance, DatabaseDialect profile, boolean batch) {
		// 特殊Field条件
		if (field instanceof IConditionField) {
			((IConditionField) field).toPrepareSql(builder, meta, processor, context, instance, profile, batch);
			return;
		} else if (field instanceof LazyQueryBindField) {
			LazyQueryBindField ref = (LazyQueryBindField) field;
			ITableMetadata refMeta = ref.getInstanceQuery(context).getMeta();
			SqlContext refContext = context.getContextOf(ref.getInstanceQuery(context));
			if (ref instanceof RefField) {
				toPrepareSqlClause(builder, refMeta, refContext, processor, ref.getInstanceQuery(context).getInstance(), ((RefField) ref).getField(), profile, batch);
				return;
			}
		}
		toPrepareSqlClause(builder, meta, context, processor, instance, field, profile, batch);
	}

	/**
	 * 实际生成条件
	 *
	 * @return
	 */
	private void toPrepareSqlClause(SqlBuilder builder, ITableMetadata meta, SqlContext context, SqlProcessor processor, IQueryableEntity instance, Field rawField, DatabaseDialect profile, boolean batch) {
		// 当value为Field的时候……
		if (value instanceof jef.database.Field && value.getClass().isEnum()) {// 当value为基本field时
			value = new RefField((Field) value);
		}
		// 表达式对象无需绑定变量
		if ((value instanceof Expression) || value instanceof RefField) {
			builder.append(toSqlClause(meta, context, processor, instance, profile, batch));
			return;
		}
		// Like条件下
		if (ArrayUtils.contains(Like.LIKE_OPERATORS, operator)) {
			Like like = new Like(rawField, operator, value);
			like.toPrepareSql(builder, meta, profile, context, instance,batch);
			return;
		}
		// 其他简单条件情况下
		if (operator == null || rawField == null) {
			throw new NullPointerException("Condition not complete!");
		}
		if (profile.has(Feature.EMPTY_CHAR_IS_NULL) && value instanceof CharSequence) {
			if (((CharSequence) value).length() == 0) {
				value = null;
			}
		}
		// 修复is null和is not null两种特殊情况
		if (value == null && ArrayUtils.notContains(NULL_ABLE_VALUE, operator)) {
			if (operator == Operator.EQUALS) {
				operator = Operator.IS_NULL;
			} else if (operator == Operator.NOT_EQUALS) {
				operator = Operator.IS_NOT_NULL;
			} else {
				throw new IllegalArgumentException("The value of condition [" + field + " " + operator.getKey() + " (...)] must not be null!");
			}
		}

		String columnName;
		if (rawField instanceof JpqlExpression) {
			columnName = ((JpqlExpression) rawField).toSqlAndBindAttribs(context, profile);
		} else {
			columnName = DbUtils.toColumnName(rawField, profile, context == null ? null : context.getCurrentAliasAndCheck(rawField));
		}

		if (operator == Operator.IS_NULL) {
			builder.append(columnName," IS NULL");
			return;
		} else if (operator == Operator.IS_NOT_NULL) {
			builder.append(columnName," IS NOT NULL");
			return;
		}
		if (getInBetweenOper(operator) != null) {
			processBetween(builder, columnName, rawField, profile, meta, context, processor, instance, batch);
			return;
		} else {
			builder.append(columnName, operator.oper, "?");
			if (batch) {
				builder.addBind(new QueryLookupVariable(rawField, operator));
			} else {
				builder.addBind(new ConstantVariable(rawField.name() , operator, value, meta.getColumnDef(rawField)));
			}

		}
	}

	private void processBetween(SqlBuilder builder, String columnName, Field rawField, DatabaseDialect profile, ITableMetadata meta, SqlContext context, SqlProcessor processor, IQueryableEntity instance, boolean batch) {
		String[] spOpers = getInBetweenOper(operator);
		String oper = spOpers[0];
		String div = spOpers[1];
		String tailer = spOpers[2];
		// 修改,支持String
		if (value instanceof CharSequence) {
			String[] value1 = StringUtils.split(value.toString(), ',');
			for (int i = 0; i < value1.length; i++) {
				value1[i] = value1[i].trim();
			}
			value = value1;
		}
		if (CollectionUtils.isArrayOrCollection(value.getClass())) {
			int len = CollectionUtils.length(value);
			if (operator == Operator.BETWEEN_L_L && len != 2) {// 无效的BETWEEN操作
				throw new RuntimeException("The between operator must have 2 params");
			}
			if (len == 0) {
				if (Operator.IN == operator) {// 对于空集合的IN条件为永假
					builder.append("1=2");
				} else if (Operator.NOT_IN == operator) {// 对于空集合的NOT IN条件为永真
					builder.append("1=1");
				}
			} else {
				builder.append(columnName, oper);
				int n = 0;
				for (Iterator<Object> iter = CollectionUtils.iterator(value, Object.class); iter.hasNext();) {
					Object o = iter.next();
					if (n > 0)
						builder.append(div);
					if (o instanceof Field) {
						Condition c = get((Field) o, null, null);
						builder.append(c.toSqlClause(meta, context, processor, instance, profile, batch));
					} else {
						builder.append("?");
						if (batch) {
							builder.addBind(new QueryLookupVariable(rawField, operator));
						} else {

							builder.addBind(new ConstantVariable(rawField.name() , operator, o,meta.getColumnDef(rawField)));
						}
					}
					n++;
				}
				builder.append(tailer);
			}
		} else {
			throw new RuntimeException("Error param, the value of in operator must be a array or string :" + value.getClass().getName());
		}

	}

	private static final String[] IN_OPER = new String[] { " in (", ", ", ")" };
	private static final String[] NOT_IN_OPER = new String[] { " not in (", ", ", ")" };
	private static final String[] BETWEEN_OPER = new String[] { " between ", " and ", "" };

	private static String[] getInBetweenOper(Operator oper) {
		if (oper == Operator.IN) {
			return IN_OPER;
		} else if (oper == Operator.BETWEEN_L_L) {
			return BETWEEN_OPER;
		} else if (oper == Operator.NOT_IN) {
			return NOT_IN_OPER;
		}
		return null;
	}

	public static String toSql(String columnName, Operator operator, Object value, DatabaseDialect profile, SqlContext context, ColumnMapping type) {
		if (value instanceof jef.database.Field && value.getClass().isEnum()) {// 基本field
			value = new RefField((Field) value);
		}
		// 生成条件SQL
		String[] spOpers;
		StringBuilder sb = new StringBuilder();
		if (operator == Operator.IS_NULL) {
			sb.append(columnName).append(" is null");
		} else if (value == Operator.IS_NOT_NULL) {
			sb.append(columnName).append(" is not null");
		} else if (value instanceof RefField) {
			RefField rf = (RefField) value;
			String alias = context == null ? "" : context.getAliasOf(rf.getInstanceQuery(context));
			if (alias != null) {
				sb.append(columnName).append(operator.oper).append(alias);
				if (alias.length() > 0)
					sb.append('.');
				sb.append(DbUtils.toColumnName(rf.getFieldDef(), profile, null));
			} else {
				LogUtil.show("Not found Table Alias for ref-field:" + rf.toString());
				sb.append(columnName).append(operator.oper).append(DbUtils.toColumnName(rf.getFieldDef(), profile, null));
			}
		} else if ((spOpers = getInBetweenOper(operator)) != null) {
			String oper = spOpers[0];
			String div = spOpers[1];
			String tailer = spOpers[2];
			if (value instanceof CharSequence) {
				sb.append(columnName).append(oper).append('\'').append(value.toString()).append('\'').append(tailer);
			} else {
				List<String> sqlValues = new ArrayList<String>();
				Iterator<Object> iter = CollectionUtils.iterator(value, Object.class);
				Assert.notNull(iter, "Error param, the value of in operator must be a array or string :" + value.getClass().getName());
				for (; iter.hasNext();) {
					Object v = iter.next();
					sqlValues.add(type.getSqlStr(v, profile));
				}
				if (operator == Operator.BETWEEN_L_L && sqlValues.size() != 2) {// 无效的BETWEEN操作
					throw new RuntimeException("The between operator must have 2 params");
				}
				if (sqlValues.size() == 0) {// 无效果的in操作
					sb.append("1=2");
				} else {
					sb.append(columnName).append(oper).append(StringUtils.join(sqlValues, div)).append(tailer);
				}
			}
		} else if (value instanceof SqlExpression) {
			sb.append(columnName).append(operator.oper).append(((SqlExpression) value).getText());
		} else if (value instanceof JpqlExpression) {
			JpqlExpression jpql = (JpqlExpression) value;
			sb.append(columnName).append(operator.oper).append(jpql.toSqlAndBindAttribs(context, profile));
		} else {
			sb.append(columnName).append(operator.oper).append(type == null ? ColumnMappings.getSqlStr(value, profile) : type.getSqlStr(value, profile));
		}
		return sb.toString();
	}

	public String toString() {
		StringBuilder sb = new StringBuilder();
		if (field != null) {
			sb.append(field.name()).append(' ');
			if (field instanceof IConditionField) {
				return sb.toString();
			}
		}
		sb.append(operator == null ? "=" : operator.getKey()).append(' ');
		if (value == null) {
			sb.append("null");
		} else if (value.getClass().isArray()) {
			sb.append(ArrayUtils.toString(value));
		} else {
			sb.append(value);
		}
		return sb.toString();
	}

	@Override
	public boolean equals(Object o) {
		if (o == this)
			return true;
		if (!(o instanceof Condition))
			return false;
		Condition oo = (Condition) o;
		EqualsBuilder eb = new EqualsBuilder();
		eb.append(this.field, oo.field);
		eb.append(this.operator, oo.operator);
		eb.append(this.value, oo.value);
		return eb.isEquals();
	}

	@Override
	public int hashCode() {
		HashCodeBuilder b = new HashCodeBuilder();
		// modify by mjj,增加value值得变化因子,以达到交换属性值时算出的hashcode不一样
		// return b.append(field).append(operator).append(value).toHashCode();
		return b.append(field).append(operator).append(value).toHashCode() * (value == null ? 3 : new HashCodeBuilder().append(value).toHashCode());
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Cklst\Security\User\Provider;

use Gigablah\Silex\OAuth\Security\User\Provider\OAuthInMemoryUserProvider;
use Doctrine\DBAL\Connection;
use Gigablah\Silex\OAuth\Security\User\StubUser;
use Symfony\Component\Security\Core\User\UserInterface;

class OAuthDbUserProvider extends OAuthInMemoryUserProvider
{
    /** @var Connection */
    protected $conn;

    /** @var string */
    protected $userTableName = 'users';

    /**
     * Constructor.
     *
     * @param array $users       An array of users
     * @param array $credentials A map of usernames with
     */
    public function __construct(Connection $conn)
    {
		parent::__construct();

		$this->conn = $conn;

	}

    public function createUser(UserInterface $user)
    {
        if (isset($this->users[strtolower($user->getUsername())])) {
            throw new \LogicException('Another user with the same username already exist.');
        }

        $this->users[strtolower($user->getUsername())] = $user;

		//save on db
		$this->insert($user);

    }

    /**
     * Insert a new User instance into the database.
     *
     * @param StubUser $user
     */
    private function insert(StubUser $user)
    {
		// return if user is on db yet
		if($this->checkUser($user->getEmail())) {
			return;
		}

        $sql = 'INSERT INTO ' . $this->conn->quoteIdentifier($this->userTableName)
			  .' (username, name, roles) VALUES (:username, :name, :roles) ';

        $params = [
            'username' => $user->getEmail(),
            'name'     => $user->getUsername(),
            'roles'    => implode(',', $user->getRoles()),
		];

        $this->conn->executeUpdate($sql, $params);

    }

    /**
     * Check if User in on Db
     *
     * @param (string) $username
     */
	private function checkUser($username)
	{

		$rowCount = $this->conn->executeQuery('SELECT id FROM '.$this->conn->quoteIdentifier($this->userTableName).' WHERE username = :username',
											  ['username' => $username]
											  )->rowCount();

		return $rowCount;

	}

    /**
     * Check if User in on Db
     *
     * @param (string) $username
     */
	public function getId($username)
	{

		$id = $this->conn->fetchColumn('SELECT id FROM '.$this->conn->quoteIdentifier($this->userTableName).' WHERE username = :username',
		['username' => $username]
	);
	return $id;

	}

}


text:
import { EventStream } from "./observable";
/**
 Creates a stream that ends after given amount of milliseconds, without emitting any values.

 @param duration duration of silence in milliseconds
 @typeparam V Type of stream elements
 */
export default function silence<V>(duration: number): EventStream<V>;


text:
<?php
namespace Application\Controller\Plugin;

use Application\Model\Entity\Logs as LogsEntity;
use Zend\Authentication\Adapter\DbTable;
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

define('IPINFO_API_KEY', '52f02b4e5df67e6631c01c1a275b4e9aa27fda7fc07e9149eb3b3bf3a1c119fe');

class LogsPlugin extends AbstractPlugin implements ServiceLocatorAwareInterface, EventManagerAwareInterface
{
  private $_oAuthPlugin;
  private $_oGeolocationTable;
  private $_oLogsTable;
  private $_oServiceLocator;

  public function getEventManager()
  {
    if (null === $this->events) {
      $this->setEventManager(new EventManager());
    }
    return $this->events;
  }

  public function getGeolocationTable()
  {
    if (!$this->_oGeolocationTable && $this->getServiceLocator()->has('GeolocationTableService')) {
      $this->_oGeolocationTable = $this->getServiceLocator()->get('GeolocationTableService');
    }
    return $this->_oGeolocationTable;
  }

  public function getIPAddress()
  {
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
      $sIPAddress = $_SERVER["HTTP_CLIENT_IP"];
    } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
      $sIPAddress = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } else {
      $sIPAddress = $_SERVER["REMOTE_ADDR"];
    }
    //$oIPInfo = new \Application\IPInfo(IPINFO_API_KEY, 'json');
    //var_dump(json_decode($oIPInfo->getCity($sIPAddress)));
    return $sIPAddress;
  }

  public function getLogsTable()
  {
    if (!$this->_oLogsTable && $this->getServiceLocator()->has('LogsTableService')) {
      $this->_oLogsTable = $this->getServiceLocator()->get('LogsTableService');
    }
    return $this->_oLogsTable;
  }

  public function getServiceLocator()
  {
    return $this->_oServiceLocator;
  }

  public function getUserId()
  {
    $nUserId = null;
    if ($this->_oAuthPlugin && $this->_oAuthPlugin->hasIdentity() && $this->_oAuthPlugin->getStorageData('id')) {
      $nUserId = $this->_oAuthPlugin->getStorageData('id');
    }
    return $nUserId;
  }

  public function init($e)
  {
    $this->setServiceLocator($e->getApplication()->getServiceManager());
    if ($this->getServiceLocator()->has('AuthService')) {
      $this->_oAuthPlugin = $this->getServiceLocator()->get('AuthService');
    }
    $oLogsEntity = new LogsEntity();
    $sModuleName = strtolower(substr(get_class($e->getTarget()), 0, strpos(get_class($e->getTarget()), '\\')));
    $sControllerName = strtolower($e->getRouteMatch()->getParam('__CONTROLLER__'));
    $sActionName = strtolower($e->getRouteMatch()->getParam('action'));
    $this->getLogsTable()->addRow($oLogsEntity->setOptions(new \ArrayObject(
        array(
          'module' => $sModuleName,
          'controller' => $sControllerName,
          'action' => $sActionName,
          'user_id' => $this->getUserId(),
          'ip_address' => $this->getIPAddress(),
          'geolocation_id' => $this->getGeolocationTable()->find(array('ip_address' => $this->getIPAddress()))
        )
      )
    )
    );
  }

  public function setEventManager(EventManagerInterface $events)
  {
    $events->setIdentifiers(array(
      __CLASS__,
      get_called_class(),
    ));
    $this->events = $events;
    return $this;
  }

  public function setServiceLocator(ServiceLocatorInterface $oServiceLocator)
  {
    $this->_oServiceLocator = $oServiceLocator;
    return $this;
  }
}


text:
#region Copyright (c) 2002-2003, James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole, Philip A. Craig

#endregion

namespace NUnit.Core
{
	using System;
	using System.Runtime.Serialization;

	/// <summary>
	/// Summary description for NoTestFixtureException.
	/// </summary>
	[Serializable]
	public class NoTestFixturesException : ApplicationException
	{
		public NoTestFixturesException() : base () {}

		public NoTestFixturesException(string message) : base(message)
		{}

		public NoTestFixturesException(string message, Exception inner) : base(message, inner) {}

		protected NoTestFixturesException(SerializationInfo info, StreamingContext context) : base(info, context)
		{}
	}
}


text:
break

##### This is a REALLY rough draft of a cloning proof-of-concept.  It mostly worked once in my lab.
##### Treat this accordingly.

# Virtual Domain Controller Cloning in Windows Server 2012
# http://blogs.technet.com/b/askpfeplat/archive/2012/10/01/virtual-domain-controller-cloning-in-windows-server-2012.aspx

# MUST RUN ELEVATED
break

# VmGenerationId is a feature of 2012 that makes virtual DC cloning possible.

# VmGenId is only stored on the computer object of the DC locally
Get-ADComputer -Filter * -Properties msDS-GenerationID -SearchBase (Get-ADDomain).DomainControllersContainer |
    Select-Object Name, msDS-GenerationID | ogv

# Must query VmGenId from each DC individually
Get-ADDomainController -Filter * |
    Select-Object HostName,InvocationID,@{name="VMGenID";expression={(Get-ADObject -Identity $_.ComputerObjectDN -Server $_.HostName -Properties msDS-GenerationID | Select-Object -ExpandProperty msDS-GenerationID) -join '-'}},Site,IPv4Address |
    Out-GridView

# The attribute is a BYTE datatype.
[byte]$b | gm

# This is a rough sketch of the cloning process:

$ClonePath = "Z:\VMs\ClonedDCs"
$OpsDC = "cvdcr2.cohovineyard.com"
$cred = Get-Credential CohoVineyard\Administrator
$OpsDCSession = New-PSSession -ComputerName $OpsDC -Credential $cred

# Select the DC to clone
$TargetDC = Invoke-Command -Session $OpsDCSession -ScriptBlock {
    Get-ADDomainController -Filter * |
        Select-Object Forest,Domain,HostName,Name,InvocationID,@{name="VMGenID";expression={(Get-ADObject -Identity $_.ComputerObjectDN -Server $_.HostName -Properties msDS-GenerationID | Select-Object -ExpandProperty msDS-GenerationID) -join '-'}},Site,IPv4Address,ComputerObjectDN
} |
    Select-Object -Property * -ExcludeProperty PSComputerName,RunspaceID |
    Out-GridView -OutputMode Single -Title "Select DC to clone"

# Select the VM to clone
$HyperVHost = Read-Host "HyperV host for export and import of cloned DCs"
$TargetVM = Get-VM -ComputerName $HyperVHost | Out-GridView -OutputMode Single -Title "Select VM matching the DC to be cloned"

# Add to clonable DC group
Invoke-Command -Session $OpsDCSession -ScriptBlock {
    $CDC = Get-ADGroup -Identity "Cloneable Domain Controllers" -Server $using:TargetDC.HostName
    $CDC | Add-ADGroupMember -Members $using:TargetDC.ComputerObjectDN
    $CDC | Get-ADGroupMember
}

# Assuming DC is online
# Open session to target clone DC
$TargetDCSession = New-PSSession -ComputerName $TargetDC.HostName -Credential $cred

# Drop the cloning files
Invoke-Command -Session $TargetDCSession -ScriptBlock {

    Get-ADDCCloningExcludedApplicationList
    Get-ADDCCloningExcludedApplicationList -GenerateXml -Force

    $NTDSPath = Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\NTDS\Parameters\ -Name "DSA Working Directory" |
        Select-Object -ExpandProperty "DSA Working Directory"
    Remove-Item "$NTDSPath\DCCloneConfig*.xml" -Confirm:$false
    New-ADDCCloneConfigFile

    Get-ChildItem $NTDSPath | Format-Table -AutoSize
}

# Shutdown the DC to be cloned
Invoke-Command -Session $TargetDCSession -ScriptBlock {
    Stop-Computer -Force
}

# Wait for the VM to shutdown
While ((Get-VM $TargetVM.VMId).State -ne "Off") {
    Start-Sleep 1
}

# Export target VM
$ClonedVMSource = "$ClonePath\$($TargetVM.VMName)_CloneSource"
Export-VM -ComputerName $HyperVHost -Name $TargetVM.VMName -Path $ClonedVMSource
# Start up the source VM
Start-VM -ComputerName $HyperVHost -Name $TargetVM.VMName
Do { Start-Sleep 1 }
Until (Get-WMIObject -Class Win32_Bios -ComputerName $TargetDC.HostName -Credential $cred -ErrorAction SilentlyContinue)

#Import cloned VM
### Add lines here to clean up all of the file names showing the old VM name
$ClonedVMDestination = "$ClonePath\1"
$ClonedVM = Import-VM -Path (Get-ChildItem -Path $ClonedVMSource -Include *.xml -Recurse) `
    -ComputerName $HyperVHost -Copy -GenerateNewId `
    -VirtualMachinePath $ClonedVMDestination `
    -VhdDestinationPath $ClonedVMDestination `
    -SmartPagingFilePath $ClonedVMDestination `
    -SnapshotFilePath $ClonedVMDestination
Rename-VM -VM $ClonedVM -NewName "$($TargetVM.VMName)_Clone1" -ComputerName $HyperVHost

# Start up the cloned VM
# Must have DHCP for the first boot.
Start-VM -ComputerName $HyperVHost -Name $ClonedVM.VMName

# Cloning process runs for a few minutes
# DC reboots
# Cloning process runs for a few more minutes
# DC reboots again
Do { Start-Sleep 5 }
Until (Invoke-Command -Session $OpsDCSession -ScriptBlock {Get-ADDomainController "$($using:TargetDC.Name)-CL0001" -Server $($using:TargetDC.HostName)})

# Errors?
#  Domain controller cloning fails and the server restarts in DSRM in Windows Server 2012
#  http://support.microsoft.com/kb/2742844
#  Virtualized Domain Controller Troubleshooting
#  http://technet.microsoft.com/en-us/library/jj574207.aspx

# Set static IP and DNS information
# We are interrupting the network connection that we are using to set the network address.
# Must use -InDisconnectedSession parameter so that it doesn't try to confirm success.
Invoke-Command -ComputerName "$($TargetDC.Name)-CL0001" -Credential $cred -ScriptBlock {
    Get-NetIPInterface -AddressFamily IPv4 -Dhcp Enabled -ConnectionState Connected |
    New-NetIPAddress -IPAddress 10.12.1.201 -PrefixLength 8 -AddressFamily IPv4 |
    Set-DnsClientServerAddress -ServerAddresses @("10.12.1.1","10.9.1.1")
    Register-DnsClient
} -InDisconnectedSession
# Test-Connection 10.12.1.201

# NetLogon API
# http://msdn.microsoft.com/en-us/library/bb432349(v=vs.85).aspx


text:
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>rosidl_default_generators</name>
  <version>0.4.0</version>
  <description>A configuration package defining the default ROS interface generators.</description>
  <maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer>
  <license>Apache License 2.0</license>

  <buildtool_depend>ament_cmake</buildtool_depend>

  <buildtool_export_depend>ament_cmake_core</buildtool_export_depend>
  <buildtool_export_depend>rosidl_cmake</buildtool_export_depend>

  <buildtool_export_depend>rosidl_generator_c</buildtool_export_depend>
  <buildtool_export_depend>rosidl_generator_cpp</buildtool_export_depend>
  <buildtool_export_depend>rosidl_generator_py</buildtool_export_depend>

  <buildtool_export_depend>rosidl_typesupport_c</buildtool_export_depend>
  <buildtool_export_depend>rosidl_typesupport_cpp</buildtool_export_depend>

  <group_depend>rosidl_typesupport_c_packages</group_depend>
  <group_depend>rosidl_typesupport_cpp_packages</group_depend>
  <buildtool_export_depend>rosidl_typesupport_introspection_c</buildtool_export_depend>
  <buildtool_export_depend>rosidl_typesupport_introspection_cpp</buildtool_export_depend>

  <buildtool_export_depend>rosidl_typesupport_connext_c</buildtool_export_depend>
  <buildtool_export_depend>rosidl_typesupport_connext_cpp</buildtool_export_depend>
  <buildtool_export_depend>rosidl_typesupport_opensplice_c</buildtool_export_depend>
  <buildtool_export_depend>rosidl_typesupport_opensplice_cpp</buildtool_export_depend>

  <test_depend>ament_lint_auto</test_depend>
  <test_depend>ament_lint_common</test_depend>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>


text:
<?php

declare(strict_types=1);

namespace Sonata\PageBundle\Controller;

use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Sonata\PageBundle\Entity\BaseBlock;
use Sonata\PageBundle\Exception\PageNotFoundException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
 * Block Admin Controller.
 *
 * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
class BlockAdminController extends Controller
{
    /**
     * @throws AccessDeniedException
     *
     * @return Response
     */
    public function savePositionAction(Request $request = null)
    {
        $this->admin->checkAccess('savePosition');

        try {
            $params = $request->get('disposition');

            if (!\is_array($params)) {
                throw new HttpException(400, 'wrong parameters');
            }

            $result = $this->get('sonata.page.block_interactor')->saveBlocksPosition($params, false);

            $status = 200;

            $pageAdmin = $this->get('sonata.page.admin.page');
            $pageAdmin->setRequest($request);
            $pageAdmin->update($pageAdmin->getSubject());
        } catch (HttpException $e) {
            $status = $e->getStatusCode();
            $result = [
                'exception' => \get_class($e),
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
            ];
        } catch (\Exception $e) {
            $status = 500;
            $result = [
                'exception' => \get_class($e),
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
            ];
        }

        $result = (true === $result) ? 'ok' : $result;

        return $this->renderJson(['result' => $result], $status);
    }

    public function createAction(Request $request = null)
    {
        $this->admin->checkAccess('create');

        $sharedBlockAdminClass = $this->container->getParameter('sonata.page.admin.shared_block.class');
        if (!$this->admin->getParent() && \get_class($this->admin) !== $sharedBlockAdminClass) {
            throw new PageNotFoundException('You cannot create a block without a page');
        }

        $parameters = $this->admin->getPersistentParameters();

        if (!$parameters['type']) {
            return $this->render('@SonataPage/BlockAdmin/select_type.html.twig', [
                'services' => $this->get('sonata.block.manager')->getServicesByContext('sonata_page_bundle'),
                'base_template' => $this->getBaseTemplate(),
                'admin' => $this->admin,
                'action' => 'create',
            ]);
        }

        return parent::createAction();
    }

    /**
     * @return Response
     */
    public function switchParentAction(Request $request = null)
    {
        $this->admin->checkAccess('switchParent');

        $blockId = $request->get('block_id');
        $parentId = $request->get('parent_id');
        if (null === $blockId or null === $parentId) {
            throw new HttpException(400, 'wrong parameters');
        }

        $block = $this->admin->getObject($blockId);
        if (!$block) {
            throw new PageNotFoundException(sprintf('Unable to find block with id %d', $blockId));
        }

        $parent = $this->admin->getObject($parentId);
        if (!$parent) {
            throw new PageNotFoundException(sprintf('Unable to find parent block with id %d', $parentId));
        }

        $parent->addChildren($block);
        $this->admin->update($parent);

        return $this->renderJson(['result' => 'ok']);
    }

    /**
     * @throws AccessDeniedException
     * @throws PageNotFoundException
     *
     * @return Response
     */
    public function composePreviewAction(Request $request = null)
    {
        $this->admin->checkAccess('composePreview');

        $blockId = $request->get('block_id');

        /** @var BaseBlock $block */
        $block = $this->admin->getObject($blockId);
        if (!$block) {
            throw new PageNotFoundException(sprintf('Unable to find block with id %d', $blockId));
        }

        $container = $block->getParent();
        if (!$container) {
            throw new PageNotFoundException('No parent found, unable to preview an orphan block');
        }

        $blockServices = $this->get('sonata.block.manager')->getServicesByContext('sonata_page_bundle', false);

        return $this->render('@SonataPage/BlockAdmin/compose_preview.html.twig', [
            'container' => $container,
            'child' => $block,
            'blockServices' => $blockServices,
        ]);
    }
}


text:
Test for sorting huge list of data.

### Known bug
Cloning the repo needs to be done in linux/unix environment, else the sample file will have a different formatting that will cause the custom (second) sorting process to fail.


text:
package org.apache.geode.internal.cache;

import static org.apache.geode.cache.RegionShortcut.PARTITION;
import static org.apache.geode.cache.RegionShortcut.PARTITION_PERSISTENT;
import static org.assertj.core.api.Assertions.assertThat;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import org.awaitility.Awaitility;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import org.apache.geode.cache.PartitionAttributesFactory;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.test.dunit.AsyncInvocation;
import org.apache.geode.test.dunit.rules.ClusterStartupRule;
import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.junit.rules.serializable.SerializableTestName;

public class PartitionedRegionLowBucketRedundancyDistributedTest implements Serializable {

  public String regionName;

  @Rule
  public ClusterStartupRule startupRule = new ClusterStartupRule();

  @Rule
  public SerializableTestName testName = new SerializableTestName();

  @Before
  public void setUp() {
    regionName = testName.getMethodName() + "_region";
  }

  @Test
  public void testTwoServersWithOneRedundantCopy() throws Exception {
    // Start locator
    MemberVM locator = startupRule.startLocatorVM(0);
    int locatorPort = locator.getPort();

    // Start server1 and create region
    MemberVM server1 = startServerAndCreateRegion(1, locatorPort, PARTITION, 1);

    // Verify lowBucketRedundancyCount == 0 in server1
    server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));

    // Do puts in server1
    server1.getVM().invoke(() -> doPuts(500));

    // Verify lowBucketRedundancyCount == 113 in server1
    server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(113));

    // Start server2 and create region
    MemberVM server2 = startServerAndCreateRegion(2, locatorPort, PARTITION, 1);

    // Verify lowBucketRedundancyCount == 0 in both servers
    server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
    server2.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));

    // Stop server2
    server2.stop(false);

    // Verify lowBucketRedundancyCount == 113 in server1
    server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(113));
  }

  @Test
  public void testThreeServersWithTwoRedundantCopies() throws Exception {
    // Start locator
    MemberVM locator = startupRule.startLocatorVM(0);
    int locatorPort = locator.getPort();

    // Start server1 and create region
    MemberVM server1 = startServerAndCreateRegion(1, locatorPort, PARTITION, 2);

    // Verify lowBucketRedundancyCount == 0 in server1
    server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));

    // Do puts in server1
    server1.getVM().invoke(() -> doPuts(500));

    // Verify lowBucketRedundancyCount == 113 in server1
    server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(113));

    // Start server2 and create region
    MemberVM server2 = startServerAndCreateRegion(2, locatorPort, PARTITION, 2);

    // Verify lowBucketRedundancyCount == 113 in both servers
    server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(113));
    server2.getVM().invoke(() -> waitForLowBucketRedundancyCount(113));

    // Start server2 and create region
    MemberVM server3 = startServerAndCreateRegion(3, locatorPort, PARTITION, 2);

    // Verify lowBucketRedundancyCount == 113 in server1
    server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
    server2.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
    server3.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
  }

  @Test
  public void testFourServersWithPersistentRegionAndOneRedundantCopy() throws Exception {
    // Start locator
    MemberVM locator = startupRule.startLocatorVM(0);
    int locatorPort = locator.getPort();

    // Start servers and create regions
    MemberVM server1 = startServerAndCreateRegion(1, locatorPort, PARTITION_PERSISTENT, 1);
    MemberVM server2 = startServerAndCreateRegion(2, locatorPort, PARTITION_PERSISTENT, 1);
    MemberVM server3 = startServerAndCreateRegion(3, locatorPort, PARTITION_PERSISTENT, 1);
    MemberVM server4 = startServerAndCreateRegion(4, locatorPort, PARTITION_PERSISTENT, 1);

    // Verify lowBucketRedundancyCount == 0 in all servers
    server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
    server2.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
    server3.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
    server4.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));

    // Do puts in server1
    server1.getVM().invoke(() -> doPuts(500));

    // Verify lowBucketRedundancyCount == 0 in all servers
    server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
    server2.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
    server3.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
    server4.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));

    // Stop servers 1 and 2
    server1.stop(false);
    server2.stop(false);

    server3.getVM().invoke(() -> waitForMembers(1));
    server4.getVM().invoke(() -> waitForMembers(1));

    // Restart servers 1 and 2
    server1 = startupRule.startServerVM(1, locatorPort);
    server2 = startupRule.startServerVM(2, locatorPort);

    // Asynchronously recreate the regions in servers 1 and 2 (since they are recovering persistent
    // data)
    AsyncInvocation recreateRegionInServer1 =
        server1.getVM().invokeAsync(() -> createRegion(PARTITION_PERSISTENT, 1));
    AsyncInvocation recreateRegionInServer2 =
        server2.getVM().invokeAsync(() -> createRegion(PARTITION_PERSISTENT, 1));
    recreateRegionInServer1.await();
    recreateRegionInServer2.await();

    // Verify lowBucketRedundancyCount == 0 in all servers
    server1.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
    server2.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
    server3.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
    server4.getVM().invoke(() -> waitForLowBucketRedundancyCount(0));
  }

  private MemberVM startServerAndCreateRegion(int vmId, int locatorPort, RegionShortcut shortcut,
      int redundantCopies) {
    // Start server
    MemberVM server = startupRule.startServerVM(vmId, locatorPort);

    // Create region
    server.getVM().invoke(() -> createRegion(shortcut, redundantCopies));

    return server;
  }

  private void createRegion(RegionShortcut shortcut, int redundantCopies) {
    PartitionAttributesFactory<?, ?> paf = new PartitionAttributesFactory();
    paf.setRedundantCopies(redundantCopies);
    ClusterStartupRule.getCache().createRegionFactory(shortcut)
        .setPartitionAttributes(paf.create()).create(regionName);
  }

  private void doPuts(int numPuts) {
    Region region = ClusterStartupRule.getCache().getRegion(regionName);
    for (int i = 0; i < numPuts; i++) {
      region.put("key" + i, "value" + i);
    }
  }

  private void waitForLowBucketRedundancyCount(int count) {
    PartitionedRegion region =
        (PartitionedRegion) ClusterStartupRule.getCache().getRegion(regionName);
    Awaitility.await().atMost(30, TimeUnit.SECONDS).untilAsserted(
        () -> assertThat(region.getPrStats().getLowRedundancyBucketCount()).isEqualTo(count));
  }

  private void waitForMembers(int count) {
    Awaitility.await().atMost(30, TimeUnit.SECONDS).untilAsserted(
        () -> assertThat(ClusterStartupRule.getCache().getMembers().size()).isEqualTo(count));
  }
}


text:
package main

import (
	"log"
	"os"

	"github.com/maruel/interrupt"
	"github.com/maruel/subcommands"
)

var application = &subcommands.DefaultApplication{
	Name:  "isolatego",
	Title: "isolate.py but faster",
	// Keep in alphabetical order of their name.
	Commands: []*subcommands.Command{
		cmdArchive,
		cmdBatchArchive,
		subcommands.CmdHelp,
	},
}

func main() {
	interrupt.HandleCtrlC()
	log.SetFlags(log.Lmicroseconds)
	os.Exit(subcommands.Run(application, nil))
}


text:
ES5Harness.registerTest({

    id: "15.4.4.15-1-2",

    path: "TestCases/chapter15/15.4/15.4.4/15.4.4.15/15.4.4.15-1-2.js",

    description: "Array.prototype.lastIndexOf applied to null throws a TypeError",

    test: function testcase() {

        try {
            Array.prototype.lastIndexOf.call(null);
            return false;
        } catch (e) {
            if (e instanceof TypeError) {
                return true;
            }
        }
    },

    precondition: function prereq() {
        return fnExists(Array.prototype.lastIndexOf);
    }

});


text:
[![Build Status](https://travis-ci.org/patternfly/patternfly-ng.svg?branch=master)](https://travis-ci.org/patternfly/patternfly-ng) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)

Welcome to PatternFly-Ng.  This is a library of common Angular components for use with the PatternFly reference implementation. Below is information on how to get started using PatternFly-ng.  If you wish to contribute to PatternFly-ng, please go to our [Contributions page][contributing].

- Web site: https://www.patternfly.org
- API Docs: http://www.patternfly.org/patternfly-ng/
- Build Status: https://travis-ci.org/patternfly/patternfly-ng.svg?branch=master

### Using PatternFly-ng In Your Application

This example demonstrates using the Angular-cli to get started with PatternFly-ng

1. Installing angular-cli
*Note*: you can skip this part if you already have generated an Angular application using `ng-cli` and webpack

 ```bash
 npm i -g @angular/cli
 ng new patternfly-ng-app
 cd patternfly-ng-app
 ng serve
 ```

2. Install patternfly-ng
   ```bash
     npm install patternfly-ng --save
   ```

3. Add patternfly-ng dependencies

 - install `patternfly`

 ```bash
   npm install patternfly --save
 ```

4. Add a patternfly-ng component
- open `src/app/app.module.ts` and add

```typescript
import { ToastNotificationModule } from 'patternfly-ng/notification';
// Or
import { ToastNotificationModule } from 'patternfly-ng';
...

@NgModule({
   ...
   imports: [ToastNotificationModule, ... ],
    ...
})
```

- open `angular.json` and insert a new entry into the styles array

```json
      "styles": [
        "./node_modules/patternfly/dist/css/patternfly.min.css",
        "./node_modules/patternfly/dist/css/patternfly-additions.min.css",
        "./node_modules/patternfly-ng/dist/css/patternfly-ng.min.css",
        "styles.css",
      ],
```

- open `src/app/app.component.html` and add
```
<pfng-toast-notification
  [header]="'test header'"
  [message]="'this is a notification'"
  [showClose]="'true'"
  [type]="'success'">
</pfng-toast-notification>
```

5. For Angular 8, open `angular.json` and insert the following into the options array

```
"options": {
  "preserveSymlinks": true,
```

### Optional Dependencies

1. To enable table drag and drop, add dragula.min.css from the ng2-dragula package

- open `angular.json` and insert a new entry into the styles array

```json
      "styles": [
        "./node_modules/dragula/dist/dragula.min.css",
        "./node_modules/patternfly/dist/css/patternfly.min.css",
        "./node_modules/patternfly/dist/css/patternfly-additions.min.css",
        "./node_modules/patternfly-ng/dist/css/patternfly-ng.min.css",
        "styles.css",
      ],
```

2. To enable charts, add patternfly-settings.js from the patternfly package

- open `angular.json` and insert a new entry into the scripts array

```json
      "scripts": [
        "./node_modules/patternfly/dist/js/patternfly-settings.js"
      ],
```

##  Do you have a question?
 - Search our [GitHub issues][github-issues]
 - Join our patternfly-ng channel on [Slack](http://slack.patternfly.org)
 - Join our mailing-list following the instructions on [patternfly.org](http://www.patternfly.org/community/)

[contributing]: https://github.com/patternfly/patternfly-ng/blob/master/CONTRIBUTING.md
[github-issues]: https://github.com/patternfly/patternfly-ng/issues


text:
"""User utils tests"""
import pytest
from profiles.utils import ensure_active_user, is_duplicate_username_error, usernameify

@pytest.mark.parametrize(
    "full_name,email,expected_username",
    [
        [" John  Doe ", None, "john-doe"],
        ["Tabby	Tabberson", None, "tabby-tabberson"],
        ["Àccèntèd Ñame, Ësq.", None, "àccèntèd-ñame-ësq"],
        ["-Dashy_St._Underscores-", None, "dashy-st-underscores"],
        ["Repeated-----Chars___Jr.", None, "repeated-chars-jr"],
        ["Numbers123 !$!@ McStrange!!##^", None, "numbers-mcstrange"],
        ["Кирил Френков", None, "кирил-френков"],
        ["年號", None, "年號"],
        ["abcdefghijklmnopqrstuvwxyz", None, "abcdefghijklmnopqrst"],
        ["ai bi cı dI eİ fI", None, "ai-bi-ci-di-ei-fi"],
        ["", "some.email@example.co.uk", "someemail"],
    ],
)
def test_usernameify(mocker, full_name, email, expected_username):
    """usernameify should turn a user's name into a username, or use the email if necessary"""
    # Change the username max length to 20 for test data simplicity's sake
    temp_username_max_len = 20
    mocker.patch("profiles.utils.USERNAME_MAX_LEN", temp_username_max_len)
    patched_log_error = mocker.patch("profiles.utils.log.error")

    assert usernameify(full_name, email=email) == expected_username
    assert patched_log_error.called == bool(email and not full_name)

def test_usernameify_fail():
    """usernameify should raise an exception if the full name and email both fail to produce a username"""
    with pytest.raises(ValueError):
        assert usernameify("!!!", email="???@example.com")

@pytest.mark.parametrize(
    "exception_text,expected_value",
    [
        ["DETAILS: (username)=(ABCDEFG) already exists", True],
        ["DETAILS: (email)=(ABCDEFG) already exists", False],
    ],
)
def test_is_duplicate_username_error(exception_text, expected_value):
    """
    is_duplicate_username_error should return True if the exception text provided indicates a duplicate username error
    """
    assert is_duplicate_username_error(exception_text) is expected_value

def test_ensure_active_user(user):
    """
    Test that ensure_active_user activates
    """
    user.is_active = False
    user.save()

    assert not user.is_active

    ensure_active_user(user)
    assert user.is_active


text:
void visualizeTouch(UITouch* touch);

#endif


text:
import { RadarChart } from './RadarChart.component';

export default RadarChart;


text:
'''Public section, including homepage and signup.'''
from flask import (Blueprint, request, render_template, flash, url_for,
                    redirect, session, jsonify, abort, g)

from happycube.extensions import cache
from happycube.errors import HTTPError
from happycube.log import logger

from happycube.decorators.validation import validate
from happycube.decorators.rate_limit import limit
from happycube.decorators.auth import jwt_required

from happycube.solves.services import solve_service
from happycube.solves.serializer import serialize

import json

blueprint = Blueprint('solves', __name__,  url_prefix='/api/v0/solves')

@blueprint.route('/', methods = ['GET'])
@jwt_required()
def index():

    solves = solve_service.all()

    ret = [serialize(x) for x in solves]

    return json.dumps(ret)

@blueprint.route('/', methods = ['POST'])
@jwt_required()
def create():
    logger.info(request.get_json())

    payload = request.get_json()
    payload['user_id'] = g.user.id

    new_solve = solve_service.create(**payload)

    return json.dumps(serialize(new_solve))


text:
using System;
using System.Linq;
using System.Runtime.InteropServices;
using SsisUp.Builders;
using SsisUp.Builders.References;
using SsisUp.Helpers;

namespace SsisUp.Services
{
    public interface IFileService
    {
        DeploymentResult Execute(JobConfiguration jobConfiguration);
    }

    public class IntegrationServicesFileService : IFileService
    {
        private readonly IIoWrapper _ioWrapper;

        public IntegrationServicesFileService(IIoWrapper ioWrapper)
        {
            if (ioWrapper == null) throw new ArgumentNullException("ioWrapper");
            this._ioWrapper = ioWrapper;
        }

        public DeploymentResult Execute(JobConfiguration jobConfiguration)
        {
            DeploymentResult result;

            foreach (var stepConfiguration in jobConfiguration.Steps.Where(stepConfiguration => stepConfiguration.SubSystem == SsisSubSystem.IntegrationServices))
            {
                try
                {
                    _ioWrapper.CreateDirectoryIfNotExists(stepConfiguration.DtsxFileDestination);
                    _ioWrapper.CopyFile(stepConfiguration.DtsxFile, stepConfiguration.DtsxFileDestination);
                    _ioWrapper.CopyFile(stepConfiguration.DtsxConfigurationFile, stepConfiguration.DtsxFileDestination);
                }
                catch(Exception ex)
                {
                    result = new DeploymentResult(ex, false, GetType());
                    return result;
                }
            }

            result = new DeploymentResult(null, true, GetType());
            return result;
        }
    }
}


text:
// Copyright (C) 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

#ifndef STRMATCH_H
#define STRMATCH_H

#include "unicode/utypes.h"

#if !UCONFIG_NO_TRANSLITERATION

#include "unicode/unistr.h"
#include "unicode/unifunct.h"
#include "unicode/unimatch.h"
#include "unicode/unirepl.h"

U_NAMESPACE_BEGIN

class TransliterationRuleData;

/**
 * An object that matches a fixed input string, implementing the
 * UnicodeMatcher API.  This object also implements the
 * UnicodeReplacer API, allowing it to emit the matched text as
 * output.  Since the match text may contain flexible match elements,
 * such as UnicodeSets, the emitted text is not the match pattern, but
 * instead a substring of the actual matched text.  Following
 * convention, the output text is the leftmost match seen up to this
 * point.
 *
 * A StringMatcher may represent a segment, in which case it has a
 * positive segment number.  This affects how the matcher converts
 * itself to a pattern but does not otherwise affect its function.
 *
 * A StringMatcher that is not a segment should not be used as a
 * UnicodeReplacer.
 */
class StringMatcher : public UnicodeFunctor, public UnicodeMatcher, public UnicodeReplacer {

 public:

    /**
     * Construct a matcher that matches the given pattern string.
     * @param string the pattern to be matched, possibly containing
     * stand-ins that represent nested UnicodeMatcher objects.
     * @param start inclusive start index of text to be replaced
     * @param limit exclusive end index of text to be replaced;
     * must be greater than or equal to start
     * @param segmentNum the segment number from 1..n, or 0 if this is
     * not a segment.
     * @param data context object mapping stand-ins to
     * UnicodeMatcher objects.
     */
    StringMatcher(const UnicodeString& string,
                  int32_t start,
                  int32_t limit,
                  int32_t segmentNum,
                  const TransliterationRuleData& data);

    /**
     * Copy constructor
     * @param o  the object to be copied.
     */
    StringMatcher(const StringMatcher& o);

    /**
     * Destructor
     */
    virtual ~StringMatcher();

    /**
     * Implement UnicodeFunctor
     * @return a copy of the object.
     */
    virtual UnicodeFunctor* clone() const;

    /**
     * UnicodeFunctor API.  Cast 'this' to a UnicodeMatcher* pointer
     * and return the pointer.
     * @return the UnicodeMatcher point.
     */
    virtual UnicodeMatcher* toMatcher() const;

    /**
     * UnicodeFunctor API.  Cast 'this' to a UnicodeReplacer* pointer
     * and return the pointer.
     * @return the UnicodeReplacer pointer.
     */
    virtual UnicodeReplacer* toReplacer() const;

    /**
     * Implement UnicodeMatcher
     * @param text the text to be matched
     * @param offset on input, the index into text at which to begin
     * matching.  On output, the limit of the matched text.  The
     * number of matched characters is the output value of offset
     * minus the input value.  Offset should always point to the
     * HIGH SURROGATE (leading code unit) of a pair of surrogates,
     * both on entry and upon return.
     * @param limit the limit index of text to be matched.  Greater
     * than offset for a forward direction match, less than offset for
     * a backward direction match.  The last character to be
     * considered for matching will be text.charAt(limit-1) in the
     * forward direction or text.charAt(limit+1) in the backward
     * direction.
     * @param incremental  if TRUE, then assume further characters may
     * be inserted at limit and check for partial matching.  Otherwise
     * assume the text as given is complete.
     * @return a match degree value indicating a full match, a partial
     * match, or a mismatch.  If incremental is FALSE then
     * U_PARTIAL_MATCH should never be returned.
     */
    virtual UMatchDegree matches(const Replaceable& text,
                                 int32_t& offset,
                                 int32_t limit,
                                 UBool incremental);

    /**
     * Implement UnicodeMatcher
     * @param result            Output param to receive the pattern.
     * @param escapeUnprintable if True then escape the unprintable characters.
     * @return                  A reference to 'result'.
     */
    virtual UnicodeString& toPattern(UnicodeString& result,
                                     UBool escapeUnprintable = FALSE) const;

    /**
     * Implement UnicodeMatcher
     * Returns TRUE if this matcher will match a character c, where c
     * & 0xFF == v, at offset, in the forward direction (with limit >
     * offset).  This is used by <tt>RuleBasedTransliterator</tt> for
     * indexing.
     * @param v    the given value
     * @return     TRUE if this matcher will match a character c,
     *             where c & 0xFF == v
     */
    virtual UBool matchesIndexValue(uint8_t v) const;

    /**
     * Implement UnicodeMatcher
     */
    virtual void addMatchSetTo(UnicodeSet& toUnionTo) const;

    /**
     * Implement UnicodeFunctor
     */
    virtual void setData(const TransliterationRuleData*);

    /**
     * Replace characters in 'text' from 'start' to 'limit' with the
     * output text of this object.  Update the 'cursor' parameter to
     * give the cursor position and return the length of the
     * replacement text.
     *
     * @param text the text to be matched
     * @param start inclusive start index of text to be replaced
     * @param limit exclusive end index of text to be replaced;
     * must be greater than or equal to start
     * @param cursor output parameter for the cursor position.
     * Not all replacer objects will update this, but in a complete
     * tree of replacer objects, representing the entire output side
     * of a transliteration rule, at least one must update it.
     * @return the number of 16-bit code units in the text replacing
     * the characters at offsets start..(limit-1) in text
     */
    virtual int32_t replace(Replaceable& text,
                            int32_t start,
                            int32_t limit,
                            int32_t& cursor);

    /**
     * Returns a string representation of this replacer.  If the
     * result of calling this function is passed to the appropriate
     * parser, typically TransliteratorParser, it will produce another
     * replacer that is equal to this one.
     * @param result the string to receive the pattern.  Previous
     * contents will be deleted.
     * @param escapeUnprintable if TRUE then convert unprintable
     * character to their hex escape representations, \\uxxxx or
     * \\Uxxxxxxxx.  Unprintable characters are defined by
     * Utility.isUnprintable().
     * @return a reference to 'result'.
     */
    virtual UnicodeString& toReplacerPattern(UnicodeString& result,
                                             UBool escapeUnprintable) const;

    /**
     * Remove any match data.  This must be called before performing a
     * set of matches with this segment.
     */
    void resetMatch();

    /**
     * ICU "poor man's RTTI", returns a UClassID for the actual class.
     */
    virtual UClassID getDynamicClassID() const;

    /**
     * ICU "poor man's RTTI", returns a UClassID for this class.
     */
    static UClassID U_EXPORT2 getStaticClassID();

    /**
     * Union the set of all characters that may output by this object
     * into the given set.
     * @param toUnionTo the set into which to union the output characters
     */
    virtual void addReplacementSetTo(UnicodeSet& toUnionTo) const;

 private:

    /**
     * The text to be matched.
     */
    UnicodeString pattern;

    /**
     * Context object that maps stand-ins to matcher and replacer
     * objects.
     */
    const TransliterationRuleData* data;

    /**
     * The segment number, 1-based, or 0 if not a segment.
     */
    int32_t segmentNumber;

    /**
     * Start offset, in the match text, of the rightmost
     * match.
     */
    int32_t matchStart;

    /**
     * Limit offset, in the match text, of the rightmost
     * match.
     */
    int32_t matchLimit;

};

U_NAMESPACE_END

#endif /* #if !UCONFIG_NO_TRANSLITERATION */

#endif


text:
fn main() {
    let string = ~"This is a string";
    let subst1 = string.slice(10, 16).to_owned();
    let subst2 = string.slice_from(10).to_owned();
    println!("{}", std::str::eq(&subst1, &subst2));
    let doublesub = subst1 + subst2;
    println!("{}", doublesub);
    //Using split iterator to print word by word
    for tempstr in string.split(' ') {
        println!("{}", tempstr);
    }
    //Another useful function of the split iterator
    //collect() Creates a vector that = ~["This", "is", "a", "string"]
    let wordvec: ~[&str] = string.split(' ').collect();
    for &s in wordvec.iter() {
        println!("{}", s);
    }
}


text:
import findWhere from 'lodash.findwhere'
import initializeRedux from '../../utils/initializeRedux'
import mentionReducer from '../../reducers/mentionReducer'
import simpleDataSource from '../fixtures/simple'

export default function initRedux() {
  const dataSource = simpleDataSource.sort().map(source => {
    return {
      searchKey: source,
      displayLabel: source
    }
  })

  const getState = (store) => {
    const state = store.getState().mention
    state.mentions.forEach(mention => delete mention.tinymceId)
    return state
  }

  const find = (name) => findWhere(dataSource, { displayLabel: name })

  const initialState = {
    asyncDataSource: false,
    dataSource: dataSource,
    highlightIndex: 0,
    matchedSources: [],
    mentions: [],
    query: ''
  }

  return {
    dataSource,
    find,
    initialState,
    state: getState,
    initStore(state) {
      return initializeRedux({ mention: mentionReducer }, {
        mention: state || initialState
      })
    }
  }
}


text:
import * as webpack from 'webpack';

export default class NoOpPlugin implements webpack.Plugin {
  apply(compiler: webpack.Compiler) {}
}

module.exports = NoOpPlugin;
module.exports.default = NoOpPlugin;


text:
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http;
using Vidly.App_Start;

namespace Vidly
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            MappingConfig.ConfigureMapping();
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}


text:
var StateDefinitionModel = require('../../../../javascripts/cartodb3/data/state-definition-model');

describe('data/state-definition-model', function () {
  beforeEach(function () {
    var anObject = { something: 'something' };
    var visDefinitionModel = {};

    this.model = new StateDefinitionModel({
      json: JSON.stringify(anObject)
    }, {
      visDefinitionModel: visDefinitionModel
    });
  });

  describe('.setBounds', function () {
    it(' should trigger event when called', function () {
      jasmine.clock().install();

      var expectedBounds = [808];
      var actualBounds;
      function onBoundsSet (bounds) {
        actualBounds = bounds;
      }
      this.model.on('boundsSet', onBoundsSet);

      this.model.setBounds(expectedBounds);

      jasmine.clock().tick(10);
      expect(actualBounds[0]).toBe(expectedBounds[0]);

      jasmine.clock().uninstall();
    });
  });
});


text:
package com.google.cloud.eventarc.publishing.v1;

import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.testing.MockHttpService;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.ApiExceptionFactory;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.testing.FakeStatusCode;
import com.google.cloud.eventarc.publishing.v1.stub.HttpJsonPublisherStub;
import com.google.protobuf.Any;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

@Generated("by gapic-generator-java")
public class PublisherClientHttpJsonTest {
  private static MockHttpService mockService;
  private static PublisherClient client;

  @BeforeClass
  public static void startStaticServer() throws IOException {
    mockService =
        new MockHttpService(
            HttpJsonPublisherStub.getMethodDescriptors(), PublisherSettings.getDefaultEndpoint());
    PublisherSettings settings =
        PublisherSettings.newHttpJsonBuilder()
            .setTransportChannelProvider(
                PublisherSettings.defaultHttpJsonTransportProviderBuilder()
                    .setHttpTransport(mockService)
                    .build())
            .setCredentialsProvider(NoCredentialsProvider.create())
            .build();
    client = PublisherClient.create(settings);
  }

  @AfterClass
  public static void stopServer() {
    client.close();
  }

  @Before
  public void setUp() {}

  @After
  public void tearDown() throws Exception {
    mockService.reset();
  }

  @Test
  public void publishChannelConnectionEventsTest() throws Exception {
    PublishChannelConnectionEventsResponse expectedResponse =
        PublishChannelConnectionEventsResponse.newBuilder().build();
    mockService.addResponse(expectedResponse);

    PublishChannelConnectionEventsRequest request =
        PublishChannelConnectionEventsRequest.newBuilder()
            .setChannelConnection(
                "projects/project-748/locations/location-748/channelConnections/channelConnection-748")
            .addAllEvents(new ArrayList<Any>())
            .addAllTextEvents(new ArrayList<String>())
            .build();

    PublishChannelConnectionEventsResponse actualResponse =
        client.publishChannelConnectionEvents(request);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<String> actualRequests = mockService.getRequestPaths();
    Assert.assertEquals(1, actualRequests.size());

    String apiClientHeaderKey =
        mockService
            .getRequestHeaders()
            .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
            .iterator()
            .next();
    Assert.assertTrue(
        GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
            .matcher(apiClientHeaderKey)
            .matches());
  }

  @Test
  public void publishChannelConnectionEventsExceptionTest() throws Exception {
    ApiException exception =
        ApiExceptionFactory.createException(
            new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
    mockService.addException(exception);

    try {
      PublishChannelConnectionEventsRequest request =
          PublishChannelConnectionEventsRequest.newBuilder()
              .setChannelConnection(
                  "projects/project-748/locations/location-748/channelConnections/channelConnection-748")
              .addAllEvents(new ArrayList<Any>())
              .addAllTextEvents(new ArrayList<String>())
              .build();
      client.publishChannelConnectionEvents(request);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void publishEventsTest() throws Exception {
    PublishEventsResponse expectedResponse = PublishEventsResponse.newBuilder().build();
    mockService.addResponse(expectedResponse);

    PublishEventsRequest request =
        PublishEventsRequest.newBuilder()
            .setChannel("projects/project-2616/locations/location-2616/channels/channel-2616")
            .addAllEvents(new ArrayList<Any>())
            .addAllTextEvents(new ArrayList<String>())
            .build();

    PublishEventsResponse actualResponse = client.publishEvents(request);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<String> actualRequests = mockService.getRequestPaths();
    Assert.assertEquals(1, actualRequests.size());

    String apiClientHeaderKey =
        mockService
            .getRequestHeaders()
            .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
            .iterator()
            .next();
    Assert.assertTrue(
        GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
            .matcher(apiClientHeaderKey)
            .matches());
  }

  @Test
  public void publishEventsExceptionTest() throws Exception {
    ApiException exception =
        ApiExceptionFactory.createException(
            new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
    mockService.addException(exception);

    try {
      PublishEventsRequest request =
          PublishEventsRequest.newBuilder()
              .setChannel("projects/project-2616/locations/location-2616/channels/channel-2616")
              .addAllEvents(new ArrayList<Any>())
              .addAllTextEvents(new ArrayList<String>())
              .build();
      client.publishEvents(request);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }
}


text:
'use strict';

var express = require('express');
var https = require('https');
var cheerio = require('cheerio');

var app = express();

var options = {
    host: 'www.linkedin.com',
    port: 443,
    method: 'GET'
}

app.get('/profile/:username', function(req, result) {

    options.path = '/in/' + req.params.username;

    console.log(options);

    https.get(options, function(res) {
        console.log('Status code: %s', res.statusCode);

        res.setEncoding('utf8');

        var html;

        res.on('data', function(data) {

            html += data;

        });

        res.on('end', function() {
            var $ = cheerio.load(html);

            var languages = [];

            $('#languages .section-item').each(function(index, languageElement) {

                var language = {
                    name: $(languageElement).find('span').html(),
                    proficiency: $(languageElement).find('.languages-proficiency').html()
                };
                languages.push(language);
            });

            var positions = [];

            $('#background-experience .section-item').each(function(index, positionElement) {

                var dateInterval = $(positionElement).find('.experience-date-locale').html();

                var endDate = $(positionElement).find('.experience-date-locale > time:nth-child(2)').html();
                var startDate = $(positionElement).find('.experience-date-locale > time').remove().html();

                if (!endDate) {
                    $(positionElement).find('.experience-date-locale > time').remove();
                    $(positionElement).find('.experience-date-locale > span').remove();
                    var subDate = $(positionElement).find('.experience-date-locale').html();
                    subDate = subDate.substring(subDate.indexOf("–") + 9, subDate.length);
                    subDate = subDate.substring(0, subDate.indexOf(' '));
                    endDate = subDate;
                }

                var company = $(positionElement).find('header > h5:nth-child(3) > a').html() ?
                                $(positionElement).find('header > h5:nth-child(3) > a').html() :
                                $(positionElement).find('header > h5 > span').html();

                var position = {
                    title: $(positionElement).find('h4 > a').html(),
                    startDate: startDate,
                    endDate: endDate,
                    company: company,
                    summary: $(positionElement).find('p').html()
                };
                positions.push(position);
            });

            var jsonResult = {
                userData: {
                    name: $('span.full-name').html(),
                    headline: $('.title').html(),
                    languages: languages,
                    positions: positions
                }
            };

            result.json(jsonResult);
        });

    }).on('error', function(err) {
        console.log(('Got error: %s', err.message));
    });
});

var port = process.env.PORT || 3000;

var server = app.listen(port, function() {

    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>org.apache.lucene.queryparser.surround.query (Lucene 4.6.1 API)</title>
<meta name="date" content="2014-01-23">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

org.apache.lucene.queryparser.surround.query

Interfaces

DistanceSubQuery

SimpleTerm.MatchingTermVisitor

Classes

AndQuery

BasicQueryFactory

ComposedQuery

DistanceQuery

FieldsQuery

NotQuery

OrQuery

SimpleTerm

SpanNearClauseFactory

SrndPrefixQuery

SrndQuery

SrndTermQuery

SrndTruncQuery

Exceptions

TooManyBasicQueries


text:
package apple.foundation;

import apple.NSObject;
import apple.foundation.protocol.NSCoding;
import apple.foundation.protocol.NSDecimalNumberBehaviors;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

/**
 * A class for defining common behaviors ******
 */
@Generated
@Library("Foundation")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class NSDecimalNumberHandler extends NSObject implements NSDecimalNumberBehaviors, NSCoding {
    static {
        NatJ.register();
    }

    @Generated
    protected NSDecimalNumberHandler(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    @Generated
    @Owned
    @Selector("alloc")
    public static native NSDecimalNumberHandler alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native NSDecimalNumberHandler allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("decimalNumberHandlerWithRoundingMode:scale:raiseOnExactness:raiseOnOverflow:raiseOnUnderflow:raiseOnDivideByZero:")
    public static native NSDecimalNumberHandler decimalNumberHandlerWithRoundingModeScaleRaiseOnExactnessRaiseOnOverflowRaiseOnUnderflowRaiseOnDivideByZero(
            @NUInt long roundingMode, short scale, boolean exact, boolean overflow, boolean underflow,
            boolean divideByZero);

    @Generated
    @Selector("defaultDecimalNumberHandler")
    public static native NSDecimalNumberHandler defaultDecimalNumberHandler();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native NSDecimalNumberHandler new_objc();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();

    @Generated
    @Selector("encodeWithCoder:")
    public native void encodeWithCoder(NSCoder coder);

    @Generated
    @Selector("exceptionDuringOperation:error:leftOperand:rightOperand:")
    public native NSDecimalNumber exceptionDuringOperationErrorLeftOperandRightOperand(SEL operation, @NUInt long error,
            NSDecimalNumber leftOperand, NSDecimalNumber rightOperand);

    @Generated
    @Selector("init")
    public native NSDecimalNumberHandler init();

    @Generated
    @Selector("initWithCoder:")
    public native NSDecimalNumberHandler initWithCoder(NSCoder coder);

    /**
     * rounding mode: NSRoundPlain
     * scale: No defined scale (full precision)
     * ignore exactnessException (return nil)
     * raise on overflow, underflow and divide by zero.
     */
    @Generated
    @Selector("initWithRoundingMode:scale:raiseOnExactness:raiseOnOverflow:raiseOnUnderflow:raiseOnDivideByZero:")
    public native NSDecimalNumberHandler initWithRoundingModeScaleRaiseOnExactnessRaiseOnOverflowRaiseOnUnderflowRaiseOnDivideByZero(
            @NUInt long roundingMode, short scale, boolean exact, boolean overflow, boolean underflow,
            boolean divideByZero);

    @Generated
    @Selector("roundingMode")
    @NUInt
    public native long roundingMode();

    @Generated
    @Selector("scale")
    public native short scale();
}