text:
/* $Id$ */

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

#include "php.h"
#include "php_xsl.h"
#include "ext/libxml/php_libxml.h"

/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_xsl_xsltprocessor_import_stylesheet, 0, 0, 1)
	ZEND_ARG_INFO(0, doc)
ZEND_END_ARG_INFO();

ZEND_BEGIN_ARG_INFO_EX(arginfo_xsl_xsltprocessor_transform_to_doc, 0, 0, 1)
	ZEND_ARG_INFO(0, doc)
ZEND_END_ARG_INFO();

ZEND_BEGIN_ARG_INFO_EX(arginfo_xsl_xsltprocessor_transform_to_uri, 0, 0, 2)
	ZEND_ARG_INFO(0, doc)
	ZEND_ARG_INFO(0, uri)
ZEND_END_ARG_INFO();

ZEND_BEGIN_ARG_INFO_EX(arginfo_xsl_xsltprocessor_transform_to_xml, 0, 0, 1)
	ZEND_ARG_INFO(0, doc)
ZEND_END_ARG_INFO();

ZEND_BEGIN_ARG_INFO_EX(arginfo_xsl_xsltprocessor_set_parameter, 0, 0, 2)
	ZEND_ARG_INFO(0, namespace)
	ZEND_ARG_INFO(0, name)
	ZEND_ARG_INFO(0, value)
ZEND_END_ARG_INFO();

ZEND_BEGIN_ARG_INFO_EX(arginfo_xsl_xsltprocessor_get_parameter, 0, 0, 2)
	ZEND_ARG_INFO(0, namespace)
	ZEND_ARG_INFO(0, name)
ZEND_END_ARG_INFO();

ZEND_BEGIN_ARG_INFO_EX(arginfo_xsl_xsltprocessor_remove_parameter, 0, 0, 2)
	ZEND_ARG_INFO(0, namespace)
	ZEND_ARG_INFO(0, name)
ZEND_END_ARG_INFO();

ZEND_BEGIN_ARG_INFO_EX(arginfo_xsl_xsltprocessor_has_exslt_support, 0, 0, 0)
ZEND_END_ARG_INFO();

ZEND_BEGIN_ARG_INFO_EX(arginfo_xsl_xsltprocessor_register_php_functions, 0, 0, 0)
	ZEND_ARG_INFO(0, restrict)
ZEND_END_ARG_INFO();

ZEND_BEGIN_ARG_INFO_EX(arginfo_xsl_xsltprocessor_set_profiling, 0, 0, 1)
	ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO();

ZEND_BEGIN_ARG_INFO_EX(arginfo_xsl_xsltprocessor_set_security_prefs, 0, 0, 1)
	ZEND_ARG_INFO(0, securityPrefs)
ZEND_END_ARG_INFO();

ZEND_BEGIN_ARG_INFO_EX(arginfo_xsl_xsltprocessor_get_security_prefs, 0, 0, 0)
ZEND_END_ARG_INFO();
/* }}} */

/*
* class xsl_xsltprocessor
*
* URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#
* Since:
*/

const zend_function_entry php_xsl_xsltprocessor_class_functions[] = {
	PHP_FALIAS(importStylesheet, xsl_xsltprocessor_import_stylesheet, arginfo_xsl_xsltprocessor_import_stylesheet)
	PHP_FALIAS(transformToDoc, xsl_xsltprocessor_transform_to_doc, arginfo_xsl_xsltprocessor_transform_to_doc)
	PHP_FALIAS(transformToUri, xsl_xsltprocessor_transform_to_uri, arginfo_xsl_xsltprocessor_transform_to_uri)
	PHP_FALIAS(transformToXml, xsl_xsltprocessor_transform_to_xml, arginfo_xsl_xsltprocessor_transform_to_xml)
	PHP_FALIAS(setParameter, xsl_xsltprocessor_set_parameter, arginfo_xsl_xsltprocessor_set_parameter)
	PHP_FALIAS(getParameter, xsl_xsltprocessor_get_parameter, arginfo_xsl_xsltprocessor_get_parameter)
	PHP_FALIAS(removeParameter, xsl_xsltprocessor_remove_parameter, arginfo_xsl_xsltprocessor_remove_parameter)
	PHP_FALIAS(hasExsltSupport, xsl_xsltprocessor_has_exslt_support, arginfo_xsl_xsltprocessor_has_exslt_support)
	PHP_FALIAS(registerPHPFunctions, xsl_xsltprocessor_register_php_functions, arginfo_xsl_xsltprocessor_register_php_functions)
	PHP_FALIAS(setProfiling, xsl_xsltprocessor_set_profiling, arginfo_xsl_xsltprocessor_set_profiling)
	PHP_FALIAS(setSecurityPrefs, xsl_xsltprocessor_set_security_prefs, arginfo_xsl_xsltprocessor_set_security_prefs)
	PHP_FALIAS(getSecurityPrefs, xsl_xsltprocessor_get_security_prefs, arginfo_xsl_xsltprocessor_get_security_prefs)
	{NULL, NULL, NULL}
};

/* {{{ php_xsl_xslt_string_to_xpathexpr()
   Translates a string to a XPath Expression */
static char *php_xsl_xslt_string_to_xpathexpr(const char *str TSRMLS_DC)
{
	const xmlChar *string = (const xmlChar *)str;

	xmlChar *value;
	int str_len;

	str_len = xmlStrlen(string) + 3;

	if (xmlStrchr(string, '"')) {
		if (xmlStrchr(string, '\'')) {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create XPath expression (string contains both quote and double-quotes)");
			return NULL;
		}
		value = (xmlChar*) safe_emalloc (str_len, sizeof(xmlChar), 0);
		snprintf(value, str_len, "'%s'", string);
	} else {
		value = (xmlChar*) safe_emalloc (str_len, sizeof(xmlChar), 0);
		snprintf(value, str_len, "\"%s\"", string);
	}
	return (char *) value;
}
/* }}} */

/* {{{ php_xsl_xslt_make_params()
   Translates a PHP array to a libxslt parameters array */
static char **php_xsl_xslt_make_params(HashTable *parht, int xpath_params TSRMLS_DC)
{

	int parsize;
	zval **value;
	char *xpath_expr, *string_key = NULL;
	ulong num_key;
	char **params = NULL;
	int i = 0;

	parsize = (2 * zend_hash_num_elements(parht) + 1) * sizeof(char *);
	params = (char **)safe_emalloc((2 * zend_hash_num_elements(parht) + 1), sizeof(char *), 0);
	memset((char *)params, 0, parsize);

	for (zend_hash_internal_pointer_reset(parht);
		zend_hash_get_current_data(parht, (void **)&value) == SUCCESS;
		zend_hash_move_forward(parht)) {

		if (zend_hash_get_current_key(parht, &string_key, &num_key, 1) != HASH_KEY_IS_STRING) {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid argument or parameter array");
			efree(params);
			return NULL;
		} else {
			if (Z_TYPE_PP(value) != IS_STRING) {
				SEPARATE_ZVAL(value);
				convert_to_string(*value);
			}

			if (!xpath_params) {
				xpath_expr = php_xsl_xslt_string_to_xpathexpr(Z_STRVAL_PP(value) TSRMLS_CC);
			} else {
				xpath_expr = estrndup(Z_STRVAL_PP(value), Z_STRLEN_PP(value));
			}
			if (xpath_expr) {
				params[i++] = string_key;
				params[i++] = xpath_expr;
			} else {
				efree(string_key);
			}
		}
	}

	params[i++] = NULL;

	return params;
}
/* }}} */

static void xsl_ext_function_php(xmlXPathParserContextPtr ctxt, int nargs, int type) /* {{{ */
{
	xsltTransformContextPtr tctxt;
	zval **args;
	zval *retval;
	int result, i, ret;
	int error = 0;
	zend_fcall_info fci;
	zval handler;
	xmlXPathObjectPtr obj;
	char *str;
	char *callable = NULL;
	xsl_object *intern;

	TSRMLS_FETCH();

	if (! zend_is_executing(TSRMLS_C)) {
		xsltGenericError(xsltGenericErrorContext,
		"xsltExtFunctionTest: Function called from outside of PHP\n");
		error = 1;
	} else {
		tctxt = xsltXPathGetTransformContext(ctxt);
		if (tctxt == NULL) {
			xsltGenericError(xsltGenericErrorContext,
			"xsltExtFunctionTest: failed to get the transformation context\n");
			error = 1;
		} else {
			intern = (xsl_object *) tctxt->_private;
			if (intern == NULL) {
				xsltGenericError(xsltGenericErrorContext,
				"xsltExtFunctionTest: failed to get the internal object\n");
				error = 1;
			}
			else if (intern->registerPhpFunctions == 0) {
				xsltGenericError(xsltGenericErrorContext,
				"xsltExtFunctionTest: PHP Object did not register PHP functions\n");
				error = 1;
			}
		}
	}

	if (error == 1) {
		for (i = nargs - 1; i >= 0; i--) {
			obj = valuePop(ctxt);
			xmlXPathFreeObject(obj);
		}
		return;
	}

	fci.param_count = nargs - 1;
	if (fci.param_count > 0) {
		fci.params = safe_emalloc(fci.param_count, sizeof(zval**), 0);
		args = safe_emalloc(fci.param_count, sizeof(zval *), 0);
	}
	/* Reverse order to pop values off ctxt stack */
	for (i = nargs - 2; i >= 0; i--) {
		obj = valuePop(ctxt);
		MAKE_STD_ZVAL(args[i]);
		switch (obj->type) {
			case XPATH_STRING:
				ZVAL_STRING(args[i],  obj->stringval, 1);
				break;
			case XPATH_BOOLEAN:
				ZVAL_BOOL(args[i],  obj->boolval);
				break;
			case XPATH_NUMBER:
				ZVAL_DOUBLE(args[i], obj->floatval);
				break;
			case XPATH_NODESET:
				if (type == 1) {
					str = xmlXPathCastToString(obj);
					ZVAL_STRING(args[i], str, 1);
					xmlFree(str);
				} else if (type == 2) {
					int j;
					dom_object *domintern = (dom_object *)intern->doc;
					array_init(args[i]);
					if (obj->nodesetval && obj->nodesetval->nodeNr > 0) {
						for (j = 0; j < obj->nodesetval->nodeNr; j++) {
							xmlNodePtr node = obj->nodesetval->nodeTab[j];
							zval *child;
							MAKE_STD_ZVAL(child);
							/* not sure, if we need this... it's copied from xpath.c */
							if (node->type == XML_NAMESPACE_DECL) {
								xmlNsPtr curns;
								xmlNodePtr nsparent;

								nsparent = node->_private;
								curns = xmlNewNs(NULL, node->name, NULL);
								if (node->children) {
									curns->prefix = xmlStrdup((char *) node->children);
								}
								if (node->children) {
									node = xmlNewDocNode(node->doc, NULL, (char *) node->children, node->name);
								} else {
									node = xmlNewDocNode(node->doc, NULL, "xmlns", node->name);
								}
								node->type = XML_NAMESPACE_DECL;
								node->parent = nsparent;
								node->ns = curns;
							} else {
								node = xmlDocCopyNodeList(domintern->document->ptr, node);
							}

							child = php_dom_create_object(node, &ret, child, domintern TSRMLS_CC);
							add_next_index_zval(args[i], child);
						}
					}
				}
				break;
			default:
				str = xmlXPathCastToString(obj);
				ZVAL_STRING(args[i], str, 1);
				xmlFree(str);
		}
		xmlXPathFreeObject(obj);
		fci.params[i] = &args[i];
	}

	fci.size = sizeof(fci);
	fci.function_table = EG(function_table);

	obj = valuePop(ctxt);
	if (obj->stringval == NULL) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Handler name must be a string");
		xmlXPathFreeObject(obj);
		valuePush(ctxt, xmlXPathNewString(""));
		if (fci.param_count > 0) {
			for (i = 0; i < nargs - 1; i++) {
				zval_ptr_dtor(&args[i]);
			}
			efree(args);
			efree(fci.params);
		}
		return;
	}
	INIT_PZVAL(&handler);
	ZVAL_STRING(&handler, obj->stringval, 1);
	xmlXPathFreeObject(obj);

	fci.function_name = &handler;
	fci.symbol_table = NULL;
	fci.object_ptr = NULL;
	fci.retval_ptr_ptr = &retval;
	fci.no_separation = 0;
	/*fci.function_handler_cache = &function_ptr;*/
	if (!zend_make_callable(&handler, &callable TSRMLS_CC)) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", callable);
		valuePush(ctxt, xmlXPathNewString(""));
	} else if ( intern->registerPhpFunctions == 2 && zend_hash_exists(intern->registered_phpfunctions, callable, strlen(callable) + 1) == 0) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Not allowed to call handler '%s()'", callable);
		/* Push an empty string, so that we at least have an xslt result... */
		valuePush(ctxt, xmlXPathNewString(""));
	} else {
		result = zend_call_function(&fci, NULL TSRMLS_CC);
		if (result == FAILURE) {
			if (Z_TYPE(handler) == IS_STRING) {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", Z_STRVAL_P(&handler));
				valuePush(ctxt, xmlXPathNewString(""));
			}
		/* retval is == NULL, when an exception occurred, don't report anything, because PHP itself will handle that */
		} else if (retval == NULL) {
		} else {
			if (retval->type == IS_OBJECT && instanceof_function( Z_OBJCE_P(retval), dom_node_class_entry TSRMLS_CC)) {
				xmlNode *nodep;
				dom_object *obj;
				if (intern->node_list == NULL) {
					ALLOC_HASHTABLE(intern->node_list);
					zend_hash_init(intern->node_list, 0, NULL, ZVAL_PTR_DTOR, 0);
				}
				zval_add_ref(&retval);
				zend_hash_next_index_insert(intern->node_list, &retval, sizeof(zval *), NULL);
				obj = (dom_object *)zend_object_store_get_object(retval TSRMLS_CC);
				nodep = dom_object_get_node(obj);
				valuePush(ctxt, xmlXPathNewNodeSet(nodep));
			} else if (retval->type == IS_BOOL) {
				valuePush(ctxt, xmlXPathNewBoolean(retval->value.lval));
			} else if (retval->type == IS_OBJECT) {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "A PHP Object cannot be converted to a XPath-string");
				valuePush(ctxt, xmlXPathNewString(""));
			} else {
				convert_to_string_ex(&retval);
				valuePush(ctxt, xmlXPathNewString( Z_STRVAL_P(retval)));
			}
			zval_ptr_dtor(&retval);
		}
	}
	efree(callable);
	zval_dtor(&handler);
	if (fci.param_count > 0) {
		for (i = 0; i < nargs - 1; i++) {
			zval_ptr_dtor(&args[i]);
		}
		efree(args);
		efree(fci.params);
	}
}
/* }}} */

