text:
#include <php.h>
#include <Zend/zend_hash.h>
#include <Zend/zend_interfaces.h>
#include <ext/standard/file.h>

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

#include "php_array_api.h"
#include "phongo_compat.h"
#include "php_phongo.h"
#include "Session.h"

#define PHONGO_MANAGER_URI_DEFAULT "mongodb://127.0.0.1/"

/**
 * Manager abstracts a cluster of Server objects (i.e. socket connections).
 *
 * Typically, users will connect to a cluster using a URI, and the Manager will
 * perform tasks such as replica set discovery and create the necessary Server
 * objects. That said, it is also possible to create a Manager with an arbitrary
 * collection of Server objects using the static factory method (this can be
 * useful for testing or administration).
 *
 * Operation methods do not take socket-level options (e.g. socketTimeoutMS).
 * Those options should be specified during construction.
 */
zend_class_entry* php_phongo_manager_ce;

/* Checks if driverOptions contains a stream context resource in the "context"
 * key and incorporates any of its SSL options into the base array that did not
 * already exist (i.e. array union). The "context" key is then unset from the
 * base array.
 *
 * This handles the merging of any legacy SSL context options and also makes
 * driverOptions suitable for serialization by removing the resource zval. */
static bool php_phongo_manager_merge_context_options(zval* zdriverOptions) /* {{{ */
{
	php_stream_context* context;
	zval *              zcontext, *zcontextOptions;

	if (!php_array_existsc(zdriverOptions, "context")) {
		return true;
	}

	zcontext = php_array_fetchc(zdriverOptions, "context");
	context  = php_stream_context_from_zval(zcontext, 1);

	if (!context) {
		phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "\"context\" driver option is not a valid Stream-Context resource");
		return false;
	}

	zcontextOptions = php_array_fetchc_array(&context->options, "ssl");

	if (!zcontextOptions) {
		phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Stream-Context resource does not contain \"ssl\" options array");
		return false;
	}

	/* When running PHP in debug mode, php_error_docref duplicates the current
	 * scope, leading to a COW violation in zend_hash_merge and
	 * zend_symtable_str_del (called by php_array_unsetc). This macro allows
	 * that violation in debug mode and is a NOOP when in non-debug. */
#if PHP_VERSION_ID >= 70200
	HT_ALLOW_COW_VIOLATION(Z_ARRVAL_P(zdriverOptions));
#endif

	php_error_docref(NULL, E_DEPRECATED, "The \"context\" driver option is deprecated.");

	/* Perform array union (see: add_function() in zend_operators.c) */
	zend_hash_merge(Z_ARRVAL_P(zdriverOptions), Z_ARRVAL_P(zcontextOptions), zval_add_ref, 0);

	php_array_unsetc(zdriverOptions, "context");

	return true;
} /* }}} */

/* Prepare authMechanismProperties for BSON encoding by converting a boolean
 * value for the "CANONICALIZE_HOST_NAME" option to a string.
 *
 * Note: URI options are case-insensitive, so we must iterate through the
 * HashTable in order to detect options. */
static void php_phongo_manager_prep_authmechanismproperties(zval* properties) /* {{{ */
{
	HashTable* ht_data;

	if (Z_TYPE_P(properties) != IS_ARRAY && Z_TYPE_P(properties) != IS_OBJECT) {
		return;
	}

	ht_data = HASH_OF(properties);

	{
		zend_string* string_key = NULL;
		zend_ulong   num_key    = 0;
		zval*        property;

		ZEND_HASH_FOREACH_KEY_VAL_IND(ht_data, num_key, string_key, property)
		{
			if (!string_key) {
				continue;
			}

			/* URI options are case-insensitive */
			if (!strcasecmp(ZSTR_VAL(string_key), "CANONICALIZE_HOST_NAME")) {
				ZVAL_DEREF(property);
				if (Z_TYPE_P(property) != IS_STRING && zend_is_true(property)) {
					SEPARATE_ZVAL_NOREF(property);
					ZVAL_NEW_STR(property, zend_string_init(ZEND_STRL("true"), 0));
				}
			}
		}
		ZEND_HASH_FOREACH_END();
	}
} /* }}} */

/* Prepare URI options for BSON encoding.
 *
 * Read preference tag sets must be an array of documents. In order to ensure
 * that empty arrays serialize as empty documents, array elements will be
 * converted to objects. php_phongo_read_preference_tags_are_valid() handles
 * actual validation of the tag set structure.
 *
 * Auth mechanism properties must have string values, so a boolean true value
 * for the "CANONICALIZE_HOST_NAME" property will be converted to "true".
 *
 * Note: URI options are case-insensitive, so we must iterate through the
 * HashTable in order to detect options. */
static void php_phongo_manager_prep_uri_options(zval* options) /* {{{ */
{
	HashTable* ht_data;

	if (Z_TYPE_P(options) != IS_ARRAY) {
		return;
	}

	ht_data = HASH_OF(options);

	{
		zend_string* string_key = NULL;
		zend_ulong   num_key    = 0;
		zval*        option;

		ZEND_HASH_FOREACH_KEY_VAL_IND(ht_data, num_key, string_key, option)
		{
			if (!string_key) {
				continue;
			}

			if (!strcasecmp(ZSTR_VAL(string_key), MONGOC_URI_READPREFERENCETAGS)) {
				ZVAL_DEREF(option);
				SEPARATE_ZVAL_NOREF(option);
				php_phongo_read_preference_prep_tagsets(option);
				continue;
			}

			if (!strcasecmp(ZSTR_VAL(string_key), MONGOC_URI_AUTHMECHANISMPROPERTIES)) {
				ZVAL_DEREF(option);
				SEPARATE_ZVAL_NOREF(option);
				php_phongo_manager_prep_authmechanismproperties(option);
				continue;
			}
		}
		ZEND_HASH_FOREACH_END();
	}
} /* }}} */

/* Selects a server for an execute method. If "for_writes" is true, a primary
 * will be selected. Otherwise, a read preference will be used to select the
 * server. If zreadPreference is NULL, the client's read preference will be
 * used. If zsession is a session object in a sharded transaction, the session
 * will be checked whether it is pinned to a server. If so, that server will be
 * selected. Otherwise, server selection
 *
 * On success, server_id will be set and the function will return true;
 * otherwise, false is returned and an exception is thrown. */
static bool php_phongo_manager_select_server(bool for_writes, bool inherit_read_preference, zval* zreadPreference, zval* zsession, mongoc_client_t* client, uint32_t* server_id) /* {{{ */
{
	mongoc_server_description_t* selected_server;
	const mongoc_read_prefs_t*   read_preference = NULL;
	bson_error_t                 error           = { 0 };

	if (zsession) {
		const mongoc_client_session_t* session = Z_SESSION_OBJ_P(zsession)->client_session;

		/* Attempt to fetch server pinned to session */
		if (mongoc_client_session_get_server_id(session) > 0) {
			*server_id = mongoc_client_session_get_server_id(session);

			return true;
		}
	}

	if (!for_writes) {
		if (zreadPreference) {
			read_preference = phongo_read_preference_from_zval(zreadPreference);
		} else if (inherit_read_preference) {
			read_preference = mongoc_client_get_read_prefs(client);
		}
	}

	selected_server = mongoc_client_select_server(client, for_writes, read_preference, &error);

	if (selected_server) {
		*server_id = mongoc_server_description_id(selected_server);
		mongoc_server_description_destroy(selected_server);

		return true;
	}

	/* Check for connection related exceptions */
	if (!EG(exception)) {
		phongo_throw_exception_from_bson_error_t(&error);
	}

	return false;
} /* }}} */

/* {{{ proto void MongoDB\Driver\Manager::__construct([string $uri = "mongodb://127.0.0.1/"[, array $options = array()[, array $driverOptions = array()]]])
   Constructs a new Manager */
static PHP_METHOD(Manager, __construct)
{
	php_phongo_manager_t* intern;
	zend_error_handling   error_handling;
	char*                 uri_string     = NULL;
	size_t                uri_string_len = 0;
	zval*                 options        = NULL;
	zval*                 driverOptions  = NULL;

	zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling);

	intern = Z_MANAGER_OBJ_P(getThis());

	/* Separate the options and driverOptions zvals, since we may end up
	 * modifying them in php_phongo_manager_prep_uri_options() and
	 * php_phongo_manager_merge_context_options() below, respectively. */
	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!a/!a/!", &uri_string, &uri_string_len, &options, &driverOptions) == FAILURE) {
		zend_restore_error_handling(&error_handling);
		return;
	}
	zend_restore_error_handling(&error_handling);

	if (options) {
		php_phongo_manager_prep_uri_options(options);
	}

	if (driverOptions && !php_phongo_manager_merge_context_options(driverOptions)) {
		/* Exception should already have been thrown */
		return;
	}

	phongo_manager_init(intern, uri_string ? uri_string : PHONGO_MANAGER_URI_DEFAULT, options, driverOptions);

	if (intern->client) {
		php_phongo_set_monitoring_callbacks(intern->client);
	}
} /* }}} */

/* {{{ proto MongoDB\Driver\ClientEncryption MongoDB\Driver\Manager::createClientEncryption(array $options)
   Return a ClientEncryption instance */
static PHP_METHOD(Manager, createClientEncryption)
{
	php_phongo_manager_t*          intern;
	php_phongo_clientencryption_t* clientencryption;
	zval*                          options;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "a", &options) == FAILURE) {
		return;
	}

	intern = Z_MANAGER_OBJ_P(getThis());

	object_init_ex(return_value, php_phongo_clientencryption_ce);
	clientencryption = Z_CLIENTENCRYPTION_OBJ_P(return_value);

	phongo_clientencryption_init(clientencryption, intern->client, options);
} /* }}} */

/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeCommand(string $db, MongoDB\Driver\Command $command[, array $options = null])
   Execute a Command */
static PHP_METHOD(Manager, executeCommand)
{
	php_phongo_manager_t* intern;
	char*                 db;
	size_t                db_len;
	zval*                 command;
	zval*                 options         = NULL;
	bool                  free_options    = false;
	zval*                 zreadPreference = NULL;
	zval*                 zsession        = NULL;
	uint32_t              server_id       = 0;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sO|z!", &db, &db_len, &command, php_phongo_command_ce, &options) == FAILURE) {
		return;
	}

	intern = Z_MANAGER_OBJ_P(getThis());

	options = php_phongo_prep_legacy_option(options, "readPreference", &free_options);

	if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
		/* Exception should already have been thrown */
		goto cleanup;
	}

	if (!phongo_parse_read_preference(options, &zreadPreference)) {
		/* Exception should already have been thrown */
		goto cleanup;
	}

	if (!php_phongo_manager_select_server(false, false, zreadPreference, zsession, intern->client, &server_id)) {
		/* Exception should already have been thrown */
		goto cleanup;
	}

	/* If the Manager was created in a different process, reset the client so
	 * that cursors created by this process can be differentiated and its
	 * session pool is cleared. */
	PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern);

	phongo_execute_command(intern->client, PHONGO_COMMAND_RAW, db, command, options, server_id, return_value);

