text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <php.h>
#include "php_ext.h"

#include <Zend/zend_closures.h>
#include <Zend/zend_string.h>

#include "kernel/main.h"
#include "kernel/memory.h"
#include "kernel/object.h"
#include "kernel/exception.h"
#include "kernel/fcall.h"
#include "kernel/array.h"
#include "kernel/operators.h"

int zephir_instance_of_ev(zval *object, const zend_class_entry *ce)
{
	zval *z = Z_ISREF_P(object) ? Z_REFVAL_P(object) : object;
	if (Z_TYPE_P(z) != IS_OBJECT) {
		php_error_docref(NULL, E_WARNING, "instanceof expects an object instance");
		return 0;
	}

	return instanceof_function(Z_OBJCE_P(z), ce);
}

/**
 * Check if an object is instance of a class
 */
int zephir_is_instance_of(zval *object, const char *class_name, unsigned int class_length)
{
	zend_class_entry *ce, *temp_ce;
	zval *z = Z_ISREF_P(object) ? Z_REFVAL_P(object) : object;

	if (Z_TYPE_P(z) == IS_OBJECT) {

		ce = Z_OBJCE_P(z);
		if (ZSTR_LEN(ce->name) == class_length) {
			if (!zend_binary_strcasecmp(ZSTR_VAL(ce->name), ZSTR_LEN(ce->name), class_name, class_length)) {
				return 1;
			}
		}

		temp_ce = zephir_fetch_class_str_ex(class_name, class_length, ZEND_FETCH_CLASS_DEFAULT);
		if (temp_ce) {
			return instanceof_function(ce, temp_ce);
		}
	}

	return 0;
}

int zephir_zval_is_traversable(zval *object)
{
	zend_class_entry *ce;
	uint32_t i;
	zval *z = Z_ISREF_P(object) ? Z_REFVAL_P(object) : object;

	if (Z_TYPE_P(z) == IS_OBJECT) {
		ce = Z_OBJCE_P(z);

		if (ce->get_iterator || (ce->parent && ce->parent->get_iterator)) {
			return 1;
		}

		for (i = 0; i < ce->num_interfaces; i++) {
			if (ce->interfaces[i] == zend_ce_aggregate ||
				ce->interfaces[i] == zend_ce_iterator ||
				ce->interfaces[i] == zend_ce_traversable
			) {
				return 1;
			}
		}
	}

	return 0;
}

/**
 * Returns the called in class in the current scope
 */
void zephir_get_called_class(zval *return_value)
{
	zend_class_entry *called_scope = zend_get_called_scope(EG(current_execute_data));
	if (called_scope) {
		ZVAL_STR(return_value, zend_string_dup(called_scope->name, 0));
	}

	if (!zend_get_executed_scope())  {
		php_error_docref(NULL, E_WARNING, "zephir_get_called_class() called from outside a class");
	}
}

zend_class_entry *zephir_fetch_class_str_ex(const char *class_name, size_t length, int fetch_type)
{
	zend_class_entry *retval;
	zend_string *str = zend_string_init(class_name, length, 0);
	retval = zend_fetch_class(str, fetch_type);
	zend_string_release(str);
	return retval;
}

/**
 * Fetches a zend class entry from a zval value
 */
zend_class_entry *zephir_fetch_class(zval *class_name)
{
	zval *z = Z_ISREF_P(class_name) ? Z_REFVAL_P(class_name) : class_name;
	if (Z_TYPE_P(z) == IS_STRING) {
		return zend_fetch_class(Z_STR_P(z), ZEND_FETCH_CLASS_DEFAULT);
	}

	php_error_docref(NULL, E_WARNING, "class name must be a string");
	return zend_standard_class_def;
}

/**
 * Returns a class name into a zval result
 */
void zephir_get_class(zval *result, zval *object, int lower)
{
	zend_class_entry *ce;
	zend_string *class_name;
	zval *z = Z_ISREF_P(object) ? Z_REFVAL_P(object) : object;

	if (Z_TYPE_P(z) == IS_OBJECT) {
		ce = Z_OBJCE_P(z);
		//zval_ptr_dtor(result);
		class_name = zend_string_init(ZSTR_VAL(ce->name), ZSTR_LEN(ce->name), 0);
		ZVAL_STR(result, class_name);

		if (lower) {
			zend_str_tolower(Z_STRVAL_P(result), Z_STRLEN_P(result));
		}

	} else {
		ZVAL_NULL(result);
		php_error_docref(NULL, E_WARNING, "zephir_get_class expects an object");
	}
}

/**
 * Returns a class name into a zval result
 */
void zephir_get_class_ns(zval *result, zval *object, int lower)
{
	int found = 0;
	unsigned int i, class_length;
	char *cursor, *class_name;
	zval *z = Z_ISREF_P(object) ? Z_REFVAL_P(object) : object;

	if (Z_TYPE_P(z) != IS_OBJECT) {
		if (Z_TYPE_P(z) != IS_STRING) {
			ZVAL_NULL(result);
			php_error_docref(NULL, E_WARNING, "zephir_get_class_ns expects an object");
			return;
		}

		class_name   = Z_STRVAL_P(z);
		class_length = Z_STRLEN_P(z);
	}
	else {
		zend_class_entry *ce = Z_OBJCE_P(z);
		class_name   = ZSTR_VAL(ce->name);
		class_length = ZSTR_LEN(ce->name);
	}

	if (!class_length) {
		ZVAL_NULL(result);
		return;
	}

	i = class_length;
	cursor = (char *) (class_name + class_length - 1);

	while (i > 0) {
		if ((*cursor) == '\\') {
			found = 1;
			break;
		}
		cursor--;
		i--;
	}

	if (found) {
		int cursor_length = class_length - i;
		cursor = (char *) emalloc(cursor_length + 1);
		memcpy(cursor, class_name + i, cursor_length);
		cursor[cursor_length] = 0;
		ZVAL_STRING(result, cursor);
		efree(cursor);
	} else {
		ZVAL_STRINGL(result, class_name, class_length);
	}

	if (lower) {
		zend_str_tolower(Z_STRVAL_P(result), Z_STRLEN_P(result));
	}
}

/**
 * Returns a namespace from a class name
 */
void zephir_get_ns_class(zval *result, zval *object, int lower)
{
	int found = 0;
	unsigned int i, j, class_length;
	char *cursor, *class_name;
	zval *z = Z_ISREF_P(object) ? Z_REFVAL_P(object) : object;

	ZVAL_NULL(result);

	if (Z_TYPE_P(z) != IS_OBJECT) {
		if (Z_TYPE_P(z) != IS_STRING) {
			php_error_docref(NULL, E_WARNING, "zephir_get_ns_class expects an object");
			return;
		}

		class_name   = Z_STRVAL_P(z);
		class_length = Z_STRLEN_P(z);
	}
	else {
		zend_class_entry *ce = Z_OBJCE_P(z);
		class_name   = ZSTR_VAL(ce->name);
		class_length = ZSTR_LEN(ce->name);
	}

	if (!class_length) {
		return;
	}

	j = 0;
	i = class_length;
	cursor = (char *) (class_name + class_length - 1);

	while (i > 0) {
		if ((*cursor) == '\\') {
			found = 1;
			break;
		}
		cursor--;
		i--;
		j++;
	}

	if (j > 0) {

		if (found) {
			int cursor_length = class_length - j - 1;
			cursor = (char *) emalloc(cursor_length + 1);
			memcpy(cursor, class_name, cursor_length);
			cursor[cursor_length] = 0;
			ZVAL_STRING(result, cursor);
			efree(cursor);
		} else {
			ZVAL_EMPTY_STRING(result);
		}

		if (lower) {
			zend_str_tolower(Z_STRVAL_P(result), Z_STRLEN_P(result));
		}
	}
}

/**
 * Checks if a class exist
 */
int zephir_class_exists(zval *class_name, int autoload)
{
	zend_class_entry *ce;
	zval *z = Z_ISREF_P(class_name) ? Z_REFVAL_P(class_name) : class_name;

	if (Z_TYPE_P(z) == IS_STRING) {
		if ((ce = zend_lookup_class_ex(Z_STR_P(z), NULL, autoload)) != NULL) {
			return (ce->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT))) == 0;
		}
		return 0;
	}

	php_error_docref(NULL, E_WARNING, "class name must be a string");
	return 0;
}

/**
 * Checks if a interface exist
 */
int zephir_interface_exists(zval *class_name, int autoload)
{
	zend_class_entry *ce;
	zval *z = Z_ISREF_P(class_name) ? Z_REFVAL_P(class_name) : class_name;

	if (Z_TYPE_P(z) == IS_STRING) {
		if ((ce = zend_lookup_class(Z_STR_P(z))) != NULL) {
			return ((ce->ce_flags & ZEND_ACC_INTERFACE) > 0);
		}
		return 0;
	}

	php_error_docref(NULL, E_WARNING, "interface name must be a string");
	return 0;
}

/**
 * Clones an object from obj to destination
 */
int zephir_clone(zval *destination, zval *obj)
{
	int status = SUCCESS;
	zend_class_entry *ce;
	zend_object_clone_obj_t clone_call;

	if (Z_TYPE_P(obj) != IS_OBJECT) {
		php_error_docref(NULL, E_ERROR, "__clone method called on non-object");
		status = FAILURE;
	} else {
		ce = Z_OBJCE_P(obj);
		clone_call =  Z_OBJ_HT_P(obj)->clone_obj;
		if (!clone_call) {
			if (ce) {
				php_error_docref(NULL, E_ERROR, "Trying to clone an uncloneable object of class %s", ZSTR_VAL(ce->name));
			} else {
				php_error_docref(NULL, E_ERROR, "Trying to clone an uncloneable object");
			}
			status = FAILURE;
		} else {
			if (!EG(exception)) {
#if PHP_VERSION_ID >= 80000
				ZVAL_OBJ(destination, clone_call(Z_OBJ_P(obj)));
#else
				ZVAL_OBJ(destination, clone_call(obj));
#endif
				if (EG(exception)) {
					zval_ptr_dtor(destination);
				}
			}
		}
	}

	return status;
}

/**
 * Checks if property exists on object
 */
int zephir_isset_property(zval *object, const char *property_name, unsigned int property_length)
{
	if (Z_TYPE_P(object) == IS_OBJECT) {
		if (EXPECTED(zend_hash_str_exists(&Z_OBJCE_P(object)->properties_info, property_name, property_length))) {
			return 1;
		}

#if PHP_VERSION_ID >= 80000
		return zend_hash_str_exists(
			Z_OBJ_HT_P(object)->get_properties(Z_OBJ_P(object)),
			property_name,
			property_length
		);
#else
		return zend_hash_str_exists(
			Z_OBJ_HT_P(object)->get_properties(object),
			property_name,
			property_length
		);
#endif
	}

	return 0;
}

/**
 * Checks if string property exists on object
 */
int zephir_isset_property_zval(zval *object, const zval *property)
{
	if (Z_TYPE_P(object) == IS_OBJECT) {
		if (Z_TYPE_P(property) == IS_STRING) {
			if (EXPECTED(zend_hash_str_exists(&Z_OBJCE_P(object)->properties_info, Z_STRVAL_P(property), Z_STRLEN_P(property)))) {
				return 1;
			} else {
#if PHP_VERSION_ID >= 80000
				return zend_hash_str_exists(
					Z_OBJ_HT_P(object)->get_properties(Z_OBJ_P(object)),
					Z_STRVAL_P(property),
					Z_STRLEN_P(property)
				);
#else
				return zend_hash_str_exists(
					Z_OBJ_HT_P(object)->get_properties(object),
					Z_STRVAL_P(property),
					Z_STRLEN_P(property)
				);
#endif
			}
		}
	}

	return 0;
}

/**
 * Lookup for the real owner of the property
 */
static inline zend_class_entry *zephir_lookup_class_ce(
	zend_class_entry *ce,
	const char *property_name,
	unsigned int property_length
) {
	zend_class_entry *original_ce = ce;
	zend_property_info *info;
	zend_class_entry *scope;
	zval member;

	ZVAL_STRINGL(&member, property_name, property_length);

	/* Backup current scope */
	scope = zephir_get_scope(0);

	while (ce) {
		/* Use the scope of the current object */
		zephir_set_scope(ce);

		info = zend_get_property_info(ce, Z_STR(member), 1);
		if (info && info != ZEND_WRONG_PROPERTY_INFO) {
			zval_ptr_dtor(&member);
			/* Restore original scope */
			zephir_set_scope(scope);

			return ce;
		}

		ce = ce->parent;
	}

	zval_ptr_dtor(&member);

	/* Restore original scope */
	zephir_set_scope(scope);

	return original_ce;
}