void xsl_ext_function_string_php(xmlXPathParserContextPtr ctxt, int nargs) /* {{{ */
{
	xsl_ext_function_php(ctxt, nargs, 1);
}
/* }}} */

void xsl_ext_function_object_php(xmlXPathParserContextPtr ctxt, int nargs) /* {{{ */
{
	xsl_ext_function_php(ctxt, nargs, 2);
}
/* }}} */

/* {{{ proto void xsl_xsltprocessor_import_stylesheet(domdocument doc);
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#
Since:
*/
PHP_FUNCTION(xsl_xsltprocessor_import_stylesheet)
{
	zval *id, *docp = NULL;
	xmlDoc *doc = NULL, *newdoc = NULL;
	xsltStylesheetPtr sheetp, oldsheetp;
	xsl_object *intern;
	int prevSubstValue, prevExtDtdValue, clone_docu = 0;
	xmlNode *nodep = NULL;
	zend_object_handlers *std_hnd;
	zval *cloneDocu, *member;

	if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oo", &id, xsl_xsltprocessor_class_entry, &docp) == FAILURE) {
		RETURN_FALSE;
	}

	nodep = php_libxml_import_node(docp TSRMLS_CC);

	if (nodep) {
		doc = nodep->doc;
	}
	if (doc == NULL) {
		php_error(E_WARNING, "Invalid Document");
		RETURN_FALSE;
	}

	/* libxslt uses _private, so we must copy the imported
	stylesheet document otherwise the node proxies will be a mess */
	newdoc = xmlCopyDoc(doc, 1);
	xmlNodeSetBase((xmlNodePtr) newdoc, (xmlChar *)doc->URL);
	prevSubstValue = xmlSubstituteEntitiesDefault(1);
	prevExtDtdValue = xmlLoadExtDtdDefaultValue;
	xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;

	sheetp = xsltParseStylesheetDoc(newdoc);
	xmlSubstituteEntitiesDefault(prevSubstValue);
	xmlLoadExtDtdDefaultValue = prevExtDtdValue;

	if (!sheetp) {
		xmlFreeDoc(newdoc);
		RETURN_FALSE;
	}

	intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);

	std_hnd = zend_get_std_object_handlers();
	MAKE_STD_ZVAL(member);
	ZVAL_STRING(member, "cloneDocument", 0);
	cloneDocu = std_hnd->read_property(id, member, BP_VAR_IS, NULL TSRMLS_CC);
	if (Z_TYPE_P(cloneDocu) != IS_NULL) {
		convert_to_long(cloneDocu);
		clone_docu = Z_LVAL_P(cloneDocu);
	}
	efree(member);
	if (clone_docu == 0) {
		/* check if the stylesheet is using xsl:key, if yes, we have to clone the document _always_ before a transformation */
		nodep = xmlDocGetRootElement(sheetp->doc);
		if (nodep && (nodep = nodep->children)) {
			while (nodep) {
				if (nodep->type == XML_ELEMENT_NODE && xmlStrEqual(nodep->name, "key") && xmlStrEqual(nodep->ns->href, XSLT_NAMESPACE)) {
					intern->hasKeys = 1;
					break;
				}
				nodep = nodep->next;
			}
		}
	} else {
		intern->hasKeys = clone_docu;
	}

	if ((oldsheetp = (xsltStylesheetPtr)intern->ptr)) {
		/* free wrapper */
		if (((xsltStylesheetPtr) intern->ptr)->_private != NULL) {
			((xsltStylesheetPtr) intern->ptr)->_private = NULL;
		}
		xsltFreeStylesheet((xsltStylesheetPtr) intern->ptr);
		intern->ptr = NULL;
	}

	php_xsl_set_object(id, sheetp TSRMLS_CC);
	RETVAL_TRUE;
}
/* }}} end xsl_xsltprocessor_import_stylesheet */

static xmlDocPtr php_xsl_apply_stylesheet(zval *id, xsl_object *intern, xsltStylesheetPtr style, zval *docp TSRMLS_DC) /* {{{ */
{
	xmlDocPtr newdocp = NULL;
	xmlDocPtr doc = NULL;
	xmlNodePtr node = NULL;
	xsltTransformContextPtr ctxt;
	php_libxml_node_object *object;
	char **params = NULL;
	int clone;
	zval *doXInclude, *member;
	zend_object_handlers *std_hnd;
	FILE *f;
	int secPrefsError = 0;
	int secPrefsValue, secPrefsIni;
	xsltSecurityPrefsPtr secPrefs = NULL;

	node = php_libxml_import_node(docp TSRMLS_CC);

	if (node) {
		doc = node->doc;
	}
	if (doc == NULL) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Document");
		return NULL;
	}

	if (style == NULL) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "No stylesheet associated to this object");
		return NULL;
	}

	if (intern->profiling) {
		if (php_check_open_basedir(intern->profiling TSRMLS_CC)) {
			f = NULL;
		} else {
			f = VCWD_FOPEN(intern->profiling, "w");
		}
	} else {
		f = NULL;
	}

	if (intern->parameter) {
		params = php_xsl_xslt_make_params(intern->parameter, 0 TSRMLS_CC);
	}

	intern->doc = emalloc(sizeof(php_libxml_node_object));
	memset(intern->doc, 0, sizeof(php_libxml_node_object));

	if (intern->hasKeys == 1) {
		doc = xmlCopyDoc(doc, 1);
	} else {
		object = (php_libxml_node_object *)zend_object_store_get_object(docp TSRMLS_CC);
		intern->doc->document = object->document;
	}

	php_libxml_increment_doc_ref(intern->doc, doc TSRMLS_CC);

	ctxt = xsltNewTransformContext(style, doc);
	ctxt->_private = (void *) intern;

	std_hnd = zend_get_std_object_handlers();

	MAKE_STD_ZVAL(member);
	ZVAL_STRING(member, "doXInclude", 0);
	doXInclude = std_hnd->read_property(id, member, BP_VAR_IS, NULL TSRMLS_CC);
	if (Z_TYPE_P(doXInclude) != IS_NULL) {
		convert_to_long(doXInclude);
		ctxt->xinclude = Z_LVAL_P(doXInclude);
	}
	efree(member);

	secPrefsValue = intern->securityPrefs;

	/* This whole if block can be removed, when we remove the xsl.security_prefs php.ini option in PHP 6+ */
	secPrefsIni= INI_INT("xsl.security_prefs");
	/* if secPrefsIni has the same value as secPrefsValue, all is fine */
	if (secPrefsIni != secPrefsValue) {
		if (secPrefsIni != XSL_SECPREF_DEFAULT) {
			/* if the ini value is not set to the default, throw an E_DEPRECATED warning */
			php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The xsl.security_prefs php.ini option is deprecated; use XsltProcessor->setSecurityPrefs() instead");
			if (intern->securityPrefsSet == 0) {
				/* if securityPrefs were not set through the setSecurityPrefs method, take the ini setting */
				secPrefsValue = secPrefsIni;
			} else {
				/* else throw a notice, that the ini setting was not used */
				php_error_docref(NULL TSRMLS_CC, E_NOTICE, "The xsl.security_prefs php.ini was not used, since the  XsltProcessor->setSecurityPrefs() method was used");
			}
		}
	}

	/* if securityPrefs is set to NONE, we don't have to do any checks, but otherwise... */
	if (secPrefsValue != XSL_SECPREF_NONE) {
		secPrefs = xsltNewSecurityPrefs();
		if (secPrefsValue & XSL_SECPREF_READ_FILE ) {
			if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_READ_FILE, xsltSecurityForbid)) {
				secPrefsError = 1;
			}
		}
		if (secPrefsValue & XSL_SECPREF_WRITE_FILE ) {
			if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_WRITE_FILE, xsltSecurityForbid)) {
				secPrefsError = 1;
			}
		}
		if (secPrefsValue & XSL_SECPREF_CREATE_DIRECTORY ) {
			if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_CREATE_DIRECTORY, xsltSecurityForbid)) {
				secPrefsError = 1;
			}
		}
		if (secPrefsValue & XSL_SECPREF_READ_NETWORK) {
			if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_READ_NETWORK, xsltSecurityForbid)) {
				secPrefsError = 1;
			}
		}
		if (secPrefsValue & XSL_SECPREF_WRITE_NETWORK) {
			if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_WRITE_NETWORK, xsltSecurityForbid)) {
				secPrefsError = 1;
			}
		}

		if (0 != xsltSetCtxtSecurityPrefs(secPrefs, ctxt)) {
			secPrefsError = 1;
		}
	}

	if (secPrefsError == 1) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can't set libxslt security properties, not doing transformation for security reasons");
	} else {
		newdocp = xsltApplyStylesheetUser(style, doc, (const char**) params,  NULL, f, ctxt);
	}
	if (f) {
		fclose(f);
	}

	xsltFreeTransformContext(ctxt);
	if (secPrefs) {
		xsltFreeSecurityPrefs(secPrefs);
	}

	if (intern->node_list != NULL) {
		zend_hash_destroy(intern->node_list);
		FREE_HASHTABLE(intern->node_list);
		intern->node_list = NULL;
	}

	php_libxml_decrement_doc_ref(intern->doc TSRMLS_CC);
	efree(intern->doc);
	intern->doc = NULL;

	if (params) {
		clone = 0;
		while(params[clone]) {
			efree(params[clone++]);
		}
		efree(params);
	}

	return newdocp;

}
/* }}} */