cleanup:
	if (free_options) {
		php_phongo_prep_legacy_option_free(options);
	}
} /* }}} */

/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeReadCommand(string $db, MongoDB\Driver\Command $command[, array $options = null])
   Execute a ReadCommand */
static PHP_METHOD(Manager, executeReadCommand)
{
	php_phongo_manager_t* intern;
	char*                 db;
	size_t                db_len;
	zval*                 command;
	zval*                 options         = NULL;
	zval*                 zreadPreference = NULL;
	uint32_t              server_id       = 0;
	zval*                 zsession        = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sO|a!", &db, &db_len, &command, php_phongo_command_ce, &options) == FAILURE) {
		return;
	}

	intern = Z_MANAGER_OBJ_P(getThis());

	if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
		/* Exception should already have been thrown */
		return;
	}

	if (!phongo_parse_read_preference(options, &zreadPreference)) {
		/* Exception should already have been thrown */
		return;
	}

	if (!php_phongo_manager_select_server(false, true, zreadPreference, zsession, intern->client, &server_id)) {
		/* Exception should already have been thrown */
		return;
	}

	/* If the Manager was created in a different process, reset the client so
	 * that cursors created by this process can be differentiated and its
	 * session pool is cleared. */
	PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern);

	phongo_execute_command(intern->client, PHONGO_COMMAND_READ, db, command, options, server_id, return_value);
} /* }}} */

/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeWriteCommand(string $db, MongoDB\Driver\Command $command[, array $options = null])
   Execute a WriteCommand */
static PHP_METHOD(Manager, executeWriteCommand)
{
	php_phongo_manager_t* intern;
	char*                 db;
	size_t                db_len;
	zval*                 command;
	zval*                 options   = NULL;
	uint32_t              server_id = 0;
	zval*                 zsession  = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sO|a!", &db, &db_len, &command, php_phongo_command_ce, &options) == FAILURE) {
		return;
	}

	intern = Z_MANAGER_OBJ_P(getThis());

	if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
		/* Exception should already have been thrown */
		return;
	}

	if (!php_phongo_manager_select_server(true, false, NULL, zsession, intern->client, &server_id)) {
		/* Exception should already have been thrown */
		return;
	}

	/* If the Manager was created in a different process, reset the client so
	 * that cursors created by this process can be differentiated and its
	 * session pool is cleared. */
	PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern);

	phongo_execute_command(intern->client, PHONGO_COMMAND_WRITE, db, command, options, server_id, return_value);
} /* }}} */

/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeReadWriteCommand(string $db, MongoDB\Driver\Command $command[, array $options = null])
   Execute a ReadWriteCommand */
static PHP_METHOD(Manager, executeReadWriteCommand)
{
	php_phongo_manager_t* intern;
	char*                 db;
	size_t                db_len;
	zval*                 command;
	zval*                 options   = NULL;
	uint32_t              server_id = 0;
	zval*                 zsession  = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sO|a!", &db, &db_len, &command, php_phongo_command_ce, &options) == FAILURE) {
		return;
	}

	intern = Z_MANAGER_OBJ_P(getThis());

	if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
		/* Exception should already have been thrown */
		return;
	}

	if (!php_phongo_manager_select_server(true, false, NULL, zsession, intern->client, &server_id)) {
		/* Exception should already have been thrown */
		return;
	}

	/* If the Manager was created in a different process, reset the client so
	 * that cursors created by this process can be differentiated and its
	 * session pool is cleared. */
	PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern);

	phongo_execute_command(intern->client, PHONGO_COMMAND_READ_WRITE, db, command, options, server_id, return_value);
} /* }}} */

/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeQuery(string $namespace, MongoDB\Driver\Query $query[, array $options = null])
   Execute a Query */
static PHP_METHOD(Manager, executeQuery)
{
	php_phongo_manager_t* intern;
	char* namespace;
	size_t   namespace_len;
	zval*    query;
	zval*    options         = NULL;
	bool     free_options    = false;
	zval*    zreadPreference = NULL;
	uint32_t server_id       = 0;
	zval*    zsession        = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sO|z!", &namespace, &namespace_len, &query, php_phongo_query_ce, &options) == FAILURE) {
		return;
	}

	intern = Z_MANAGER_OBJ_P(getThis());

	options = php_phongo_prep_legacy_option(options, "readPreference", &free_options);

	if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
		/* Exception should already have been thrown */
		goto cleanup;
	}

	if (!phongo_parse_read_preference(options, &zreadPreference)) {
		/* Exception should already have been thrown */
		goto cleanup;
	}

	if (!php_phongo_manager_select_server(false, true, zreadPreference, zsession, intern->client, &server_id)) {
		/* Exception should already have been thrown */
		goto cleanup;
	}

	/* If the Manager was created in a different process, reset the client so
	 * that cursors created by this process can be differentiated and its
	 * session pool is cleared. */
	PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern);

	phongo_execute_query(intern->client, namespace, query, options, server_id, return_value);

cleanup:
	if (free_options) {
		php_phongo_prep_legacy_option_free(options);
	}
} /* }}} */

/* {{{ proto MongoDB\Driver\WriteResult MongoDB\Driver\Manager::executeBulkWrite(string $namespace, MongoDB\Driver\BulkWrite $zbulk[, array $options = null])
   Executes a BulkWrite (i.e. any number of insert, update, and delete ops) */
static PHP_METHOD(Manager, executeBulkWrite)
{
	php_phongo_manager_t* intern;
	char* namespace;
	size_t                  namespace_len;
	zval*                   zbulk;
	php_phongo_bulkwrite_t* bulk;
	zval*                   options      = NULL;
	bool                    free_options = false;
	uint32_t                server_id    = 0;
	zval*                   zsession     = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sO|z!", &namespace, &namespace_len, &zbulk, php_phongo_bulkwrite_ce, &options) == FAILURE) {
		return;
	}

	intern = Z_MANAGER_OBJ_P(getThis());
	bulk   = Z_BULKWRITE_OBJ_P(zbulk);

	options = php_phongo_prep_legacy_option(options, "writeConcern", &free_options);

	if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
		/* Exception should already have been thrown */
		return;
	}

	if (!php_phongo_manager_select_server(true, false, NULL, zsession, intern->client, &server_id)) {
		/* Exception should already have been thrown */
		goto cleanup;
	}

	/* If the Server was created in a different process, reset the client so
	 * that its session pool is cleared. */
	PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern);

	phongo_execute_bulk_write(intern->client, namespace, bulk, options, server_id, return_value);

cleanup:
	if (free_options) {
		php_phongo_prep_legacy_option_free(options);
	}
} /* }}} */

/* {{{ proto MongoDB\Driver\ReadConcern MongoDB\Driver\Manager::getReadConcern()
   Returns the ReadConcern associated with this Manager */
static PHP_METHOD(Manager, getReadConcern)
{
	php_phongo_manager_t* intern;

	intern = Z_MANAGER_OBJ_P(getThis());

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	phongo_readconcern_init(return_value, mongoc_client_get_read_concern(intern->client));
} /* }}} */

/* {{{ proto MongoDB\Driver\ReadPreference MongoDB\Driver\Manager::getReadPreference()
   Returns the ReadPreference associated with this Manager */
static PHP_METHOD(Manager, getReadPreference)
{
	php_phongo_manager_t* intern;

	intern = Z_MANAGER_OBJ_P(getThis());

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	phongo_readpreference_init(return_value, mongoc_client_get_read_prefs(intern->client));
} /* }}} */

/* {{{ proto MongoDB\Driver\Server[] MongoDB\Driver\Manager::getServers()
   Returns the Servers associated with this Manager */
static PHP_METHOD(Manager, getServers)
{
	php_phongo_manager_t*         intern;
	mongoc_server_description_t** sds;
	size_t                        i, n = 0;

	intern = Z_MANAGER_OBJ_P(getThis());

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	sds = mongoc_client_get_server_descriptions(intern->client, &n);
	array_init_size(return_value, n);

	for (i = 0; i < n; i++) {
		zval obj;

		phongo_server_init(&obj, intern->client, mongoc_server_description_id(sds[i]));
		add_next_index_zval(return_value, &obj);
	}

	mongoc_server_descriptions_destroy_all(sds, n);
} /* }}} */

/* {{{ proto MongoDB\Driver\WriteConcern MongoDB\Driver\Manager::getWriteConcern()
   Returns the WriteConcern associated with this Manager */
static PHP_METHOD(Manager, getWriteConcern)
{
	php_phongo_manager_t* intern;

	intern = Z_MANAGER_OBJ_P(getThis());

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	phongo_writeconcern_init(return_value, mongoc_client_get_write_concern(intern->client));
} /* }}} */

/* {{{ proto MongoDB\Driver\Server MongoDB\Driver\Manager::selectServers(MongoDB\Driver\ReadPreference $readPreference)
   Returns a suitable Server for the given ReadPreference */
static PHP_METHOD(Manager, selectServer)
{
	php_phongo_manager_t* intern;
	zval*                 zreadPreference = NULL;
	uint32_t              server_id       = 0;

	intern = Z_MANAGER_OBJ_P(getThis());

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &zreadPreference, php_phongo_readpreference_ce) == FAILURE) {
		return;
	}

	if (!php_phongo_manager_select_server(false, true, zreadPreference, NULL, intern->client, &server_id)) {
		/* Exception should already have been thrown */
		return;
	}

	phongo_server_init(return_value, intern->client, server_id);
} /* }}} */

/* {{{ proto MongoDB\Driver\Session MongoDB\Driver\Manager::startSession([array $options = null])
   Returns a new client session */