/**
 * Checks whether obj is an object and reads a property from this object.
 *
 * This function is intended to use in initializer.  Do not use it for a
 * regular property updating.
 */
int zephir_read_property_ex(
	zval *result,
	zval *object,
	const char *property_name,
	uint32_t property_length, int flags
) {
	zend_class_entry *scope;
	int retval;

	if (Z_TYPE_P(object) == IS_OBJECT) {
		zend_class_entry *ce;

		/* Backup current scope */
		scope = zephir_get_scope(0);
		ce = Z_OBJCE_P(object);

		/* Lookup for the real owner of the property */
		if (ce->parent) {
			ce = zephir_lookup_class_ce(ce, property_name, property_length);
		}

		/* Use the scope of the found object */
		zephir_set_scope(ce);
	}
	/* Read the property */
	retval = zephir_read_property(result, object, property_name, property_length, flags);

	if (Z_TYPE_P(object) == IS_OBJECT) {
		/* Restore original scope */
		zephir_set_scope(scope);
	}

	return retval;
}

/**
 * Checks whether obj is an object and reads a property from this object
 */
int zephir_read_property(
	zval *result,
	zval *object,
	const char *property_name,
	uint32_t property_length,
	int flags
) {
	zval property, tmp;
	zval *res;

	ZVAL_UNDEF(&tmp);

	if (Z_TYPE_P(object) != IS_OBJECT) {
		if ((flags & PH_NOISY) == PH_NOISY) {
			php_error_docref(NULL, E_NOTICE, "Trying to get property '%s' of non-object", property_name);
		}

		ZVAL_NULL(result);
		return FAILURE;
	}

	if (!Z_OBJ_HT_P(object)->read_property) {
		zend_error(E_CORE_ERROR, "Property %s of class %s cannot be read", property_name, ZSTR_VAL(Z_OBJCE_P(object)->name));
	}

	ZVAL_STRINGL(&property, property_name, property_length);
#if PHP_VERSION_ID >= 80000
	res = Z_OBJ_HT_P(object)->read_property(Z_OBJ_P(object), Z_STR(property),
											flags ? BP_VAR_IS : BP_VAR_R,
											NULL, &tmp);
#else
	res = Z_OBJ_HT_P(object)->read_property(object, &property,
											flags ? BP_VAR_IS : BP_VAR_R,
											NULL, &tmp);
#endif

	if ((flags & PH_READONLY) == PH_READONLY) {
		ZVAL_COPY_VALUE(result, res);
	} else {
		ZVAL_COPY(result, res);
	}

	zval_ptr_dtor(&property);

	return SUCCESS;
}

/**
 * Fetches a property using a const char
 */
int zephir_fetch_property(zval *result, zval *object, const char *property_name, uint32_t property_length, int silent)
{
	if (zephir_isset_property(object, property_name, property_length)) {
		zephir_read_property(result, object, property_name, property_length, 0);
		return 1;
	}

	ZVAL_NULL(result);
	return 0;
}

/**
 * Fetches a property using a zval property
 */
int zephir_fetch_property_zval(zval *result, zval *object, zval *property, int silent)
{
	if (UNEXPECTED(Z_TYPE_P(property) != IS_STRING)) {
		ZVAL_NULL(result);
		return 0;
	}

	if (zephir_isset_property(object, Z_STRVAL_P(property), Z_STRLEN_P(property))) {
		zephir_read_property(result, object, Z_STRVAL_P(property), Z_STRLEN_P(property), 0);
		return 1;
	}

	ZVAL_NULL(result);
	return 0;
}

int zephir_return_property(zval *return_value, zval *object, char *property_name, unsigned int property_length)
{
	ZVAL_NULL(return_value);
	return zephir_read_property(return_value, object, property_name, property_length, 0);
}

/**
 * Reads a property from an object
 */
int zephir_read_property_zval(zval *result, zval *object, zval *property, int flags)
{
	if (UNEXPECTED(Z_TYPE_P(property) != IS_STRING)) {
		if ((flags & PH_NOISY) == PH_NOISY) {
			php_error_docref(NULL, E_NOTICE, "Cannot access empty property %d", Z_TYPE_P(property));
		}

		ZVAL_NULL(result);
		return FAILURE;
	}

	return zephir_read_property(result, object, Z_STRVAL_P(property), Z_STRLEN_P(property), flags);
}

/**
 * Checks whether obj is an object and updates property with another zval.
 *
 * This function is intended to use in initializer.  Do not use it for a
 * regular property updating.
 */
int zephir_update_property_zval_ex(
	zval *object,
	const char *property_name,
	unsigned int property_length,
	zval *value
) {
	zend_class_entry *scope;
	int retval;

	if (Z_TYPE_P(object) == IS_OBJECT) {
		zend_class_entry *ce;

		/* Backup current scope */
		scope = zephir_get_scope(0);
		ce = Z_OBJCE_P(object);

		/* Lookup for the real owner of the property */
		if (ce->parent) {
			ce = zephir_lookup_class_ce(ce, property_name, property_length);
		}

		/* Use the scope of the found object */
		zephir_set_scope(ce);
	}
	/* Update the property */
	retval = zephir_update_property_zval(object, property_name, property_length, value);

	if (Z_TYPE_P(object) == IS_OBJECT) {
		/* Restore original scope */
		zephir_set_scope(scope);
	}

	return retval;
}

/**
 * Checks whether obj is an object and updates property with another zval
 */
int zephir_update_property_zval(
	zval *object,
	const char *property_name,
	unsigned int property_length,
	zval *value
) {
	zval property, sep_value;

	if (Z_TYPE_P(object) != IS_OBJECT) {
		php_error_docref(NULL, E_WARNING, "Attempt to assign property '%s' of non-object", property_name);
		return FAILURE;
	}

	if (!Z_OBJ_HT_P(object)->write_property) {
		zend_error(E_CORE_ERROR, "Property %s of class %s cannot be updated", property_name, ZSTR_VAL(Z_OBJCE_P(object)->name));
	}

	ZVAL_STRINGL(&property, property_name, property_length);
	ZVAL_COPY_VALUE(&sep_value, value);
	if (Z_TYPE(sep_value) == IS_ARRAY) {
		ZVAL_ARR(&sep_value, zend_array_dup(Z_ARR(sep_value)));
		if (EXPECTED(!(GC_FLAGS(Z_ARRVAL(sep_value)) & IS_ARRAY_IMMUTABLE))) {
			if (UNEXPECTED(GC_REFCOUNT(Z_ARR(sep_value)) > 0)) {
				GC_DELREF(Z_ARR(sep_value));
			}
		}
	}

	/* write_property will add 1 to refcount,
	   so no Z_TRY_ADDREF_P(value) is necessary */
#if PHP_VERSION_ID >= 80000
	Z_OBJ_HT_P(object)->write_property(Z_OBJ_P(object), Z_STR(property), &sep_value, 0);
#else
	Z_OBJ_HT_P(object)->write_property(object, &property, &sep_value, 0);
#endif

	zval_ptr_dtor(&property);

	if (UNEXPECTED(EG(exception))) {
		return FAILURE;
	}

	return SUCCESS;
}

/**
 * Checks whether obj is an object and updates zval property with another zval
 */
int zephir_update_property_zval_zval(zval *object, zval *property, zval *value)
{
	if (Z_TYPE_P(property) != IS_STRING) {
		php_error_docref(NULL, E_WARNING, "Property should be string");
		return FAILURE;
	}

	return zephir_update_property_zval(object, Z_STRVAL_P(property), Z_STRLEN_P(property), value);
}

/**
 * Updates an array property
 */
int zephir_update_property_array(zval *object, const char *property, uint32_t property_length, const zval *index, zval *value)
{
	zval tmp, sep_value;
	int separated = 0;

	if (Z_TYPE_P(object) != IS_OBJECT) {
		return SUCCESS;
	}

	zephir_read_property(&tmp, object, property, property_length, PH_NOISY | PH_READONLY);

	/** Separation only when refcount > 1 */
	if (Z_REFCOUNTED(tmp)) {
		if (Z_REFCOUNT(tmp) > 1) {
			if (!Z_ISREF(tmp)) {
				zval new_zv;
				ZVAL_DUP(&new_zv, &tmp);
				ZVAL_COPY_VALUE(&tmp, &new_zv);
				Z_TRY_DELREF(new_zv);
				Z_ADDREF(tmp);
				separated = 1;
			}
		}
	} else {
		zval new_zv;
		ZVAL_DUP(&new_zv, &tmp);
		ZVAL_COPY_VALUE(&tmp, &new_zv);
		Z_TRY_DELREF(new_zv);
		separated = 1;
	}

	/** Convert the value to array if not is an array */
	if (Z_TYPE(tmp) != IS_ARRAY) {
		if (separated) {
			convert_to_array(&tmp);
		} else {
			array_init(&tmp);
			separated = 1;
		}

		if (Z_REFCOUNTED(tmp)) {
			if (Z_REFCOUNT(tmp) > 1) {
				if (!Z_ISREF(tmp)) {
					Z_DELREF(tmp);
				}
			}
		}
	}

	if (Z_TYPE_P(value) == IS_ARRAY) {
		ZVAL_ARR(&sep_value, zend_array_dup(Z_ARR_P(value)));
	} else {
		ZVAL_COPY(&sep_value, value);
	}

	if (Z_TYPE_P(index) == IS_STRING) {
		zend_symtable_str_update(Z_ARRVAL(tmp), Z_STRVAL_P(index), Z_STRLEN_P(index), &sep_value);
	} else if (Z_TYPE_P(index) == IS_LONG) {
		zend_hash_index_update(Z_ARRVAL(tmp), Z_LVAL_P(index), &sep_value);
	} else if (Z_TYPE_P(index) == IS_NULL) {
		zend_hash_next_index_insert(Z_ARRVAL(tmp), &sep_value);
	}

	if (separated) {
		zephir_update_property_zval(object, property, property_length, &tmp);
		zephir_ptr_dtor(&tmp);
	}

	return SUCCESS;
}

/**
 * Appends a zval value to an array property
 */
int zephir_update_property_array_append(zval *object, char *property, unsigned int property_length, zval *value)
{
	zval tmp, sep_value;
	int separated = 0;

	ZVAL_UNDEF(&tmp);

	if (Z_TYPE_P(object) != IS_OBJECT) {
		return SUCCESS;
	}

	zephir_read_property(&tmp, object, property, property_length, PH_NOISY | PH_READONLY);

	/** Separation only when refcount > 1 */
	if (Z_REFCOUNTED(tmp)) {
		if (Z_REFCOUNT(tmp) > 1) {
			if (!Z_ISREF(tmp)) {
				zval new_zv;
				ZVAL_DUP(&new_zv, &tmp);
				ZVAL_COPY_VALUE(&tmp, &new_zv);
				if (Z_REFCOUNT(tmp) > 1) {
				    Z_TRY_DELREF(new_zv);
				}
				separated = 1;
			}
		}
	} else {
		zval new_zv;
		ZVAL_DUP(&new_zv, &tmp);
		ZVAL_COPY_VALUE(&tmp, &new_zv);
		Z_TRY_DELREF(new_zv);
		separated = 1;

		/**
		 * class A {
		 *     protected foo;
		 *
		 *     public function test() {
		 *         let this->foo[] = 42;
		 *     }
		 * }
		 *
		 * In this case: Z_REFCOUNT(tmp) == 0
		 */
		if (Z_REFCOUNTED(tmp)) {
			if (EXPECTED(Z_REFCOUNT(tmp) == 0)) {
				Z_ADDREF(tmp);
			}
		}
	}

	/** Convert the value to array if not is an array */
	if (Z_TYPE(tmp) != IS_ARRAY) {
		if (separated) {
			convert_to_array(&tmp);
		} else {
			array_init(&tmp);
			separated = 1;
		}

		if (Z_REFCOUNTED(tmp)) {
			if (Z_REFCOUNT(tmp) > 1) {
				if (!Z_ISREF(tmp)) {
					Z_DELREF(tmp);
				}
			}
		}
	}

	if (Z_TYPE_P(value) == IS_ARRAY) {
		ZVAL_ARR(&sep_value, zend_array_dup(Z_ARR_P(value)));
	} else {
		ZVAL_COPY(&sep_value, value);
	}

	add_next_index_zval(&tmp, &sep_value);

	if (separated) {
		zephir_update_property_zval(object, property, property_length, &tmp);
		zephir_ptr_dtor(&tmp);
	}

	return SUCCESS;
}