/* {{{ proto domdocument xsl_xsltprocessor_transform_to_doc(domnode doc);
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#
Since:
*/
PHP_FUNCTION(xsl_xsltprocessor_transform_to_doc)
{
	zval *id, *docp = NULL;
	xmlDoc *newdocp;
	xsltStylesheetPtr sheetp;
	int ret, ret_class_len=0;
	char *ret_class = NULL;
	xsl_object *intern;

	id = getThis();
	intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);
	sheetp = (xsltStylesheetPtr) intern->ptr;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o|s!", &docp, &ret_class, &ret_class_len) == FAILURE) {
		RETURN_FALSE;
	}

	newdocp = php_xsl_apply_stylesheet(id, intern, sheetp, docp TSRMLS_CC);

	if (newdocp) {
		if (ret_class) {
			int found;
			char *curclass_name;
			zend_class_entry *curce, **ce;
			php_libxml_node_object *interndoc;

			curce = Z_OBJCE_P(docp);
			curclass_name = curce->name;
			while (curce->parent != NULL) {
				curce = curce->parent;
			}

			found = zend_lookup_class(ret_class, ret_class_len, &ce TSRMLS_CC);
			if ((found != SUCCESS) || !instanceof_function(*ce, curce TSRMLS_CC)) {
				xmlFreeDoc(newdocp);
				php_error_docref(NULL TSRMLS_CC, E_WARNING,
					"Expecting class compatible with %s, '%s' given", curclass_name, ret_class);
				RETURN_FALSE;
			}

			object_init_ex(return_value, *ce);

			interndoc = (php_libxml_node_object *)zend_objects_get_address(return_value TSRMLS_CC);
			php_libxml_increment_doc_ref(interndoc, newdocp TSRMLS_CC);
			php_libxml_increment_node_ptr(interndoc, (xmlNodePtr)newdocp, (void *)interndoc TSRMLS_CC);
		} else {
			DOM_RET_OBJ((xmlNodePtr) newdocp, &ret, NULL);
		}
	} else {
		RETURN_FALSE;
	}

}
/* }}} end xsl_xsltprocessor_transform_to_doc */

/* {{{ proto int xsl_xsltprocessor_transform_to_uri(domdocument doc, string uri);
*/
PHP_FUNCTION(xsl_xsltprocessor_transform_to_uri)
{
	zval *id, *docp = NULL;
	xmlDoc *newdocp;
	xsltStylesheetPtr sheetp;
	int ret, uri_len;
	char *uri;
	xsl_object *intern;

	id = getThis();
	intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);
	sheetp = (xsltStylesheetPtr) intern->ptr;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "op", &docp, &uri, &uri_len) == FAILURE) {
		RETURN_FALSE;
	}

	newdocp = php_xsl_apply_stylesheet(id, intern, sheetp, docp TSRMLS_CC);

	ret = -1;
	if (newdocp) {
		ret = xsltSaveResultToFilename(uri, newdocp, sheetp, 0);
		xmlFreeDoc(newdocp);
	}

	RETVAL_LONG(ret);
}
/* }}} end xsl_xsltprocessor_transform_to_uri */

/* {{{ proto string xsl_xsltprocessor_transform_to_xml(domdocument doc);
*/
PHP_FUNCTION(xsl_xsltprocessor_transform_to_xml)
{
	zval *id, *docp = NULL;
	xmlDoc *newdocp;
	xsltStylesheetPtr sheetp;
	int ret;
	xmlChar *doc_txt_ptr;
	int doc_txt_len;
	xsl_object *intern;

	id = getThis();
	intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);
	sheetp = (xsltStylesheetPtr) intern->ptr;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &docp) == FAILURE) {
		RETURN_FALSE;
	}

	newdocp = php_xsl_apply_stylesheet(id, intern, sheetp, docp TSRMLS_CC);

	ret = -1;
	if (newdocp) {
		ret = xsltSaveResultToString(&doc_txt_ptr, &doc_txt_len, newdocp, sheetp);
		if (doc_txt_ptr && doc_txt_len) {
			RETVAL_STRINGL(doc_txt_ptr, doc_txt_len, 1);
			xmlFree(doc_txt_ptr);
		}
		xmlFreeDoc(newdocp);
	}

	if (ret < 0) {
		RETURN_FALSE;
	}
}
/* }}} end xsl_xsltprocessor_transform_to_xml */

/* {{{ proto bool xsl_xsltprocessor_set_parameter(string namespace, mixed name [, string value]);
*/
PHP_FUNCTION(xsl_xsltprocessor_set_parameter)
{

	zval *id;
	zval *array_value, **entry, *new_string;
	xsl_object *intern;
	char *string_key, *name, *value, *namespace;
	ulong idx;
	int string_key_len, namespace_len, name_len, value_len;
	DOM_GET_THIS(id);

	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "sa", &namespace, &namespace_len, &array_value) == SUCCESS) {
		intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);
		zend_hash_internal_pointer_reset(Z_ARRVAL_P(array_value));

		while (zend_hash_get_current_data(Z_ARRVAL_P(array_value), (void **)&entry) == SUCCESS) {
			SEPARATE_ZVAL(entry);
			convert_to_string_ex(entry);

			if (zend_hash_get_current_key_ex(Z_ARRVAL_P(array_value), &string_key, &string_key_len, &idx, 0, NULL) != HASH_KEY_IS_STRING) {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid parameter array");
				RETURN_FALSE;
			}

			ALLOC_ZVAL(new_string);
			Z_ADDREF_PP(entry);
			COPY_PZVAL_TO_ZVAL(*new_string, *entry);

			zend_hash_update(intern->parameter, string_key, string_key_len, &new_string, sizeof(zval*), NULL);
			zend_hash_move_forward(Z_ARRVAL_P(array_value));
		}
		RETURN_TRUE;

	} else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "sss", &namespace, &namespace_len, &name, &name_len, &value, &value_len) == SUCCESS) {

		intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);

		MAKE_STD_ZVAL(new_string);
		ZVAL_STRING(new_string, value, 1);

		zend_hash_update(intern->parameter, name, name_len + 1, &new_string, sizeof(zval*), NULL);
		RETURN_TRUE;
	} else {
		WRONG_PARAM_COUNT;
	}

}
/* }}} end xsl_xsltprocessor_set_parameter */

/* {{{ proto string xsl_xsltprocessor_get_parameter(string namespace, string name);
*/
PHP_FUNCTION(xsl_xsltprocessor_get_parameter)
{
	zval *id;
	int name_len = 0, namespace_len = 0;
	char *name, *namespace;
	zval **value;
	xsl_object *intern;

	DOM_GET_THIS(id);

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &namespace, &namespace_len, &name, &name_len) == FAILURE) {
		RETURN_FALSE;
	}
	intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);
	if ( zend_hash_find(intern->parameter, name, name_len + 1,  (void**) &value) == SUCCESS) {
		convert_to_string_ex(value);
		RETVAL_STRING(Z_STRVAL_PP(value),1);
	} else {
		RETURN_FALSE;
	}
}
/* }}} end xsl_xsltprocessor_get_parameter */

/* {{{ proto bool xsl_xsltprocessor_remove_parameter(string namespace, string name);
*/
PHP_FUNCTION(xsl_xsltprocessor_remove_parameter)
{
	zval *id;
	int name_len = 0, namespace_len = 0;
	char *name, *namespace;
	xsl_object *intern;

	DOM_GET_THIS(id);

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &namespace, &namespace_len, &name, &name_len) == FAILURE) {
		RETURN_FALSE;
	}
	intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);
	if ( zend_hash_del(intern->parameter, name, name_len + 1) == SUCCESS) {
		RETURN_TRUE;
	} else {
		RETURN_FALSE;
	}
}
/* }}} end xsl_xsltprocessor_remove_parameter */

/* {{{ proto void xsl_xsltprocessor_register_php_functions([mixed $restrict]);
*/
PHP_FUNCTION(xsl_xsltprocessor_register_php_functions)
{
	zval *id;
	xsl_object *intern;
	zval *array_value, **entry, *new_string;
	int  name_len = 0;
	char *name;

	DOM_GET_THIS(id);

	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "a",  &array_value) == SUCCESS) {
		intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);
		zend_hash_internal_pointer_reset(Z_ARRVAL_P(array_value));

		while (zend_hash_get_current_data(Z_ARRVAL_P(array_value), (void **)&entry) == SUCCESS) {
			SEPARATE_ZVAL(entry);
			convert_to_string_ex(entry);

			MAKE_STD_ZVAL(new_string);
			ZVAL_LONG(new_string,1);

			zend_hash_update(intern->registered_phpfunctions, Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, &new_string, sizeof(zval*), NULL);
			zend_hash_move_forward(Z_ARRVAL_P(array_value));
		}
		intern->registerPhpFunctions = 2;

	} else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "s",  &name, &name_len) == SUCCESS) {
		intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);

		MAKE_STD_ZVAL(new_string);
		ZVAL_LONG(new_string,1);
		zend_hash_update(intern->registered_phpfunctions, name, name_len + 1, &new_string, sizeof(zval*), NULL);
		intern->registerPhpFunctions = 2;

	} else {
		intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);
		intern->registerPhpFunctions = 1;
	}

}
/* }}} end xsl_xsltprocessor_register_php_functions(); */

/* {{{ proto bool xsl_xsltprocessor_set_profiling(string filename) */
PHP_FUNCTION(xsl_xsltprocessor_set_profiling)
{
	zval *id;
	xsl_object *intern;
	char *filename = NULL;
	int filename_len;
	DOM_GET_THIS(id);

	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "p!", &filename, &filename_len) == SUCCESS) {
		intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);
		if (intern->profiling) {
			efree(intern->profiling);
		}
		if (filename != NULL) {
			intern->profiling = estrndup(filename,filename_len);
		} else {
			intern->profiling = NULL;
		}
		RETURN_TRUE;
	} else {
		WRONG_PARAM_COUNT;
	}
}
/* }}} end xsl_xsltprocessor_set_profiling */

/* {{{ proto long xsl_xsltprocessor_set_security_prefs(long securityPrefs) */
PHP_FUNCTION(xsl_xsltprocessor_set_security_prefs)
{
	zval *id;
	xsl_object *intern;
	long securityPrefs, oldSecurityPrefs;

	DOM_GET_THIS(id);
 	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &securityPrefs) == FAILURE) {
		return;
	}
	intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);
	oldSecurityPrefs = intern->securityPrefs;
	intern->securityPrefs = securityPrefs;
	/* set this to 1 so that we know, it was set through this method. Can be removed, when we remove the ini setting */
	intern->securityPrefsSet = 1;
	RETURN_LONG(oldSecurityPrefs);
}
/* }}} end xsl_xsltprocessor_set_security_prefs */

/* {{{ proto long xsl_xsltprocessor_get_security_prefs() */
PHP_FUNCTION(xsl_xsltprocessor_get_security_prefs)
{
	zval *id;
	xsl_object *intern;

	DOM_GET_THIS(id);
	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "") == SUCCESS) {
		intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC);
		RETURN_LONG(intern->securityPrefs);
	} else {
		WRONG_PARAM_COUNT;
	}
}
/* }}} end xsl_xsltprocessor_get_security_prefs */

/* {{{ proto bool xsl_xsltprocessor_has_exslt_support();
*/
PHP_FUNCTION(xsl_xsltprocessor_has_exslt_support)
{
#if HAVE_XSL_EXSLT
	RETURN_TRUE;
#else
	RETURN_FALSE;
#endif
}
/* }}} end xsl_xsltprocessor_has_exslt_support(); */

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


text:
// Copyright (c) Dapplo and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using Dapplo.ActiveDirectory.Entities;
using Dapplo.ActiveDirectory.Enums;