static PHP_METHOD(Manager, startSession)
{
	php_phongo_manager_t*     intern;
	zval*                     options = NULL;
	mongoc_session_opt_t*     cs_opts = NULL;
	mongoc_client_session_t*  cs;
	bson_error_t              error    = { 0 };
	mongoc_transaction_opt_t* txn_opts = NULL;

	intern = Z_MANAGER_OBJ_P(getThis());

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|a!", &options) == FAILURE) {
		return;
	}

	if (options && php_array_existsc(options, "causalConsistency")) {
		cs_opts = mongoc_session_opts_new();
		mongoc_session_opts_set_causal_consistency(cs_opts, php_array_fetchc_bool(options, "causalConsistency"));
	}

	if (options && php_array_existsc(options, "defaultTransactionOptions")) {
		zval* txn_options = php_array_fetchc(options, "defaultTransactionOptions");

		/* Thrown exception and return if the defaultTransactionOptions is not an array */
		if (Z_TYPE_P(txn_options) != IS_ARRAY) {
			phongo_throw_exception(
				PHONGO_ERROR_INVALID_ARGUMENT,
				"Expected \"defaultTransactionOptions\" option to be an array, %s given",
				PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(txn_options));
			goto cleanup;
		}

		/* Parse transaction options */
		txn_opts = php_mongodb_session_parse_transaction_options(txn_options);

		/* If an exception is thrown while parsing, the txn_opts struct is also
		 * NULL, so no need to free it here */
		if (EG(exception)) {
			goto cleanup;
		}

		/* If the options are non-empty, add them to the client session opts struct */
		if (txn_opts) {
			if (!cs_opts) {
				cs_opts = mongoc_session_opts_new();
			}

			mongoc_session_opts_set_default_transaction_opts(cs_opts, txn_opts);
			mongoc_transaction_opts_destroy(txn_opts);
		}
	}

	/* If the Manager was created in a different process, reset the client so
	 * that its session pool is cleared. This will ensure that we do not re-use
	 * a server session (i.e. LSID) created by a parent process. */
	PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern);

	cs = mongoc_client_start_session(intern->client, cs_opts, &error);

	if (cs) {
		phongo_session_init(return_value, cs);
	} else {
		phongo_throw_exception_from_bson_error_t(&error);
	}

cleanup:
	if (cs_opts) {
		mongoc_session_opts_destroy(cs_opts);
	}
} /* }}} */

/* {{{ MongoDB\Driver\Manager function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Manager___construct, 0, 0, 0)
	ZEND_ARG_INFO(0, uri)
	ZEND_ARG_ARRAY_INFO(0, options, 0)
	ZEND_ARG_ARRAY_INFO(0, driverOptions, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(ai_Manager_createClientEncryption, 0, 0, 1)
	ZEND_ARG_ARRAY_INFO(0, options, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(ai_Manager_executeCommand, 0, 0, 2)
	ZEND_ARG_INFO(0, db)
	ZEND_ARG_OBJ_INFO(0, command, MongoDB\\Driver\\Command, 0)
	ZEND_ARG_INFO(0, options)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(ai_Manager_executeRWCommand, 0, 0, 2)
	ZEND_ARG_INFO(0, db)
	ZEND_ARG_OBJ_INFO(0, command, MongoDB\\Driver\\Command, 0)
	ZEND_ARG_ARRAY_INFO(0, options, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(ai_Manager_executeQuery, 0, 0, 2)
	ZEND_ARG_INFO(0, namespace)
	ZEND_ARG_OBJ_INFO(0, zquery, MongoDB\\Driver\\Query, 0)
	ZEND_ARG_INFO(0, options)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(ai_Manager_executeBulkWrite, 0, 0, 2)
	ZEND_ARG_INFO(0, namespace)
	ZEND_ARG_OBJ_INFO(0, zbulk, MongoDB\\Driver\\BulkWrite, 0)
	ZEND_ARG_INFO(0, options)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(ai_Manager_selectServer, 0, 0, 1)
	ZEND_ARG_OBJ_INFO(0, readPreference, MongoDB\\Driver\\ReadPreference, 1)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(ai_Manager_startSession, 0, 0, 0)
	ZEND_ARG_ARRAY_INFO(0, options, 1)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(ai_Manager_void, 0, 0, 0)
ZEND_END_ARG_INFO()

static zend_function_entry php_phongo_manager_me[] = {
	/* clang-format off */
	PHP_ME(Manager, __construct, ai_Manager___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Manager, createClientEncryption, ai_Manager_createClientEncryption, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Manager, executeCommand, ai_Manager_executeCommand, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Manager, executeReadCommand, ai_Manager_executeRWCommand, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Manager, executeWriteCommand, ai_Manager_executeRWCommand, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Manager, executeReadWriteCommand, ai_Manager_executeCommand, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Manager, executeQuery, ai_Manager_executeQuery, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Manager, executeBulkWrite, ai_Manager_executeBulkWrite, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Manager, getReadConcern, ai_Manager_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Manager, getReadPreference, ai_Manager_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Manager, getServers, ai_Manager_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Manager, getWriteConcern, ai_Manager_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Manager, selectServer, ai_Manager_selectServer, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_ME(Manager, startSession, ai_Manager_startSession, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_Manager_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
	PHP_FE_END
	/* clang-format on */
};
/* }}} */

/* {{{ MongoDB\Driver\Manager object handlers */
static zend_object_handlers php_phongo_handler_manager;

static void php_phongo_manager_free_object(zend_object* object) /* {{{ */
{
	php_phongo_manager_t* intern = Z_OBJ_MANAGER(object);

	zend_object_std_dtor(&intern->std);

	if (intern->client) {
		MONGOC_DEBUG("Not destroying persistent client for Manager");
		intern->client = NULL;
	}

	if (intern->client_hash) {
		efree(intern->client_hash);
	}
} /* }}} */

static zend_object* php_phongo_manager_create_object(zend_class_entry* class_type) /* {{{ */
{
	php_phongo_manager_t* intern = NULL;

	intern = PHONGO_ALLOC_OBJECT_T(php_phongo_manager_t, class_type);

	zend_object_std_init(&intern->std, class_type);
	object_properties_init(&intern->std, class_type);

	PHONGO_SET_CREATED_BY_PID(intern);

	intern->std.handlers = &php_phongo_handler_manager;

	return &intern->std;
} /* }}} */

static HashTable* php_phongo_manager_get_debug_info(zval* object, int* is_temp) /* {{{ */
{
	php_phongo_manager_t*         intern;
	mongoc_server_description_t** sds;
	size_t                        i, n = 0;
	zval                          retval = ZVAL_STATIC_INIT;
	zval                          cluster;

	*is_temp = 1;
	intern   = Z_MANAGER_OBJ_P(object);

	array_init_size(&retval, 2);

	ADD_ASSOC_STRING(&retval, "uri", mongoc_uri_get_string(mongoc_client_get_uri(intern->client)));

	sds = mongoc_client_get_server_descriptions(intern->client, &n);

	array_init_size(&cluster, n);

	for (i = 0; i < n; i++) {
		zval obj;

		if (!php_phongo_server_to_zval(&obj, sds[i])) {
			/* Exception already thrown */
			zval_ptr_dtor(&obj);
			zval_ptr_dtor(&cluster);
			goto done;
		}

		add_next_index_zval(&cluster, &obj);
	}

	ADD_ASSOC_ZVAL_EX(&retval, "cluster", &cluster);

done:
	mongoc_server_descriptions_destroy_all(sds, n);

	return Z_ARRVAL(retval);
} /* }}} */
/* }}} */

void php_phongo_manager_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
	zend_class_entry ce;

	INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "Manager", php_phongo_manager_me);
	php_phongo_manager_ce                = zend_register_internal_class(&ce);
	php_phongo_manager_ce->create_object = php_phongo_manager_create_object;
	PHONGO_CE_FINAL(php_phongo_manager_ce);
	PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_manager_ce);

	memcpy(&php_phongo_handler_manager, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
	php_phongo_handler_manager.get_debug_info = php_phongo_manager_get_debug_info;
	php_phongo_handler_manager.free_obj       = php_phongo_manager_free_object;
	php_phongo_handler_manager.offset         = XtOffsetOf(php_phongo_manager_t, std);
} /* }}} */

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phoma phellodendri Bres.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Fractal Server</title>
    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="viewport" content="width=device-width, user-scalable=no,
    initial-scale=1.0, maximum-scale=1.0">

    <link href="/static/css/bootstrap.css" rel="stylesheet">

    <link href="/static/css/bootstrap-responsive.css" rel="stylesheet">

    <link rel="shortcut icon" href="/static/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/static/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/static/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="/static/ico/apple-touch-icon-57-precomposed.png">

          Fractal Server

              {{range $k := .}}

{{$k}}

              {{end}}

Draw some fractals

 Choose a fractal type from the
                    nav bar at the top of the window
                Choose a fractal type by clicking
                    a button below

Navigate around like you would Google Maps (tweak the
                numbers in the lower right corner if you want)

Enjoy

            {{range $k := .}}

{{$k}}

            {{end}}

Favorite fractals people have saved

            <button id="hide" class="btn btn-mini btn-primary">Hide</button>
            <button id="share" class="btn btn-mini btn-inverse">Share</button>

            <button class="close" data-dismiss="modal">×</button>

Use the following link to share

URL

Save this fractal to the homepage

            <form action="/bookmarks/add">
                Name:
                <input name="name" id="name" type="text">
                <input name="url" id="url" type="hidden">

                <button id="save" class="btn btn-inverse" type="submit">Save</button>

            </form>

            Close


text:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:id="@+id/me_mailbox_fragment">
    <TextView
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_gravity="center"

        android:id="@+id/me_mailbox_fragment_mailbox"
        android:text="@string/string_Mailbox" />

    <TextView
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_below="@+id/me_mailbox_fragment_mailbox"
        android:layout_gravity="center"

        android:id="@+id/me_mailbox_fragment_combo"
        android:text="@string/string_Combo"/>

    <TextView
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_below="@+id/me_mailbox_fragment_combo"
        android:layout_gravity="center"
        android:text="@string/me_mailbox_instructions"
        android:id="@+id/me_mailbox_fragment_helper"/>
</RelativeLayout>


text:
<wid_header></wid_header>

<mod_menu></mod_menu>

<mod_contact></mod_contact>

<wid_footer></wid_footer>


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>CSL Behring | Transplant Rejection</title>
	<link rel="stylesheet" type="text/css" href="../scp-typeface/latofonts.css">
	<link rel="stylesheet" href="../scp-css/bootstrap.css">
	<link rel="stylesheet" href="../scp-css/csl-scp-style.css">

						Transplant Franchise Homepage

Solid Organ Transplantation SCP

				  	<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#csl-nav" aria-expanded="false">

Navigation

			      	</button>

							SCP Overview

							Strategy

							Communications Platform

Communications Platform

					<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#csl-side-nav" aria-expanded="false">

			      	</button>

							Solid Organ Transplantation and CSL Behring

CSL Behring Transplant Franchise

Solid Organ Transplantation Overview

US Federal Regulations and Solid Organ Transplantation

							Organ Availability and Patient-Donor Matching

Organ Donation

Matching Organs

Desensitization

							Organ Viability/ Ischemia-Reperfusion
 Injury and Its Consequences

Organ Damage Due to Ischemic Injury

Rationale for C1-INH in IRI Leading to DGF

Unmet Need in DGF

Primary Graft Dysfunction

Organ Preservation

Potential Role of Alpha-1 Proteinase Inhibitor in Reducing IRI and Preventing Its Consequences

							Transplant Rejection