/**
 * Multiple array-offset update
 */
int zephir_update_property_array_multi(zval *object, const char *property, uint32_t property_length, zval *value, const char *types, int types_length, int types_count, ...)
{
	va_list ap;
	zval tmp_arr;
	int separated = 0;

	if (Z_TYPE_P(object) == IS_OBJECT) {
		zephir_read_property(&tmp_arr, object, property, property_length, PH_NOISY | PH_READONLY);

		/** Separation only when refcount > 1 */
		if (Z_REFCOUNTED(tmp_arr)) {
			if (Z_REFCOUNT(tmp_arr) > 1) {
				if (!Z_ISREF(tmp_arr)) {
					zval new_zv;
					ZVAL_DUP(&new_zv, &tmp_arr);
					ZVAL_COPY_VALUE(&tmp_arr, &new_zv);
					Z_TRY_DELREF(new_zv);
					Z_ADDREF(tmp_arr);
					separated = 1;
				}
			}
		} else {
			zval new_zv;
			ZVAL_DUP(&new_zv, &tmp_arr);
			ZVAL_COPY_VALUE(&tmp_arr, &new_zv);
			Z_TRY_DELREF(new_zv);
			separated = 1;
		}

		/** Convert the value to array if not is an array */
		if (Z_TYPE(tmp_arr) != IS_ARRAY) {
			if (separated) {
				convert_to_array(&tmp_arr);
			} else {
				array_init(&tmp_arr);
				separated = 1;
			}

			if (Z_REFCOUNTED(tmp_arr)) {
				if (Z_REFCOUNT(tmp_arr) > 1) {
					if (!Z_ISREF(tmp_arr)) {
						Z_DELREF(tmp_arr);
					}
				}
			}
		}

		va_start(ap, types_count);
		zephir_array_update_multi_ex(&tmp_arr, value, types, types_length, types_count, ap);
		va_end(ap);

		if (separated) {
			zephir_update_property_zval(object, property, property_length, &tmp_arr);
			zephir_ptr_dtor(&tmp_arr);
		}
	}

	return SUCCESS;
}

int zephir_unset_property(zval* object, const char* name)
{
	if (Z_TYPE_P(object) != IS_OBJECT) {
		return FAILURE;
	}

	zval member;
	zend_class_entry *scope;

	ZVAL_STRING(&member, name);

	/* Backup current scope */
	scope = zephir_get_scope(0);

	/* Use caller's scope */
	zephir_set_scope(Z_OBJCE_P(object));
#if PHP_VERSION_ID >= 80000
	Z_OBJ_HT_P(object)->unset_property(Z_OBJ_P(object), Z_STR(member), 0);
#else
	Z_OBJ_HT_P(object)->unset_property(object, &member, 0);
#endif
	/* Restore original scope */
	zephir_set_scope(scope);

	return SUCCESS;
}

/**
 * Unsets an index in an array property
 *
 * TODO: This only works with zephir_read_property() + zephir_array_unset_string(), which might be incorrect
 */
int zephir_unset_property_array(zval *object, char *property, unsigned int property_length, zval *index)
{
	zval tmp;
	int separated = 0;

	if (Z_TYPE_P(object) == IS_OBJECT) {
		zephir_read_property(&tmp, object, property, property_length, PH_NOISY_CC);
		Z_TRY_DELREF(tmp);

		/** Separation only when refcount > 1 */
		if (Z_REFCOUNTED(tmp)) {
			if (Z_REFCOUNT(tmp) > 1) {
				if (!Z_ISREF(tmp)) {
					zval new_zv;
					ZVAL_DUP(&new_zv, &tmp);
					ZVAL_COPY_VALUE(&tmp, &new_zv);
					Z_TRY_DELREF(new_zv);
					separated = 1;
				}
			}
		} else {
			zval new_zv;
			ZVAL_DUP(&new_zv, &tmp);
			ZVAL_COPY_VALUE(&tmp, &new_zv);
			Z_TRY_DELREF(new_zv);
			separated = 1;
		}

		zephir_array_unset(&tmp, index, PH_SEPARATE);

		if (separated) {
			zephir_update_property_zval(object, property, property_length, &tmp);
		}
	}

	return SUCCESS;
}

int zephir_method_exists_ex(zval *object, const char *method_name, unsigned int method_len)
{
	zend_class_entry *ce;
	union _zend_function *func = NULL;
	zend_string *method;

	if (EXPECTED(Z_TYPE_P(object) == IS_OBJECT)) {
		ce = Z_OBJCE_P(object);
	} else if (Z_TYPE_P(object) == IS_STRING) {
		ce = zend_fetch_class(Z_STR_P(object), ZEND_FETCH_CLASS_DEFAULT);
	} else {
		return FAILURE;
	}

	if (zend_hash_str_exists(&ce->function_table, method_name, method_len)) {
		return SUCCESS;
	}

	method = zend_string_init(method_name, method_len, 0);
	if (
		   Z_TYPE_P(object) == IS_OBJECT
		&& Z_OBJ_HT_P(object)->get_method
		&& (func = Z_OBJ_HT_P(object)->get_method(&Z_OBJ_P(object), method, NULL))
	) {
		if (func->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) {
			int status = (func->common.scope == zend_ce_closure && zend_string_equals_literal(method, ZEND_INVOKE_FUNC_NAME));

			zend_string_release(method);
			zend_string_release(func->common.function_name);
			zend_free_trampoline(func);
			return status ? SUCCESS : FAILURE;
		}

		zend_string_release(method);
		return SUCCESS;
	}

	zend_string_release(method);
	return FAILURE;
}

int zephir_method_exists(zval *object, const zval *method_name)
{
	if (Z_TYPE_P(method_name) != IS_STRING) {
		zend_error(E_WARNING, "method_exists expected a string");
		return 0;
	}

	char *lcname = zend_str_tolower_dup(Z_STRVAL_P(method_name), Z_STRLEN_P(method_name));
	int res = zephir_method_exists_ex(object, lcname, Z_STRLEN_P(method_name));
	efree(lcname);

	return res;
}

int zephir_read_static_property_ce(zval *result, zend_class_entry *ce, const char *property, int len, int flags)
{
	zval *tmp = zend_read_static_property(ce, property, len, (zend_bool) ZEND_FETCH_CLASS_SILENT);

	ZVAL_NULL(result);
	if (tmp) {
		if ((flags & PH_READONLY) == PH_READONLY) {
			ZVAL_COPY_VALUE(result, tmp);
		} else {
			ZVAL_COPY(result, tmp);
		}

		return SUCCESS;
	}

	return FAILURE;
}

/**
 * TODO: Use directly zend_update_static_property()
 */
int zephir_update_static_property_ce(zend_class_entry *ce, const char *property_name, uint32_t property_length, zval *value)
{
	return zend_update_static_property(ce, property_name, property_length, value);
}

int zephir_add_static_property_ce(zend_class_entry *ce, const char *property_name, uint32_t property_length, zval *value)
{
	zval tmp_value, new_value;
	zephir_read_static_property_ce(&tmp_value, ce, property_name, property_length, PH_NOISY | PH_READONLY);
	zephir_add_function(&new_value, &tmp_value, value);
	return zend_update_static_property(ce, property_name, property_length, &new_value);
}

int zephir_sub_static_property_ce(zend_class_entry *ce, const char *property_name, uint32_t property_length, zval *value)
{
	zval tmp_value, new_value;
	zephir_read_static_property_ce(&tmp_value, ce, property_name, property_length, PH_NOISY | PH_READONLY);
	zephir_sub_function(&new_value, &tmp_value, value);
	return zend_update_static_property(ce, property_name, property_length, &new_value);
}

/*
 * Multiple array-offset update
 */
int zephir_update_static_property_array_multi_ce(
	zend_class_entry *ce,
	const char *property,
	uint32_t property_length,
	zval *value,
	const char *types,
	int types_length,
	int types_count,
	...
) {
	va_list ap;
	zval tmp_arr;
	int separated = 0;

	ZVAL_UNDEF(&tmp_arr);

	zephir_read_static_property_ce(&tmp_arr, ce, property, property_length, PH_NOISY | PH_READONLY);

	/** Separation only when refcount > 1 */
	if (Z_REFCOUNTED(tmp_arr)) {
		if (Z_REFCOUNT(tmp_arr) > 1) {
			if (!Z_ISREF(tmp_arr)) {
				zval new_zv;
				ZVAL_DUP(&new_zv, &tmp_arr);
				ZVAL_COPY_VALUE(&tmp_arr, &new_zv);
				Z_TRY_DELREF(new_zv);
				Z_ADDREF(tmp_arr);
				separated = 1;
			}
		}
	} else {
		zval new_zv;
		ZVAL_DUP(&new_zv, &tmp_arr);
		ZVAL_COPY_VALUE(&tmp_arr, &new_zv);
		Z_TRY_DELREF(new_zv);
		separated = 1;
	}

	/** Convert the value to array if not is an array */
	if (Z_TYPE(tmp_arr) != IS_ARRAY) {
		if (separated) {
			convert_to_array(&tmp_arr);
		} else {
			array_init(&tmp_arr);
			separated = 1;
		}

		if (Z_REFCOUNTED(tmp_arr)) {
			if (Z_REFCOUNT(tmp_arr) > 1) {
				if (!Z_ISREF(tmp_arr)) {
					Z_DELREF(tmp_arr);
				}
			}
		}
	}

	va_start(ap, types_count);
	SEPARATE_ZVAL_NOREF(&tmp_arr);
	zephir_array_update_multi_ex(&tmp_arr, value, types, types_length, types_count, ap);
	va_end(ap);

	if (separated) {
		zend_update_static_property(ce, property, property_length, &tmp_arr);
	}

	if (Z_REFCOUNTED(tmp_arr)) {
		if (Z_REFCOUNT(tmp_arr) > 1) {
			if (!Z_ISREF(tmp_arr)) {
				Z_DELREF(tmp_arr);
			}
		}
	}

	return SUCCESS;
}

/**
 * Increments an object property
 */
int zephir_property_incr_decr(zval *object, char *property_name, unsigned int property_length, unsigned int increment)
{
	zval tmp;
	zend_class_entry *ce;
	int separated = 0;

	ZVAL_UNDEF(&tmp);

	if (Z_TYPE_P(object) != IS_OBJECT) {
		php_error_docref(NULL, E_WARNING, "Attempt to assign property of non-object");
		return FAILURE;
	}

	ce = Z_OBJCE_P(object);
	if (ce->parent) {
		ce = zephir_lookup_class_ce(ce, property_name, property_length);
	}

	zephir_read_property(&tmp, object, property_name, property_length, 0);
	if (Z_TYPE(tmp) > IS_UNDEF) {
		Z_TRY_DELREF(tmp);

		/** Separation only when refcount > 1 */
		if (Z_REFCOUNTED(tmp)) {
			if (Z_REFCOUNT(tmp) > 1) {
				if (!Z_ISREF(tmp)) {
					zval new_zv;
					ZVAL_DUP(&new_zv, &tmp);
					ZVAL_COPY_VALUE(&tmp, &new_zv);
					Z_TRY_DELREF(new_zv);
					separated = 1;
				}
			}
		} else {
			zval new_zv;
			ZVAL_DUP(&new_zv, &tmp);
			ZVAL_COPY_VALUE(&tmp, &new_zv);
			Z_TRY_DELREF(new_zv);
			separated = 1;
		}

		if (increment) {
			zephir_increment(&tmp);
		} else {
			zephir_decrement(&tmp);
		}

		if (separated) {
			zephir_update_property_zval(object, property_name, property_length, &tmp);
		}
	}

	return SUCCESS;
}

/* Imported since PHP is so nice to define this in a .c file... */
typedef struct _zend_closure {
	zend_object       std;
	zend_function     func;
	zval              this_ptr;
	zend_class_entry *called_scope;
	zif_handler       orig_internal_handler;
} zend_closure;