namespace Dapplo.ActiveDirectory.Tests.Entities;

/// <summary>
///     Simple predefined object for user information
/// </summary>
public interface IUser : IAdObject
{
	[AdProperty(UserProperties.DisplayName)]
	string DisplayName { get; set; }

	[AdProperty(UserProperties.DistinguishedName)]
	string DistinguishedName { get; set; }

	[AdProperty(UserProperties.MemberOfGroups)]
	IList<DistinguishedName> Groups { get; set; }

	[AdProperty(UserProperties.Surname)]
	string Name { get; set; }

	[AdProperty(UserProperties.TelephoneNumber)]
	string TelephoneNumber { get; set; }

	[AdProperty(UserProperties.Thumbnail)]
	byte[] Thumbnail { get; set; }

	[AdProperty(UserProperties.AccountExpires)]
	DateTimeOffset? AccountExpires { get; set; }
}

redpajama_set_name: RedPajamaGithub


text:
<#
    DESCRIPTION:
        Check binding order is set correctly for "Production" as the primary network adapter then as applicable for other interfaces.
        If no "Production" adapter is found, then "Management" should be first.

    REQUIRED-INPUTS:
        ManagementAdapterNames - "LIST" - Names or partial names of Management network adapters
        ProductionAdapterNames - "LIST" - Names or partial names of Production network adapters

    DEFAULT-VALUES:
        ManagementAdapterNames = @('Management', 'MGMT', 'MGT')
        ProductionAdapterNames = @('Production', 'PROD', 'PRD')

    DEFAULT-STATE:
        Enabled

    RESULTS:
        PASS:
            Binding order correctly set
        WARNING:
        FAIL:
            No network adapters found
            Production or management adapters not listed
            Binding order incorrect, {name} should be first
            Registry setting not found
        MANUAL:
        NA:

    APPLIES:
        All Servers

    REQUIRED-FUNCTIONS:
        None
#>