Transplant Rejection Overview

Antibody-Mediated Rejection

The Potential Role of
C1-INH in Chronic AMR

Transplant Rejection

TR-1

Advances in solid organ transplantation techniques and therapies have markedly improved the rate of successful transplant procedures; however, organ rejection remains one of the greatest limitations in transplantation as a leading cause of allograft loss.1,2,3

TR-1a

Long-term survival rates are shorter in kidney transplant recipients who experience episodes of acute rejection compared with those who do not, with mean allograft survival of 6.6 years and 12.5 years, respectively.2

TR-2

Transplant rejection occurs when an adaptive immune response to the allograft is initiated by immune recognition of cell surface molecules that induce an antigenic stimulus. This response can be mediated by T cells or antibodies primarily targeting non-self (ie, donor) major histocompatibility complex (MHC) molecules.4,5

TR-3

T cell–mediated rejection, or cellular rejection, occurs when naïve T cells are activated by antigen-presenting cells that bear allogeneic MHC molecules and have co-stimulatory activity. The antigen-presenting cells can be of donor origin carried by the allograft (direct allorecognition) or can be recipient antigen-presenting cells that have taken up allogeneic proteins from the allograft (indirect allorecognition).5,6

TR-3a

The relative contributions of both direct and indirect allorecognition to allograft rejection are unknown. Direct allorecognition is thought to be responsible for acute rejection, and indirect allorecognition is thought to activate macrophages that cause tissue injury and fibrosis, which are important in the development of alloantibodies.5

TR-4

Antibody-mediated responses are a leading cause of allograft rejection. Antibody-mediated rejection, or humoral rejection, occurs when a transplant recipient has either pre-existing antibodies or de novo antibodies to the donor's blood group antigens or MHC antigens. Pre-existing donor-specific antibodies (DSAs) can cause a complement-dependent reaction within minutes of transplantation, resulting in rapid rejection of the allograft.5,6,7

TR-5

The adaptive immune system is considered the main immune response and cause of allograft rejection; however, the innate immune system can play a role through initiating and amplifying the adaptive immune system.4

TR-6

Irrespective of any genetic difference between the donor and recipient, activation of the innate immune system is triggered by tissue injury sustained during donor death, ischemia, and reperfusion.4

TR-6a

The innate immune system facilitates activation of the adaptive immune system by recognizing markers of tissue injury, known as damage-associated molecular patterns (DAMPs).4

TR-6b

When the presence of DAMPs is detected by innate immune cells, a potent inflammatory response occurs, which identifies the allograft as a site of injury and inflammation.4

TR-6c

The inflammatory response caused by activation of the innate immune system modifies the integrity of the endothelial cell lining of the allograft – triggering the release of antigens, inducing production of acute-phase proteins including complement factors, and stimulating the migration of antigen-presenting cells (APCs) that can augment activation of T cells and bind alloantibodies secreted by activated B cells.4

TR-7

There are four categories with distinct mechanistic and clinical features used to classify transplant rejection: hyperacute rejection, accelerated rejection, acute rejection, and chronic rejection. Each type of rejection has unique features, including symptoms, time-course, and survival, that vary depending on the organ type.3

Mechanistic and Clinical Features of Rejection in Kidney Transplantation3,8,9,10,11

DSAs, donor-specific antibodies.

TR-8

Hyperacute rejection and acute cellular rejection can be devastating, although they are currently less worrisome because of modern screening techniques, desensitization protocols that can help prevent hyperacute rejection, and immunosuppressant regimens that successfully prevent and treat acute T cell–mediated rejection.7,8,11,12

TR-8a

Current prevention strategies using a combination of calcineurin inhibitors, mycophenolate, and induction therapy have decreased the incidence of acute rejection to <20% and improved 1-year allograft survival rates to 95% in kidney transplant recipients.7

TR-8b

Early T cell–mediated acute rejection can be treated successfully with immunosuppressant therapies because the mechanisms of action of these therapies target T-cell response.7

Pharmacologic Agents Used for the Prevention or Treatment of T Cell–Mediated Rejection7

AMR, antibody-mediated rejection; GM-CSF, granulocyte-macrophage colony-stimulating factor; IL, interleukin; MAC, membrane attack complex; Treg, regulatory T cell.

TR-9

Despite the success of current standard immunosuppression regimens in preventing and treating T cell–mediated rejection, a substantial number of kidney transplant recipients still experience episodes of rejection due to the development of donor-specific antibodies (DSAs).7

TR-10

Acute and chronic antibody-mediated rejection have emerged as the most important factors jeopardizing long-term transplant success and are an imminent threat due to poor treatment options.7

TR-11

The standard-of-care treatment for acute antibody-mediated rejection, specifically in kidney transplant, includes one or more of the following agents with or without corticosteroids: plasma exchange, intravenous immunoglobulin (IVIG), rituximab, or lymphocyte-depleting antibody. However, optimal strategies to treat acute antibody-mediated rejection have not yet been determined, and additional randomized, controlled trials are needed to study new potentially effective therapies.6

Pharmacologic Agents Used for the Prevention or Treatment of Acute AMR7,13

AMR, antibody-mediated rejection; Bax, Bcl-2 associated X protein; Bcl-2, B cell lymphoma; Bcl-xL, B cell lymphoma-extra large; cFLIP, cellular FLICE-like inhibitory protein; DSA, donor-specific antibody; IkB, inhibitor of kappa B; MAC, membrane attack complex; RITUX ERAH, Effects of Rituximab on Acute Humoral Rejection in Renal Transplantation; TRAIL, tumor necrosis factor (TNF)–related apoptosis-inducing ligand;
XIAP, X-linked inhibitor of apoptosis protein.

TR-12

Chronic antibody-mediated rejection is progressive and is a significant barrier to long-term allograft survival because there are no treatment options available.2,3

TR-13

The development of new immunosuppressive drugs during the 1990s has significantly reduced the incidence of acute T cell–mediated rejection and has improved short-term allograft survival; however, the treatment of antibody-mediated rejection, the major contributor to late allograft failure, has not significantly changed, and there is currently no effective treatment for chronic antibody-mediated rejection.11,12

TR-14

Because cellular rejection is now sufficiently managed through immunosuppressant therapy, current transplant research focuses on new strategies to minimize the impact of acute and chronic antibody-mediated rejection. Recently, there has been increasing interest in therapies that inhibit complement activation, as high DSA levels are known to activate complement factors in antibody-mediated rejection.14,15

References

Lamarche C, Côté JM, Sénécal L, Cardinal H. efficacy of acute cellular rejection treatment according to Banff score in kidney transplant recipients: a systematic review. Transplant Direct. 2016;2(12):e115. doi 10.1097/TXD.0000000000000626.

Bhatti AB, Usman M. Chronic renal transplant rejection and possible anti-proliferative drug targets. Cureus. 2015;7(11): e376. doi 10.7759/cureus.376.

Chinen J, Buckely RH. Transplantation immunology: solid organ and bone marrow. J Allergy Clin Immunol. 2010;125(2 Suppl 2):S324-S335.

Wood KJ, Goto R. Mechanisms of rejection: current perspectives. Transplantation. 2012;93(1):1-10.

Janeway CA Jr, Travers P, Walport M, Shlomchik M. Responses to alloantigens and transplant rejection. In: Austin P, Lawrence E, eds. Immunobiology: The Immune System in Health and Disease. 5th edition. New York: Garland Science; 2001.

Kidney Disease: Improving Global Outcomes (KDIGO) Transplant Work Group. KDIGO clinical practice guideline for the care of kidney transplant recipients. Am J Transplant. 2009;9(Suppl 3):S1-S155.

Bamoulid J, Staeck O, Halleck F, et al. Advances in pharmacotherapy to treat kidney transplant rejection. Expert Opin Pharmacother. 2015;16(11):1627-1648.

Joudeh A, Saliba KA, Topping KA, Sis B. Pathologic basis of antibody-mediated organ transplant rejection: from pathogenesis to diagnosis. Curr Opin Organ Transplant. 2013;18(4):478-485.

Loupy A, Haas M, Solez K, et al. The Banff 2015 kidney meeting report: current challenges in rejection classification and prospects for adopting molecular pathology. Am J Transplant. 2017;17(1):28-41.

Davis S, Cooper JE. Acute antibody-mediated rejection in kidney transplant recipients. Transplant Rev (Orlando). 2017;31(1):47-54.

Hara S. Current pathological perspectives on chronic rejection in renal allografts. Clin Exp Nephrol. 2016 Nov 16 [Epub ahead of print]. doi 10.1007/s10157-016-1361-x.

Haririan A. Current status of the evaluation and management of antibody-mediated rejection in kidney transplantation. Curr Opin Nephrol Hypertens. 2015;24(6):576-581.

Garces JC, Giusti S, Staffeld-Coit C, Bohorquez H, Cohen AJ, Loss GE. Antibody-mediated rejection: a review. The Ochsner Journal. 2017;17(1):46-55.

Stegall MD, Chedid MF, Cornell LD. The role of complement in antibody-mediated rejection in kidney transplantation. Nat Rev Nephrol. 2012;8(11):670-678.

Chen G, Chen S, Chen X. Role of complement and perspectives for intervention in transplantation. Immunobiology. 2013;218(5):817-827.

Disclaimer

						This communication pillar is for internal use only, as a basis for communications related to the CSL Behring Transplant Franchise. Creation of material from these approved messages and references does not constitute approval in another context. All individual communications must undergo the full CSL Behring review process and evaluation for copyright permissions appropriate for intended use.

© 2017 CSL Behring


text:
package clusterrolebinding

import "testing"

func TestClusterRoleBinding(t *testing.T) {}


text:
"use strict";

import '../libApi';

/**
 * @name SlidingWindowCollection
 * @memberof module:core.collections
 * @class Коллекция-обертка, отображающая указанный интервал родительской Backbone-коллекции (скользящее окно).
 * @constructor
 * @extends Backbone.Collection
 * @param {Object} options Объект опций.
 * @param {Number} [options.position=0] Изначальное значении позиции окна.
 * @param {Number} [options.windowSize=0] Изначальное значение размера окна (количество элементов).
 * */