/**
 * Creates a closure
 */
int zephir_create_closure_ex(zval *return_value, zval *this_ptr, zend_class_entry *ce, const char *method_name, uint32_t method_length)
{
	zend_function *function_ptr;
	zend_closure *closure;

	if ((function_ptr = zend_hash_str_find_ptr(&ce->function_table, method_name, method_length)) == NULL) {
		ZVAL_NULL(return_value);
		return FAILURE;
	}

	zend_create_closure(return_value, function_ptr, ce, ce, this_ptr);
	// Make sure we can use a closure multiple times
	closure = (zend_closure*)Z_OBJ_P(return_value);
	closure->func.internal_function.handler = closure->orig_internal_handler;
	return SUCCESS;
}

/**
 * Creates a new instance dynamically. Call constructor without parameters
 */
int zephir_create_instance(zval *return_value, const zval *class_name)
{
	zend_class_entry *ce;

	if (Z_TYPE_P(class_name) != IS_STRING) {
		zephir_throw_exception_string(spl_ce_RuntimeException, SL("Invalid class name"));
		return FAILURE;
	}

	ce = zend_fetch_class(Z_STR_P(class_name), ZEND_FETCH_CLASS_DEFAULT);
	if (!ce) {
		ZVAL_NULL(return_value);
		return FAILURE;
	}

	if(UNEXPECTED(object_init_ex(return_value, ce) != SUCCESS)) {
    	return FAILURE;
    }

	if (EXPECTED(Z_OBJ_HT_P(return_value)->get_constructor)) {
		zend_object* obj    = Z_OBJ_P(return_value);
		zend_function* ctor = Z_OBJ_HT_P(return_value)->get_constructor(obj);
		if (ctor) {
			zend_fcall_info fci;
			zend_fcall_info_cache fcc;

			zend_class_entry* ce = Z_OBJCE_P(return_value);

			fci.size             = sizeof(fci);
			fci.object           = obj;
			fci.retval           = 0;
			fci.param_count      = 0;
			fci.params           = 0;
#if PHP_VERSION_ID < 80000
			fci.no_separation = 1;
#else
			fci.named_params = NULL;
#endif

			ZVAL_NULL(&fci.function_name);

			fcc.object           = obj;
			fcc.called_scope     = ce;
			fcc.calling_scope    = ce;
			fcc.function_handler = ctor;

			return zend_fcall_info_call(&fci, &fcc, NULL, NULL);
		}
	}

	return SUCCESS;
}

/**
 * Creates a new instance dynamically calling constructor with parameters
 */
int zephir_create_instance_params(zval *return_value, const zval *class_name, zval *params)
{
	zend_class_entry *ce;

	if (Z_TYPE_P(class_name) != IS_STRING) {
		zephir_throw_exception_string(spl_ce_RuntimeException, SL("Invalid class name"));
		return FAILURE;
	}

	if (Z_TYPE_P(params) != IS_ARRAY) {
		zephir_throw_exception_string(spl_ce_RuntimeException, SL("Instantiation parameters must be an array"));
		return FAILURE;
	}

	ce = zend_fetch_class(Z_STR_P(class_name), ZEND_FETCH_CLASS_AUTO);
	if (!ce) {
		ZVAL_NULL(return_value);
		return FAILURE;
	}

	if(UNEXPECTED(object_init_ex(return_value, ce) != SUCCESS)) {
    	return FAILURE;
    }

	if (EXPECTED(Z_OBJ_HT_P(return_value)->get_constructor)) {
		zend_object* obj    = Z_OBJ_P(return_value);
		zend_function* ctor = Z_OBJ_HT_P(return_value)->get_constructor(obj);
		if (ctor) {
			int status;
			zend_fcall_info fci;
			zend_fcall_info_cache fcc;

			zend_class_entry* ce = Z_OBJCE_P(return_value);

			fci.size             = sizeof(fci);
			fci.object           = obj;
			fci.retval           = 0;
			fci.param_count      = 0;
			fci.params           = 0;
#if PHP_VERSION_ID < 80000
			fci.no_separation = 1;
#else
			fci.named_params = NULL;
#endif
			ZVAL_NULL(&fci.function_name);

			fcc.object           = obj;
			fcc.called_scope     = ce;
			fcc.calling_scope    = ce;
			fcc.function_handler = ctor;

			zend_fcall_info_args_ex(&fci, fcc.function_handler, params);
			status = zend_fcall_info_call(&fci, &fcc, NULL, NULL);
			zend_fcall_info_args_clear(&fci, 1);
			return status;
		}
	}

	return SUCCESS;
}


text:
require 'uri'
require 'aws-sdk-resources'

module URI
  def self.seahorse_encode_www_form(params)
    params.map {|key, value|
      encoded_key = encode_www_form_component(key)

      if value.nil?
        encoded_key
      elsif value.respond_to?(:to_ary)
        value.to_ary.map {|v|
          if v.nil?
            # bug?
            #encoded_key
          else
            encoded_key + '=' + Seahorse::Util.uri_escape(v)
          end
        }.join('&')
      else
        encoded_key + '=' + Seahorse::Util.uri_escape(value)
      end
    }.join('&')
  end
end

redpajama_set_name: RedPajamaGithub


text:
/**
 * \file sys/ioctl.h
 */

/*
 * Copyright (c) 2011, 2012, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, CAB F.78, Universitaetstr. 6, CH-8092 Zurich,
 * Attn: Systems Group.
 */

/*-
 * Copyright (c) 1982, 1986, 1990, 1993, 1994
 *	The Regents of the University of California.  All rights reserved.
 * (c) UNIX System Laboratories, Inc.
 * All or some portions of this file are derived from material licensed
 * to the University of California by American Telephone and Telegraph
 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
 * the permission of UNIX System Laboratories, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)ioctl.h	8.6 (Berkeley) 3/28/94
 * $FreeBSD$
 */

#ifndef	_SYS_IOCTL_H_
#define	_SYS_IOCTL_H_

#include <sys/ioccom.h>

//#include <sys/filio.h>
//#include <sys/sockio.h>
#include <sys/ttycom.h>

#endif /* !_SYS_IOCTL_H_ */


text:
package org.apache.wink.itest.providers.readers;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;

@Provider
@Consumes(value = {"application/json"})
public class MyMessageBodyReaderJSONForShort implements MessageBodyReader<Short> {

    public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
        return true;
    }

    public Short readFrom(Class<Short> arg0,
                          Type arg1,
                          Annotation[] arg2,
                          MediaType arg3,
                          MultivaluedMap<String, String> arg4,
                          InputStream arg5) throws IOException, WebApplicationException {
        /* do nothing */
        return null;
    }

}


text:
Various Docker images used on the Diego project.

#### Updating the Diego Docker images