Function net-04-binding-order
{
    $result        = newResult
    $result.server = $env:ComputerName
    $result.name   = $script:lang['Name']
    $result.check  = 'net-04-binding-order'

    #... CHECK STARTS HERE ...#

    Try
    {
        [System.Collections.ArrayList]$BindOrder = @()
        [System.Collections.ArrayList]$BindList  = @((Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\TcpIp\Linkage' -Name 'Bind' -ErrorAction SilentlyContinue).'Bind')
        If ($BindList.Count -gt 0)
        {
            $BindList | ForEach-Object -Process {
                [string]$DeviceID = "{$($_.Split('{')[1])"
                [object]$gCIMi    = (Get-CimInstance -ClassName 'Win32_NetworkAdapter' -Filter "GUID='$DeviceID'" -Property 'NetConnectionID' -ErrorAction SilentlyContinue)

                If ([string]::IsNullOrEmpty($gCIMi) -eq $false)
                {
                    [void]$BindOrder.Add($($gCIMi.NetConnectionID))
                    $result.data     += "$($gCIMi.NetConnectionID),#"
                }
            }
        }
        Else
        {
            $result.result  = $script:lang['Fail']
            $result.message = $script:lang['f001']
            $result.data    = ''
            Return $result
        }

        [boolean]$prodExists = $false
        [boolean]$mgmtExists = $false

        If ($BindOrder.Count -eq 0)
        {
            $result.result  = $script:lang['Fail']
            $result.message = $script:lang['f002']
            $result.data    = ''
        }
        Else
        {
            # Check if 'Production' actually exists
            $script:chkValues['ProductionAdapterNames'] | ForEach-Object -Process {
                # Check if first binding is 'Production'
                If ($BindOrder[0] -like "$_*" )
                {
                    $prodExists     = $true
                    $result.result  = $script:lang['Pass']
                    $result.message = $script:lang['p001']
                }
                ElseIf ($BindOrder -like "$_*")
                {
                    $prodExists     =    $true
                    $result.result  =    $script:lang['Fail']
                    $result.message = ($($script:lang['f003']) -f $script:chkValues['ProductionAdapterNames'][0])
                }
            }

            If ($prodExists -eq $false)
            {
                # No 'Production', check for 'Management'
                $script:chkValues['ManagementAdapterNames'] | ForEach-Object -Process {
                    # Check if first binding is 'Management'
                    If ($BindOrder[0] -like "$_*")
                    {
                        $mgmtExists     = $true
                        $result.result  = $script:lang['Pass']
                        $result.message = $script:lang['p001']
                    }
                    ElseIf ($BindOrder -like "$_*")
                    {
                        $mgmtExists     =    $true
                        $result.result  =    $script:lang['Fail']
                        $result.message = ($($script:lang['f003']) -f $script:chkValues['ManagementAdapterNames'][0])
                    }
                }
            }
        }

        If (($prodExists -eq $false) -and ($mgmtExists -eq $false))
        {
            $result.result  = $script:lang['Fail']
            $result.message = $script:lang['f002']
        }
    }
    Catch
    {
        $result.result  = $script:lang['Error']
        $result.message = $script:lang['Script-Error']
        $result.data    = $_.Exception.Message
    }

    Return $result
}


text:
import FontIcon from "components/Icon/FontIcon";
import { FormattedMessage } from "react-intl";

const SampleDataMessage = () => (
  <span style={styles.warntext} data-qa="sample-data-message">
    <FontIcon type="WarningSolid" style={styles.iconStyle} />
    <FormattedMessage id="Dataset.SampleDatasetWarn" />
  </span>
);

export default SampleDataMessage;

const styles = {
  warntext: {
    display: "inline-flex",
    alignItems: "center",
    userSelect: "text",
  },
  iconStyle: {
    height: 24,
  },
};


text:
<?
session_start();
$idusuario = $_SESSION["idusuario"];
$nombre_usuario = $_SESSION["nombre_usuario"];
$apellido_usuario = $_SESSION["apellido_usuario"];

require_once('conexion/conexion.php');

$category=$_POST['category'];
$subcategory=$_POST['subcategory'];
$nombre=$_POST['nombre'];
$descripcion=$_POST['descripcion'];
$monto=$_POST['monto'];
$cantidad=$_POST['cantidad'];

$condicion=$_POST['condicion'];
$foto=$_POST['file'];

$hoy = date("Y-m-d");

// $numUploadedfileses la cantidad de fotos que hay subidas
$numUploadedfiles = count($_FILES['file']['name']);

if($numUploadedfiles>8){$numUploadedfiles=8;}

$query2 = "INSERT INTO producto (usuario_idusuario,fecha_ingreso,nombre_producto,descripcion_producto,categoria_idcategoria,monto_producto,cantidad_producto,condicion_producto,tipo_producto_idtipo_producto,puntuacion,cant_fotos) VALUES ('$idusuario','$hoy','$nombre','$descripcion','$category','$monto','$cantidad','$condicion','$subcategory','','$numUploadedfiles')";
mysqli_query($db, $query2) or die(mysqli_error($db));

$id=mysqli_insert_id($db);

// crear carpeta si no existe  ... $id es el id del producto agregado
$carpetaDestino = 'fotos/'.$idusuario.'/producto/'.$id.'/';
if (!file_exists($carpetaDestino)) { mkdir($carpetaDestino, 0777, true);}

# si hay algun archivo que subir
if($_FILES["file"]["name"][0])
{
	# recorremos todos los arhivos que se han subido
	for($i=0;$i<$numUploadedfiles;$i++)
	{
		# si es un formato de imagen
		if($_FILES["file"]["type"][$i]=="image/jpeg" || $_FILES["file"]["type"][$i]=="image/pjpeg" || $_FILES["file"]["type"][$i]=="image/gif" || $_FILES["file"]["type"][$i]=="image/png")
		{
			$origen=$_FILES["file"]["tmp_name"][$i];
			$destino=$carpetaDestino.$_FILES["file"]["name"][$i];

 			# movemos el archivo
			@move_uploaded_file($origen, $destino);

				if($i==0){$index1=1;}else{$index1='';}

				$tipo_imagen=$_FILES["file"]["type"][$i];

				// grabar compra
				$query = "INSERT INTO fotos_productos (producto_idproducto,tipo_imagen,index1,index2,ruta_fotos) VALUES ('$id','$tipo_imagen','$index1','','$destino')";
				mysqli_query($db, $query) or die(mysqli_error($db));

         }

	}

}
?>
<script>
	history.back(-1);
</script>


text:
FROM debian:jessie

MAINTAINER Thomas Debost <t@tomdeb.org>

COPY ./apt_sources.list /etc/apt/sources.list

RUN  apt update && \
     DEBIAN_FRONTEND=noninteractive apt-get install -yq --no-install-recommends cacti cacti-spine

RUN  apt install -yq snmp-mibs-downloader && \
     download-mibs

COPY ./root.crontab /root/crontab
RUN apt-get install -yq --no-install-recommends cron && \
    crontab < /root/crontab

RUN rm /usr/share/cacti/site/include/config.php

COPY ./cacti_debian.php /usr/share/cacti/site/include/config.php
RUN chmod 640 /usr/share/cacti/site/include/config.php && \
    chgrp www-data /usr/share/cacti/site/include/config.php

COPY ./cacti_spine.conf /etc/cacti/spine.conf

COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

ENTRYPOINT /entrypoint.sh


text:
export * from './events';
export * from './model';


text:
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var open = require('gulp-open');
var license = require('gulp-license');

function isArray (arr) {
	return typeof path == 'object' && path.hasOwnProperty('length');
}

function genFile (path, filename, shouldUglify, dist) {
	var fileList = [];
	if (isArray(path)) {
		fileList = path;
	} else {
		fileList.push(path);
	}
	var file = gulp.src(fileList);
	if (shouldUglify) {
		file
		.pipe(concat(filename.replace('.js', '.min.js')))
		.pipe(uglify())
		.pipe(gulp.dest(dist));
	}
	file
	.pipe(concat(filename))
	.pipe(gulp.dest(dist));
}

gulp.task('build', function () {
    genFile('./src/angular-json-explorer.js', 'angular-json-explorer.js', true, './dist');
    genFile('./src/angular-json-explorer.css', 'angular-json-explorer.css', false, './dist');
});

gulp.task('run', function () {
	gulp.src('./demo/demo.html')
	.pipe(open('<%file.path%>'));
});

gulp.task('default', ['build', 'run']);


text:
layout: episode
permalink: /stops/20/
type: stop
section_title: Dia a dia na Vila
title: A presença de artistas de circo na Vila Itororó
page_rank: 20
stop_id: 20
audio_file: 20.mp3
hero_images:
 - path: 2001.jpg
   alt_text: foto Marina Klautau
---


text:
SensibleData-Apps-DataViewer
============================


text:
package bamboo.task;

public class Linktext {
    private float pagerank;
    private String caption;

    public float getPagerank() {
        return pagerank;
    }

    public void setPagerank(float pagerank) {
        this.pagerank = pagerank;
    }

    public String getCaption() {
        return caption;
    }

    public void setCaption(String caption) {
        this.caption = caption;
    }
}


text:
CK_VISIBLE_PUBLIC HCkDirTree CkDirTree_Create(void);
CK_VISIBLE_PUBLIC void CkDirTree_Dispose(HCkDirTree handle);
CK_VISIBLE_PUBLIC void CkDirTree_getBaseDir(HCkDirTree cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkDirTree_putBaseDir(HCkDirTree cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkDirTree_baseDir(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC void CkDirTree_getDebugLogFilePath(HCkDirTree cHandle, HCkString retval);
CK_VISIBLE_PUBLIC void CkDirTree_putDebugLogFilePath(HCkDirTree cHandle, const char *newVal);
CK_VISIBLE_PUBLIC const char *CkDirTree_debugLogFilePath(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC BOOL CkDirTree_getDoneIterating(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC int CkDirTree_getFileSize32(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC __int64 CkDirTree_getFileSize64(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC void CkDirTree_getFullPath(HCkDirTree cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkDirTree_fullPath(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC void CkDirTree_getFullUncPath(HCkDirTree cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkDirTree_fullUncPath(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC BOOL CkDirTree_getIsDirectory(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC void CkDirTree_getLastErrorHtml(HCkDirTree cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkDirTree_lastErrorHtml(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC void CkDirTree_getLastErrorText(HCkDirTree cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkDirTree_lastErrorText(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC void CkDirTree_getLastErrorXml(HCkDirTree cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkDirTree_lastErrorXml(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC BOOL CkDirTree_getRecurse(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC void CkDirTree_putRecurse(HCkDirTree cHandle, BOOL newVal);
CK_VISIBLE_PUBLIC void CkDirTree_getRelativePath(HCkDirTree cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkDirTree_relativePath(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC BOOL CkDirTree_getUtf8(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC void CkDirTree_putUtf8(HCkDirTree cHandle, BOOL newVal);
CK_VISIBLE_PUBLIC BOOL CkDirTree_getVerboseLogging(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC void CkDirTree_putVerboseLogging(HCkDirTree cHandle, BOOL newVal);
CK_VISIBLE_PUBLIC void CkDirTree_getVersion(HCkDirTree cHandle, HCkString retval);
CK_VISIBLE_PUBLIC const char *CkDirTree_version(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC BOOL CkDirTree_AdvancePosition(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC BOOL CkDirTree_BeginIterate(HCkDirTree cHandle);
CK_VISIBLE_PUBLIC BOOL CkDirTree_SaveLastError(HCkDirTree cHandle, const char *path);
#endif


text:
namespace eja
{
	class entity;
	class chat_request_data;

	class chat_command final : public entity_command
	{
		make_factory(chat_command);

	private:
		// Utility
		bool validate(const std::shared_ptr<client_request_message>& request_message, const std::shared_ptr<chat_request_data>& request_data) const;

	public:
		chat_command() { }
		chat_command(const std::shared_ptr<entity>& entity) : entity_command(entity) { }

		// Interface
		std::shared_ptr<group_request_message> execute(const std::string& text) const;
		std::shared_ptr<group_request_message> execute(const std::shared_ptr<entity>& entity, const std::string& text) const;
		void execute(const std::shared_ptr<client_request_message>& request_message, const std::shared_ptr<chat_request_data>& request_data) const;

		// Static
		static ptr create(const std::shared_ptr<entity>& entity) { return std::make_shared<chat_command>(entity); }
	};
}

#endif


text:
const URL = "http://mochi.test:8888/browser/browser/components/thumbnails/" +
            "test/background_red_redirect.sjs";

/**
 * These tests ensure that we save and provide thumbnails for redirecting sites.
 */
function runTests() {
  // Kick off history by loading a tab first or the test fails in single mode.
  yield addTab(URL);
  gBrowser.removeTab(gBrowser.selectedTab);

  // Create a tab, redirecting to a page with a red background.
  yield addTab(URL);
  yield captureAndCheckColor(255, 0, 0, "we have a red thumbnail");

  // Wait until the referrer's thumbnail's file has been written.
  yield whenFileExists(URL);
  yield checkThumbnailColor(URL, 255, 0, 0, "referrer has a red thumbnail");
}

function whenFileExists(aURL) {
  let callback = next;

  let file = PageThumbsStorage.getFileForURL(aURL);
  if (!file.exists())
    callback = function () whenFileExists(aURL);

  executeSoon(callback);
}


text:
package com.intellij.openapi.vcs.ex;

import com.intellij.codeInsight.hint.EditorFragmentComponent;
import com.intellij.codeInsight.hint.EditorHintListener;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.diff.DiffContentFactory;
import com.intellij.diff.DiffManager;
import com.intellij.diff.comparison.ByWord;
import com.intellij.diff.comparison.ComparisonPolicy;
import com.intellij.diff.contents.DiffContent;
import com.intellij.diff.contents.DocumentContent;
import com.intellij.diff.fragments.DiffFragment;
import com.intellij.diff.requests.SimpleDiffRequest;
import com.intellij.diff.util.DiffDrawUtil;
import com.intellij.diff.util.DiffUtil;
import com.intellij.diff.util.TextDiffType;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory;
import com.intellij.openapi.editor.highlighter.FragmentedEditorHighlighter;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.PlainTextFileType;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.progress.util.BackgroundTaskUtil;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vcs.VcsApplicationSettings;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.*;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;

import static com.intellij.diff.util.DiffUtil.getDiffType;
import static com.intellij.diff.util.DiffUtil.getLineCount;

public abstract class LineStatusMarkerPopupRenderer extends LineStatusMarkerRenderer {
  public LineStatusMarkerPopupRenderer(@NotNull LineStatusTrackerBase<?> tracker) {
    super(tracker);
  }

  @Override
  protected boolean canDoAction(@NotNull Editor editor, @NotNull List<? extends Range> ranges, @NotNull MouseEvent e) {
    return isInsideMarkerArea(e);
  }

  @Override
  protected void doAction(@NotNull Editor editor, @NotNull List<? extends Range> ranges, @NotNull MouseEvent e) {
    Range range = ranges.get(0);
    if (ranges.size() > 1) {
      scrollAndShow(editor, range);
    }
    else {
      showHint(editor, range, e);
    }
  }

  @NotNull
  protected abstract List<AnAction> createToolbarActions(@NotNull Editor editor, @NotNull Range range, @Nullable Point mousePosition);

  @NotNull
  protected FileType getFileType() {
    return PlainTextFileType.INSTANCE;
  }

  protected boolean isShowInnerDifferences() {
    return VcsApplicationSettings.getInstance().SHOW_LST_WORD_DIFFERENCES;
  }

  @Nullable
  protected JComponent createAdditionalInfoPanel(@NotNull Editor editor,
                                                 @NotNull Range range,
                                                 @Nullable Point mousePosition,
                                                 @NotNull Disposable disposable) {
    return null;
  }

  public void scrollAndShow(@NotNull Editor editor, @NotNull Range range) {
    if (!myTracker.isValid()) return;
    final Document document = myTracker.getDocument();
    int line = Math.min(range.getType() == Range.DELETED ? range.getLine2() : range.getLine2() - 1, getLineCount(document) - 1);
    final int lastOffset = document.getLineStartOffset(line);
    editor.getCaretModel().moveToOffset(lastOffset);
    editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);

    showAfterScroll(editor, range);
  }

  public void showAfterScroll(@NotNull Editor editor, @NotNull Range range) {
    editor.getScrollingModel().runActionOnScrollingFinished(() -> {
      Range newRange = myTracker.findRange(range);
      if (newRange != null) showHintAt(editor, newRange, null);
    });
  }

  public void showHint(@NotNull Editor editor, @NotNull Range range, @NotNull MouseEvent e) {
    final JComponent comp = (JComponent)e.getComponent(); // shall be EditorGutterComponent, cast is safe.
    final JLayeredPane layeredPane = comp.getRootPane().getLayeredPane();
    final Point point = SwingUtilities.convertPoint(comp, ((EditorEx)editor).getGutterComponentEx().getWidth(), e.getY(), layeredPane);
    showHintAt(editor, range, point);
    e.consume();
  }

  public void showHintAt(@NotNull Editor editor, @NotNull Range range, @Nullable Point mousePosition) {
    if (!myTracker.isValid()) return;
    final Disposable disposable = Disposer.newDisposable();

    FileType fileType = getFileType();
    List<DiffFragment> wordDiff = computeWordDiff(range);

    installMasterEditorHighlighters(editor, range, wordDiff, disposable);
    JComponent editorComponent = createEditorComponent(editor, range, fileType, wordDiff);

    ActionToolbar toolbar = buildToolbar(editor, range, mousePosition, disposable);
    toolbar.updateActionsImmediately(); // we need valid ActionToolbar.getPreferredSize() to calc size of popup
    toolbar.setReservePlaceAutoPopupIcon(false);

    JComponent additionalInfoPanel = createAdditionalInfoPanel(editor, range, mousePosition, disposable);

    PopupPanel popupPanel = new PopupPanel(editor, toolbar, editorComponent, additionalInfoPanel);

    LightweightHint hint = new LightweightHint(popupPanel);
    HintListener closeListener = new HintListener() {
      @Override
      public void hintHidden(@NotNull final EventObject event) {
        Disposer.dispose(disposable);
      }
    };
    hint.addHintListener(closeListener);

    int line = editor.getCaretModel().getLogicalPosition().line;
    Point point = HintManagerImpl.getHintPosition(hint, editor, new LogicalPosition(line, 0), HintManager.UNDER);
    if (mousePosition != null) { // show right after the nearest line
      int lineHeight = editor.getLineHeight();
      int delta = (point.y - mousePosition.y) % lineHeight;
      if (delta < 0) delta += lineHeight;
      point.y = mousePosition.y + delta;
    }
    point.x -= popupPanel.getEditorTextOffset(); // align main editor with the one in popup

    int flags = HintManager.HIDE_BY_CARET_MOVE | HintManager.HIDE_BY_TEXT_CHANGE | HintManager.HIDE_BY_SCROLLING;
    HintManagerImpl.getInstanceImpl().showEditorHint(hint, editor, point, flags, -1, false, new HintHint(editor, point));

    ApplicationManager.getApplication().getMessageBus().connect(disposable)
      .subscribe(EditorHintListener.TOPIC, (project, newHint, newHintFlags) -> {
        // Ex: if popup re-shown by ToggleByWordDiffAction
        if (newHint.getComponent() instanceof PopupPanel) {
          PopupPanel newPopupPanel = (PopupPanel)newHint.getComponent();
          if (newPopupPanel.getEditor().equals(editor)) {
            hint.hide();
          }
        }
      });

    if (!hint.isVisible()) {
      closeListener.hintHidden(new EventObject(hint));
    }
  }

  @Nullable
  private List<DiffFragment> computeWordDiff(@NotNull Range range) {
    if (!isShowInnerDifferences()) return null;
    if (range.getType() != Range.MODIFIED) return null;

    final CharSequence vcsContent = getVcsContent(range);
    final CharSequence currentContent = getCurrentContent(range);

    return BackgroundTaskUtil.tryComputeFast(
      indicator -> ByWord.compare(vcsContent, currentContent, ComparisonPolicy.DEFAULT, indicator), 200);
  }

  private void installMasterEditorHighlighters(@NotNull Editor editor,
                                               @NotNull Range range,
                                               @Nullable List<DiffFragment> wordDiff,
                                               @NotNull Disposable parentDisposable) {
    if (wordDiff == null) return;
    final List<RangeHighlighter> highlighters = new ArrayList<>();

    int currentStartShift = getCurrentTextRange(range).getStartOffset();
    for (DiffFragment fragment : wordDiff) {
      int currentStart = currentStartShift + fragment.getStartOffset2();
      int currentEnd = currentStartShift + fragment.getEndOffset2();
      TextDiffType type = getDiffType(fragment);

      highlighters.addAll(DiffDrawUtil.createInlineHighlighter(editor, currentStart, currentEnd, type));
    }

    Disposer.register(parentDisposable, () -> highlighters.forEach(RangeMarker::dispose));
  }

  @Nullable
  private JComponent createEditorComponent(@NotNull Editor editor,
                                           @NotNull Range range,
                                           @Nullable FileType fileType,
                                           @Nullable List<DiffFragment> wordDiff) {
    if (range.getType() == Range.INSERTED) return null;

    TextRange vcsTextRange = getVcsTextRange(range);
    String content = getVcsContent(range).toString();

    EditorHighlighterFactory highlighterFactory = EditorHighlighterFactory.getInstance();
    EditorHighlighter highlighter = highlighterFactory.createEditorHighlighter(myTracker.getProject(), getFileName(myTracker.getDocument()));
    highlighter.setText(myTracker.getVcsDocument().getImmutableCharSequence());
    FragmentedEditorHighlighter fragmentedHighlighter = new FragmentedEditorHighlighter(highlighter, vcsTextRange);

    Color backgroundColor = EditorFragmentComponent.getBackgroundColor(editor, true);

    EditorTextField field = new EditorTextField(content);
    field.setBorder(null);
    field.setOneLineMode(false);
    field.ensureWillComputePreferredSize();
    field.setFontInheritedFromLAF(false);

    field.addSettingsProvider(uEditor -> {
      uEditor.setVerticalScrollbarVisible(true);
      uEditor.setHorizontalScrollbarVisible(true);

      uEditor.setRendererMode(true);
      uEditor.setBorder(null);

      uEditor.setColorsScheme(editor.getColorsScheme());
      uEditor.setBackgroundColor(backgroundColor);
      uEditor.getSettings().setCaretRowShown(false);

      uEditor.getSettings().setTabSize(editor.getSettings().getTabSize(editor.getProject()));
      uEditor.getSettings().setUseTabCharacter(editor.getSettings().isUseTabCharacter(editor.getProject()));

      uEditor.setHighlighter(fragmentedHighlighter);

      if (wordDiff != null) {
        for (DiffFragment fragment : wordDiff) {
          int vcsStart = fragment.getStartOffset1();
          int vcsEnd = fragment.getEndOffset1();
          TextDiffType type = getDiffType(fragment);

          DiffDrawUtil.createInlineHighlighter(uEditor, vcsStart, vcsEnd, type);
        }
      }
    });

    JPanel panel = JBUI.Panels.simplePanel(field);
    panel.setBorder(EditorFragmentComponent.createEditorFragmentBorder(editor));
    panel.setBackground(backgroundColor);

    DataManager.registerDataProvider(panel, data -> {
      if (CommonDataKeys.HOST_EDITOR.is(data)) {
        return field.getEditor();
      }
      return null;
    });

    return panel;
  }

  private static String getFileName(@NotNull Document document) {
    final VirtualFile file = FileDocumentManager.getInstance().getFile(document);
    if (file == null) return "";
    return file.getName();
  }

  @NotNull
  private ActionToolbar buildToolbar(@NotNull Editor editor,
                                     @NotNull Range range,
                                     @Nullable Point mousePosition,
                                     @NotNull Disposable parentDisposable) {
    List<AnAction> actions = createToolbarActions(editor, range, mousePosition);

    JComponent editorComponent = editor.getComponent();
    for (AnAction action : actions) {
      DiffUtil.registerAction(action, editorComponent);
    }

    Disposer.register(parentDisposable, new Disposable() {
      @Override
      public void dispose() {
        ActionUtil.getActions(editorComponent).removeAll(actions);
      }
    });

    return ActionManager.getInstance().createActionToolbar(ActionPlaces.TOOLBAR, new DefaultActionGroup(actions), true);
  }

  private static class PopupPanel extends JPanel {
    @Nullable private final JComponent myEditorComponent;
    @NotNull private final Editor myEditor;

    PopupPanel(@NotNull Editor editor,
               @NotNull ActionToolbar toolbar,
               @Nullable JComponent editorComponent,
               @Nullable JComponent additionalInfo) {
      super(new BorderLayout());
      setOpaque(false);

      myEditor = editor;
      myEditorComponent = editorComponent;
      boolean isEditorVisible = myEditorComponent != null;

      Color borderColor = new JBColor(Gray._206, Gray._75);

      JComponent toolbarComponent = toolbar.getComponent();
      toolbarComponent.setBorder(null);

      JComponent toolbarPanel = JBUI.Panels.simplePanel(toolbarComponent);
      Border outsideToolbarBorder = JBUI.Borders.customLine(borderColor, 1, 1, isEditorVisible ? 0 : 1, 1);
      Border insideToolbarBorder = JBUI.Borders.empty(1, 5);
      toolbarPanel.setBorder(BorderFactory.createCompoundBorder(outsideToolbarBorder, insideToolbarBorder));

      if (additionalInfo != null) {
        toolbarPanel.add(additionalInfo, BorderLayout.EAST);
      }

      if (myEditorComponent != null) {
        // default border of EditorFragmentComponent is replaced here with our own.
        Border outsideEditorBorder = JBUI.Borders.customLine(borderColor, 1);
        Border insideEditorBorder = JBUI.Borders.empty(2);
        myEditorComponent.setBorder(BorderFactory.createCompoundBorder(outsideEditorBorder, insideEditorBorder));
      }

      // 'empty space' to the right of toolbar
      JPanel emptyPanel = new JPanel();
      emptyPanel.setOpaque(false);
      emptyPanel.setPreferredSize(new Dimension());

      JPanel topPanel = new JPanel(new BorderLayout());
      topPanel.setOpaque(false);
      topPanel.add(toolbarPanel, BorderLayout.WEST);
      topPanel.add(emptyPanel, BorderLayout.CENTER);

      add(topPanel, BorderLayout.NORTH);
      if (myEditorComponent != null) add(myEditorComponent, BorderLayout.CENTER);

      // transfer clicks into editor
      MouseAdapter listener = new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
          transferEvent(e, editor);
        }

        @Override
        public void mouseClicked(MouseEvent e) {
          transferEvent(e, editor);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
          transferEvent(e, editor);
        }
      };
      emptyPanel.addMouseListener(listener);
    }

    @NotNull
    public Editor getEditor() {
      return myEditor;
    }

    private static void transferEvent(MouseEvent e, Editor editor) {
      editor.getContentComponent().dispatchEvent(SwingUtilities.convertMouseEvent(e.getComponent(), e, editor.getContentComponent()));
    }

    public int getEditorTextOffset() {
      return EditorFragmentComponent.createEditorFragmentBorder(myEditor).getBorderInsets(myEditorComponent).left;
    }
  }

  @NotNull
  private CharSequence getCurrentContent(Range range) {
    return DiffUtil.getLinesContent(myTracker.getDocument(), range.getLine1(), range.getLine2());
  }

  @NotNull
  private CharSequence getVcsContent(Range range) {
    return DiffUtil.getLinesContent(myTracker.getVcsDocument(), range.getVcsLine1(), range.getVcsLine2());
  }

  @NotNull
  private TextRange getCurrentTextRange(@NotNull Range range) {
    return DiffUtil.getLinesRange(myTracker.getDocument(), range.getLine1(), range.getLine2());
  }

  @NotNull
  private TextRange getVcsTextRange(@NotNull Range range) {
    return DiffUtil.getLinesRange(myTracker.getVcsDocument(), range.getVcsLine1(), range.getVcsLine2());
  }

  protected abstract class RangeMarkerAction extends DumbAwareAction {
    @NotNull private final Range myRange;
    @NotNull private final Editor myEditor;

    public RangeMarkerAction(@NotNull Editor editor, @NotNull Range range, @Nullable String actionId) {
      myRange = range;
      myEditor = editor;
      if (actionId != null) ActionUtil.copyFrom(this, actionId);
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
      Range newRange = myTracker.findRange(myRange);
      e.getPresentation().setEnabled(newRange != null && !myEditor.isDisposed() && isEnabled(myEditor, newRange));
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      Range newRange = myTracker.findRange(myRange);
      if (newRange != null) actionPerformed(myEditor, newRange);
    }

    protected abstract boolean isEnabled(@NotNull Editor editor, @NotNull Range range);

    protected abstract void actionPerformed(@NotNull Editor editor, @NotNull Range range);
  }

  public class ShowNextChangeMarkerAction extends RangeMarkerAction {
    public ShowNextChangeMarkerAction(@NotNull Editor editor, @NotNull Range range) {
      super(editor, range, "VcsShowNextChangeMarker");
    }

    @Override
    protected boolean isEnabled(@NotNull Editor editor, @NotNull Range range) {
      return myTracker.getNextRange(range.getLine1()) != null;
    }

    @Override
    protected void actionPerformed(@NotNull Editor editor, @NotNull Range range) {
      Range targetRange = myTracker.getNextRange(range.getLine1());
      if (targetRange != null) LineStatusMarkerPopupRenderer.this.scrollAndShow(editor, targetRange);
    }
  }

  public class ShowPrevChangeMarkerAction extends RangeMarkerAction {
    public ShowPrevChangeMarkerAction(@NotNull Editor editor, @NotNull Range range) {
      super(editor, range, "VcsShowPrevChangeMarker");
    }

    @Override
    protected boolean isEnabled(@NotNull Editor editor, @NotNull Range range) {
      return myTracker.getPrevRange(range.getLine1()) != null;
    }

    @Override
    protected void actionPerformed(@NotNull Editor editor, @NotNull Range range) {
      Range targetRange = myTracker.getPrevRange(range.getLine1());
      if (targetRange != null) LineStatusMarkerPopupRenderer.this.scrollAndShow(editor, targetRange);
    }
  }

  public class CopyLineStatusRangeAction extends RangeMarkerAction {
    public CopyLineStatusRangeAction(@NotNull Editor editor, @NotNull Range range) {
      super(editor, range, IdeActions.ACTION_COPY);
    }

    @Override
    protected boolean isEnabled(@NotNull Editor editor, @NotNull Range range) {
      return Range.DELETED == range.getType() || Range.MODIFIED == range.getType();
    }

    @Override
    protected void actionPerformed(@NotNull Editor editor, @NotNull Range range) {
      final String content = getVcsContent(range) + "\n";
      CopyPasteManager.getInstance().setContents(new StringSelection(content));
    }
  }

  public class ShowLineStatusRangeDiffAction extends RangeMarkerAction {
    public ShowLineStatusRangeDiffAction(@NotNull Editor editor, @NotNull Range range) {
      super(editor, range, IdeActions.ACTION_SHOW_DIFF_COMMON);
    }

    @Override
    protected boolean isEnabled(@NotNull Editor editor, @NotNull Range range) {
      return true;
    }

    @Override
    protected void actionPerformed(@NotNull Editor editor, @NotNull Range range) {
      Range ourRange = expand(range, myTracker.getDocument(), myTracker.getVcsDocument());

      DiffContent vcsContent = createDiffContent(myTracker.getVcsDocument(),
                                                 myTracker.getVirtualFile(),
                                                 getVcsTextRange(ourRange));
      DiffContent currentContent = createDiffContent(myTracker.getDocument(),
                                                     myTracker.getVirtualFile(),
                                                     getCurrentTextRange(ourRange));

      SimpleDiffRequest request = new SimpleDiffRequest(VcsBundle.message("dialog.title.diff.for.range"),
                                                        vcsContent, currentContent,
                                                        VcsBundle.message("diff.content.title.up.to.date"),
                                                        VcsBundle.message("diff.content.title.current.range"));

      DiffManager.getInstance().showDiff(myTracker.getProject(), request);
    }

    @NotNull
    private DiffContent createDiffContent(@NotNull Document document, @Nullable VirtualFile highlightFile, @NotNull TextRange textRange) {
      final Project project = myTracker.getProject();
      DocumentContent content = DiffContentFactory.getInstance().create(project, document, highlightFile);
      return DiffContentFactory.getInstance().createFragment(project, content, textRange);
    }

    @NotNull
    private Range expand(@NotNull Range range, @NotNull Document document, @NotNull Document uDocument) {
      boolean canExpandBefore = range.getLine1() != 0 && range.getVcsLine1() != 0;
      boolean canExpandAfter = range.getLine2() < getLineCount(document) && range.getVcsLine2() < getLineCount(uDocument);
      int offset1 = range.getLine1() - (canExpandBefore ? 1 : 0);
      int uOffset1 = range.getVcsLine1() - (canExpandBefore ? 1 : 0);
      int offset2 = range.getLine2() + (canExpandAfter ? 1 : 0);
      int uOffset2 = range.getVcsLine2() + (canExpandAfter ? 1 : 0);
      return new Range(offset1, offset2, uOffset1, uOffset2);
    }
  }

  public class ToggleByWordDiffAction extends ToggleAction implements DumbAware {
    @NotNull private final Editor myEditor;
    @NotNull private final Range myRange;
    @Nullable private final Point myMousePosition;

    public ToggleByWordDiffAction(@NotNull Editor editor,
                                  @NotNull Range range,
                                  @Nullable Point position) {
      super("Highlight Words", null, AllIcons.Actions.Highlighting);
      myEditor = editor;
      myRange = range;
      myMousePosition = position;
    }

    @Override
    public boolean isSelected(@NotNull AnActionEvent e) {
      return VcsApplicationSettings.getInstance().SHOW_LST_WORD_DIFFERENCES;
    }

    @Override
    public void setSelected(@NotNull AnActionEvent e, boolean state) {
      if (!myTracker.isValid()) return;
      VcsApplicationSettings.getInstance().SHOW_LST_WORD_DIFFERENCES = state;

      Range newRange = myTracker.findRange(myRange);
      if (newRange != null) LineStatusMarkerPopupRenderer.this.showHintAt(myEditor, newRange, myMousePosition);
    }
  }
}


text:
$(function() {
	var $wrapper = $('#wrapper');

	// theme switcher
	var theme_match = String(window.location).match(/[?&]theme=([a-z0-9]+)/);
	var theme = (theme_match && theme_match[1]) || 'default';
	var themes = ['default','legacy','bootstrap2','bootstrap3'];
	$('head').append('<link rel="stylesheet" href="../dist/css/selectize.' + theme + '.css">');

	var $themes = $('
').addClass('theme-selector').insertAfter('h1');
	for (var i = 0; i < themes.length; i++) {
		$themes.append('' + themes[i] + '');
	}

	// display scripts on the page
	$('script', $wrapper).each(function() {
		var code = this.text;
		if (code && code.length) {
			var lines = code.split('\n');
			var indent = null;

			for (var i = 0; i < lines.length; i++) {
				if (/^[	 ]*$/.test(lines[i])) continue;
				if (!indent) {
					var lineindent = lines[i].match(/^([ 	]+)/);
					if (!lineindent) break;
					indent = lineindent[1];
				}
				lines[i] = lines[i].replace(new RegExp('^' + indent), '');
			}

			var code = $.trim(lines.join('\n')).replace(/	/g, '    ');
			var $pre = $('
').addClass('js').text(code);
			$pre.insertAfter(this);
		}
	});

	// show current input values
	$('select.selectized,input.selectized', $wrapper).each(function() {
		var $container = $('
').addClass('value').html('Current Value: ');
		var $value = $('').appendTo($container);
		var $input = $(this);
		var update = function(e) { $value.text(JSON.stringify($input.val())); }

		$(this).on('change', update);
		update();

		$container.insertAfter($input);
	});
});


text:
cd /root

echo 'deb http://archive.ubuntu.com/ubuntu precise main universe' > /etc/apt/sources.list
apt-get update

# Setup Essentials
apt-get install -y wget vim python-software-properties software-properties-common sudo net-tools inetutils-ping

# Setup Supervisor
apt-get install -y wget python-setuptools
easy_install supervisor
mv /root/supervisord.conf /etc

# Setup SSH Server
apt-get install -y openssh-server
mkdir -p /var/run/sshd
mkdir -p /root/.ssh
mv id_rsa.pub /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
chown root:root -R /root
echo 'AuthorizedKeysFile  /root/.ssh/authorized_keys' >> /etc/ssh/sshd_config
echo 'PermitRootLogin  without-password' >> /etc/ssh/sshd_config

# Setup PostgreSQL
useradd -b / -s /bin/bash postgres # Do it before install so we get uid 1000
add-apt-repository ppa:pitti/postgresql
apt-get update
apt-get -y install postgresql-9.2 postgresql-client-9.2 postgresql-contrib-9.2

# Configure PostgreSQL
sudo -u postgres psql -c "CREATE ROLE docker PASSWORD 'docker' SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN;"
service stop postgres

mkdir -p /postgres
mv /var/lib/postgresql/9.2/main /postgres/data
mv /etc/postgresql/9.2/main/postgresql.conf /postgres/data

echo "host    all             all             0.0.0.0/0               md5" >> /etc/postgresql/9.2/main/pg_hba.conf
sed -i -e "s,'/var/lib/postgresql/9.2/main','/postgres/data',g" /postgres/data/postgresql.conf
sed -i -e "s,#listen_addresses = 'localhost',listen_addresses='*',g" /postgres/data/postgresql.conf


text:
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace cdc;

namespace tests
{
	TEST_CLASS(AntForage_tests)
	{
	public:

		TEST_METHOD(AntForage_create)
		{
			AntForage goal;
		}

		TEST_METHOD(AntForage_isFinished)
		{
			AntForage goal;
			Assert::IsFalse(goal.isFinished());
		}
	};
}


text:
<web-app version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>mvcServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/spring-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvcServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>


text:
import { AsyncIterableX } from '../../asynciterable/asynciterablex';
import { buffer } from '../../asynciterable/operators/buffer';

/**
 * @ignore
 */
export function bufferProto<T>(
  this: AsyncIterableX<T>,
  count: number,
  skip?: number
): AsyncIterableX<T[]> {
  return buffer<T>(count, skip)(this);
}

AsyncIterableX.prototype.buffer = bufferProto;

declare module '../../asynciterable/asynciterablex' {
  interface AsyncIterableX<T> {
    buffer: typeof bufferProto;
  }
}


text:
<link rel="import" href="../components/core-elements/core-elements.html">
<link rel="import" href="../components/paper-elements/paper-elements.html">
<link rel="import" href="../components/core-icons/av-icons.html">

<polymer-element name="tomato-toolbar">
    <template>
        <style>
            core-icon-button {
                -webkit-app-region: no-drag;
            }

            core-toolbar {
                -webkit-app-region: drag;
                background-color: #FF8A80;
            }
        </style>
        <core-toolbar>
        <core-icon-button icon="close" on-click="{{onClose}}">
            </core-icon-button>
            <div flex>
            </div>
            <core-icon-button icon="settings"></core-icon-button>
        </core-toolbar>
        <script>
            (function(Polymer) {
                Polymer('tomato-toolbar', {
                    onClose: function() {
                        window.close();
                    }
                });
            })(Polymer);
        </script>
    </template>

</polymer-element>


text:
namespace System.Security.Cryptography {
    using System;
    using System.Diagnostics.Contracts;

[System.Runtime.InteropServices.ComVisible(true)]
    public abstract class DES : SymmetricAlgorithm
    {
        private static  KeySizes[] s_legalBlockSizes = {
            new KeySizes(64, 64, 0)
        };
        private static  KeySizes[] s_legalKeySizes = {
            new KeySizes(64, 64, 0)
        };

        //
        // protected constructors
        //

        protected DES() {
            KeySizeValue = 64;
            BlockSizeValue = 64;
            FeedbackSizeValue = BlockSizeValue;
            LegalBlockSizesValue = s_legalBlockSizes;
            LegalKeySizesValue = s_legalKeySizes;
        }

        //
        // public properties
        //

        public override byte[] Key {
            get {
                if (KeyValue == null) {
                    // Never hand back a weak or semi-weak key
                    do {
                        GenerateKey();
                    } while (IsWeakKey(KeyValue) || IsSemiWeakKey(KeyValue));
                }
                return (byte[]) KeyValue.Clone();
            }
            set {
                if (value == null) throw new ArgumentNullException("value");
                Contract.EndContractBlock();
                if (!ValidKeySize(value.Length * 8)) { // must convert bytes to bits
                    throw new ArgumentException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
                }
                if (IsWeakKey(value)) {
                    throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKey_Weak"),"DES");
                }
                if (IsSemiWeakKey(value)) {
                    throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKey_SemiWeak"),"DES");
                }
                KeyValue = (byte[]) value.Clone();
                KeySizeValue = value.Length * 8;
            }
        }

        //
        // public methods
        //

        new static public DES Create() {
#if FULL_AOT_RUNTIME
        return new System.Security.Cryptography.DESCryptoServiceProvider ();
#else
            return Create("System.Security.Cryptography.DES");
#endif
        }

        new static public DES Create(String algName) {
            return (DES) CryptoConfig.CreateFromName(algName);
        }

        public static bool IsWeakKey(byte[] rgbKey) {
            if (!IsLegalKeySize(rgbKey)) {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
            }
            byte[] rgbOddParityKey = Utils.FixupKeyParity(rgbKey);
            UInt64 key = QuadWordFromBigEndian(rgbOddParityKey);
            if ((key == 0x0101010101010101) ||
                (key == 0xfefefefefefefefe) ||
                (key == 0x1f1f1f1f0e0e0e0e) ||
                (key == 0xe0e0e0e0f1f1f1f1)) {
                return(true);
            }
            return(false);
        }

        public static bool IsSemiWeakKey(byte[] rgbKey) {
            if (!IsLegalKeySize(rgbKey)) {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
            }
            byte[] rgbOddParityKey = Utils.FixupKeyParity(rgbKey);
            UInt64 key = QuadWordFromBigEndian(rgbOddParityKey);
            if ((key == 0x01fe01fe01fe01fe) ||
                (key == 0xfe01fe01fe01fe01) ||
                (key == 0x1fe01fe00ef10ef1) ||
                (key == 0xe01fe01ff10ef10e) ||
                (key == 0x01e001e001f101f1) ||
                (key == 0xe001e001f101f101) ||
                (key == 0x1ffe1ffe0efe0efe) ||
                (key == 0xfe1ffe1ffe0efe0e) ||
                (key == 0x011f011f010e010e) ||
                (key == 0x1f011f010e010e01) ||
                (key == 0xe0fee0fef1fef1fe) ||
                (key == 0xfee0fee0fef1fef1)) {
                return(true);
            }
            return(false);
        }

        //
        // private methods
        //

        private static bool IsLegalKeySize(byte[] rgbKey) {
            if (rgbKey != null && rgbKey.Length == 8) return(true);
            return(false);
        }

        private static UInt64 QuadWordFromBigEndian(byte[] block)
        {
            UInt64 x;
            x =  (
                  (((UInt64)block[0]) << 56) | (((UInt64)block[1]) << 48) |
                  (((UInt64)block[2]) << 40) | (((UInt64)block[3]) << 32) |
                  (((UInt64)block[4]) << 24) | (((UInt64)block[5]) << 16) |
                  (((UInt64)block[6]) << 8) | ((UInt64)block[7])
                  );
            return(x);
        }
    }
}


text:
.. _distributing:

#############################
Distributing Your Application
#############################

.. contents::
  :local:
  :backlinks: none
  :depth: 2

This document describes how to distribute Portable Native Client applications
on the web, and Native Client applications through the
`Chrome Web Store </webstore>`_ (CWS).

Portable Native Client
======================

Portable Native Client is enabled by default for web pages, so no separate
distribution step is requred. Making PNaCl a part of your web application is as
simple as embedding a manifest file that points to a **pexe**. See the
:doc:`technical overview <../overview>` for more details.

.. image:: /images/nacl-in-a-web-app.png

The only constraint for distributing PNaCl modules with a web application is
abiding by the `Same-origin policy
<http://en.wikipedia.org/wiki/Same_origin_policy>`_. The PNaCl manifest and
**pexe** must either be served from the same domain with the HTML, or the `CORS
mechanism <http://en.wikipedia.org/wiki/Cross-origin_resource_sharing>`_ should
be used to safely host them on a different domain.

Non-portable Native Client
==========================

NaCl modules are only allowed for applications distributed through the `Chrome
Web Store (CWS) <https://chrome.google.com/webstore/category/apps>`_
The CWS requirement is in place to prevent the proliferation of Native Client
executables (**nexe**\s) compiled for specific architecures (e.g., x86-32,
x86-64, or ARM).

In general, the considerations and guidelines for distributing applications
through the Chrome Web Store apply to applications that contain NaCl modules as
well. Here are a few pointers to relevant documentation:

* `CWS Overview </webstore>`_
* `Choosing an App Type </webstore/choosing>`_
* `Getting started with packaged apps </apps/about_apps>`_
* `Hosted apps <https://developers.google.com/chrome/apps/docs/developers_guide>`_
* `Chrome extensions </extensions>`_

In this document, we'll focus only on distribution issues specific to
applications that contain NaCl modules.

.. _distributing_packaged:

Packaged application
--------------------

A packaged application is a special zip file (with a .crx extension) hosted in
the Chrome Web Store. This file contains all of the application parts: A Chrome
Web Store manifest file (manifest.json), an icon, and all of the regular Native
Client application files. Refer to
`Packaged Apps </apps/about_apps>`_
for more information about creating a packaged application.

Reducing the size of the user download package
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. Note::
   :class: note

   **Tip:**
   Packaging an app in a multi-platform zip file can significantly reduce the
   download and storage requirements for the app.

As described above, to upload a packaged app to the CWS you have to create a zip
file with all the resources that your app needs, including .nexe files for
multiple architectures (x86-64, x86-32, and ARM). Prior to Chrome 28, when users
installed your app they had to download a .crx file from the CWS with all the
included .nexe files.

Starting with Chrome 28, the Chrome Web Store includes a feature called
**multi-platform zip files.** This feature lets you structure your application
directory and zip file in a way that reduces the size of the user download
package.  Here's how this feature works:

* You still include all the .nexe files in the zip file that you upload to
  the CWS, but you designate specific .nexe files (and other files if
  appropriate) for specific architectures.
* The Chrome Web Store re-packages your app, so that users only download
  the files that they need for their specific architecture.

Here is how to use this feature:

#. Create a directory called ``_platform_specific``.
   Put this directory at the same level where your CWS manifest file,
   ``manifest.json``, is located.

#. Create a subdirectory for each specific architecture that you support,
   and add the files for each architecture in the relevant subdirectory.

   Here is a sample app directory structure:

   .. naclcode::
     :prettyprint: 0

     |-- my_app_directory/
     |       |-- manifest.json
     |       |-- my_app.html
     |       |-- my_module.nmf
     |       +-- css/
     |       +-- images/
     |       +-- scripts/
     |       |-- _platform_specific/
     |       |       |-- x86-64/
     |       |       |       |-- my_module_x86_64.nexe
     |       |       |-- x86-32/
     |       |       |       |-- my_module_x86_32.nexe
     |       |       |-- arm/
     |       |       |       |-- my_module_arm.nexe
     |       |       |-- all/
     |       |       |       |-- my_module_x86_64.nexe
     |       |       |       |-- my_module_x86_64.nexe
     |       |       |       |-- my_module_x86_32.nexe

   Please note a few important points about the app directory structure:

   * The architecture-specific subdirectories:

     * can have arbitrary names;
     * must be directly under the ``_platform_specific`` directory; and
     * must be listed in the CWS manifest file (see step 3 below).

   * You can include a fallback subdirectory that provides a download package
     with all the architecture-specific files.  (In the example above this
     is the ``all/`` subdirectory.) This folder is used if the user has an
     earlier version of Chrome (prior to Chrome 28) that does not support
     multi-platform zip files.

   * You cannot include any files directly in the folder
     ``_platform_specific``.  All architecture-specific files
     must be under one of the architecture-specific subdirectories.

   * Files that are not under the ``_platform_specific`` directory are
     included in all download packages.  (In the example above, that
     includes ``my_app.html``, ``my_module.nmf``,
     and the ``css/``, ``images/``, and ``scripts/`` directories.)

#. Modify the CWS manifest file, ``manifest.json``, so that it specifies which
   subdirectory under ``_platform_specific`` corresponds to which architecture.

   The CWS manifest file must include a new name/value pair, where the name
   is ``platforms`` and the value is an array.  The array has an object for
   each Native Client architecture with two name/value pairs:

   +----------------------+---------------------------------------+
   | Name                 | Value                                 |
   +======================+=======================================+
   | ``nacl_arch``        | ``x86-64``, ``x86-32``, or ``arm``    |
   +----------------------+---------------------------------------+
   | ``sub_package_path`` | the path of the directory (starting   |
   |                      | with ``_platform_specific``) that     |
   |                      | contains the files for the designated |
   |                      | NaCl architecture                     |
   +----------------------+---------------------------------------+

   Here is a sample ``manifest.json`` file:

   .. naclcode::
     :prettyprint: 0

     {
       "name": "My Reminder App",
       "description": "A reminder app that syncs across Chrome browsers.",
       "manifest_version": 2,
       "minimum_chrome_version": "28",
       "offline_enabled": true,
       "version": "0.3",
       "permissions": [
         {"fileSystem": ["write"]},
         "alarms",
         "storage"
       ],
       "app": {
         "background": {
           "scripts": ["scripts/background.js"]
         }
       },
       "icons": {
         "16": "images/icon-16x16.png",
         "128": "images/icon-128x128.png"
       },
       "platforms": [
         {
           "nacl_arch": "x86-64",
           "sub_package_path": "_platform_specific/x86-64/"
         },
         {
           "nacl_arch": "x86-32",
           "sub_package_path": "_platform_specific/x86-32/"
         },
         {
           "nacl_arch": "arm",
           "sub_package_path": "_platform_specific/arm/"
         },
         {
           "sub_package_path": "_platform_specific/all/"
         }
       ]
     }

   Note the last entry in the CWS manifest file above, which specifies a
   ``sub_package_path`` without a corresponding ``nacl_arch``. This entry
   identifies the fallback directory, which is included in the download
   package if the user architecture does not match any of the listed NaCl
   architectures, or if the user is using an older version of Chrome that
   does not support multi-platform zip files.

#. Modify your application as necessary so that it uses the files for the
   correct user architecture.

   To reference architecture-specific files, use the JavaScript API
   `chrome.runtime.getPlatformInfo() </extensions/runtime.html#method-getPlatformInfo>`_.
   As an example, if you have architecture-specific files in the directories
   ``x86-64``, ``x86-32``, and ``arm``, you can use the following JavaScript
   code to create a path for the files:

   .. naclcode::

      function getPath(name) {
        return '_platform_specific/' +
          chrome.runtime.getPlatformInfo().nacl_arch +
          '/' + name;
      }

#. Test your app, create a zip file, and upload the app to the CWS as before.

.. _additional_considerations_packaged:

Additional considerations for a packaged application
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

* In the description of your application in the CWS, make sure to mention that
  your application is a Native Client application that only works with the
  Chrome browser. Also make sure to identify the minimum version of Chrome
  that your application requires.
* Hosted and packaged applications have a "launch" parameter in the CWS
  manifest. This parameter is present only in apps (not extensions), and it
  tells Google Chrome what to show when a user starts an installed app. For
  example:

  .. naclcode::
    :prettyprint: 0

    "launch": {
      "web_url": "http://mail.google.com/mail/"
    }

* If you want to write local data using the Pepper
  `FileIO </native-client/peppercpp/classpp_1_1_file_i_o>`_
  API, you must set the 'unlimitedStorage' permission in your Chrome Web
  Store manifest file, just as you would for a JavaScript application that
  uses the HTML5 File API.
* For packaged applications, you can only use in-app purchases.
* You can place your application in the Google Web Store with access only to
  certain people for testing. See `Publishing to test accounts
  </webstore/publish>`_ for more information.

Extension
---------

The NaCl-specific notes for a :ref:`package application <distributing_packaged>`
apply to extensions as well.

Hosted application
------------------

The .html file, .nmf file (Native Client manifest file), and .nexe files must
be served from the same domain, and the Chrome Web Store manifest file must
specify the correct, verified domain. Other files can be served from the same
or another domain.

In addition, see :ref:`Additional considerations for a packaged application <additional_considerations_packaged>`.

Registering Native Client modules to handle MIME types
------------------------------------------------------

If you want Chrome to use a Native Client module to display a particular type
of content, you can associate the MIME type of that content with the Native
Client module. Use the ``nacl_modules`` attribute in the Chrome Web Store
manifest file to register a Native Client module as the handler for one or more
specific MIME types. For example, the bold code in the snippet below registers
a Native Client module as the content handler for the OpenOffice spreadsheet
MIME type:

.. naclcode::
  :prettyprint: 0

  {
     "name": "My Native Client Spreadsheet Viewer",
     "version": "0.1",
     "description": "Open spreadsheets right in your browser.",
     "nacl_modules": [{
        "path": "SpreadsheetViewer.nmf",
        "mime_type": "application/vnd.oasis.opendocument.spreadsheet"
     }]
  }

The value of "path" is the location of a Native Client manifest file (.nmf)
within the application directory. For more information on Native Client
manifest files, see :ref:`Manifest Files <manifest_file>`.

The value of "mime_type" is a specific MIME type that you want the Native
Client module to handle. Each MIME type can be associated with only one .nmf
file, but a single .nmf file might handle multiple MIME types. The following
example shows an extension with two .nmf files that handle three MIME types.

.. naclcode::
  :prettyprint: 0

  {
     "name": "My Native Client Spreadsheet and Document Viewer",
     "version": "0.1",
     "description": "Open spreadsheets and documents right in your browser.",
     "nacl_modules": [{
       "path": "SpreadsheetViewer.nmf",
       "mime_type": "application/vnd.oasis.opendocument.spreadsheet"
     },
     {
        "path": "SpreadsheetViewer.nmf",
        "mime_type": "application/vnd.oasis.opendocument.spreadsheet-template"
     },
     {
        "path": "DocumentViewer.nmf",
        "mime_type": "application/vnd.oasis.opendocument.text"
     }]
  }

The ``nacl_modules`` attribute is optional---specify this attribute only if
you want Chrome to use a Native Client module to display a particular type of
content.


text:
package salestaxes;

import java.math.BigDecimal;
import java.util.*;

public class ShoppingBasket {

	private final List<Item> items;

	public ShoppingBasket() {
		super();
		this.items = new LinkedList<>();
	}

	public void add(Item item) {
		this.items.add(item);
	}

	public Receipt toReceipt() {
		List<Receipt.Line> lines = new LinkedList<>();
		for (Item item : items) lines.add(item.toReceiptLine());
		return new Receipt(lines);
	}

	public static class Item {

		private static final double GOOD_TAX_RATE   = 10.;
		private static final double IMPORT_TAX_RATE =  5.;

		@SuppressWarnings("unused")
		private final String name;
		private final BigDecimal price;
		private final boolean taxFree;
		private final boolean imported;

		public Item(String name, BigDecimal price, boolean taxFree) {
			this(name, price, taxFree, false);
		}

		public Item(String name, BigDecimal price, boolean taxFree, boolean imported) {
			super();
			this.name = name;
			this.price = price;
			this.taxFree = taxFree;
			this.imported = imported;
		}

		public BigDecimal price() {
			return price;
		}

		public BigDecimal salesTaxes() {
			BigDecimal importTaxes = (imported)
					? percentage(IMPORT_TAX_RATE, price)
					: BigDecimal.ZERO;
			BigDecimal goodtypeTaxes = (taxFree)
					? BigDecimal.ZERO
					: percentage(GOOD_TAX_RATE, price);
			return goodtypeTaxes.add(importTaxes);
		}

		private static BigDecimal percentage(double percentage, BigDecimal amount) {
			double value = amount.doubleValue() * percentage / 100.;
			double rounded = Math.ceil(value * 20.) / 20.;
			return BigDecimal.valueOf(rounded);
		}

		public Receipt.Line toReceiptLine() {
			return new Receipt.Line(this, salesTaxes());
		}

	}

}


text:
package org.apache.hadoop.hdfs.web.resources;

/** The FileSystem path parameter. */
public class UriFsPathParam extends StringParam {
  /** Parameter name. */
  public static final String NAME = "path";

  private static final Domain DOMAIN = new Domain(NAME, null);

  /**
   * Constructor.
   * @param str a string representation of the parameter value.
   */
  public UriFsPathParam(String str) {
    super(DOMAIN, str);
  }

  @Override
  public String getName() {
    return NAME;
  }

  /** @return the absolute path. */
  public final String getAbsolutePath() {
    final String path = getValue(); //The first / has been stripped out.
    return path == null? null: "/" + path;
  }
}