let SlidingWindowCollection = Backbone.Collection.extend(/** @lends module:core.collections.SlidingWindowCollection.prototype */ {
    constructor: function (collection, options) //noinspection JSHint
    {
        options = options || {};
        this.parentCollection = collection;
        this.innerCollection = new Backbone.Collection();

        //noinspection JSUnresolvedVariable,JSHint
        options.close_with && this.__bindLifecycle(options.close_with, 'close');
        //noinspection JSUnresolvedVariable,JSHint
        options.destroy_with && this.__bindLifecycle(options.destroy_with, 'destroy');

        this.state = {
            position: options.position || 0,
            windowSize: options.windowSize || 0
        };

        this.__rebuildModels();

        this.listenTo(collection, 'add', this.__onAdd);
        this.listenTo(collection, 'remove', this.__onRemove);
        this.listenTo(collection, 'reset',  this.__onReset);
        this.listenTo(collection, 'sort',  this.__onSort);

        _.each([
            'add',
            'remove',
            'reset',
            'sort'
        ], function (eventName)
        {
            this.listenTo(this.innerCollection, eventName, function () {
                var args = _.toArray(arguments);
                args.unshift(eventName);
                this.trigger.apply(this, args);
            });
        }, this);

        this.initialize.apply(this, arguments);
    },

    __rebuildModels: function (options) {
        options = options || {};
        var newModels = this.parentCollection.chain().rest(this.state.position).first(this.state.windowSize).value();
        this.innerCollection.reset(newModels, _.extend(options, { silent: true }));
        this.models = this.innerCollection.models;
        this.length = this.innerCollection.length;
        this.trigger('reset', this, _.clone(options));
        if (this.models.length !== newModels.length) {
            throw new Error('SlidingWindowCollection size mismatch: does parent collection have models with duplicated id?');
        }
    },

    __buildModelsInternal: function (list)
    {
        for (var i = 0, len = list.length; i < len; i++) {
            var model = list.at(i);
            this.models.push(model);
            model.collection = this;
            this._byId[model.cid] = model;
            if (model.id) {
                this._byId[model.id] = model;
            }
            //noinspection JSHint
            !model.collapsed && model.children && this.__buildModelsInternal(model.children);
        }
        this.length = this.models.length;
    },

    __bindLifecycle: function (view, methodName) {
        view.on(methodName, _.bind(this.stopListening, this));
    },

    __onSort: function (collection, options) {
        this.__rebuildModels(options);
    },

    __onAdd: function (model, collection, options) {
        this.__rebuildModels(options);
    },

    __onRemove: function (model, collection, options) {
        this.__rebuildModels(options);
    },

    __onReset: function (collection, options) {
        this.__rebuildModels(options);
    },

    sort: function (options)
    {
        this.parentCollection.sort(options);
    },

    /**
     * Обновить размер скользящего окна
     * @param {Number} newWindowSize Новый размер скользящего окна
     * */
    updateWindowSize: function (newWindowSize)
    {
        if (this.state.windowSize !== newWindowSize) {
            this.state.windowSize = newWindowSize;
            this.__rebuildModels();
        }
    },

    /**
     * Обновить позицию скользящего окна
     * @param {Number} newPosition Новая позиция скользящего окна
     * */
    updatePosition: function (newPosition)
    {
        if (this.state.windowSize === undefined) {
            throw 'updatePosition() has been called before setting window size';
        }

        newPosition = this.__normalizePosition(newPosition);
        if (newPosition === this.state.position) {
            return newPosition;
        }

        var actualWindowSize = this.innerCollection.length;
        var delta = newPosition - this.state.position;
        var oldValues;
        var newValues;
        if (Math.abs(delta) < actualWindowSize) {
            // update collection via add/remove
            if (delta > 0) {
                oldValues = this.innerCollection.first(delta);
                this.length -= oldValues.length;
                this.innerCollection.remove(oldValues);
                newValues = this.parentCollection.chain().rest(this.state.position + actualWindowSize).first(delta).value();
                this.length += newValues.length;
                this.innerCollection.add(newValues);
            } else {
                if (this.length >= this.state.windowSize) {
                    oldValues = this.innerCollection.last(-delta);
                    this.length -= oldValues.length;
                    this.innerCollection.remove(oldValues);
                }

                newValues = this.parentCollection.chain().rest(newPosition).first(-delta).value();
                this.length += newValues.length;
                this.innerCollection.add(newValues, {
                    at: 0
                });
            }
            this.state.position = newPosition;
        } else {
            this.state.position = newPosition;
            this.__rebuildModels();
        }

        return newPosition;
    },

    __normalizePosition: function (position)
    {
        var maxPos = Math.max(0, this.parentCollection.length - 1);
        return Math.max(0, Math.min(maxPos, position));
    }
});

// methods that alter data should proxy to the parent collection
_.each(['add', 'remove', 'set', 'reset', 'push', 'pop', 'unshift', 'shift', 'slice', 'sync', 'fetch'], function (methodName) {
    SlidingWindowCollection.prototype[methodName] = function () {
        return this.parentCollection[methodName].apply(this.parentCollection, _.toArray(arguments));
    };
});

// methods that retrieves data should proxy to the inner collection
_.each(['each', 'at', 'get', 'filter', 'map'], function (methodName) {
    SlidingWindowCollection.prototype[methodName] = function () {
        return this.innerCollection[methodName].apply(this.innerCollection, _.toArray(arguments));
    };
});

_.extend(SlidingWindowCollection.prototype, Backbone.Events);

export default SlidingWindowCollection;


text:
====================
 Sphinx Integration
====================

Usage
=====

cliff supports integration with Sphinx by way of a `Sphinx directives`__.

Preparation
-----------

Before using the :rst:dir:`autoprogram-cliff` directive you must add
`'cliff.sphinxext'` extension module to a list of `extensions` in `conf.py`:

.. code-block:: python

   extensions = ['cliff.sphinxext']

Directive
---------

.. rst:directive:: .. autoprogram-cliff:: <namespace> or <app class>

   Automatically document an instance of :py:class:`cliff.command.Command`
   or :py:class:`cliff.app.App`
   including a description, usage summary, and overview of all options.

   .. important::

      There are two modes in this directive: **command** mode and **app**
      mode. The directive takes one required argument and the mode is
      determined based on the argument specified.

   The **command** mode documents various information of a specified instance of
   :py:class:`cliff.command.Command`. The **command** mode takes the namespace
   that the command(s) can be found in as the argument. This is generally
   defined in the `entry_points` section of either `setup.cfg` or
   `setup.py`. You can specify which command(s) should be displayed using
   `:command:` option.

   .. code-block:: rst

       .. autoprogram-cliff:: openstack.compute.v2
          :command: server add fixed ip

   The **app** mode documents various information of a specified instance of
   :py:class:`cliff.app.App`. The **app** mode takes the python path of the
   corresponding class as the argument. In the **app** mode, `:application:`
   option is usually specified so that the command name is shown in the
   rendered output.

   .. code-block:: rst

       .. autoprogram-cliff:: cliffdemo.main.DemoApp
          :application: cliffdemo

   Refer to the example_ below for more information.

   In addition, the following directive options can be supplied:

   `:command:`
     The name of the command, as it would appear if called from the command
     line without the executable name. This will be defined in `setup.cfg` or
     `setup.py` albeit with underscores. This is optional and `fnmatch-style`__
     wildcarding is supported. Refer to the example_ below for more
     information.

     This option is effective only in the **command** mode.

   `:arguments`
     The arguments to be passed when the cliff application is instantiated.
     Some cliff applications requires arguments when instantiated.
     This option can be used to specify such arguments.

     This option is effective only in the **app** mode.

   `:application:`
     The top-level application name, which will be prefixed before all
     commands. This option overrides the global option
     `autoprogram_cliff_application` described below.
     In most cases the global configuration is enough, but this option is
     useful if your sphinx document handles multiple cliff applications.

     .. seealso:: The ``autoprogram_cliff_application`` configuration option.

   `:ignored:`
     A comma-separated list of options to exclude from documentation for this
     option. This is useful for options that are of low value.

     .. seealso:: The ``autoprogram_cliff_ignored`` configuration option.

   The following global configuration values are supported. These should be
   placed in `conf.py`:

   `autoprogram_cliff_application`
     The top-level application name, which will be prefixed before all
     commands. This is generally defined in the `console_scripts` attribute of
     the `entry_points` section of either `setup.cfg` or `setup.py`. Refer to
     the example_ below for more information.

     For example:

     .. code-block:: python

        autoprogram_cliff_application = 'my-sample-application'

     Defaults to ``''``

     .. seealso:: The ``:command:`` directive option.
     .. seealso:: The ``:application:`` directive option.

   `autoprogram_cliff_ignored`
     A global list of options to exclude from documentation. This can be used
     to prevent duplication of common options, such as those used for
     pagination, across **all** options.

     For example:

     .. code-block:: python

        autoprogram_cliff_ignored = ['--help', '--page', '--order']

     Defaults to ``['--help']``

     .. seealso:: The ``:ignored:`` directive option.

.. seealso::

    Module `sphinxcontrib.autoprogram`
      An equivalent library for use with plain-old `argparse` applications.

    Module `sphinx-click`
      An equivalent library for use with `click` applications.

.. important::

    The :rst:dir:`autoprogram-cliff` directive emits :rst:dir:`code-block`
    snippets marked up as `shell` code. This requires `pygments` >= 0.6.

.. _example:

Examples
========

Simple Example (`demoapp`)
--------------------------

`cliff` provides a sample application, :doc:`demoapp`, to demonstrate some of the
features of `cliff`. This application :ref:`is documented <demoapp-sphinx>`
using the `cliff.sphinxext` Sphinx extension.

Advanced Example (`python-openstackclient`)
-------------------------------------------

It is also possible to document larger applications, such as
`python-openstackclient`__. Take a sample `setup.cfg` file, which is a minimal
version of the `setup.cfg` provided by the `python-openstackclient` project:

.. code-block:: ini

    [entry_points]
    console_scripts =
        openstack = openstackclient.shell:main

    openstack.compute.v2 =
        host_list = openstackclient.compute.v2.host:ListHost
        host_set = openstackclient.compute.v2.host:SetHost
        host_show = openstackclient.compute.v2.host:ShowHost

This will register three commands - ``host list``, ``host set`` and ``host
show`` - for a top-level executable called ``openstack``. To document the first
of these, add the following:

.. code-block:: rst

    .. autoprogram-cliff:: openstack.compute.v2
       :command: host list

You could also register all of these at once like so:

.. code-block:: rst

    .. autoprogram-cliff:: openstack.compute.v2
       :command: host *

Finally, if these are the only commands available in that namespace, you can
omit the `:command:` parameter entirely:

.. code-block:: rst

    .. autoprogram-cliff:: openstack.compute.v2

In all cases, you should add the following to your `conf.py` to ensure all
usage examples show the full command name:

.. code-block:: python

    autoprogram_cliff_application = 'openstack'

__ http://www.sphinx-doc.org/en/stable/extdev/markupapi.html
__ https://docs.python.org/3/library/fnmatch.html
__ https://docs.openstack.org/python-openstackclient/


text:
package actor

type EventStreamProcess struct {
	system *ActorSystem
}

func NewEventStreamProcess(actorSystem *ActorSystem) *EventStreamProcess {
	return &EventStreamProcess{system: actorSystem}
}