1. Download and start Docker on your machine following [these instructions](https://docs.docker.com/machine/get-started/).

1. Clone this repository onto your machine and change into its root directory.

   ```
   git clone https://github.com/cloudfoundry-incubator/diego-dockerfiles.git && cd diego-dockerfiles
   ```

1. `make` the appropriate Docker image target from the list below (for example, `make golang-ci` to build the `golang-ci` Docker image). Alternatively, run `make all` to build all of the images. By default, images are created with the `latest` tag. To specify a different tag name, set the `TAG` environment variable to that tag name.

   - `diego-docker-app`
   - `diego-units-ci`
   - `golang-ci`
   - `inigo-ci`

1. Push the Docker image to Dockerhub:
   - To push all of the images, run `make push`.
   - To push a specific image, run `docker push <IMAGE>`.

## Reporting issues and requesting features

Please report all issues and feature requests in [cloudfoundry/diego-release](https://github.com/cloudfoundry/diego-release/issues).


text:
package javax.mail.search;

/**
 * A Term that provides matching criteria for Strings.
 *
 * @version $Rev$ $Date$
 */
public abstract class StringTerm extends SearchTerm {

	private static final long serialVersionUID = 1274042129007696269L;

    /**
     * If true, case should be ignored during matching.
     */
    protected boolean ignoreCase;

    /**
     * The pattern associated with this term.
     */
    protected String pattern;

    /**
     * Constructor specifying a pattern.
     * Defaults to case insensitive matching.
     * @param pattern the pattern for this term
     */
    protected StringTerm(final String pattern) {
        this(pattern, true);
    }

    /**
     * Constructor specifying pattern and case sensitivity.
     * @param pattern the pattern for this term
     * @param ignoreCase if true, case should be ignored during matching
     */
    protected StringTerm(final String pattern, final boolean ignoreCase) {
        this.pattern = pattern;
        this.ignoreCase = ignoreCase;
    }

    /**
     * Return the pattern associated with this term.
     * @return the pattern associated with this term
     */
    public String getPattern() {
        return pattern;
    }

    /**
     * Indicate if case should be ignored when matching.
     * @return if true, case should be ignored during matching
     */
    public boolean getIgnoreCase() {
        return ignoreCase;
    }

    /**
     * Determine if the pattern associated with this term is a substring of the
     * supplied String. If ignoreCase is true then case will be ignored.
     *
     * @param match the String to compare to
     * @return true if this patter is a substring of the supplied String
     */
    protected boolean match(final String match) {
        final int matchLength = pattern.length();
        final int length = match.length() - matchLength;

        for (int i = 0; i <= length; i++) {
            if (match.regionMatches(ignoreCase, i, pattern, 0, matchLength)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean equals(final Object other) {
        if (this == other) {
			return true;
		}
        if (other instanceof StringTerm == false) {
			return false;
		}

        final StringTerm term = (StringTerm)other;

        if (ignoreCase) {
            return term.pattern.equalsIgnoreCase(pattern) && term.ignoreCase == ignoreCase;
        }
        else {
            return term.pattern.equals(pattern) && term.ignoreCase == ignoreCase;
        }
    }

    @Override
    public int hashCode() {
        return pattern.hashCode() + (ignoreCase ? 32 : 79);
    }
}


text:
This template will deploy and configure a Windows Server 2016 TP4 core VM instance with Windows Server Containers. These items are performed by the template:

- Deploy the TP4 Windows Server Container Image.
- Create inbound network security group rules for HTTP, RDP and Docker.
- Create inbound Windows Firewall rules for HTTP and Docker (custom script extensions).
- Modify the Docker Daemon configuration file to listen for incoming requests on port 2375 (custom script extension).

Windows Server 2016 TP4 and Windows Server Container are in an early preview release and are not production ready and or supported.

> Microsoft Azure does not support Hyper-V containers. To complete Hyper-V Container exercises, you need an on-prem container host.


text:
var BaseRouter = require('../../../shared/base/router'),
  sinon = require('sinon'),
  chai = require('chai'),
  should = chai.should();

chai.use(require('sinon-chai'));

describe('BaseRouter', function () {
  describe('initialization', function () {
    var testCases = [
        {
          options: { entryPath: 'foobar/' },
          expectedOptions: {
            entryPath: 'foobar/',
            paths: {
              entryPath: 'foobar/',
              routes: 'foobar/app/routes',
              controllerDir: 'foobar/app/controllers'
            }
          }
        },
        {
          options: {
            paths: {
              entryPath: 'foobar/',
              routes: '/some/other/location/MyRoutes.js',
              controllerDir: 'another/different/location/'
            }
          },
          expectedOptions: {
            paths: {
              entryPath: 'foobar/',
              routes: '/some/other/location/MyRoutes.js',
              controllerDir: 'another/different/location/'
            }
          }
        },
        {
          options: { entryPath: 'foobar/' },
          expectedOptions: {
            entryPath: 'foobar/',
            paths: {
              entryPath: 'foobar/',
              routes: 'foobar/app/routes',
              controllerDir: 'foobar/app/controllers'
            }
          }
        },
        {
          options: { entryPath: '' },
          expectedOptions: {
            entryPath: '',
            paths: {
              entryPath: '',
              routes: 'app/routes',
              controllerDir: 'app/controllers'
            }
          }
        }
      ];

    testCases.forEach(function(testCase) {
      it('should initialize the paths options', function() {
        var router = new BaseRouter(testCase.options);
        router.options.should.be.deep.equal(testCase.expectedOptions);
      });
    });

  });

  describe('router instance', function() {
    var router;

    beforeEach(function() {
      router = new BaseRouter({entryPath: 'MyAppRootPath/'});
    });

    describe('getAction', function () {
      it('should return the controller path in AMD environment', function () {
        var action;

        BaseRouter.setAMDEnvironment(true);
        action = router.getAction({controller: 'home'});

        action.should.be.equal('MyAppRootPath/app/controllers/home_controller')
        BaseRouter.setAMDEnvironment(false);
      });

      it('should load the controller in non AMD environments', function () {
        var action,
          controller = { index: sinon.spy() },
          loadController = sinon.stub(router, 'loadController').returns(controller);

        action = router.getAction({controller: 'home', action: 'index'});

        loadController.should.have.been.calledOnce;
        loadController.should.have.been.calledWith('home');
        action.should.be.equal(controller.index);
      });
    });

    describe('getRedirect', function() {
      it('should return undefined if no redirect is given', function() {
        var redirect = router.getRedirect({});
        should.not.exist(redirect);
      });

      it('should return a string if the redirect is given as a string', function() {
        var route = {redirect: '/home'},
          redirect = router.getRedirect(route);

        redirect.should.be.equal('/home');
      });

      it('should return the result of a given function', function() {
        var params = {foo: 'bar'},
          route = {redirect: function(params) {
            return params.foo;
          }},
          redirect = router.getRedirect(route, params);

        redirect.should.be.equal('bar');
      });
    });

    describe('buildRoutes', function() {
      it('should add route definitions', function () {
        var getRouteBuilder = sinon.stub(router, 'getRouteBuilder'),
          route = sinon.stub(router, 'route');

        getRouteBuilder.returns(function (match) {
          match('/foobar', 'foobar#index');
        });
        router.buildRoutes();

        route.should.have.been.calledOnce;
        route.should.have.been.calledWithExactly('/foobar', 'foobar#index');
      });
    });

    describe('route', function() {
      var action, handler, getAction, getHandler;

      beforeEach(function() {
        action = sinon.spy();
        handler = sinon.spy();
        getAction = sinon.stub(router, 'getAction').returns(action);
        getHandler = sinon.stub(router, 'getHandler').returns(handler);
      });

      it('should trigger an event and pass the correct route object', function() {
        var trigger = sinon.stub(router, 'trigger');

        router.route('/home', 'home#index');

        trigger.should.have.been.calledOnce;
        trigger.should.have.been.calledWithExactly('route:add', [
          '/home',
          { controller: 'home', action: 'index' },
          handler
        ]);
      });
    });
  });
});


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > The Nice Lady

						Expand All | Collapse All

The Nice Lady

  Calvin answered the phone. A woman said, "Hello. I'm Ruth. I'm a volunteer for Alzheimer's." She sounded like an old woman. She said the organization was trying to raise money. He asked how she got his number. She said his number was on her list. He said that he was on the Do Not Call list. He told her not to call his number again. She apologized. He hung up. Later, he felt guilty. He shouldn't have been so rude to that sweet old lady. He looked at "Calls Received on his phone. He dialed the Alzheimer's number. "Hello, can I speak to Ruth?" he asked. A man asked, "Ruth who?" Calvin didn't know Ruth's last name. The man said he would ask around and find Ruth. "I just wanted to apologize to her for hanging up on her," Calvin said. The man said he would pass on Calvin's apology.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
from __future__ import print_function
from builtins import range
from random import randint
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.pca import H2OPrincipalComponentAnalysisEstimator as H2OPCA

def pca_scoring_history_importance():
    """
    This test aims to check and make sure PCA returns the scoring history and importance which are
    reported missing for certain PCA mode.  Apart from changing the PCA mode, I throw in the transform
    type to test as well randomly.
    """
    transform_types = ["NONE", "STANDARDIZE", "NORMALIZE", "DEMEAN", "DESCALE"]
    transformN = transform_types[randint(0, len(transform_types)-1)]

    print("Importing australia.csv data...\n")
    australia = h2o.upload_file(pyunit_utils.locate("smalldata/extdata/australia.csv"))
    col_indices = list(range(0, australia.ncol))

    print("transform is {0}.\n".format(transformN))
    # checking out PCA with GramSVD
    print("@@@@@@  Building PCA with GramSVD...\n")
    gramSVD = H2OPCA(k=3, transform=transformN)
    gramSVD.train(x=col_indices, training_frame=australia)

    # check PCA with PCA set to Randomized
    print("@@@@@@  Building PCA with Randomized...\n")
    randomizedPCA = H2OPCA(k=3, transform=transformN, pca_method="Randomized", compute_metrics=True,
                         use_all_factor_levels=True)
    randomizedPCA.train(x=col_indices, training_frame=australia)

    # compare singular values and stuff with GramSVD
    print("@@@@@@  Comparing eigenvalues between GramSVD and Randomized...\n")
    pyunit_utils.assert_H2OTwoDimTable_equal(gramSVD._model_json["output"]["importance"],
                                           randomizedPCA._model_json["output"]["importance"],
                                           ["Standard deviation", "Cumulative Proportion", "Cumulative Proportion"],
                                           tolerance=1e-3)
    print("@@@@@@  Comparing eigenvectors between GramSVD and Randomized...\n")
    # compare singular vectors
    pyunit_utils.assert_H2OTwoDimTable_equal(gramSVD._model_json["output"]["eigenvectors"],
                                           randomizedPCA._model_json["output"]["eigenvectors"],
                                           randomizedPCA._model_json["output"]["names"], tolerance=5e-2,
                                           check_sign=True)

    # check PCA with PCA set to Power
    print("@@@@@@  Building PCA with Power...\n")
    powerPCA = H2OPCA(k=3, transform=transformN, pca_method="Power", compute_metrics=True, use_all_factor_levels=True)
    powerPCA.train(x=col_indices, training_frame=australia)

    # compare singular values and stuff with GramSVD
    print("@@@@@@  Comparing eigenvalues between GramSVD and Power...\n")
    pyunit_utils.assert_H2OTwoDimTable_equal(gramSVD._model_json["output"]["importance"],
                                           powerPCA._model_json["output"]["importance"],
                                           ["Standard deviation", "Cumulative Proportion", "Cumulative Proportion"])
    print("@@@@@@  Comparing eigenvectors between GramSVD and Power...\n")
    # compare singular vectors
    pyunit_utils.assert_H2OTwoDimTable_equal(gramSVD._model_json["output"]["eigenvectors"],
                                           powerPCA._model_json["output"]["eigenvectors"],
                                           powerPCA._model_json["output"]["names"], tolerance=1e-5, check_sign=True)

    # check PCA with PCA set to GLRM
    print("@@@@@@  Building PCA with GLRM...\n")
    glrmPCA = H2OPCA(k=3, transform=transformN, pca_method="GLRM", compute_metrics=True, use_all_factor_levels=True)
    glrmPCA.train(x=col_indices, training_frame=australia)

    # compare singular values and stuff with GramSVD
    print("@@@@@@  Comparing eigenvalues between GramSVD and GLRM...\n")
    pyunit_utils.assert_H2OTwoDimTable_equal(gramSVD._model_json["output"]["importance"],
                                           glrmPCA._model_json["output"]["importance"],
                                           ["Standard deviation", "Cumulative Proportion", "Cumulative Proportion"],
                                           tolerance=2e-2)
    print("@@@@@@  Comparing eigenvectors between GramSVD and GLRM...\n")
    # compare singular vectors
    pyunit_utils.assert_H2OTwoDimTable_equal(gramSVD._model_json["output"]["eigenvectors"],
                                           glrmPCA._model_json["output"]["eigenvectors"],
                                           glrmPCA._model_json["output"]["names"], tolerance=2e-1,check_sign=True)

    # make sure we find the scoring history and it is not empty for all the PCA modes
    # just check and make sure the cell_values exceed 0
    assert len(gramSVD._model_json["output"]["scoring_history"].cell_values) > 0, "PCA Scoring history setting " \
                                                                                "pca_method to GramSVD is empty."
    assert len(powerPCA._model_json["output"]["scoring_history"].cell_values) > 0, "PCA Scoring history setting " \
                                                                                "pca_method to using is empty."
    assert len(randomizedPCA._model_json["output"]["scoring_history"].cell_values) > 0, "PCA Scoring history setting " \
                                                                                "pca_method to Randomized is " \
                                                                                "empty."
    assert len(glrmPCA._model_json["output"]["scoring_history"].cell_values) > 0, "PCA Scoring history setting " \
                                                                                "pca_method to GLRM is empty."

if __name__ == "__main__":
    pyunit_utils.standalone_test(pca_scoring_history_importance)
else:
    pca_scoring_history_importance()


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Reversi</title>
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="../css/reset.css">
    <link rel="stylesheet" href="../css/main.css">
    <link rel="stylesheet" href="../css/qunit.css">

a

b

c

d

e

f

g

h

1

2

3

4

5

6

7

8

White: 2

Black: 2


text:
namespace tadpole {

void register_builtins(VM& vm) {
  // fn help() -> nil
  vm.define_native("help", [](sz_t, Value*) -> Value {
        std::cout
          << colorful::fg::green << "Welcome to Tadpole! This is the help utility."
          << colorful::reset << std::endl << std::endl;

        std::cout << "print(...)      Prints the values to stdout stream" << std::endl;
        std::cout << "exit()          Exit the Tadpole terminal" << std::endl;
        std::cout << "time()          Returns the current time in seconds since the Epoch" << std::endl;
        std::cout << "clock()         Returns the CPU time since the start of the process" << std::endl;
        std::cout << "gc_count()      Returns number of objects tracked by GC" << std::endl;
        std::cout << "gc_threshold()  Returns the current collection thresholds" << std::endl;
        std::cout << "gc_threshold(n) Sets the collection thresholds" << std::endl;
        std::cout << "gc_collect()    Run a full collection" << std::endl;

        return nullptr;
      });

  // fn print(arg1: Value, arg2: Value, ...) -> nil
  vm.define_native("print", [](sz_t nargs, Value* args) -> Value {
        for (sz_t i = 0; i < nargs; ++i)
          std::cout << args[i] << " ";
        std::cout << std::endl;

        return nullptr;
      });

  // fn exit() -> nil
  vm.define_native("exit", [&vm](sz_t, Value*) -> Value {
        vm.terminate();
        return nullptr;
      });

  // fn time() -> numeric
  //
  // @returns
  //  timestamp: numerics -> unit is seconds
  vm.define_native("time", [](sz_t, Value*) -> Value {
        return std::chrono::duration_cast<std::chrono::milliseconds>(
            std::chrono::system_clock::now().time_since_epoch()).count() / 1000.0;
      });

  // fn clock() -> numeric
  //
  // @returns
  //  clock: numeric -> unit is us
  vm.define_native("clock", [](sz_t, Value*) -> Value {
        return std::chrono::duration_cast<std::chrono::microseconds>(
            std::chrono::steady_clock::now().time_since_epoch()).count();
      });

  // fn gc_count() -> numeric
  //
  // @returns
  //  gc_count: numeric -> number of current objects
  vm.define_native("gc_count", [](sz_t, Value*) -> Value {
        return GC::get_instance().get_count();
      });

  // fn gc_threshold() -> numeric
  //
  // @returns
  //  threshold: numeric -> current number of gc threshold
  //
  //
  // fn gc_threshold(threshold: numeric) -> numeric
  //
  // @args
  //  threshold: numeric -> number of gc threshold
  //
  // @returns
  //  gc_threshold: numeric -> current numeric of gc threshold
  vm.define_native("gc_threshold", [](sz_t nargs, Value* args) -> Value {
        if (nargs == 1 && args != nullptr && args[0].as_numeric())
          GC::get_instance().set_threshold(args[0].as_integer<sz_t>());
        return GC::get_instance().get_threshold();
      });

  // fn gc_collect() -> nil
  vm.define_native("gc_collect", [](sz_t, Value*) -> Value {
        GC::get_instance().collect();
        return nullptr;
      });
}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Report of the Department of Agriculture, Government Research Institute of Formosa 85: 67 (1943)

#### Original name
Phyllosticta yugokwa Sawada

### Remarks
null


text:
function handleSelect (selectedKey) {
  alert('selected ' + selectedKey);
}

var navInstance = (
    <Nav bsStyle="tabs" activeKey={1} onSelect={handleSelect}>
      <NavItem eventKey={1} href="/home">NavItem 1 content</NavItem>
      <NavItem eventKey={2} title="Item">NavItem 2 content</NavItem>
      <NavItem eventKey={3} disabled={true}>NavItem 3 content</NavItem>
      <DropdownButton eventKey={4} title="Dropdown" navItem={true}>
        <MenuItem eventKey="4.1">Action</MenuItem>
        <MenuItem eventKey="4.2">Another action</MenuItem>
        <MenuItem eventKey="4.3">Something else here</MenuItem>
        <MenuItem divider />
        <MenuItem eventKey="4.4">Separated link</MenuItem>
      </DropdownButton>
    </Nav>
  );

React.render(navInstance, mountNode);


text:
package smallsql.database;

final class ExpressionFunctionACos extends ExpressionFunctionReturnFloat {

    final int getFunction(){ return SQLTokenizer.ACOS; }

    final double getDouble() throws Exception{
		if(isNull()) return 0;
        return Math.acos( param1.getDouble() );
    }
}


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

namespace BTDB.IOC.CRegs
{
    class FactoryImpl : ICReg, ICRegILGen
    {
        readonly Type _type;
        readonly int _instanceIndex;

        public FactoryImpl(ContainerImpl container, Func<object> buildFunc, Type type)
        {
            _type = type;
            _instanceIndex = container.AddInstance(buildFunc);
        }

        string ICRegILGen.GenFuncName(IGenerationContext context)
        {
            return "Factory_" + _type.ToSimpleName();
        }

        public void GenInitialization(IGenerationContext context)
        {
            context.GetSpecific<InstancesLocalGenCtxHelper>().Prepare();
        }

        public bool IsCorruptingILStack(IGenerationContext context)
        {
            return false;
        }

        public IILLocal GenMain(IGenerationContext context)
        {
            var localInstances = context.GetSpecific<InstancesLocalGenCtxHelper>().MainLocal;
            var localInstance = context.IL.DeclareLocal(_type, "instance");
            context.IL
                .Ldloc(localInstances)
                .LdcI4(_instanceIndex)
                .LdelemRef()
                .Castclass(typeof(Func<object>))
                .Call(() => default(Func<object>).Invoke())
                .Castclass(_type)
                .Stloc(localInstance);
            return localInstance;
        }

        public IEnumerable<INeed> GetNeeds(IGenerationContext context)
        {
            yield return Need.ContainerNeed;
        }

        public bool IsSingletonSafe()
        {
            return true;
        }

        public void Verify(ContainerVerification options, ContainerImpl container)
        {
        }
    }
}


text:
"""Demonstrate how to write reusable command line tools.

A `pykern.pkcli` module is designed to be used from any context
any other piece of code. Since we use `argh`, it makes it easy
to dispatch with a bit of glue so that all you have to do is write
a function.

Documentation should be provided as a normal docstring for the function.
See `echo`.

You should set up your project directory with `pykern.pkcli.projex`,
which will give you a shell command that gets automatically
installed. Each project has one such command. For example,
`pykern.pykern_console` is the module that invokes all `pykern`
pkcli functions.

To invoke `echo`, use the shell command::

    $ pykern pkexample echo something
    howdy: something

The output of the function is printed on stdout so if you don't
have to print messages, and the function can be used in other
contexts where stdout is not useful (e.g. returned to a brower).

If you invoke this module without arguments, you get a list of
functions you can call:

    $ pykern pkexample
    usage: pykern pkexample [-h] {echo,primes} ...
    pykern pkexample: error: too few arguments

This list only includes "public" functions (not beginning with
an underscore).

In your project, you'll have your own function, for example,
you can start Sirepo with::

    $ sirepo service http
     * Running on http://0.0.0.0:8000/
     * Restarting with reloader

The module `sirepo.sirepo_console` is automatically installed
as a shell command by ``setup.py``, and `pykern.pkcli` searches
for modules to invoke in the package `sirepo.pkcli`. In fact,
you can list out all modules by invoking ``sirepo`` without
any arguments::

    $ sirepo
    usage: sirepo module command [args...]
    Modules:
    celery
    elegant
    service
    srw
    warp

:copyright: Copyright (c) 2016 RadiaSoft LLC.  All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from pykern import pkcli
import itertools

def echo(suffix, prefix="howdy: "):
    """Concatenate prefix and suffix

    Args:
        to_echo (str): what to print and must be at least five chars
        prefix (str): what to put in front of `to_echo` ["howdy: "]

    Returns:
        str: prefix + suffix
    """
    if len(suffix) < 5:
        # We raise argument and other errors with command_error, which
        # raises `pkcli.CommandError` in a nice way. We use Unix-style
        # error messages, that is, problematic object followed by colon
        # followed by an error message and any other details.
        pkcli.command_error("{}: suffix is too short (< 5 chars)", suffix)
    # Instead of printing messages in the simple case, we just
    # return the value. This way the function can be used in
    # other contexts. argh prints the return of the function to stdout.
    return prefix + suffix


text:
static NSString * const LKRoomNameKey = @"name";
static NSString * const LKRoomDevicesKey = @"x10_devices";
static NSString * const LKRoomHasColorsKey = @"has_colors";

@interface LKRoom ()

@property (nonatomic) NSString *name;
@property (nonatomic) NSArray *devices;
@property (nonatomic) BOOL hasColors;

@end

@implementation LKRoom

+ (instancetype)roomWithDictionary:(NSDictionary *)dict {
    LKRoom *room = [[LKRoom alloc] init];
    room.name = dict[LKRoomNameKey];
    room.hasColors = dict[LKRoomHasColorsKey] == [NSNull null] ? NO : [dict[LKRoomHasColorsKey] boolValue];

    NSMutableArray *devices = [NSMutableArray array];
    for (NSDictionary *deviceDict in dict[LKRoomDevicesKey]) {
        [devices addObject:[LKX10Device deviceWithDictionary:deviceDict]];
    }
    room.devices = [devices copy];

    return room;
}

@end


text:
{# ------------------------------------------------------- #}
{# ONE OFF VIEW educationandtraining #}
{# This page can use any data from http:localhost:2000/cms/#/form/educationandtraining/ #}
{# Webhook uses the SWIG.js (like Djagno/Twig) templating system. Their documentation is here: #}
{# http://paularmstrong.github.io/swig/docs/tags/ #}
{# Learn about calling data into Webhook pages here: #}
{# http://www.webhook.com/docs/template-rules-and-filters/ #}
{# ------------------------------------------------------- #}
{# Confused what extends and blocks do? Watch a primer: #}
{# http://www.webhook.com/docs/template-inheritance-blocks/ #}
{% extends "templates/partials/base.html" %}
{# This sets our page <title>. It will append this educationandtraining's name to the site title defined in base.html #}
{% block title %}{% parent %} - {{ cms.educationandtraining.name }}{% endblock %}
{% block content %}

{{ cms.educationandtraining.name }}

        Name:
        {{ cms.educationandtraining.name }}

        Create Date:
        {# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #}
        {{ cms.educationandtraining.create_date|date('F d Y') }}

        Last Updated:
        {# Format the date. You can use PHP's date function to format as needed. http://php.net/manual/en/function.date.php #}
        {{ cms.educationandtraining.last_updated|date('F d Y') }}

        Education:
        {# Loop of your Repeatable Form items. Remember, you can sort the order in your CMS if you need. #}

        {% for row in cms.educationandtraining.education %}

              Institution:
              {# Relationship. Note that use the label you set for the relation, not the content-type name. #}
                {# You can ouput more than just the name. Feel free to output more fields from the CMS. #}
                {{ row.institution.name }}

              Degree:
              {{ row.degree }}

              Year:
              {{ row.year }}

              Department:
              {{ row.department }}

              Additional Notes:
              {{ row.additional_notes }}

        {% endfor %}

        Pedagogical and Technical Training:
        {# Loop of your Repeatable Form items. Remember, you can sort the order in your CMS if you need. #}

        {% for row in cms.educationandtraining.pedagogical_and_technical_training %}

              Title:
              {{ row.title }}

              Department:
              {{ row.department }}

              Institution:
              {# Relationship. Note that use the label you set for the relation, not the content-type name. #}
                {# You can ouput more than just the name. Feel free to output more fields from the CMS. #}
                {{ row.institution.name }}

              Timeframe:
              {{ row.timeframe }}

              Overview:
              {{ row.overview }}

        {% endfor %}

        Preview URL:
        {{ cms.educationandtraining.preview_url }}

        Slug:
        {{ cms.educationandtraining.slug }}

{% endblock %}


text:
package org.codemucker.jtest.bean.tester.hashcodeequals;

public class TstBeanHashCodeChangesPerInvocation {

	private String fieldA;

	private int fieldB = 0;

	public String getFieldA() {
		return fieldA;
	}

	public void setFieldA(String fieldA) {
		this.fieldA = fieldA;
	}

	@Override
	public int hashCode() {
		return fieldB++;
	}

}


text:
package com.amazonaws.services.wafv2.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.wafv2.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * Regex JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RegexJsonUnmarshaller implements Unmarshaller<Regex, JsonUnmarshallerContext> {

    public Regex unmarshall(JsonUnmarshallerContext context) throws Exception {
        Regex regex = new Regex();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("RegexString", targetDepth)) {
                    context.nextToken();
                    regex.setRegexString(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return regex;
    }

    private static RegexJsonUnmarshaller instance;

    public static RegexJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new RegexJsonUnmarshaller();
        return instance;
    }
}


text:
<?php

namespace CEOFESABundle\Repository;

use Doctrine\ORM\EntityRepository;

class DParcoursRepository extends EntityRepository
{
    public function getParcoursDevis($id_devis){
        return $this
        ->createQueryBuilder('d')
        ->where('d.dprDevis = :idDevis')
        ->setParameter('idDevis',$id_devis)
        ;
    }

    public function getStagiairesDevis($id_devis){
    	return $this->createQueryBuilder('n')
        ->where('n.dprDevis = :idDevis')
        ->groupBy('n.dprNumero')
        ->orderBy('n.dprNumero','ASC')
        ->setParameter('idDevis', $id_devis)
        ;
    }
}


text:
import * as types from '../mutation_types'
import service from '../../services/posts/index'
export const getAllPost = ({ dispatch }, tags) => {
  return service.getDraftList(tags).then(res => {
    if (res.success) {
      dispatch(types.RECEIVE_ALL_POSTS, res.data)
      if (res.data.length) {
        dispatch(types.POST_FOCUS, 0)
      }
    }
  })
}
export const focusOnPost = ({ dispatch }, index) => {
  dispatch(types.POST_FOCUS, index)
}
export const editPost = ({ dispatch }) => {
  dispatch(types.POST_EDIT)
}
export const savePost = ({ dispatch }) => {
  dispatch(types.POST_SAVE)
}
export const editPostTitle = ({ dispatch }) => {
  dispatch(types.POST_TITLE_EDIT)
}
export const savePostTitle = ({ dispatch }) => {
  dispatch(types.POST_TITLE_SAVE)
}
export const deletePost = ({ dispatch, state }) => {
  if (state.post.postSaved) {
    return service.deleteDraft(state.post.currentPostId).then(res => {
      if (res.success) {
        dispatch(types.POST_DELETE)
      }
    })
  } else {
    let err = new Error()
    err.error_message = '文章尚未保存,请稍后再试'
    return Promise.reject(err)
  }
}
export const publishPost = ({ dispatch, state }) => {
  return service.publish(state.post.currentPostId).then(res => {
    if (res.success) {
      dispatch(types.POST_PUBLISH, res.data.article.id)
    }
  })
}
export const submitPostTitle = ({ dispatch, state }, title) => {
  return service.modifyDraftTitle(state.post.currentPostId, title).then(res => {
    if (res.success) {
      dispatch(types.POST_TITLE_MODIFY, title)
      dispatch(types.POST_LAST_EDIT_TIME, res.data.lastEditTime)
    }
  })
}
export const submitPostExcerpt = ({ dispatch}, excerpt, time) => {
  dispatch(types.POST_EXCERPT_MODIFY, excerpt)
  dispatch(types.POST_LAST_EDIT_TIME, time)
}

export const createPost = ({dispatch}) => {
  return service.createDraft('新文章').then(res => {
    if (res.success) {
      dispatch(types.POST_CREATE, res.data)
    } else {
      return Promise.reject('')
    }
  })
}
export const postTagsModify = ({dispatch}, time) => {
  dispatch(types.POST_TAG_MODIFY)
  dispatch(types.POST_LAST_EDIT_TIME, time)
}


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>chimichanga cancun...mmmm... preporucam svima</Text>
  <Rating>6</Rating>
  <Source>http://pauza.hr/menu/meduza-catering-savica</Source>
</CrawlItem>


text:
<?php

class MassMailer extends CodonModule {

	public function HTMLHead() {
		$this->set('sidebar', 'sidebar_mailer.php');
	}

	public function index() {
        $this->checkPermission(EMAIL_PILOTS);
		$this->set('allgroups', PilotGroups::getAllGroups());
		$this->render('mailer_form.php');
	}

	public function sendmail() {
        $this->checkPermission(EMAIL_PILOTS);
		echo '
Sending email
';
		if ($this->post->subject == '' || trim($this->post->message) == '') {
			$this->set('message', 'You must enter a subject and message!');
			$this->render('core_error.php');
			return;
		}

		if (count($this->post->groups) == 0) {
			$this->set('message', 'You must select groups to send to!');
			$this->render('core_error.php');
			return;
		}

		echo 'Sending email...
';

		$pilotarray = array();
		//Begin the nice long assembly of e-mail addresses
		foreach ($this->post->groups as $groupid) {
			if ($groupid == 'all') {
				$all_pilots = PilotData::findPilots(array());
				foreach ($all_pilots as $pilot) {
					$pilotarray[$pilot->pilotid] = $pilot;
				}

				break;
			} else {
				$tmp = PilotGroups::getUsersInGroup($groupid);
				if (count($tmp) == 0 || !is_array($tmp)) {
					continue;
				}

				foreach ($tmp as $pilot) {
					$pilotarray[$pilot->pilotid] = $pilot;
				}
			}
		}

		$subject = DB::escape($this->post->subject);
		$message = stripslashes($this->post->message) . PHP_EOL . PHP_EOL;

		# Do some quick fixing of obvious formatting errors
		$message = str_replace('
', '
', $message);
		foreach ($pilotarray as $pilot) {
			echo 'Sending for ' . $pilot->firstname . ' ' . $pilot->lastname . '
';

			# Variable replacements
			$send_message = str_replace('{PILOT_FNAME}', $pilot->firstname, $message);
			$send_message = str_replace('{PILOT_LNAME}', $pilot->lastname, $send_message);
			$send_message = str_replace('{PILOT_ID}', PilotData::GetPilotCode($pilot->code, $pilot->pilotid), $send_message);
			$send_message = utf8_encode($send_message);

			Util::SendEmail($pilot->email, $subject, $send_message);
		}

		echo 'Complete!';

		LogData::addLog(Auth::$userinfo->pilotid, 'Sent pass mail');
		return;
	}

}


text:
package com.madisp.bad.demo;

import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

/**
 * Created with IntelliJ IDEA.
 * User: madis
 * Date: 3/20/13
 * Time: 8:44 AM
 */
public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		View v = new FrameLayout(this);
		v.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
		v.setId(R.id.mainContainer);
		setContentView(v);

		if (savedInstanceState == null) {
			FragmentTransaction ft = getFragmentManager().beginTransaction();
			ft.add(R.id.mainContainer, new ListFragment());
			ft.commit();
		}
	}
}


text:
package org.languagetool.chunking;

import edu.washington.cs.knowitall.logic.LogicExpression;
import edu.washington.cs.knowitall.regex.Expression;
import edu.washington.cs.knowitall.regex.ExpressionFactory;

/**
 * @since 2.9
 */
final class TokenExpressionFactory extends ExpressionFactory<ChunkTaggedToken> {

  private final boolean caseSensitive;

  /**
   * @param caseSensitive whether word tokens should be compared case-sensitively - also used for regular expressions
   */
  TokenExpressionFactory(boolean caseSensitive) {
    this.caseSensitive = caseSensitive;
  }

  @Override
  public Expression.BaseExpression<ChunkTaggedToken> create(String expr) {
    LogicExpression<ChunkTaggedToken> logicExpression = LogicExpression.compile(expr, input -> new TokenPredicate(input, caseSensitive));
    return new Expression.BaseExpression<ChunkTaggedToken>(expr) {
      @Override
      public boolean apply(ChunkTaggedToken token) {
        return logicExpression.apply(token);
      }
    };
  }

}


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

    // Organize the controller name and dependencies here for easy recognition
    var controllerId = 'TestSubjects';
    angular.module('app').controller(controllerId, ['common', 'datacontext', '$routeParams', TestSubjects]);

    // This is our controller...  think of it as a controller with a view model in it
    function TestSubjects(common, datacontext, $routeParams) {

        // Organizing all of the variables and functions here allows us to get a quick look at
        // what the controller is doing
        var getLogFn = common.logger.getLogFn;
        var log = getLogFn(controllerId);
        var logError = getLogFn(controllerId, 'error');

        var vm = this;
        vm.title = 'Test Subjects';
        vm.testSubjects = [];
        vm.siteId = $routeParams.trialSiteID;
        vm.studyId = $routeParams.studyId;

        // Our event handlers
        vm.getTestSubjects = getTestSubjects;
        vm.search = search;

        // Call this function when our controller is loaded
        activate();

        // ============  The work & logic
        // ============  From here down we are implementing the functions that we defined above.  Clean organization.

        // The activate method takes care of any work that is needed to get the view up and running.
        // Things like calling a service to get data options for dropdowns, populate arrays, etc.
        // This convention will be used with all controllers.
        function activate() {
            var promises = [];
            common.activateController(promises, controllerId)
                .then(function () { log('Activated Create View'); });
            vm.getTestSubjects();
            vm.testSubjectOptions = {
                data: 'vm.testSubjects',
                showFilter: true,
                enableColumnResize: true,
                enableRowSelection: true,
                columnDefs: [
                    {
                        field: 'Subject_ID', displayName: 'Subject ID'
                    },
                    {
                        field: 'Subject_RecruitedDate', displayName: 'Date Received'
                    },
                    {
                        field: 'Subject_FirstName', displayName: 'First Name'
                    },
                    {
                        field: 'Subject_LastName', displayName: 'Last Name'
                    },
                    {
                        field: 'Subject_SSN', displayName: 'SSN'
                    },
                    {
                        field: 'Subject_DateOfBirth', displayName: 'DOB'
                    },
                    {
                        field: 'Subject_Gender', displayName: 'Gender'
                    }

                ]
            }
        }

        function search(){

        }

        function getTestSubjects(){
            vm.query = 'MATCH (PI)-[:RUNS_TRIAL]-(TS)<-[:HAS_SITE]-(S) WHERE S.Study_ID = "' + vm.studyId + '" AND TS.TrialSite_ID="' + vm.siteId + '" WITH TS OPTIONAL MATCH (TS)-[:HAS_SUBJECT]-(T) RETURN T.Subject_ID AS Subject_ID, T.Subject_FirstName AS Subject_FirstName, T.Subject_LastName AS Subject_LastName, T.Subject_SSN AS Subject_SSN,T.Subject_DateOfBirth AS Subject_DateOfBirth, T.Subject_Gender AS Subject_Gender, T.Subject_RecruitedDate AS Subject_RecruitedDate, T.Subject_LastVisitCompleted AS Subject_LastVisitCompleted, T.Subject_Withdrawal_Date AS Subject_Withdrawal_Date, T.TrialSite_DateFileReceived AS TrialSite_DateFileReceive ORDER BY Subject_ID';
            console.log(vm.query);
            return datacontext.runAdhocQuery(vm.query).then(function(result){
                console.log(result.data.responseData);
                return vm.testSubjects = result.data.responseData;
            });
        }

    }
})();


text:
import pika
import json
import base64
import time
import os
import redis
import logging
import farm_template_py3

global connection
from web_access_py3 import *

class Remote_Interface_server():

   def __init__(self ):
        self.redis                 = redis
        self.cmds                  = {}
        self.cmds["GET_WEB_PAGE"]  = self.get_web_page
        self.cmds["POST_WEB_PAGE"] = self.post_web_page
        self.cmds["PING"]          = self.ping

   def get_web_page( self, command_data ):

       results = web_client.get_path( command_data["path"] )
       return results

   def post_web_page( self, command_data ):
       results = web_client.post_path( path = command_data["path"], payload = command_data["data"] )

       return results

   def ping( self, command_data ):
      pass

   def process_commands( self, command_data ):

       try:
           object_data = {}
           command = command_data["command"]
           print( "command",command )
           if self.cmds.has_key( command ):
               result = self.cmds[command]( command_data)
               return  json.dumps( result )
           else:

              object_data = {}
              object_data["reply"] = "BAD_COMMAND_1"
              return json.dumps(object_data)

       except:

           object_data = {}
           object_data["reply"] = "BAD_COMMAND_2"
           object_data["results"] = None
           raise
           return json.dumps(object_data)

def on_request(ch, method, props, body):
    global rt

    try:

       input_data   = json.loads( base64.b64decode(body))

       output_data  = rt.process_commands( input_data )

    except:

       output_data = {}
       output_data["reply"] = "BAD_COMMAND_3"
       output_data["results"] = None
       output_data = json.dumps(output_data)

    response     = base64.b64encode(  output_data )

    ch.basic_publish(exchange='',
                     routing_key=props.reply_to,
                     properties=pika.BasicProperties(correlation_id = \
                                                     props.correlation_id),
                     body= str(response) )
    ch.basic_ack(delivery_tag = method.delivery_tag)

if __name__ == "__main__":

   gm = farm_template_py3.Graph_Management("PI_1","main_remote","LaCima_DataStore")
   #
   # Now Find Data Stores
   #
   #
   #
   data_store_nodes = gm.find_data_stores()
   # find ip and port for redis data store
   data_server_ip   = data_store_nodes[0]["ip"]
   data_server_port = data_store_nodes[0]["port"]
   # find ip and port for ip server
   print( "data_server_ip",data_server_ip,data_server_port)
   redis_handle = redis.StrictRedis( host = data_server_ip, port=data_server_port, db = 2 )

   user_name = redis_handle.hget("web_gateway", "user_name" ).decode("utf-8")

   password  = redis_handle.hget("web_gateway", "password"  ).decode("utf-8")

   vhost     = redis_handle.hget("web_gateway", "vhost"     ).decode("utf-8")

   queue     = redis_handle.hget("web_gateway", "queue"     ).decode("utf-8")

   port      = int(redis_handle.hget("web_gateway", "port"  ))
   server    = redis_handle.hget("web_gateway", "server"    ).decode("utf-8")

   web_client = Web_Client_Interface( )
   logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.CRITICAL)

   rt = Remote_Interface_server()
   credentials = pika.PlainCredentials( user_name, password )
   parameters = pika.ConnectionParameters(server,
                                           port,  #ssl port
                                           vhost,
                                           credentials,
                                           ssl = True ,
                                          heartbeat_interval=2000 )
   connection = pika.BlockingConnection(parameters)
   channel = connection.channel()
   #connection.socket.settimeout(10000)
   #channel.queue_delete(queue=queue)
   #time.sleep(20)
   channel.queue_declare(queue=queue)
   channel.basic_qos(prefetch_count=1)
   channel.basic_consume(on_request, queue=queue)
   print (" [x] Awaiting RPC requests")

   channel.start_consuming()
   #   print "start consuming is ended"


text:
package com.exxeta.iss.sonar.esql.tree.symbols.type;

import com.exxeta.iss.sonar.esql.api.tree.statement.CreateProcedureStatementTree;

public class ProcedureType extends RoutineType {

  private CreateProcedureStatementTree createProcedureStatementTree;

  protected ProcedureType() {
    super(Callability.CALLABLE);
  }

  @Override
  public Kind kind() {
    return Kind.PROCEDURE;
  }

  public static ProcedureType create(CreateProcedureStatementTree createProcedureStatementTree) {
    ProcedureType type = new ProcedureType();
    type.createProcedureStatementTree = createProcedureStatementTree;
    return type;
  }

  public CreateProcedureStatementTree createProcedureStatementTree() {
    return createProcedureStatementTree;
  }
}


text: Serial Peripheral Interface for Atmel's XMega line of microcontrollers


text:
const qs = require('qs')

const { assertBreadcrumbs } = require('../../support/assertions')
const { contactFaker } = require('../../fakers/contacts')
const urls = require('../../../../../src/lib/urls')
const fixtures = require('../../fixtures')

describe('Company Contacts Collections', () => {
  const ukContact = contactFaker({
    id: '1',
    first_name: 'Hanna',
    last_name: 'Reinger',
    name: 'Hanna Reinger',
    job_title: 'Dynamic Accountability Administrator',
    email: 'gloria33@gmail.com',
    archived: false,
    company: {
      name: 'Murray, Price and Hodkiewicz',
    },
    company_uk_region: {
      name: 'London',
    },
    company_sector: {
      name: 'Advanced Engineering',
    },
    primary: true,
    telephone_number: '02071234567',
    full_telephone_number: '+44 02071234567',
    modified_on: '2020-08-10T19:09:35.276Z',
  })

  const foreignContact = contactFaker({
    id: '2',
    first_name: 'Ted',
    last_name: 'Woods',
    name: 'Ted Woods',
    job_title: 'Legacy Branding Agent',
    company: {
      name: 'Murray, Price and Hodkiewicz',
    },
    company_uk_region: null,
    company_sector: {
      name: 'Creative and Media',
    },
    address_country: {
      name: 'United States',
    },
    primary: false,
    telephone_countrycode: '',
    telephone_number: '',
    full_telephone_number: '(0045) 48770000',
    modified_on: '2020-01-25T19:09:35.276Z',
  })

  const contacts = [ukContact, foreignContact]

  const buildQueryString = () =>
    qs.stringify({
      archived: ['false'],
      sortby: 'modified_on:desc',
    })

  context('API payload', () => {
    it('should have the correct payload', () => {
      const queryString = buildQueryString()
      cy.intercept('POST', '/api-proxy/v3/search/contact', {
        body: {
          count: 0,
          results: [],
        },
      }).as('apiRequest')
      cy.visit(
        `${urls.companies.contacts(fixtures.company.dnbCorp.id)}?${queryString}`
      )
      cy.wait('@apiRequest').then(({ request }) => {
        expect(request.body).to.deep.equal({
          offset: 0,
          limit: 10,
          archived: false,
          sortby: 'modified_on:desc',
          company: fixtures.company.dnbCorp.id,
        })
      })
    })
  })

  context('Viewing the companies contacts collection list page', () => {
    before(() => {
      cy.intercept('POST', '/api-proxy/v3/search/contact', {
        body: {
          count: contacts.length,
          results: contacts,
        },
      }).as('apiRequest')
      cy.visit(urls.companies.contacts(fixtures.company.dnbCorp.id))
      cy.wait('@apiRequest')
    })

    it('should render breadcrumbs', () => {
      assertBreadcrumbs({
        Home: urls.dashboard(),
        Companies: urls.companies.index(),
        [fixtures.company.dnbCorp.name]: urls.companies.detail(
          fixtures.company.dnbCorp.id
        ),
        Contacts: null,
      })
    })

    it('should render a title', () => {
      cy.get('h2').should('have.text', '2 contacts')
    })

    it('should not render a "Remove all filters" button', () => {
      cy.get('[data-test="clear-filters"]').should('not.exist')
    })

    it('should render an "Add contact" button', () => {
      cy.get('[data-test="add-collection-item-button"]').should(
        'have.text',
        'Add contact'
      )
    })

    it('should have all sort options', () => {
      cy.get('[data-test="sortby"] option').then((options) => {
        const sortOptions = [...options].map((o) => ({
          value: o.value,
          label: o.label,
        }))
        expect(sortOptions).to.deep.eq([
          { value: 'created_on:desc', label: 'Recently created' },
          { value: 'created_on:asc', label: 'Oldest' },
          { value: 'modified_on:desc', label: 'Recently updated' },
          { value: 'modified_on:asc', label: 'Least recently updated' },
          { value: 'last_name:asc', label: 'Last name A-Z' },
          { value: 'address_country.name:asc', label: 'Country A-Z' },
          { value: 'company.name:asc', label: 'Company A-Z' },
        ])
      })
    })

    it('should display a list of contacts', () => {
      cy.get('[data-test="collection-list"]').should('have.length', 1)
      cy.get('[data-test="collection-item"]').should(
        'have.length',
        contacts.length
      )
    })
  })

  context('UK contact', () => {
    before(() => {
      cy.intercept('POST', '/api-proxy/v3/search/contact', {
        body: {
          count: contacts.length,
          results: contacts,
        },
      }).as('apiRequest')
      cy.visit(urls.companies.contacts(fixtures.company.dnbCorp.id))
      cy.wait('@apiRequest')
    })

    beforeEach(() => {
      cy.get('[data-test="collection-item"]').eq(0).as('firstListItem')
    })

    it('should have a link with the contact name', () => {
      cy.get('@firstListItem')
        .find('h3')
        .children()
        .should('have.text', 'Hanna Reinger')
        .should('have.attr', 'href', '/contacts/1/details')
    })

    it('should contain a primary contact badge', () => {
      cy.get('@firstListItem')
        .find('[data-test="badge"]')
        .should('contain', 'Primary')
    })

    it('should not contain an archived badge', () => {
      cy.get('@firstListItem')
        .find('[data-test="badge"]')
        .should('not.contain', 'Archived')
    })

    it('should render the updated date and time', () => {
      cy.get('@firstListItem')
        .find('h4')
        .should('have.text', 'Updated on 10 Aug 2020, 8:09pm')
    })

    it('should not render the company name', () => {
      cy.get('@firstListItem')
        .find('[data-test="metadata-item"]')
        .should('not.contain', 'Company Murray, Price and Hodkiewicz')
    })

    it('should render the job title', () => {
      cy.get('@firstListItem')
        .find('[data-test="metadata-item"]')
        .eq(0)
        .should('contain', 'Job title Dynamic Accountability Administrator')
    })

    it('should render the sector', () => {
      cy.get('@firstListItem')
        .find('[data-test="metadata-item"]')
        .eq(1)
        .should('contain', 'Sector Advanced Engineering')
    })

    it('should render the country', () => {
      cy.get('@firstListItem')
        .find('[data-test="metadata-item"]')
        .eq(2)
        .should('contain', 'Country United Kingdom')
    })

    it('should render the UK region', () => {
      cy.get('@firstListItem')
        .find('[data-test="metadata-item"]')
        .eq(3)
        .should('contain', 'UK region London')
    })

    it('should render the UK telephone number', () => {
      cy.get('@firstListItem')
        .find('[data-test="metadata-item"]')
        .eq(4)
        .should('contain', 'Phone number +44 02071234567')
    })

    it('should render the email', () => {
      cy.get('@firstListItem')
        .find('[data-test="metadata-item"]')
        .eq(5)
        .should('contain', 'Email gloria33@gmail.com')
    })
  })

  context('Foreign contact', () => {
    before(() => {
      cy.intercept('POST', '/api-proxy/v3/search/contact', {
        body: {
          count: contacts.length,
          results: contacts,
        },
      }).as('apiRequest')
      cy.visit(urls.companies.contacts(fixtures.company.dnbCorp.id))
      cy.wait('@apiRequest')
    })

    beforeEach(() => {
      cy.get('[data-test="collection-item"]').eq(1).as('secondListItem')
    })

    it('should have a link with the contact name', () => {
      cy.get('@secondListItem')
        .find('h3')
        .children()
        .should('have.text', 'Ted Woods')
        .should('have.attr', 'href', '/contacts/2/details')
    })

    it('should not contain a primary contact badge', () => {
      cy.get('@secondListItem').find('[data-test="badge"]').should('not.exist')
    })

    it('should render the updated date and time', () => {
      cy.get('@secondListItem')
        .find('h4')
        .should('have.text', 'Updated on 25 Jan 2020, 7:09pm')
    })

    it('should not render the company name', () => {
      cy.get('@secondListItem')
        .find('[data-test="metadata-item"]')
        .should('not.contain', 'Company Murray, Price and Hodkiewicz')
    })

    it('should render the job title', () => {
      cy.get('@secondListItem')
        .find('[data-test="metadata-item"]')
        .eq(0)
        .should('contain', 'Job title Legacy Branding Agent')
    })

    it('should render the sector', () => {
      cy.get('@secondListItem')
        .find('[data-test="metadata-item"]')
        .eq(1)
        .should('contain', 'Sector Creative and Media')
    })

    it('should render the foreign country', () => {
      cy.get('@secondListItem')
        .find('[data-test="metadata-item"]')
        .eq(2)
        .should('contain', 'Country United States')
    })

    it('should not render the UK region', () => {
      cy.get('@secondListItem')
        .find('[data-test="metadata-item"]')
        .should('not.contain', 'UK region')
    })

    it('should render the telephone number', () => {
      cy.get('@secondListItem')
        .find('[data-test="metadata-item"]')
        .eq(3)
        .should('contain', 'Phone number (0045) 48770000')
    })
  })

  context('when viewing contacts for an archived company', () => {
    before(() => {
      cy.visit(urls.companies.contacts(fixtures.company.archivedLtd.id))
    })

    it('should render a meta title', () => {
      cy.title().should(
        'eq',
        'Contacts - Archived Ltd - Companies - DIT Data Hub'
      )
    })

    it('should render the archived summary', () => {
      cy.get('[data-test="archived-details"]').should(
        'contain',
        'Why can I not add a contact?'
      )
    })

    it('should render an archived explanation', () => {
      cy.get('[data-test="archived-details"]').should(
        'contain',
        'Contacts cannot be added to an archived company.'
      )
    })

    it('should render "Click here to unarchive"', () => {
      cy.get('[data-test="archived-details"]')
        .find('a')
        .should('have.text', 'Click here to unarchive')
        .should(
          'have.attr',
          'href',
          `/companies/${fixtures.company.archivedLtd.id}/unarchive`
        )
    })

    it('should not render an "Add contact" button', () => {
      cy.get('[data-test="add-collection-item-button"]').should('not.exist')
    })
  })
})


text:
import logging

ENV = 'development'
APP_DEBUG = True # Avoid using this in debug mode

# CORS configuration
CORS_HEADERS = 'Content-Type'
CORS_ORIGINS = '*'

KEYSPACE = "annotator_supreme3"

#Logging
LOG_LEVEL = logging.INFO


text:
package application

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import redis.RedisClient
import routes.ApiRoute
import scalikejdbc.{ ConnectionPool, ConnectionPoolSettings }
import services.TodoService
import shade.memcached.{ Configuration, Memcached }

import scala.concurrent.Await
import scala.concurrent.duration._

object Main extends App {

  val config = ConfigFactory.load()
  val applicationName = config.getString("application.name")

  implicit val system = ActorSystem(applicationName, config)
  implicit val materializer = ActorMaterializer()

  // ////
  // ExecutionContext
  implicit val nonBlockingEc = system.dispatcher
  val blockingEc = system.dispatchers.lookup("application.blocking-io-dispatcher")

  // ////
  // DB access settings
  val driverClass = config.getString("application.rdb.driver")
  val dbUrl = config.getString("application.rdb.url")
  val dbUser = config.getString("application.rdb.user")
  val dbPass = config.getString("application.rdb.pass")
  val initialPoolSize = config.getInt("application.rdb.initial-pool-size")
  val maxPoolSize = config.getInt("application.rdb.max-pool-size")
  val connectionTimeout = config.getDuration("application.rdb.connection-timeout").toMillis
  Class.forName(driverClass)
  ConnectionPool.singleton(dbUrl, dbUser, dbPass, ConnectionPoolSettings(initialPoolSize, maxPoolSize, connectionTimeout))

  // ////
  // memcached client settings
  val memcachedHost = config.getString("application.memcached.host")
  val memcachedPort = config.getInt("application.memcached.port")
  val memcachedClient = Memcached(Configuration(s"$memcachedHost:$memcachedPort"))(nonBlockingEc)

  // ////
  // redis client settings
  val redisHost = config.getString("application.redis.host")
  val redisPort = config.getInt("application.redis.port")
  val redisClient = RedisClient(redisHost, redisPort)

  // ////
  // service class settings
  val todoService = new TodoService(memcachedClient, redisClient)(nonBlockingEc, blockingEc)

  // ////
  // route settings
  val routes = {
    new ApiRoute(todoService).route
  }

  // ////
  // http server binding
  val host = config.getString("application.host")
  val port = config.getInt("application.port")
  val bindingFuture = Http().bindAndHandle(routes, host, port).foreach(println)

  sys.addShutdownHook({
    Await.result(system.terminate(), 10.seconds)
    ConnectionPool.closeAll()
  })

}