func (e *EventStreamProcess) SendUserMessage(pid *PID, message interface{}) {
	_, msg, _ := UnwrapEnvelope(message)
	e.system.EventStream.Publish(msg)
}

func (e *EventStreamProcess) SendSystemMessage(pid *PID, message interface{}) {
	// pass
}

func (e *EventStreamProcess) Stop(pid *PID) {
	// pass
}


text:
/*global hoe */

hoe.Property = function(default_, nullable){
    this.type = null;
    this.default = default_!==undefined ? default_ : null;
    this.nullable = nullable===false ? false : true;
};

hoe.Property.prototype.set = function(val){
    return val;
};

hoe.Property.prototype.to_plain = function(val){
    return val;
};

hoe.Property.prototype.check_type = function(val){
    //undefined is never accepted
    if (val === undefined){
        throw Error('Invalid value type, undefined');
    }
};

hoe.PropertyString = hoe.inherit(hoe.Property, function(){
    hoe.Property.apply(this, arguments);
    this.type = 'string';
});

hoe.PropertyString.prototype.check_type = function(val){
    if (!(typeof val === 'string' || val instanceof String)){
        throw Error('Invalid value type, not a String');
    }
};

hoe.PropertyNumber = hoe.inherit(hoe.Property, function(){
    hoe.Property.apply(this, arguments);
    this.type = 'number';
});

hoe.PropertyNumber.prototype.check_type = function(val){
    if (!(typeof val === 'number' || val instanceof Number)){
        throw Error('Invalid value type, not a Number');
    }
};

hoe.PropertyBoolean = hoe.inherit(hoe.Property, function(){
    hoe.Property.apply(this, arguments);
    this.type = 'boolean';
});

hoe.PropertyBoolean.prototype.check_type = function(val){
    if (!(typeof val === 'boolean' || val instanceof Boolean)){
        throw Error('Invalid value type, not a Boolean');
    }
};

hoe.PropertyDate = hoe.inherit(hoe.Property, function(){
    hoe.Property.apply(this, arguments);
    this.type = 'Date';
});

// we accept a date object or any constructor parameter for a date
hoe.PropertyDate.prototype.set = function(val){
    if (!(val instanceof Date)){
        return new Date(val);
    }
    return val;
};

hoe.PropertyDate.prototype.to_plain = function(val){
    if (val === null){
        return null;
    }
    return val.valueOf();
};

hoe.PropertyDate.prototype.check_type = function(val){
    if (!(val instanceof Date)){
        throw Error('Invalid value type, not a Date');
    }
};

hoe.Model = hoe.Type(function(data){
    this.init_model(data);
});

hoe.Model.prototype.init_model = function(data){
    var desc = this.Properties;
    var consumed = 0; // count number of data items used
    for (var k in desc){
        // set value
        if (k in data){
            this[k] = desc[k].set(data[k]);
            consumed++;
        }
        else {
            this[k] = desc[k].default;
        }

        // validate type value
        if (this[k] === null){
            if (desc[k].nullable===false){
                throw Error('Value can not be null.');
            }
        }
        else {
            // check correct type
            desc[k].check_type(this[k]);
        }
    }

    // check there were no unused values in data
    if (Object.keys(data).length != consumed){
        throw Error('Some data do not belong to model description.');
    }
};

hoe.Model.prototype.as_plain = function(){
    var data = {};
    var desc = this.Properties;
    for (var k in desc){
        data[k] = desc[k].to_plain(this[k]);
    }
    return data;
};


text:
module artemis.utils {
  "use strict";

  // Thanks to Riven
  // From: http://riven8192.blogspot.com/2009/08/fastmath-sincos-lookup-tables.html
  export class TrigLUT {

    public static sin(rad:number):number {
      return TrigLUT.sin_[(rad * TrigLUT.radToIndex) & TrigLUT.SIN_MASK];
    }

    public static cos(rad:number):number {
      return TrigLUT.cos_[(rad * TrigLUT.radToIndex) & TrigLUT.SIN_MASK];
    }

    public static sinDeg(deg:number):number {
      return TrigLUT.sin_[(deg * TrigLUT.degToIndex) & TrigLUT.SIN_MASK];
    }

    public static cosDeg(deg:number):number {
      return TrigLUT.cos_[(deg * TrigLUT.degToIndex) & TrigLUT.SIN_MASK];
    }

    private static RAD:number;
    private static DEG:number;
    private static SIN_BITS:number;
    private static SIN_MASK:number;
    private static SIN_COUNT:number;
    private static radFull:number;
    private static radToIndex:number;
    private static degFull:number;
    private static degToIndex:number;
    private static sin_:number[];
    private static cos_:number[];

    static init(update:boolean) {
      TrigLUT.RAD = Math.PI / 180.0;
      TrigLUT.DEG = 180.0 / Math.PI;

      TrigLUT.SIN_BITS = 12;
      TrigLUT.SIN_MASK = ~(-1 << TrigLUT.SIN_BITS);
      TrigLUT.SIN_COUNT = TrigLUT.SIN_MASK + 1;

      TrigLUT.radFull = (Math.PI * 2.0);
      TrigLUT.degFull = (360.0);
      TrigLUT.radToIndex = TrigLUT.SIN_COUNT / TrigLUT.radFull;
      TrigLUT.degToIndex = TrigLUT.SIN_COUNT / TrigLUT.degFull;

      TrigLUT.sin_ = new Array(TrigLUT.SIN_COUNT);
      TrigLUT.cos_ = new Array(TrigLUT.SIN_COUNT);

      for (var i = 0; i < TrigLUT.SIN_COUNT; i++) {
        TrigLUT.sin_[i] = Math.sin((i + 0.5) / TrigLUT.SIN_COUNT * TrigLUT.radFull);
        TrigLUT.cos_[i] = Math.cos((i + 0.5) / TrigLUT.SIN_COUNT * TrigLUT.radFull);
      }

      if (update) {
        Math.sin = TrigLUT.sin;
        Math.cos = TrigLUT.cos;
      }
    }
  }
}


text:
import PDFViewerApplication from './pdf_viewer_application';
import SecondaryToolbar from './secondary_toolbar';
import OverlayManager from './overlay_manager';
import HandTool from './hand_tool';
import PresentationModeState from './presentation_mode_state';
import noContextMenuHandler from './no_context_menu_handler';
import './globals';
import './moz_print_callback_polyfill';

'use strict';

export default function(url) {

PDFJS.imageResourcesPath = 'assets/ember-cli-pdf-js/cmaps/images/';
PDFJS.workerSrc = 'assets/ember-cli-pdf-js/pdf.worker.js';
PDFJS.cMapUrl = 'assets/ember-cli-pdf-js/cmaps/';
PDFJS.cMapPacked = true;

function webViewerInitialized() {
  var file = url;

  var fileInput = document.createElement('input');
  fileInput.id = 'fileInput';
  fileInput.className = 'fileInput';
  fileInput.setAttribute('type', 'file');
  fileInput.oncontextmenu = noContextMenuHandler;
  document.body.appendChild(fileInput);

  if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
    document.getElementById('openFile').setAttribute('hidden', 'true');
    document.getElementById('secondaryOpenFile').setAttribute('hidden', 'true');
  } else {
    document.getElementById('fileInput').value = null;
  }

  var locale = PDFJS.locale || navigator.language;
  mozL10n.setLanguage(locale);

  if (!PDFViewerApplication.supportsPrinting) {
    document.getElementById('print').classList.add('hidden');
    document.getElementById('secondaryPrint').classList.add('hidden');
  }

  if (!PDFViewerApplication.supportsFullscreen) {
    document.getElementById('presentationMode').classList.add('hidden');
    document.getElementById('secondaryPresentationMode').
      classList.add('hidden');
  }

  if (PDFViewerApplication.supportsIntegratedFind) {
    document.getElementById('viewFind').classList.add('hidden');
  }

  // Listen for unsupported features to trigger the fallback UI.
  PDFJS.UnsupportedManager.listen(
    PDFViewerApplication.fallback.bind(PDFViewerApplication));

  // Suppress context menus for some controls
  document.getElementById('scaleSelect').oncontextmenu = noContextMenuHandler;

  var mainContainer = document.getElementById('mainContainer');
  var outerContainer = document.getElementById('outerContainer');
  mainContainer.addEventListener('transitionend', function(e) {
    if (e.target === mainContainer) {
      var event = document.createEvent('UIEvents');
      event.initUIEvent('resize', false, false, window, 0);
      window.dispatchEvent(event);
      outerContainer.classList.remove('sidebarMoving');
    }
  }, true);

  document.getElementById('sidebarToggle').addEventListener('click',
    function() {
      this.classList.toggle('toggled');
      outerContainer.classList.add('sidebarMoving');
      outerContainer.classList.toggle('sidebarOpen');
      PDFViewerApplication.sidebarOpen =
        outerContainer.classList.contains('sidebarOpen');
      if (PDFViewerApplication.sidebarOpen) {
        PDFViewerApplication.refreshThumbnailViewer();
      }
      PDFViewerApplication.forceRendering();
    });

  document.getElementById('viewThumbnail').addEventListener('click',
    function() {
      PDFViewerApplication.switchSidebarView('thumbs');
    });

  document.getElementById('viewOutline').addEventListener('click',
    function() {
      PDFViewerApplication.switchSidebarView('outline');
    });

  document.getElementById('viewAttachments').addEventListener('click',
    function() {
      PDFViewerApplication.switchSidebarView('attachments');
    });

  document.getElementById('previous').addEventListener('click',
    function() {
      PDFViewerApplication.page--;
    });

  document.getElementById('next').addEventListener('click',
    function() {
      PDFViewerApplication.page++;
    });

  document.getElementById('zoomIn').addEventListener('click',
    function() {
      PDFViewerApplication.zoomIn();
    });

  document.getElementById('zoomOut').addEventListener('click',
    function() {
      PDFViewerApplication.zoomOut();
    });

  document.getElementById('pageNumber').addEventListener('click', function() {
    this.select();
  });

  document.getElementById('pageNumber').addEventListener('change', function() {
    // Handle the user inputting a floating point number.
    PDFViewerApplication.page = (this.value | 0);

    if (this.value !== (this.value | 0).toString()) {
      this.value = PDFViewerApplication.page;
    }
  });

  document.getElementById('scaleSelect').addEventListener('change',
    function() {
      PDFViewerApplication.setScale(this.value, false);
    });

  document.getElementById('presentationMode').addEventListener('click',
    SecondaryToolbar.presentationModeClick.bind(SecondaryToolbar));

  document.getElementById('openFile').addEventListener('click',
    SecondaryToolbar.openFileClick.bind(SecondaryToolbar));

  document.getElementById('print').addEventListener('click',
    SecondaryToolbar.printClick.bind(SecondaryToolbar));

  document.getElementById('download').addEventListener('click',
    SecondaryToolbar.downloadClick.bind(SecondaryToolbar));

  if (file && file.lastIndexOf('file:', 0) === 0) {
    // file:-scheme. Load the contents in the main thread because QtWebKit
    // cannot load file:-URLs in a Web Worker. file:-URLs are usually loaded
    // very quickly, so there is no need to set up progress event listeners.
    PDFViewerApplication.setTitleUsingUrl(file);
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
      PDFViewerApplication.open(new Uint8Array(xhr.response), 0);
    };
    try {
      xhr.open('GET', file);
      xhr.responseType = 'arraybuffer';
      xhr.send();
    } catch (e) {
      PDFViewerApplication.error(mozL10n.get('loading_error', null,
        'An error occurred while loading the PDF.'), e);
    }
    return;
  }

  if (file) {
    PDFViewerApplication.open(file, 0);
  }
}

document.addEventListener('pagerendered', function (e) {
  var pageNumber = e.detail.pageNumber;
  var pageIndex = pageNumber - 1;
  var pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex);

  if (PDFViewerApplication.sidebarOpen) {
    var thumbnailView = PDFViewerApplication.pdfThumbnailViewer.
                        getThumbnail(pageIndex);
    thumbnailView.setImage(pageView);
  }

  if (PDFJS.pdfBug && Stats.enabled && pageView.stats) {
    Stats.add(pageNumber, pageView.stats);
  }

  if (pageView.error) {
    PDFViewerApplication.error(mozL10n.get('rendering_error', null,
      'An error occurred while rendering the page.'), pageView.error);
  }

  // If the page is still visible when it has finished rendering,
  // ensure that the page number input loading indicator is hidden.
  if (pageNumber === PDFViewerApplication.page) {
    var pageNumberInput = document.getElementById('pageNumber');
    pageNumberInput.classList.remove(PAGE_NUMBER_LOADING_INDICATOR);
  }

}, true);

document.addEventListener('textlayerrendered', function (e) {
  var pageIndex = e.detail.pageNumber - 1;
  var pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex);

}, true);

document.addEventListener('namedaction', function (e) {
  // Processing couple of named actions that might be useful.
  // See also PDFLinkService.executeNamedAction
  var action = e.action;
  switch (action) {
    case 'GoToPage':
      document.getElementById('pageNumber').focus();
      break;

    case 'Find':
      if (!this.supportsIntegratedFind) {
        this.findBar.toggle();
      }
      break;
  }
}, true);

window.addEventListener('presentationmodechanged', function (e) {
  var active = e.detail.active;
  var switchInProgress = e.detail.switchInProgress;
  PDFViewerApplication.pdfViewer.presentationModeState =
    switchInProgress ? PresentationModeState.CHANGING :
    active ? PresentationModeState.FULLSCREEN : PresentationModeState.NORMAL;
});

function updateViewarea() {
  if (!PDFViewerApplication.initialized) {
    return;
  }
  PDFViewerApplication.pdfViewer.update();
}

window.addEventListener('updateviewarea', function (evt) {
  if (!PDFViewerApplication.initialized) {
    return;
  }
  var location = evt.location;

  PDFViewerApplication.store.initializedPromise.then(function() {
    PDFViewerApplication.store.setMultiple({
      'exists': true,
      'page': location.pageNumber,
      'zoom': location.scale,
      'scrollLeft': location.left,
      'scrollTop': location.top
    }).catch(function() {
      // unable to write to storage
    });
  });
  var href =
    PDFViewerApplication.pdfLinkService.getAnchorUrl(location.pdfOpenParams);
  document.getElementById('viewBookmark').href = href;
  document.getElementById('secondaryViewBookmark').href = href;

  // Update the current bookmark in the browsing history.
  PDFViewerApplication.pdfHistory.updateCurrentBookmark(location.pdfOpenParams,
                                                        location.pageNumber);

  // Show/hide the loading indicator in the page number input element.
  var pageNumberInput = document.getElementById('pageNumber');
  var currentPage =
    PDFViewerApplication.pdfViewer.getPageView(PDFViewerApplication.page - 1);

  if (currentPage.renderingState === RenderingStates.FINISHED) {
    pageNumberInput.classList.remove(PAGE_NUMBER_LOADING_INDICATOR);
  } else {
    pageNumberInput.classList.add(PAGE_NUMBER_LOADING_INDICATOR);
  }
}, true);

window.addEventListener('resize', function webViewerResize(evt) {
  if (PDFViewerApplication.initialized &&
      (document.getElementById('pageAutoOption').selected ||
       /* Note: the scale is constant for |pageActualOption|. */
       document.getElementById('pageFitOption').selected ||
       document.getElementById('pageWidthOption').selected)) {
    var selectedScale = document.getElementById('scaleSelect').value;
    PDFViewerApplication.setScale(selectedScale, false);
  }
  updateViewarea();

  // Set the 'max-height' CSS property of the secondary toolbar.
  SecondaryToolbar.setMaxHeight(document.getElementById('viewerContainer'));
});

window.addEventListener('hashchange', function webViewerHashchange(evt) {
  if (PDFViewerApplication.pdfHistory.isHashChangeUnlocked) {
    var hash = document.location.hash.substring(1);
    if (!hash) {
      return;
    }
    if (!PDFViewerApplication.isInitialViewSet) {
      PDFViewerApplication.initialBookmark = hash;
    } else {
      PDFViewerApplication.pdfLinkService.setHash(hash);
    }
  }
});

window.addEventListener('change', function webViewerChange(evt) {
  var files = evt.target.files;
  if (!files || files.length === 0) {
    return;
  }
  var file = files[0];

  if (!PDFJS.disableCreateObjectURL &&
      typeof URL !== 'undefined' && URL.createObjectURL) {
    PDFViewerApplication.open(URL.createObjectURL(file), 0);
  } else {
    // Read the local file into a Uint8Array.
    var fileReader = new FileReader();
    fileReader.onload = function webViewerChangeFileReaderOnload(evt) {
      var buffer = evt.target.result;
      var uint8Array = new Uint8Array(buffer);
      PDFViewerApplication.open(uint8Array, 0);
    };
    fileReader.readAsArrayBuffer(file);
  }

  PDFViewerApplication.setTitleUsingUrl(file.name);

  // URL does not reflect proper document location - hiding some icons.
  document.getElementById('viewBookmark').setAttribute('hidden', 'true');
  document.getElementById('secondaryViewBookmark').
    setAttribute('hidden', 'true');
  document.getElementById('download').setAttribute('hidden', 'true');
  document.getElementById('secondaryDownload').setAttribute('hidden', 'true');
}, true);

function selectScaleOption(value) {
  var options = document.getElementById('scaleSelect').options;
  var predefinedValueFound = false;
  for (var i = 0; i < options.length; i++) {
    var option = options[i];
    if (option.value !== value) {
      option.selected = false;
      continue;
    }
    option.selected = true;
    predefinedValueFound = true;
  }
  return predefinedValueFound;
}

window.addEventListener('localized', function localized(evt) {
  document.getElementsByTagName('html')[0].dir = mozL10n.getDirection();

  PDFViewerApplication.animationStartedPromise.then(function() {
    // Adjust the width of the zoom box to fit the content.
    // Note: If the window is narrow enough that the zoom box is not visible,
    //       we temporarily show it to be able to adjust its width.
    var container = document.getElementById('scaleSelectContainer');
    if (container.clientWidth === 0) {
      container.setAttribute('style', 'display: inherit;');
    }
    if (container.clientWidth > 0) {
      var select = document.getElementById('scaleSelect');
      select.setAttribute('style', 'min-width: inherit;');
      var width = select.clientWidth + SCALE_SELECT_CONTAINER_PADDING;
      select.setAttribute('style', 'min-width: ' +
                                   (width + SCALE_SELECT_PADDING) + 'px;');
      container.setAttribute('style', 'min-width: ' + width + 'px; ' +
                                      'max-width: ' + width + 'px;');
    }

    // Set the 'max-height' CSS property of the secondary toolbar.
    SecondaryToolbar.setMaxHeight(document.getElementById('viewerContainer'));
  });
}, true);

window.addEventListener('scalechange', function scalechange(evt) {
  document.getElementById('zoomOut').disabled = (evt.scale === MIN_SCALE);
  document.getElementById('zoomIn').disabled = (evt.scale === MAX_SCALE);

  var customScaleOption = document.getElementById('customScaleOption');
  customScaleOption.selected = false;

  if (!PDFViewerApplication.updateScaleControls &&
      (document.getElementById('pageAutoOption').selected ||
       document.getElementById('pageActualOption').selected ||
       document.getElementById('pageFitOption').selected ||
       document.getElementById('pageWidthOption').selected)) {
    updateViewarea();
    return;
  }

  if (evt.presetValue) {
    selectScaleOption(evt.presetValue);
    updateViewarea();
    return;
  }

  var predefinedValueFound = selectScaleOption('' + evt.scale);
  if (!predefinedValueFound) {
    var customScale = Math.round(evt.scale * 10000) / 100;
    customScaleOption.textContent =
      mozL10n.get('page_scale_percent', { scale: customScale }, '{{scale}}%');
    customScaleOption.selected = true;
  }
  updateViewarea();
}, true);

window.addEventListener('pagechange', function pagechange(evt) {
  var page = evt.pageNumber;
  if (evt.previousPageNumber !== page) {
    document.getElementById('pageNumber').value = page;
    if (PDFViewerApplication.sidebarOpen) {
      PDFViewerApplication.pdfThumbnailViewer.scrollThumbnailIntoView(page);
    }
  }
  var numPages = PDFViewerApplication.pagesCount;

  document.getElementById('previous').disabled = (page <= 1);
  document.getElementById('next').disabled = (page >= numPages);

  document.getElementById('firstPage').disabled = (page <= 1);
  document.getElementById('lastPage').disabled = (page >= numPages);

  // we need to update stats
  if (PDFJS.pdfBug && Stats.enabled) {
    var pageView = PDFViewerApplication.pdfViewer.getPageView(page - 1);
    if (pageView.stats) {
      Stats.add(page, pageView.stats);
    }
  }
}, true);

function handleMouseWheel(evt) {
  var MOUSE_WHEEL_DELTA_FACTOR = 40;
  var ticks = (evt.type === 'DOMMouseScroll') ? -evt.detail :
              evt.wheelDelta / MOUSE_WHEEL_DELTA_FACTOR;
  var direction = (ticks < 0) ? 'zoomOut' : 'zoomIn';

  if (PDFViewerApplication.pdfViewer.isInPresentationMode) {
    evt.preventDefault();
    PDFViewerApplication.scrollPresentationMode(ticks *
                                                MOUSE_WHEEL_DELTA_FACTOR);
  } else if (evt.ctrlKey || evt.metaKey) {
    // Only zoom the pages, not the entire viewer.
    evt.preventDefault();
    PDFViewerApplication[direction](Math.abs(ticks));
  }
}

window.addEventListener('DOMMouseScroll', handleMouseWheel);
window.addEventListener('mousewheel', handleMouseWheel);

window.addEventListener('click', function click(evt) {
  if (SecondaryToolbar.opened &&
      PDFViewerApplication.pdfViewer.containsElement(evt.target)) {
    SecondaryToolbar.close();
  }
}, false);

window.addEventListener('keydown', function keydown(evt) {
  if (OverlayManager.active) {
    return;
  }

  var handled = false;
  var cmd = (evt.ctrlKey ? 1 : 0) |
            (evt.altKey ? 2 : 0) |
            (evt.shiftKey ? 4 : 0) |
            (evt.metaKey ? 8 : 0);

  var pdfViewer = PDFViewerApplication.pdfViewer;
  var isViewerInPresentationMode = pdfViewer && pdfViewer.isInPresentationMode;

  // First, handle the key bindings that are independent whether an input
  // control is selected or not.
  if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) {
    // either CTRL or META key with optional SHIFT.
    switch (evt.keyCode) {
      case 70: // f
        if (!PDFViewerApplication.supportsIntegratedFind) {
          PDFViewerApplication.findBar.open();
          handled = true;
        }
        break;
      case 71: // g
        if (!PDFViewerApplication.supportsIntegratedFind) {
          PDFViewerApplication.findBar.dispatchEvent('again',
                                                     cmd === 5 || cmd === 12);
          handled = true;
        }
        break;
      case 61: // FF/Mac '='
      case 107: // FF '+' and '='
      case 187: // Chrome '+'
      case 171: // FF with German keyboard
        if (!isViewerInPresentationMode) {
          PDFViewerApplication.zoomIn();
        }
        handled = true;
        break;
      case 173: // FF/Mac '-'
      case 109: // FF '-'
      case 189: // Chrome '-'
        if (!isViewerInPresentationMode) {
          PDFViewerApplication.zoomOut();
        }
        handled = true;
        break;
      case 48: // '0'
      case 96: // '0' on Numpad of Swedish keyboard
        if (!isViewerInPresentationMode) {
          // keeping it unhandled (to restore page zoom to 100%)
          setTimeout(function () {
            // ... and resetting the scale after browser adjusts its scale
            PDFViewerApplication.setScale(DEFAULT_SCALE_VALUE, true);
          });
          handled = false;
        }
        break;
    }
  }

  // CTRL or META without shift
  if (cmd === 1 || cmd === 8) {
    switch (evt.keyCode) {
      case 83: // s
        PDFViewerApplication.download();
        handled = true;
        break;
    }
  }

  // CTRL+ALT or Option+Command
  if (cmd === 3 || cmd === 10) {
    switch (evt.keyCode) {
      case 80: // p
        PDFViewerApplication.requestPresentationMode();
        handled = true;
        break;
      case 71: // g
        // focuses input#pageNumber field
        document.getElementById('pageNumber').select();
        handled = true;
        break;
    }
  }

  if (handled) {
    evt.preventDefault();
    return;
  }

  // Some shortcuts should not get handled if a control/input element
  // is selected.
  var curElement = document.activeElement || document.querySelector(':focus');
  var curElementTagName = curElement && curElement.tagName.toUpperCase();
  if (curElementTagName === 'INPUT' ||
      curElementTagName === 'TEXTAREA' ||
      curElementTagName === 'SELECT') {
    // Make sure that the secondary toolbar is closed when Escape is pressed.
    if (evt.keyCode !== 27) { // 'Esc'
      return;
    }
  }

  if (cmd === 0) { // no control key pressed at all.
    switch (evt.keyCode) {
      case 38: // up arrow
      case 33: // pg up
      case 8: // backspace
        if (!isViewerInPresentationMode &&
            PDFViewerApplication.currentScaleValue !== 'page-fit') {
          break;
        }
        /* in presentation mode */
        /* falls through */
      case 37: // left arrow
        // horizontal scrolling using arrow keys
        if (pdfViewer.isHorizontalScrollbarEnabled) {
          break;
        }
        /* falls through */
      case 75: // 'k'
      case 80: // 'p'
        PDFViewerApplication.page--;
        handled = true;
        break;
      case 27: // esc key
        if (SecondaryToolbar.opened) {
          SecondaryToolbar.close();
          handled = true;
        }
        if (!PDFViewerApplication.supportsIntegratedFind &&
            PDFViewerApplication.findBar.opened) {
          PDFViewerApplication.findBar.close();
          handled = true;
        }
        break;
      case 40: // down arrow
      case 34: // pg down
      case 32: // spacebar
        if (!isViewerInPresentationMode &&
            PDFViewerApplication.currentScaleValue !== 'page-fit') {
          break;
        }
        /* falls through */
      case 39: // right arrow
        // horizontal scrolling using arrow keys
        if (pdfViewer.isHorizontalScrollbarEnabled) {
          break;
        }
        /* falls through */
      case 74: // 'j'
      case 78: // 'n'
        PDFViewerApplication.page++;
        handled = true;
        break;

      case 36: // home
        if (isViewerInPresentationMode || PDFViewerApplication.page > 1) {
          PDFViewerApplication.page = 1;
          handled = true;
        }
        break;
      case 35: // end
        if (isViewerInPresentationMode || (PDFViewerApplication.pdfDocument &&
            PDFViewerApplication.page < PDFViewerApplication.pagesCount)) {
          PDFViewerApplication.page = PDFViewerApplication.pagesCount;
          handled = true;
        }
        break;

      case 72: // 'h'
        if (!isViewerInPresentationMode) {
          HandTool.toggle();
        }
        break;
      case 82: // 'r'
        PDFViewerApplication.rotatePages(90);
        break;
    }
  }

  if (cmd === 4) { // shift-key
    switch (evt.keyCode) {
      case 32: // spacebar
        if (!isViewerInPresentationMode &&
            PDFViewerApplication.currentScaleValue !== 'page-fit') {
          break;
        }
        PDFViewerApplication.page--;
        handled = true;
        break;

      case 82: // 'r'
        PDFViewerApplication.rotatePages(-90);
        break;
    }
  }

  if (!handled && !isViewerInPresentationMode) {
    // 33=Page Up  34=Page Down  35=End    36=Home
    // 37=Left     38=Up         39=Right  40=Down
    if (evt.keyCode >= 33 && evt.keyCode <= 40 &&
        !pdfViewer.containsElement(curElement)) {
      // The page container is not focused, but a page navigation key has been
      // pressed. Change the focus to the viewer container to make sure that
      // navigation by keyboard works as expected.
      pdfViewer.focus();
    }
    // 32=Spacebar
    if (evt.keyCode === 32 && curElementTagName !== 'BUTTON' &&
        !pdfViewer.containsElement(curElement)) {
      pdfViewer.focus();
    }
  }

  if (cmd === 2) { // alt-key
    switch (evt.keyCode) {
      case 37: // left arrow
        if (isViewerInPresentationMode) {
          PDFViewerApplication.pdfHistory.back();
          handled = true;
        }
        break;
      case 39: // right arrow
        if (isViewerInPresentationMode) {
          PDFViewerApplication.pdfHistory.forward();
          handled = true;
        }
        break;
    }
  }

  if (handled) {
    evt.preventDefault();
  }
});

window.addEventListener('beforeprint', function beforePrint(evt) {
  PDFViewerApplication.beforePrint();
});

window.addEventListener('afterprint', function afterPrint(evt) {
  PDFViewerApplication.afterPrint();
});

(function animationStartedClosure() {
  // The offsetParent is not set until the pdf.js iframe or object is visible.
  // Waiting for first animation.
  PDFViewerApplication.animationStartedPromise = new Promise(
      function (resolve) {
    window.requestAnimationFrame(resolve);
  });
})();

  PDFViewerApplication.initialize().then(webViewerInitialized);
};


text:
{% extends 'home.html' %}

{% block container %}

    {% with messages = get_flashed_messages() %}
      {% if messages %}

        {% for message in messages %}

{{ message }}

        {% endfor %}

      {% endif %}
    {% endwith %}
    <form method="POST" action="{{ url_for('idleg.register') }}" role="form">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>

{{ rform.username.label }}: {{  rform.username() }}

{{ rform.email.label }}: {{  rform.email() }}

{{ rform.password.label }}: {{  rform.password() }}

{{ rform.confirm.label }}: {{ rform.confirm() }}

      <button type="submit" class="btn btn-default"> Submit</button>
    </form>

{% endblock %}


text:
Imports System.Threading.Tasks

Public Class Quicksort
    Inherits Sort
    Dim mbolSortUmlauts As Boolean

    ''' <summary>
    ''' Quicksorts an array
    ''' </summary>
    ''' <param name="arr">Unsorted array</param>
    ''' <returns>Sorted string</returns>
    Async Function Sort(ByVal arr As Array, ByVal bolSortUmlauts As Boolean) As Task(Of String)
        Dim QuickSortTask As Task(Of String) = Task.Factory.StartNew(Function()
                                                                         mbolSortUmlauts = bolSortUmlauts
                                                                         QuickPartition(arr, 0, arr.Length - 1)
                                                                         Return arrayToString(arr)
                                                                     End Function)
        Dim result As String = Await QuickSortTask
        Return result
    End Function

    ''' <summary>
    ''' Partitions and swaps an array recursively
    ''' </summary>
    ''' <param name="arr">Unsorted array</param>
    ''' <param name="loIdx">Lowest index to sort</param>
    ''' <param name="hiIdx">Highest index to sort</param>
    Sub QuickPartition(ByRef arr As Array, ByVal loIdx As Integer, ByVal hiIdx As Integer)
        Dim lo As Integer = loIdx
        Dim hi As Integer = hiIdx

        Dim pivot As Object = arr((lo + hi) \ 2) ' get center value
        Do Until lo > hi
            Do While isGreater(pivot, arr(lo), mbolSortUmlauts) ' check from left to right until char is >= pivot
                lo += 1
            Loop
            Do While isGreater(arr(hi), pivot, mbolSortUmlauts) ' check from right to left until char is <= pivot
                hi -= 1
            Loop
            If lo <= hi Then ' if lo is still smaller than hi it means something was on the wrong side
                Swap(arr, lo, hi)
                lo += 1
                hi -= 1
            End If
        Loop
        If (lo < hiIdx) Then QuickPartition(arr, lo, hiIdx)
        If (hi > loIdx) Then QuickPartition(arr, loIdx, hi)
    End Sub

End Class


text:
using System;

namespace Test.Core
{
    public enum ContactType
    {
        Home,
        Business,
        Personal,
        Mobile

    }
}