text:
<?php
	/**
	 * Elgg relationships.
	 * Stub containing relationship functions, making import and export easier.
	 *
	 * @package Elgg
	 * @subpackage Core
	 * @author Curverider Ltd <info@elgg.com>
	 * @link http://elgg.org/
	 */

	/**
	 * Relationship class.
	 *
	 * @author Curverider Ltd
	 * @package Elgg
	 * @subpackage Core
	 */
	class ElggRelationship implements
		Importable,
		Exportable,
		Loggable,	// Can events related to this object class be logged
		Iterator,	// Override foreach behaviour
		ArrayAccess // Override for array access
	{
		/**
		 * This contains the site's main properties (id, etc)
		 * @var array
		 */
		protected $attributes;

		/**
		 * Construct a new site object, optionally from a given id value or row.
		 *
		 * @param mixed $id
		 */
		function __construct($id = null)
		{
			$this->attributes = array();

			if (!empty($id)) {

				if ($id instanceof stdClass)
					$relationship = $id; // Create from db row
				else
					$relationship = get_relationship($id);

				if ($relationship) {
					$objarray = (array) $relationship;
					foreach($objarray as $key => $value) {
						$this->attributes[$key] = $value;
					}
				}
			}
		}

		/**
		 * Class member get overloading
		 *
		 * @param string $name
		 * @return mixed
		 */
		protected function __get($name) {
			if (isset($this->attributes[$name]))
				return $this->attributes[$name];

			return null;
		}

		/**
		 * Class member set overloading
		 *
		 * @param string $name
		 * @param mixed $value
		 * @return mixed
		 */
		protected function __set($name, $value) {
			$this->attributes[$name] = $value;
			return true;
		}

		/**
		 * Save the relationship
		 *
		 * @return int the relationship id
		 */
		public function save()
		{
			if ($this->id > 0)
			{
				delete_relationship($this->id);
			}

			$this->id = add_entity_relationship($this->guid_one, $this->relationship, $this->guid_two);
			if (!$this->id) throw new IOException(sprintf(elgg_new('IOException:UnableToSaveNew'), get_class()));

			return $this->id;

		}

		/**
		 * Delete a given relationship.
		 */
		public function delete()
		{
			return delete_relationship($this->id);
		}

		/**
		 * Get a URL for this relationship.
		 *
		 * @return string
		 */
		public function getURL()
		{
			return get_relationship_url($this->id);
		}

		// EXPORTABLE INTERFACE ////////////////////////////////////////////////////////////

		/**
		 * Return an array of fields which can be exported.
		 */
		public function getExportableValues()
		{
			return array(
				'id',
				'guid_one',
				'relationship',
				'guid_two'
			);
		}

		/**
		 * Export this relationship
		 *
		 * @return array
		 */
		public function export()
		{
			$uuid = get_uuid_from_object($this);
			$relationship = new ODDRelationship(
				guid_to_uuid($this->guid_one),
				$this->relationship,
				guid_to_uuid($this->guid_two)
			);

			$relationship->setAttribute('uuid', $uuid);

			return $relationship;
		}

		// IMPORTABLE INTERFACE ////////////////////////////////////////////////////////////

		/**
		 * Import a relationship
		 *
		 * @param array $data
		 * @param int $version
		 * @return ElggRelationship
		 * @throws ImportException
		 */
		public function import(ODD $data)
		{
			if (!($element instanceof ODDRelationship))
				throw new InvalidParameterException(elgg_echo('InvalidParameterException:UnexpectedODDClass'));

			$uuid_one = $data->getAttribute('uuid1');
			$uuid_two = $data->getAttribute('uuid2');

			// See if this entity has already been imported, if so then we need to link to it
			$entity1 = get_entity_from_uuid($uuid_one);
			$entity2 = get_entity_from_uuid($uuid_two);
			if (($entity1) && ($entity2))
			{
				// Set the item ID
				$this->attributes['guid_one'] = $entity1->getGUID();
				$this->attributes['guid_two'] = $entity2->getGUID();

				// Map verb to relationship
				//$verb = $data->getAttribute('verb');
				//$relationship = get_relationship_from_verb($verb);
				$relationship = $data->getAttribute('type');

				if ($relationship)
				{
					$this->attributes['relationship'] = $relationship;
					// save
					$result = $this->save();
					if (!$result)
						throw new ImportException(sprintf(elgg_echo('ImportException:ProblemSaving'), get_class()));

					return $this;
				}
			}
		}

		// SYSTEM LOG INTERFACE ////////////////////////////////////////////////////////////

		/**
		 * Return an identification for the object for storage in the system log.
		 * This id must be an integer.
		 *
		 * @return int
		 */
		public function getSystemLogID() { return $this->id;	}

		/**
		 * Return the class name of the object.
		 */
		public function getClassName() { return get_class($this); }

		/**
		 * For a given ID, return the object associated with it.
		 * This is used by the river functionality primarily.
		 * This is useful for checking access permissions etc on objects.
		 */
		public function getObjectFromID($id) { return get_relationship($id); }

		/**
		 * Return the GUID of the owner of this object.
		 */
		public function getObjectOwnerGUID() { return $this->owner_guid; }

		/**
		 * Return a type of the object - eg. object, group, user, relationship, metadata, annotation etc
		 */
		public function getType() { return 'relationship'; }

		/**
		 * Return a subtype. For metadata & annotations this is the 'name' and for relationship this is the relationship type.
		 */
		public function getSubtype() { return $this->relationship; }

		// ITERATOR INTERFACE //////////////////////////////////////////////////////////////
		/*
		 * This lets an entity's attributes be displayed using foreach as a normal array.
		 * Example: http://www.sitepoint.com/print/php5-standard-library
		 */

		private $valid = FALSE;

   		function rewind()
   		{
   			$this->valid = (FALSE !== reset($this->attributes));
   		}

   		function current()
   		{
   			return current($this->attributes);
   		}

   		function key()
   		{
   			return key($this->attributes);
   		}

   		function next()
   		{
   			$this->valid = (FALSE !== next($this->attributes));
   		}

   		function valid()
   		{
   			return $this->valid;
   		}

   		// ARRAY ACCESS INTERFACE //////////////////////////////////////////////////////////
		/*
		 * This lets an entity's attributes be accessed like an associative array.
		 * Example: http://www.sitepoint.com/print/php5-standard-library
		 */

		function offsetSet($key, $value)
		{
   			if ( array_key_exists($key, $this->attributes) ) {
     			$this->attributes[$key] = $value;
   			}
 		}

 		function offsetGet($key)
 		{
   			if ( array_key_exists($key, $this->attributes) ) {
     			return $this->attributes[$key];
   			}
 		}

 		function offsetUnset($key)
 		{
   			if ( array_key_exists($key, $this->attributes) ) {
     			$this->attributes[$key] = ""; // Full unsetting is dangerious for our objects
   			}
 		}

 		function offsetExists($offset)
 		{
   			return array_key_exists($offset, $this->attributes);
 		}
	}

	/**
	 * Convert a database row to a new ElggRelationship
	 *
	 * @param stdClass $row
	 * @return stdClass or ElggMetadata
	 */
	function row_to_elggrelationship($row)
	{
		if (!($row instanceof stdClass))
			return $row;

		return new ElggRelationship($row);
	}

	/**
	 * Return a relationship.
	 *
	 * @param int $id
	 */
	function get_relationship($id)
	{
		global $CONFIG;

		$id = (int)$id;

		return row_to_elggrelationship(get_data_row("SELECT * from {$CONFIG->dbprefix}entity_relationships where id=$id"));
	}

	/**
	 * Delete a specific relationship.
	 *
	 * @param int $id
	 */
	function delete_relationship($id)
	{
		global $CONFIG;

		$id = (int)$id;

		$result = delete_data("delete from {$CONFIG->dbprefix}entity_relationships where id=$id");

		return $result;
	}

	/**
	 * Define an arbitrary relationship between two entities.
	 * This relationship could be a friendship, a group membership or a site membership.
	 *
	 * This function lets you make the statement "$guid_one has $relationship with $guid_two".
	 *
	 * @param int $guid_one
	 * @param string $relationship
	 * @param int $guid_two
	 */
	function add_entity_relationship($guid_one, $relationship, $guid_two)
	{
		global $CONFIG;

		$guid_one = (int)$guid_one;
		$relationship = sanitise_string($relationship);
		$guid_two = (int)$guid_two;

		// Check for duplicates
		if (check_entity_relationship($guid_one, $relationship, $guid_two))
			return false;

		$result = insert_data("INSERT into {$CONFIG->dbprefix}entity_relationships (guid_one, relationship, guid_two) values ($guid_one, '$relationship', $guid_two)");

		if ($result!==false) {
			$obj = get_relationship($result);
			if (trigger_elgg_event('create', $relationship, $obj)) {
				return true;
			} else {
				delete_relationship($result);
			}
		}

		return false;
	}

	/**
	 * Determine whether or not a relationship between two entities exists and returns the relationship object if it does
	 *
	 * @param int $guid_one The GUID of the entity "owning" the relationship
	 * @param string $relationship The type of relationship
	 * @param int $guid_two The GUID of the entity the relationship is with
	 * @return object|false Depending on success
	 */
	function check_entity_relationship($guid_one, $relationship, $guid_two)
	{
		global $CONFIG;

		$guid_one = (int)$guid_one;
		$relationship = sanitise_string($relationship);
		$guid_two = (int)$guid_two;

		if ($row = get_data_row("SELECT * FROM {$CONFIG->dbprefix}entity_relationships WHERE guid_one=$guid_one AND relationship='$relationship' AND guid_two=$guid_two limit 1")) {
			return $row;
		}
		return false;
	}

	/**
	 * Remove an arbitrary relationship between two entities.
	 *
	 * @param int $guid_one
	 * @param string $relationship
	 * @param int $guid_two
	 */
	function remove_entity_relationship($guid_one, $relationship, $guid_two)
	{
		global $CONFIG;

		$guid_one = (int)$guid_one;
		$relationship = sanitise_string($relationship);
		$guid_two = (int)$guid_two;

		$obj = check_entity_relationship($guid_one, $relationship, $guid_two);
		if ($obj == false) return false;

		if (trigger_elgg_event('delete', $relationship, $obj)) {
			return delete_data("DELETE from {$CONFIG->dbprefix}entity_relationships where guid_one=$guid_one and relationship='$relationship' and guid_two=$guid_two");
		} else {
			return false;
		}
	}

	/**
	 * Removes all arbitrary relationships originating from a particular entity
	 *
	 * @param int $guid_one The GUID of the entity
	 * @param string $relationship The name of the relationship (optionally)
	 * @param true|false $inverse Whether we're deleting inverse relationships (default false)
	 * @param string $type The type of entity to limit this relationship delete to (defaults to all)
	 * @return true|false Depending on success
	 */
	function remove_entity_relationships($guid_one, $relationship = "", $inverse = false, $type = '') {

		global $CONFIG;

		$guid_one = (int) $guid_one;

		if (!empty($relationship)) {
			$relationship = sanitise_string($relationship);
			$where = "and er.relationship='$relationship'";
		} else {
			$where = "";
		}

		if (!empty($type)) {
			$type = sanitise_string($type);
			if (!$inverse) {
				$join = " join {$CONFIG->dbprefix}entities e on e.guid = er.guid_two ";
			} else {
				$join = " join {$CONFIG->dbprefix}entities e on e.guid = er.guid_one ";
				$where .= " and ";
			}
			$where .= " and e.type = '{$type}' ";
		} else {
			$join = "";
		}

		if (!$inverse) {
			$sql = "DELETE er from {$CONFIG->dbprefix}entity_relationships as er {$join} where guid_one={$guid_one} {$where}";
			return delete_data($sql);
		} else {
			$sql = "DELETE er from {$CONFIG->dbprefix}entity_relationships as er {$join} where guid_two={$guid_one} {$where}";
			return delete_data($sql);
		}

	}

	/**
	 * Get all the relationships for a given guid.
	 *
	 * @param int $guid
	 */
	function get_entity_relationships($guid)
	{
		global $CONFIG;

		$guid = (int)$guid;

		$query = "SELECT * from {$CONFIG->dbprefix}entity_relationships where guid_one=$guid";

		return get_data($query, "row_to_elggrelationship");
	}

	/**
	 * Return entities matching a given query joining against a relationship.
	 *
	 * @param string $relationship The relationship eg "friends_of"
	 * @param int $relationship_guid The guid of the entity to use query
	 * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of"
	 * @param string $type
	 * @param string $subtype
	 * @param int $owner_guid
	 * @param string $order_by
	 * @param int $limit
	 * @param int $offset
	 * @param boolean $count Set to true if you want to count the number of entities instead (default false)
	 * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites.
	 * @return array|int|false An array of entities, or the number of entities, or false on failure
	 */
	function get_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship = false, $type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0)
	{
		global $CONFIG;

		$relationship = sanitise_string($relationship);
		$relationship_guid = (int)$relationship_guid;
		$inverse_relationship = (bool)$inverse_relationship;
		$type = sanitise_string($type);
		$subtype = get_subtype_id($type, $subtype);
		$owner_guid = (int)$owner_guid;
		if ($order_by == "") $order_by = "time_created desc";
		$order_by = sanitise_string($order_by);
		$limit = (int)$limit;
		$offset = (int)$offset;
		$site_guid = (int) $site_guid;
		if ($site_guid == 0)
			$site_guid = $CONFIG->site_guid;

		//$access = get_access_list();

		$where = array();

		if ($relationship!="")
			$where[] = "r.relationship='$relationship'";
		if ($relationship_guid)
			$where[] = ($inverse_relationship ? "r.guid_two='$relationship_guid'" : "r.guid_one='$relationship_guid'");
		if ($type != "")
			$where[] = "e.type='$type'";
		if ($subtype)
			$where[] = "e.subtype=$subtype";
		if ($owner_guid != "")
			$where[] = "e.container_guid='$owner_guid'";
		if ($site_guid > 0)
			$where[] = "e.site_guid = {$site_guid}";

		// Select what we're joining based on the options
		$joinon = "e.guid = r.guid_one";
		if (!$inverse_relationship)
			$joinon = "e.guid = r.guid_two";

		if ($count) {
			$query = "SELECT count(distinct e.guid) as total ";
		} else {
			$query = "SELECT distinct e.* ";
		}
		$query .= " from {$CONFIG->dbprefix}entity_relationships r JOIN {$CONFIG->dbprefix}entities e on $joinon where ";
		foreach ($where as $w)
			$query .= " $w and ";
		$query .= get_access_sql_suffix("e"); // Add access controls
		if (!$count) {
			$query .= " order by $order_by limit $offset, $limit"; // Add order and limit
			return get_data($query, "entity_row_to_elggstar");
		} else {
			if ($count = get_data_row($query)) {
				return $count->total;
			}
		}
		return false;

	}

	/**
	 * Returns a viewable list of entities by relationship
	 *
	 * @see elgg_view_entity_list
	 *
	 * @param string $relationship The relationship eg "friends_of"
	 * @param int $relationship_guid The guid of the entity to use query
	 * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of"
	 * @param string $type The type of entity (eg 'object')
	 * @param string $subtype The entity subtype
	 * @param int $owner_guid The owner (default: all)
	 * @param int $limit The number of entities to display on a page
	 * @param true|false $fullview Whether or not to display the full view (default: true)
	 * @param true|false $viewtypetoggle Whether or not to allow gallery view
	 * @param true|false $pagination Whether to display pagination (default: true)
	 * @return string The viewable list of entities
	 */
	function list_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship = false, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) {

		$limit = (int) $limit;
		$offset = (int) get_input('offset');
		$count = get_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship, $type, $subtype, $owner_guid, "", $limit, $offset, true);
		$entities = get_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship, $type, $subtype, $owner_guid, "", $limit, $offset);

		return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination);

	}

	/**
	 * Gets the number of entities by a the number of entities related to them in a particular way.
	 * This is a good way to get out the users with the most friends, or the groups with the most members.
	 *
	 * @param string $relationship The relationship eg "friends_of"
	 * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" (default: true)
	 * @param string $type The type of entity (default: all)
	 * @param string $subtype The entity subtype (default: all)
	 * @param int $owner_guid The owner of the entities (default: none)
	 * @param int $limit
	 * @param int $offset
	 * @param boolean $count Set to true if you want to count the number of entities instead (default false)
	 * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites.
	 * @return array|int|false An array of entities, or the number of entities, or false on failure
	 */

	function get_entities_by_relationship_count($relationship, $inverse_relationship = true, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $count = false, $site_guid = 0) {

		global $CONFIG;

		$relationship = sanitise_string($relationship);
		$inverse_relationship = (bool)$inverse_relationship;
		$type = sanitise_string($type);
		if ($subtype AND !$subtype = get_subtype_id($type, $subtype))
			return false;
		$owner_guid = (int)$owner_guid;
		$order_by = sanitise_string($order_by);
		$limit = (int)$limit;
		$offset = (int)$offset;
		$site_guid = (int) $site_guid;
		if ($site_guid == 0)
			$site_guid = $CONFIG->site_guid;

		//$access = get_access_list();

		$where = array();

		if ($relationship!="")
			$where[] = "r.relationship='$relationship'";
		if ($inverse_relationship) {
			$on = 'e.guid = r.guid_two';
		} else {
			$on = 'e.guid = r.guid_one';
		}
		if ($type != "")
			$where[] = "e.type='$type'";
		if ($subtype)
			$where[] = "e.subtype=$subtype";
		if ($owner_guid != "")
			$where[] = "e.container_guid='$owner_guid'";
		if ($site_guid > 0)
			$where[] = "e.site_guid = {$site_guid}";

		if ($count) {
			$query = "SELECT count(distinct e.guid) as total ";
		} else {
			$query = "SELECT e.*, count(e.guid) as total ";
		}

		$query .= " from {$CONFIG->dbprefix}entity_relationships r JOIN {$CONFIG->dbprefix}entities e on {$on} where ";

		if (!empty($where))
		foreach ($where as $w)
			$query .= " $w and ";
		$query .= get_access_sql_suffix("e"); // Add access controls

		if (!$count) {
			$query .= " group by e.guid ";
			$query .= " order by total desc limit {$offset}, {$limit}"; // Add order and limit
			return get_data($query, "entity_row_to_elggstar");
		} else {
			if ($count = get_data_row($query)) {
				return $count->total;
			}
		}

		return false;

	}

	/**
	 * Displays a human-readable list of entities
	 *
	 * @param string $relationship The relationship eg "friends_of"
	 * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" (default: true)
	 * @param string $type The type of entity (eg 'object')
	 * @param string $subtype The entity subtype
	 * @param int $owner_guid The owner (default: all)
	 * @param int $limit The number of entities to display on a page
	 * @param true|false $fullview Whether or not to display the full view (default: true)
	 * @param true|false $viewtypetoggle Whether or not to allow gallery view
	 * @param true|false $pagination Whether to display pagination (default: true)
	 * @return string The viewable list of entities
	 */

	function list_entities_by_relationship_count($relationship, $inverse_relationship = true, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) {

		$limit = (int) $limit;
		$offset = (int) get_input('offset');
		$count = get_entities_by_relationship_count($relationship,$inverse_relationship,$type,$subtype,$owner_guid,0,0,true);
		$entities = get_entities_by_relationship_count($relationship,$inverse_relationship,$type,$subtype,$owner_guid,$limit,$offset);

		return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination);

	}

	/**
	 * Gets the number of entities by a the number of entities related to them in a particular way also constrained by
	 * metadata
	 *
	 * @param string $relationship The relationship eg "friends_of"
	 * @param int $relationship_guid The guid of the entity to use query
	 * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" (default: true)
	 * @param String $meta_name The metadata name
	 * @param String $meta_value The metadata value
	 * @param string $type The type of entity (default: all)
	 * @param string $subtype The entity subtype (default: all)
	 * @param int $owner_guid The owner of the entities (default: none)
	 * @param int $limit
	 * @param int $offset
	 * @param boolean $count Set to true if you want to count the number of entities instead (default false)
	 * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites.
	 * @return array|int|false An array of entities, or the number of entities, or false on failure
	 */
	function get_entities_from_relationships_and_meta($relationship, $relationship_guid, $inverse_relationship = false, $meta_name = "", $meta_value = "", $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $count = false, $site_guid = 0)
	{

		global $CONFIG;

		$relationship = sanitise_string($relationship);
		$inverse_relationship = (bool)$inverse_relationship;
		$relationship_guid = (int)$relationship_guid;
		$type = sanitise_string($type);
		if ($subtype AND !$subtype = get_subtype_id($type, $subtype))
			return false;
		$owner_guid = (int)$owner_guid;
		$order_by = sanitise_string($order_by);
		$limit = (int)$limit;
		$offset = (int)$offset;
		$site_guid = (int) $site_guid;
		if ($site_guid == 0)
			$site_guid = $CONFIG->site_guid;

		$meta_n = get_metastring_id($meta_name);
		$meta_v = get_metastring_id($meta_value);

		//$access = get_access_list();

		$where = array();

		if ($relationship!="")
			$where[] = "r.relationship='$relationship'";

		$on = "e.guid = r.guid_one";
		if (!$inverse_relationship)
			$on = "e.guid = r.guid_two";

		if ($type != "")
			$where[] = "e.type='$type'";
		if ($subtype)
			$where[] = "e.subtype=$subtype";
		if ($owner_guid != "")
			$where[] = "e.container_guid='$owner_guid'";
		if ($site_guid > 0)
			$where[] = "e.site_guid = {$site_guid}";
		if ($relationship_guid)
			$where[] = ($inverse_relationship ? "r.guid_two='$relationship_guid'" : "r.guid_one='$relationship_guid'");

		$metajoin = "";
		if (($meta_name!=="") || ($meta_value!=="")) {
			$metajoin = " JOIN {$CONFIG->dbprefix}metadata m on e.guid=m.entity_guid";

			if ($meta_name!=="")
				$where[] = "m.name_id='$meta_n'";
			if ($meta_value!=="")
				$where[] = "m.value_id='$meta_v'";
		}

		if ($count) {
			$query = "SELECT count(distinct e.guid) as total ";
		} else {
			$query = "SELECT distinct e.*, count(e.guid) as total ";
		}

		$query .= " from {$CONFIG->dbprefix}entity_relationships r JOIN {$CONFIG->dbprefix}entities e on {$on} {$metajoin} where ";

		if (!empty($where))
		foreach ($where as $w)
			$query .= " $w and ";
		$query .= get_access_sql_suffix("e"); // Add access controls
		if (($meta_name!=="") || ($meta_value!=="")) $query .= ' and ' . get_access_sql_suffix("m"); // Add access controls

		if (!$count) {
			$query .= " group by e.guid ";
			$query .= " order by total desc limit {$offset}, {$limit}"; // Add order and limit

			return get_data($query, "entity_row_to_elggstar");
		} else {
			if ($count = get_data_row($query)) {
				return $count->total;
			}
		}

		return false;
	}

	/**
	 * Sets the URL handler for a particular relationship type
	 *
	 * @param string $function_name The function to register
	 * @param string $relationship_type The relationship type.
	 * @return true|false Depending on success
	 */
	function register_relationship_url_handler($function_name, $relationship_type = "all") {
		global $CONFIG;

		if (!is_callable($function_name)) return false;

		if (!isset($CONFIG->relationship_url_handler)) {
			$CONFIG->relationship_url_handler = array();
		}

		$CONFIG->relationship_url_handler[$relationship_type] = $function_name;

		return true;

	}

	/**
	 * Get the url for a given relationship.
	 *
	 * @param unknown_type $id
	 * @return unknown
	 */
	function get_relationship_url($id)
	{
		global $CONFIG;

		$id = (int)$id;

		if ($relationship = get_relationship($id))
		{
			$view = elgg_get_viewtype();

			$guid = $relationship->guid_one;
			$type = $relationship->relationship;

			$url = "";

			$function = "";
			if (isset($CONFIG->relationship_url_handler[$type]))
				$function = $CONFIG->relationship_url_handler[$type];
			if (isset($CONFIG->relationship_url_handler['all']))
				$function = $CONFIG->relationship_url_handler['all'];

			if (is_callable($function)) {
				$url = $function($relationship);
			}

			if ($url == "") {

				$nameid = $relationship->id;

				$url = $CONFIG->wwwroot  . "export/$view/$guid/relationship/$nameid/";
			}

			return $url;

		}

		return false;
	}

	/**** HELPER FUNCTIONS FOR RELATIONSHIPS OF TYPE 'ATTACHED' ****/

	 /**
     * Function to determine if the object trying to attach to other, has already done so
     * @param int $guid_one This is the target object
     * @param int $guid_two This is the object trying to attach to $guid_one
     * @return true | false
     **/

     function already_attached($guid_one, $guid_two){

         if($attached = check_entity_relationship($guid_one, "attached", $guid_two)){
             return true;
         }else{
             return false;
         }
     }

     /**
     * Function to get all objects attached to a particular object
     * @param int $guid
     * @param string $type - the type of object to return e.g. 'file', 'friend_of' etc
     * @return an array of objects
    **/

        function get_attachments($guid, $type=""){

            $attached = get_entities_from_relationship("attached", $guid, $inverse_relationship = false, $type, $subtype = "", $owner_guid = 0, $order_by = "time_created desc", $limit = 10, $offset = 0, $count = false, $site_guid = 0);
            return $attached;

        }

     /**
     * Function to remove a particular attachment between two objects
     * @param int $guid_one This is the target object
     * @param int $guid_two This is the object to remove from $guid_one
     * @return a view
    **/

        function remove_attachment($guid_one, $guid_two){

            if(already_attached($guid_one, $guid_two))
                remove_entity_relationship($guid_one, "attached", $guid_two);

        }

     /**
     * Function to start the process of attaching one object to another
     * @param int $guid_one This is the target object
     * @param int $guid_two This is the object trying to attach to $guid_one
     * @return a view
    **/

        function make_attachment($guid_one, $guid_two){

            if(!(already_attached($guid_one, $guid_two)))
                if(add_entity_relationship($guid_one, "attached", $guid_two))
                    return true;

        }

	/**
	 *  Handler called by trigger_plugin_hook on the "import" event.
	 */
	function import_relationship_plugin_hook($hook, $entity_type, $returnvalue, $params)
	{
		$element = $params['element'];

		$tmp = NULL;

		if ($element instanceof ODDRelationship)
		{
			$tmp = new ElggRelationship();
			$tmp->import($element);

			return $tmp;
		}
	}

	/**
	 *  Handler called by trigger_plugin_hook on the "export" event.
	 */
	function export_relationship_plugin_hook($hook, $entity_type, $returnvalue, $params)
	{
		global $CONFIG;

		// Sanity check values
		if ((!is_array($params)) && (!isset($params['guid'])))
			throw new InvalidParameterException(elgg_echo('InvalidParameterException:GUIDNotForExport'));

		if (!is_array($returnvalue))
			throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonArrayReturnValue'));

		$guid = (int)$params['guid'];

		$result = get_entity_relationships($guid);

		if ($result)
		{
			foreach ($result as $r)
				$returnvalue[] = $r->export();
		}

		return $returnvalue;
	}

    /**
     * An event listener which will notify users based on certain events.
     *
     * @param unknown_type $event
     * @param unknown_type $object_type
     * @param unknown_type $object
     */
	function relationship_notification_hook($event, $object_type, $object)
	{
		global $CONFIG;

		if (
			($object instanceof ElggRelationship) &&
			($event == 'create') &&
			($object_type == 'friend')
		)
		{
			$user_one = get_entity($object->guid_one);
			$user_two = get_entity($object->guid_two);

			// Notify target user
			return notify_user($object->guid_two, $object->guid_one, sprintf(elgg_echo('friend:newfriend:subject'), $user_one->name),
				sprintf(elgg_echo("friend:newfriend:body"), $user_one->name, $CONFIG->site->url . "pg/profile/" . $user_one->username)
			);
		}
	}

	/** Register the import hook */
	register_plugin_hook("import", "all", "import_relationship_plugin_hook", 3);

	/** Register the hook, ensuring entities are serialised first */
	register_plugin_hook("export", "all", "export_relationship_plugin_hook", 3);

	/** Register event to listen to some events **/
	register_elgg_event_handler('create','friend','relationship_notification_hook');
?>


text:
namespace uc
{
    namespace os
    {
        namespace windows
        {
            class com_initializer : private util::noncopyable
            {
            public:
                com_initializer()
                {
                    HRESULT hr = ::CoInitializeEx(nullptr, COINIT_MULTITHREADED);

                    bool success = (hr == S_OK || hr == S_FALSE);

                    if (!success)
                    {
                        throw com_exception(hr);
                    }
                }

                ~com_initializer()
                {
                    ::CoUninitialize();
                }

            };
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.arakhne.afc.ui.vector;

import java.lang.ref.SoftReference;
import java.net.URL;

import org.arakhne.afc.math.continous.object2d.Point2f;
import org.arakhne.afc.math.continous.object2d.Rectangle2f;
import org.arakhne.afc.math.continous.object2d.Shape2f;
import org.arakhne.afc.math.generic.Point2D;
import org.arakhne.afc.ui.Graphics2DLOD;
import org.arakhne.afc.ui.TextAlignment;
import org.arakhne.afc.vmutil.Resources;

/** This graphic context permits to display
 *  something with a level of details.
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 * @deprecated see JavaFX API
 */
@Deprecated
public abstract class AbstractVectorGraphics2D implements VectorGraphics2D {

	private boolean isInteriorPainted = true;
	private boolean isOutlinePainted = true;
	private String interiorText = null;
	private Color outlineColor = null;
	private Color fillColor = null;
	private Paint paint = null;

	private static SoftReference<Image> noPictureBuffer = null;
	private static SoftReference<Image> noTransparentPictureBuffer = null;

	/**
	 */
	public AbstractVectorGraphics2D() {
		//
	}

	private static Image getNoPicture() {
		Image noPictureImage = noPictureBuffer==null ? null : noPictureBuffer.get();
		if (noPictureImage==null) {
			URL url = Resources.getResource(AbstractVectorGraphics2D.class, "no_picture.png");  //$NON-NLS-1$
			if (url!=null) {
				try {
					noPictureImage = VectorToolkit.image(url);
					noPictureBuffer = new SoftReference<>(noPictureImage);
				}
				catch(Throwable exception) {
					noPictureImage = null;
					noPictureBuffer = null;
				}
			}
		}
		return noPictureImage;
	}

	private static Image getTransparentNoPicture() {
		Image noPictureImage = noTransparentPictureBuffer==null ? null : noTransparentPictureBuffer.get();
		if (noPictureImage==null) {
			Image originalImage = getNoPicture();
			if (originalImage!=null) {
				noPictureImage = VectorToolkit.image(originalImage, -.5f);
				noTransparentPictureBuffer = new SoftReference<>(noPictureImage);
			}
		}
		return noPictureImage;
	}

	@Override
	public final void drawDefaultImage(float dx1, float dy1, float dx2, float dy2) {
		Image noPictureImage;
		if (getLOD()==Graphics2DLOD.SHADOW) {
			noPictureImage = getTransparentNoPicture();
		}
		else {
			noPictureImage = getNoPicture();
		}

		if (noPictureImage!=null) {
			drawImage(
					null,
					noPictureImage,
					dx1, dy1, dx2, dy2,
					0, 0, noPictureImage.getWidth(null), noPictureImage.getHeight(null),
					null);
		}
		else {
			setInteriorPainted(true);
			Rectangle2f bounds = new Rectangle2f();
			bounds.setFromCorners(dx1, dy1, dx2, dy2);
			draw(bounds);
		}
	}

	/**
	 * @param fillColor is the initial filling color.
	 * @param outlineColor is the initial outline color.
	 * @param paint is the initial painting object.
	 * @param isInteriorPainted is the initial interior painting flag.
	 * @param isOutlinePainted is the initial outline painting flag.
	 * @param interiorText is the initial text inside a shape.
	 */
	public AbstractVectorGraphics2D(Color fillColor, Color outlineColor, Paint paint, boolean isInteriorPainted, boolean isOutlinePainted, String interiorText) {
		this.fillColor = fillColor;
		this.outlineColor = outlineColor;
		this.paint = paint;
		this.isInteriorPainted = isInteriorPainted;
		this.isOutlinePainted = isOutlinePainted;
		this.interiorText = interiorText;
	}

	@Override
	public void dispose() {
		this.isInteriorPainted = true;
		this.isOutlinePainted = true;
		this.interiorText = null;
		this.outlineColor = this.fillColor = null;
		this.paint = null;
	}

	@Override
	public void reset() {
		this.isInteriorPainted = true;
		this.isOutlinePainted = true;
		this.interiorText = null;
		this.outlineColor = this.fillColor = null;
		this.paint = null;
	}

	/** Log the given message.
	 *
	 * @param message is the message to log.
	 */
	protected void log(String message) {
		System.out.println(toString()+": "+message);  //$NON-NLS-1$
	}

	/** Log the given message.
	 *
	 * @param message is the message to log out.
	 * @param exception is the exception to log out.
	 */
	protected void log(String message, Throwable exception) {
		String tag = toString();
		System.out.println(tag+": "+message);  //$NON-NLS-1$
		System.out.println(tag+": "+exception.getLocalizedMessage());  //$NON-NLS-1$
		exception.printStackTrace();
	}

	/** Clean the state machine prior to any drawing.
	 */
	protected void preDrawing() {
		//
	}

	/** Clean the state machine after any drawing.
	 */
	protected void postDrawing() {
		this.interiorText = null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Font getDefaultFont() {
		return VectorToolkit.font();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Paint setPaint(Paint paint) {
		Paint o = this.paint;
		this.paint = paint;
		return o;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Color setFillColor(Color color) {
		Color o = this.fillColor;
		this.fillColor = color;
		return o;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Color setOutlineColor(Color color) {
		Color o = this.outlineColor;
		this.outlineColor = color;
		return o;
	}

	@Override
	public void setColors(Color fillingColor, Color outlineColor) {
		if (fillingColor!=null) {
			setFillColor(fillingColor);
			setInteriorPainted(true);
		}
		else {
			setInteriorPainted(false);
		}
		if (outlineColor!=null) {
			setOutlineColor(fillingColor);
			setOutlineDrawn(true);
		}
		else {
			setOutlineDrawn(false);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Color getFillColor() {
		return this.fillColor;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Color getOutlineColor() {
		return this.outlineColor;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Paint getPaint() {
		return this.paint;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean isInteriorPainted() {
		return this.isInteriorPainted;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setInteriorPainted(boolean painted) {
		this.isInteriorPainted = painted;
	}

	@Override
	public Point2D computeTextPosition(String text, Rectangle2f bounds,
			TextAlignment halign, TextAlignment valign) {
		FontMetrics fm = getFontMetrics();
		float width = fm.stringWidth(text);
		float height = fm.getHeight();
		float x = 0;
		float y = 0;

		switch(halign) {
		case CENTER_ALIGN:
			x = bounds.getMinX() + (bounds.getWidth() - width) / 2f;
			break;
		case LEFT_ALIGN:
			x = bounds.getMinX();
			break;
		case RIGHT_ALIGN:
			x = bounds.getMinX() + bounds.getWidth() - width;
			break;
		default:
			throw new IllegalArgumentException();
		}

		switch(getStringAnchor()) {
		case UPPER_LEFT:
			switch(valign) {
			case CENTER_ALIGN:
				y = bounds.getMinY() + (bounds.getHeight() - height) / 2f;
				break;
			case LEFT_ALIGN:
				y = bounds.getMinY();
				break;
			case RIGHT_ALIGN:
				y = bounds.getMinY() + bounds.getHeight() - height;
				break;
			default:
				throw new IllegalArgumentException();
			}
			break;
		case LEFT_BASELINE:
			switch(valign) {
			case CENTER_ALIGN:
				y = bounds.getMinY() + (bounds.getHeight() - height) / 2f + fm.getMaxAscent();
				break;
			case LEFT_ALIGN:
				y = bounds.getMinY() + fm.getMaxAscent();
				break;
			case RIGHT_ALIGN:
				y = bounds.getMinY() + bounds.getHeight() - fm.getMaxDescent();
				break;
			default:
				throw new IllegalArgumentException();
			}
			break;
		case LOWER_LEFT:
			switch(valign) {
			case CENTER_ALIGN:
				y = bounds.getMinY() + (bounds.getHeight() + height) / 2f;
				break;
			case LEFT_ALIGN:
				y = bounds.getMinY() + fm.getHeight();
				break;
			case RIGHT_ALIGN:
				y = bounds.getMaxY();
				break;
			default:
				throw new IllegalArgumentException();
			}
			break;
		default:
			throw new IllegalArgumentException();
		}
		return new Point2f(x, y);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean isOutlineDrawn() {
		return this.isOutlinePainted;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setOutlineDrawn(boolean outlined) {
		this.isOutlinePainted = outlined;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getInteriorText() {
		return this.interiorText;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setInteriorText(String interiorText) {
		this.interiorText = interiorText;
	}

	/** This method paint a string into the rectangle of this figure and
	 * not outside. The text is centered on the figure.
	 *
	 * @param text the text to draw.
	 * @param figureBounds are the bounds of the figure that may be used during the drawing.
	 * @param clip is the shape that should be used for clipping.
	 */
	protected final void paintString(String text, Rectangle2f figureBounds, Shape2f clip) {
		Point2D p = computeTextPosition(text, figureBounds, TextAlignment.CENTER_ALIGN, TextAlignment.CENTER_ALIGN);
		paintString( text, p.getX(), p.getY(), clip );
	}

	/** This method paint a string into the rectangle of this figure and
	 * not outside. The text is centered on the figure.
	 * In opposite to {@link #drawString(String, float, float, Shape2f)},
	 * thius function does not invoke {@link #preDrawing()} nor
	 * {@link #postDrawing()}.
	 *
	 * @param text the text to draw.
	 * @param x is the position of the text.
	 * @param y is the position of the text.
	 * @param clip is the shape that should be used for clipping.
	 */
	protected abstract void paintString(String text, float x, float y, Shape2f clip);

	@Override
	public final void drawString(String str, float x, float y) {
		preDrawing();
		paintString(str, x,  y, null);
		postDrawing();
	}

	@Override
	public final void drawString(String str, float x, float y, Shape2f clip) {
		preDrawing();
		paintString(str, x,  y, null);
		postDrawing();
	}
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_65b.c
Label Definition File: CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close.label.xml
Template File: source-sinks-65b.tmpl.c
*/
/*
 * @description
 * CWE: 775 Missing Release of File Descriptor or Handle After Effective Lifetime
 * BadSource:  Open a file using CreateFile()
 * Sinks:
 *    GoodSink: Close the file using CloseHandle()
 *    BadSink : Do not close file
 * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer
 *
 * */

#include "std_testcase.h"

#include <windows.h>

#ifndef OMITBAD

void CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_65b_badSink(HANDLE data)
{
    /* FLAW: No attempt to close the file */
    ; /* empty statement needed for some flow variants */
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G uses the BadSource with the GoodSink */
void CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_65b_goodB2GSink(HANDLE data)
{
    /* FIX: If the file is still opened, close it */
    if (data != INVALID_HANDLE_VALUE)
    {
        CloseHandle(data);
    }
}

#endif /* OMITGOOD */


text:
import React from 'react';
import BigCalendar from 'react-big-calendar';
import moment from 'moment';
import '../styles/react-big-calendar.scss';
import events from '../styles/events.scss';
import axios from 'axios';
import UpcomingEvents from '../components/UpcomingEvents';
import { WP_DOMAIN } from '../../wp.config';
import { Link } from 'react-router';
import upcomingevents from '../styles/upcomingevents.scss';

BigCalendar.setLocalizer(
  BigCalendar.momentLocalizer(moment)
);

class Events extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            eventsList: [],
            mobileEventsList: [],
            selectedEvent:

,
            eventHidden: true,
            x: 0,
            y: 0
        };
        this.setEvent = this.setEvent.bind(this);
        this.hidePopup = this.hidePopup.bind(this);
    }

    componentWillMount() {
        axios.get(`${WP_DOMAIN}/wp-json/wp/v2/events`)
            .then((res) => {
                this.setState({eventsList: res.data.map((data) => {
                    return {
                        title: data.title.rendered,
                        description: data.acf.event_description,
                        reservations: data.link,
                        start: data.acf.event_start_date + ' ' + data.acf.event_time,
                        end: '',
                        isThumbnail: data.acf.is_thumbnail,
                        image: data.acf.event_image,
                        eventTicketLink: data.acf.event_ticket_link
                    };
                })
            });
                this.setState({mobileEventsList: res.data});
            })
            .catch((err) => {
                console.log(err, 'there was an error');
            });
    }

    componentDidMount() {
        window.scrollTo(0, 0);
    }

    showOverlay(event) {
        event.currentTarget.style.opacity = '1';
    }

    hideOverlay(event) {
        event.currentTarget.style.opacity = '0';
    }

    hidePopup() {
        this.setState({eventHidden: true});
    }

    setEvent(event, e) {
        let X = e.nativeEvent.pageX;
        const Y = e.nativeEvent.pageY - 200;

        if (X < 200) {
            X += 50;
        } else {
            X -= 400;
        }

        const renderHTML = (rawHTML) => React.createElement('div', { dangerouslySetInnerHTML: { __html: rawHTML } });
        this.setState({x: X, y: Y}, () => {
            const CURRENT_EVENT =
                    (

                        <div className={`${events.image_wrapper} ${upcomingevents.image_wrapper}`}>

                                {event.eventTicketLink ? (
                                    <Link href={`${event.eventTicketLink}`} className="button" rel="external" target="_blank">Buy Tickets</Link>
                                ) : (
                                    <Link className="button" to="/guestlist">Guestlist</Link>
                                )}

                                <Link className="button" to="/table-reservations">Table Reservations</Link>

{renderHTML(event.title)}

                            {event.start}

{renderHTML(event.description)}

);
            this.setState({selectedEvent: CURRENT_EVENT});
            this.showEvent(event);
        });
    }

    showEvent() {
        this.setState({eventHidden: false});
        return (

{this.state.selectedEvent}

        );
    }

    eventStyleGetter() {
        return {
            style: {
                backgroundColor: 'none',
                // background: 'url(' + event.image + ')',
                borderRadius: '0',
                opacity: 1,
                color: 'white',
                position: 'float',
                display: 'block'
            }
        };
    }

    EventMonth({ event }) {
        const renderHTML = (rawHTML) => React.createElement('div', { dangerouslySetInnerHTML: { __html: rawHTML } });
        if (event.isThumbnail) {
            return (

                    <div className={events.event_image} style={{
                        backgroundImage: `url(${event.image})`,
                        backgroundSize: 'contain',
                        backgroundRepeat: 'no-repeat',
                        opacity: 0.6,
                        height: '100vh',
                        width: '13%',
                        position: 'absolute',
                        top: 0,
                        zIndex: '-1'
                    }}>

                    {renderHTML(event.title)}

            );
        }
        return (

                {renderHTML(event.title)}

        );
    }

    DayWrapper() {
        return (

        );
    }

    render() {
        return (

                    <div className={events.overlay} style={{left: `${this.state.x}px`, top: `${this.state.y}px`, display: `${
                        this.state.eventHidden ? 'none' : 'block'}`}}
                        onMouseLeave={this.hidePopup}
                    >
                        {this.state.selectedEvent}

                    <BigCalendar
                    className={events.calendar}
                    events={this.state.eventsList}
                    views={['month', 'agenda']}
                    endAccessor="start"
                    eventPropGetter={(this.eventStyleGetter)}
                    components={{
                        month: {
                            event: this.EventMonth
                        }
                    }}
                    onSelectEvent={this.setEvent}
                    />

                        <UpcomingEvents eventsList={this.state.mobileEventsList} />

        );
    }
}

Events.propTypes = {
    eventsList: React.PropTypes.array
};

export default Events;


text:
<?php

namespace app\modules\user\models\forms;
use Yii;
use app\modules\user\models\User;
use yii\base\Model;

/**
 * Форма восстановления пароля
 * Class PasswordResetForm
 * @package lowbase\user\models\forms
 */
class PasswordResetForm extends Model
{
    public $email;      // Электронная почта
    public $password;   // Пароль
    /**
     * Правила валидации
     * @return array
     */
    public function rules()
    {
        return [
            [['email', 'password'], 'required'], // Обязательны для заполнения
            [['password'], 'string', 'min' => 6],   // Пароль минимум 4 символа
            ['email', 'email'], // Электронная почта
            ['email', 'exist',
                'targetClass' => 'app\modules\user\models\User',
                'message' => 'User with Email is not registered.'
            ],  // Значение электронной почты должно присутствовать в базе данных
        ];
    }
    /**
     * Наименования полей формы
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'password' => 'New password',
            'email' => 'Email',
        ];
    }
    /**
     * Отправка сообщения с подтверждением
     * нового пароля
     * @return bool
     */
    public function sendEmail()
    {
        /* @var $user User */
        $user = User::findOne(['email' => $this->email]);
        if ($user) {
            if (!User::isPasswordResetTokenValid($user->password_reset_token)) {
                $user->generatePasswordResetToken();
            }
            //print_r('343434');
            if ($user->save(false)) {
               // print_r('454545');
                // Отправка по шаблону письма "passwordResetToken"
                $view = '@app/modules/user/mail/passwordResetToken';
                if (method_exists(\Yii::$app->controller->module, 'getCustomMailView')) {
                    $view = \Yii::$app->controller->module->getCustomMailView('passwordResetToken', $view);
                }
                return \Yii::$app->mailer->compose($view, [
                    'model' => $user,
                    'password' => $this->password
                ])
                    ->setFrom(\Yii::$app->config->get('adminEmail'))
                    ->setTo($this->email)
                    ->setSubject('Password Reset Online')
                    ->send();
            }
        }
        return false;
    }
}


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.base.memory;

import android.content.ComponentCallbacks2;
import android.os.Looper;

import androidx.test.filters.SmallTest;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowLooper;

import org.chromium.base.MemoryPressureLevel;
import org.chromium.base.ThreadUtils;
import org.chromium.base.supplier.Supplier;
import org.chromium.base.test.BaseRobolectricTestRunner;

import java.util.concurrent.TimeUnit;

/**
 * Test for MemoryPressureMonitor.
 */
@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class MemoryPressureMonitorTest {
    private MemoryPressureMonitor mMonitor;

    private static class TestPressureCallback implements MemoryPressureCallback {
        private Integer mReportedPressure;

        public void assertCalledWith(@MemoryPressureLevel int expectedPressure) {
            Assert.assertNotNull("Callback was not called", mReportedPressure);
            Assert.assertEquals(expectedPressure, (int) mReportedPressure);
        }

        public void assertNotCalled() {
            Assert.assertNull(mReportedPressure);
        }

        public void reset() {
            mReportedPressure = null;
        }

        @Override
        public void onPressure(@MemoryPressureLevel int pressure) {
            assertNotCalled();
            mReportedPressure = pressure;
        }
    }

    private static class TestPressureSupplier implements Supplier<Integer> {
        private @MemoryPressureLevel Integer mPressure;
        private boolean mIsCalled;

        public TestPressureSupplier(@MemoryPressureLevel Integer pressure) {
            mPressure = pressure;
        }

        @Override
        public @MemoryPressureLevel Integer get() {
            assertNotCalled();
            mIsCalled = true;
            return mPressure;
        }

        public void assertCalled() {
            Assert.assertTrue(mIsCalled);
        }

        public void assertNotCalled() {
            Assert.assertFalse(mIsCalled);
        }
    }

    private static final int THROTTLING_INTERVAL_MS = 1000;

    @Before
    public void setUp() {
        // Explicitly set main thread as UiThread. Other places rely on that.
        ThreadUtils.setUiThread(Looper.getMainLooper());

        // Pause main thread to get control over when tasks are run (see runUiThreadFor()).
        ShadowLooper.pauseMainLooper();

        mMonitor = new MemoryPressureMonitor(THROTTLING_INTERVAL_MS);
        mMonitor.setCurrentPressureSupplierForTesting(null);
    }

    /**
     * Runs all UiThread tasks posted |delayMs| in the future.
     * @param delayMs
     */
    private void runUiThreadFor(long delayMs) {
        ShadowLooper.idleMainLooper(delayMs, TimeUnit.MILLISECONDS);
    }

    @Test
    @SmallTest
    public void testTrimLevelTranslation() {
        Integer[][] trimLevelToPressureMap = {//
                // Levels >= TRIM_MEMORY_COMPLETE map to CRITICAL.
                {ComponentCallbacks2.TRIM_MEMORY_COMPLETE + 1, MemoryPressureLevel.CRITICAL},
                {ComponentCallbacks2.TRIM_MEMORY_COMPLETE, MemoryPressureLevel.CRITICAL},

                // TRIM_MEMORY_RUNNING_CRITICAL maps to CRITICAL.
                {ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL, MemoryPressureLevel.CRITICAL},

                // Levels < TRIM_MEMORY_COMPLETE && >= TRIM_MEMORY_BACKGROUND map to MODERATE.
                {ComponentCallbacks2.TRIM_MEMORY_COMPLETE - 1, MemoryPressureLevel.MODERATE},
                {ComponentCallbacks2.TRIM_MEMORY_BACKGROUND + 1, MemoryPressureLevel.MODERATE},
                {ComponentCallbacks2.TRIM_MEMORY_BACKGROUND, MemoryPressureLevel.MODERATE},

                // Other levels are not mapped.
                {ComponentCallbacks2.TRIM_MEMORY_BACKGROUND - 1, null},
                {ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW, null},
                {ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE, null},
                {ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN, null}};
        for (Integer[] trimLevelAndPressure : trimLevelToPressureMap) {
            int trimLevel = trimLevelAndPressure[0];
            Integer expectedPressure = trimLevelAndPressure[1];
            Integer actualPressure = MemoryPressureMonitor.memoryPressureFromTrimLevel(trimLevel);
            Assert.assertEquals(expectedPressure, actualPressure);
        }
    }

    @Test
    @SmallTest
    public void testThrottleInterval() {
        TestPressureCallback callback = new TestPressureCallback();
        mMonitor.setReportingCallbackForTesting(callback);

        // First notification should go through.
        mMonitor.notifyPressure(MemoryPressureLevel.NONE);
        callback.assertCalledWith(MemoryPressureLevel.NONE);

        callback.reset();

        // This one should be throttled.
        mMonitor.notifyPressure(MemoryPressureLevel.NONE);
        callback.assertNotCalled();

        runUiThreadFor(THROTTLING_INTERVAL_MS - 1);

        // We're still within the throttling interval, so this notification should
        // still be throttled.
        mMonitor.notifyPressure(MemoryPressureLevel.NONE);
        callback.assertNotCalled();

        runUiThreadFor(1);

        // We're past the throttling interval at this point, so this notification
        // should go through.
        mMonitor.notifyPressure(MemoryPressureLevel.NONE);
        callback.assertCalledWith(MemoryPressureLevel.NONE);
    }

    @Test
    @SmallTest
    public void testChangeNotIgnored() {
        TestPressureCallback callback = new TestPressureCallback();
        mMonitor.setReportingCallbackForTesting(callback);

        mMonitor.notifyPressure(MemoryPressureLevel.NONE);
        callback.assertCalledWith(MemoryPressureLevel.NONE);

        callback.reset();

        // Second notification is throttled, but should be reported after the
        // throttling interval ends.
        mMonitor.notifyPressure(MemoryPressureLevel.MODERATE);
        callback.assertNotCalled();

        runUiThreadFor(THROTTLING_INTERVAL_MS - 1);

        // Shouldn't be reported at this point.
        callback.assertNotCalled();

        runUiThreadFor(1);

        callback.assertCalledWith(MemoryPressureLevel.MODERATE);
    }

    @Test
    @SmallTest
    public void testNoopChangeIgnored() {
        TestPressureCallback callback = new TestPressureCallback();
        mMonitor.setReportingCallbackForTesting(callback);

        mMonitor.notifyPressure(MemoryPressureLevel.NONE);
        callback.assertCalledWith(MemoryPressureLevel.NONE);

        callback.reset();

        // Report MODERATE and then NONE, so that the throttling interval finishes with the
        // same pressure that started it (i.e. NONE). In this case MODERATE should be ignored.
        mMonitor.notifyPressure(MemoryPressureLevel.MODERATE);
        mMonitor.notifyPressure(MemoryPressureLevel.NONE);

        runUiThreadFor(THROTTLING_INTERVAL_MS);

        callback.assertNotCalled();
    }

    @Test
    @SmallTest
    public void testPollingInitiallyDisabled() {
        TestPressureSupplier pressureSupplier =
                new TestPressureSupplier(MemoryPressureLevel.MODERATE);
        mMonitor.setCurrentPressureSupplierForTesting(pressureSupplier);

        mMonitor.notifyPressure(MemoryPressureLevel.CRITICAL);
        runUiThreadFor(THROTTLING_INTERVAL_MS);

        // We finished the interval with CRITICAL, but since polling is disabled, we shouldn't
        // poll the current pressure.
        pressureSupplier.assertNotCalled();
    }

    @Test
    @SmallTest
    public void testEnablePollingPolls() {
        TestPressureCallback callback = new TestPressureCallback();
        mMonitor.setReportingCallbackForTesting(callback);

        TestPressureSupplier pressureSupplier =
                new TestPressureSupplier(MemoryPressureLevel.MODERATE);
        mMonitor.setCurrentPressureSupplierForTesting(pressureSupplier);

        mMonitor.enablePolling();

        // When polling is enabled, current pressure should be retrieved and reported.
        pressureSupplier.assertCalled();
        callback.assertCalledWith(MemoryPressureLevel.MODERATE);
    }

    @Test
    @SmallTest
    public void testNullSupplierResultIgnored() {
        TestPressureCallback callback = new TestPressureCallback();
        mMonitor.setReportingCallbackForTesting(callback);

        TestPressureSupplier pressureSupplier = new TestPressureSupplier(null);
        mMonitor.setCurrentPressureSupplierForTesting(pressureSupplier);

        mMonitor.enablePolling();

        // The pressure supplier should be called, but its null result should be ignored.
        pressureSupplier.assertCalled();
        callback.assertNotCalled();
    }

    @Test
    @SmallTest
    public void testEnablePollingRespectsThrottling() {
        TestPressureSupplier pressureSupplier =
                new TestPressureSupplier(MemoryPressureLevel.MODERATE);
        mMonitor.setCurrentPressureSupplierForTesting(pressureSupplier);

        mMonitor.notifyPressure(MemoryPressureLevel.NONE);

        // The notification above started a throttling interval, so we shouldn't ask for the
        // current pressure when polling is enabled.
        mMonitor.enablePolling();

        pressureSupplier.assertNotCalled();
    }

    @Test
    @SmallTest
    public void testPollingIfCRITICAL() {
        TestPressureCallback callback = new TestPressureCallback();
        mMonitor.setReportingCallbackForTesting(callback);

        TestPressureSupplier pressureSupplier =
                new TestPressureSupplier(MemoryPressureLevel.MODERATE);
        mMonitor.setCurrentPressureSupplierForTesting(pressureSupplier);

        mMonitor.notifyPressure(MemoryPressureLevel.CRITICAL);
        callback.reset();

        mMonitor.enablePolling();

        runUiThreadFor(THROTTLING_INTERVAL_MS - 1);

        // Pressure should be polled after the interval ends, not before.
        pressureSupplier.assertNotCalled();

        runUiThreadFor(1);

        // We started and finished the throttling interval with CRITICAL pressure, so
        // we should poll the current pressure at the end of the interval.
        pressureSupplier.assertCalled();
        callback.assertCalledWith(MemoryPressureLevel.MODERATE);
    }

    @Test
    @SmallTest
    public void testNoPollingIfNotCRITICAL() {
        TestPressureSupplier pressureSupplier = new TestPressureSupplier(MemoryPressureLevel.NONE);
        mMonitor.setCurrentPressureSupplierForTesting(pressureSupplier);

        mMonitor.notifyPressure(MemoryPressureLevel.MODERATE);

        mMonitor.enablePolling();

        runUiThreadFor(THROTTLING_INTERVAL_MS);

        // We started and finished the throttling interval with non-CRITICAL pressure,
        // so no polling should take place.
        pressureSupplier.assertNotCalled();
    }

    @Test
    @SmallTest
    public void testNoPollingIfChangedToCRITICAL() {
        TestPressureSupplier pressureSupplier = new TestPressureSupplier(MemoryPressureLevel.NONE);
        mMonitor.setCurrentPressureSupplierForTesting(pressureSupplier);

        mMonitor.notifyPressure(MemoryPressureLevel.MODERATE);
        mMonitor.notifyPressure(MemoryPressureLevel.CRITICAL);

        mMonitor.enablePolling();

        runUiThreadFor(THROTTLING_INTERVAL_MS);

        // We finished the throttling interval with CRITITCAL, but started with MODERATE,
        // so no polling should take place.
        pressureSupplier.assertNotCalled();
    }

    @Test
    @SmallTest
    public void testDisablePolling() {
        TestPressureSupplier pressureSupplier = new TestPressureSupplier(MemoryPressureLevel.NONE);
        mMonitor.setCurrentPressureSupplierForTesting(pressureSupplier);

        mMonitor.notifyPressure(MemoryPressureLevel.CRITICAL);

        mMonitor.enablePolling();

        runUiThreadFor(THROTTLING_INTERVAL_MS - 1);

        // Whether polling is enabled or not should be taken into account only after the interval
        // finishes, so disabling it here should have the same affect as if it was never enabled.
        mMonitor.disablePolling();

        runUiThreadFor(1);

        pressureSupplier.assertNotCalled();
    }
}


text:
var port = 3000;

var express = require('express');
var path = require('path');

var app = express();

app.use(express.logger('dev'));
app.use(app.router);
app.use(express.static(path.join(__dirname, 'resources')));

app.listen(port, function () {
	console.log('Express server listening on port ' + port);
});


text:
package org.diirt.datasource.expression;

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

/**
 * Implementation class for {@link DesiredRateReadWriteExpressionList}.
 *
 * @param <R> type of read payload
 * @param <W> type of write payload
 * @author carcassi
 */
public class DesiredRateReadWriteExpressionListImpl<R, W> implements DesiredRateReadWriteExpressionList<R, W> {

    private List<DesiredRateReadWriteExpression<R, W>> desiredRateReadWriteExpressions = new ArrayList<DesiredRateReadWriteExpression<R, W>>();

    final void addThis() {
        desiredRateReadWriteExpressions.add((DesiredRateReadWriteExpression<R, W>) this);
    }

    @Override
    public final DesiredRateReadWriteExpressionList<R, W> and(DesiredRateReadWriteExpressionList<? extends R, ? extends W> expressions) {
        @SuppressWarnings("unchecked")
        DesiredRateReadWriteExpressionList<R, W> newExpression = (DesiredRateReadWriteExpressionList<R, W>) (DesiredRateReadWriteExpressionList) expressions;
        desiredRateReadWriteExpressions.addAll(newExpression.getDesiredRateReadWriteExpressions());
        return this;
    }

    @Override
    public final List<DesiredRateReadWriteExpression<R, W>> getDesiredRateReadWriteExpressions() {
        return desiredRateReadWriteExpressions;
    }

    @Override
    public final DesiredRateExpressionList<R> and(DesiredRateExpressionList<? extends R> expressions) {
        @SuppressWarnings("unchecked")
        DesiredRateExpressionList<R> newExpression = (DesiredRateExpressionList<R>) (DesiredRateExpressionList) expressions;
        return new DesiredRateExpressionListImpl<R>(desiredRateReadWriteExpressions).and(newExpression);
    }

    @Override
    public final List<DesiredRateExpression<R>> getDesiredRateExpressions() {
        return Collections.<DesiredRateExpression<R>>unmodifiableList(desiredRateReadWriteExpressions);
    }

    @Override
    public final WriteExpressionList<W> and(WriteExpressionList<? extends W> expressions) {
        @SuppressWarnings("unchecked")
        WriteExpressionList<W> newExpression = (WriteExpressionList<W>) (WriteExpressionList) expressions;
        return new WriteExpressionListImpl<W>(desiredRateReadWriteExpressions).and(newExpression);
    }

    @Override
    public final List<WriteExpression<W>> getWriteExpressions() {
        return Collections.<WriteExpression<W>>unmodifiableList(desiredRateReadWriteExpressions);
    }

}


text:
<!DOCTYPE html>

    <title>---</title>
    <link rel="stylesheet" href="/js/libs/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/style.css">

    <link rel="stylesheet" href="/js/libs/bootstrap-tag.css">

Project Victory – Banned Users

Connected

Disconnected

Insert twiter usernames below (without "@" symbol and using a comma to seperate or press enter to add):

            <input type="text" name="tags" id="tags" class="span10">

Save changes


text: A really cool IRC bouncer.


text:
angular.module('os.administrative.user.detail', ['os.administrative.models'])
  .controller('UserDetailCtrl', function(
    $scope, $q, $translate, $state, $stateParams, user,
    User, AuthDomain, AuthService, PvManager, Alerts, DeleteUtil, Util, VueApp) {

    function init() {
      if (!$stateParams.old || $stateParams.old == 'false') {
        var url = $state.href($state.$current.name, $stateParams);
        VueApp.setVueView(url.substring(2), {});
        return;
      }

      $scope.user = user;
      loadPvs();
    }

    function loadPvs() {
      $scope.sites = PvManager.getSites();
      $scope.domains = [];
      AuthDomain.getDomainNames().then(function(domains) {
        $scope.domains = domains;
      })
    }

    function updateStatus(status, msgKey) {
      $scope.user.updateStatus(status).then(
        function(savedUser) {
          $scope.user = savedUser;
          Alerts.success(msgKey);
        }
      );
    }

    $scope.editUser = function(property, value) {
      var d = $q.defer();
      d.resolve({});
      return d.promise;
    }

    $scope.activate = function() {
      var s = $scope.user.activityStatus;
      var msgKey = s == 'Locked' ? 'user_unlocked' : (s == 'Closed' ? 'user_reactivated' : 'user_request_approved');
      updateStatus('Active', 'user.' + msgKey);
    }

    $scope.archive = function() {
      updateStatus('Closed', 'user.user_archived');
    }

    $scope.lock = function() {
      updateStatus('Locked', 'user.user_locked');
    }

    $scope.deleteUser = function() {
      DeleteUtil.delete($scope.user, {
        onDeleteState: 'user-list',
        confirmDelete: $scope.user.activityStatus == 'Pending' ? 'user.confirm_reject' : undefined
      });
    }

    $scope.impersonate = function() {
      Util.showConfirm({
        title: 'user.impersonate_as',
        input: {user: $scope.user},
        confirmMsg: 'user.confirm_impersonate_as',
        ok: function() {
          AuthService.impersonate($scope.user).then(
            function() {
              $state.go('home', {}, {reload: true});
            }
          );
        }
      });
    }

    init();

  });


text: Testing my mobile git


text:
<?php

namespace Tests\LeagueOfLegendsBundle\Controller\Player;

use Symfony\Component\HttpFoundation\Request;
use Tests\WebTestCase;

class PlayersRiotAccountsControllerTest extends WebTestCase
{
    const BASE_URL = '/lol/players';
    const PLAYER_TOUCOUILLE_UUID = '39a1dfaa-291a-4966-8e5b-73962b58fddb';
    const RIOT_ACCOUNT_TOUCOUILLE_UUID = 'cdbca45a-be09-4261-a9a8-b8f354b7c5d7';

    /**
     * @group smoke
     *
     * @param string $uuid
     * @param int    $expectedStatusCode
     *
     * @dataProvider getPlayersRiotAccountsProvider
     */
    public function testGetPlayersRiotAccounts($uuid, $expectedStatusCode)
    {
        $this->client->request(Request::METHOD_GET, self::BASE_URL."/{$uuid}/riot-accounts");

        self::assertEquals($expectedStatusCode, $this->client->getResponse()->getStatusCode());

        if (200 !== $expectedStatusCode) {
            return;
        }

        $riotAccounts = $this->getJsonResponse();

        foreach ($riotAccounts as $riotAccount) {
			self::assertObjectHasAttribute('uuid', $riotAccount);
            self::assertAttributeEquals('55497402', 'riot_id', $riotAccount);
            self::assertAttributeEquals(false, 'smurf', $riotAccount);
            self::assertAttributeEquals(25, 'profile_icon_id', $riotAccount);
            self::assertObjectHasAttribute('summoner_name', $riotAccount);
        }
    }

    public function getPlayersRiotAccountsProvider(): array
    {
        return [
            'Get existing player riot accounts' => [self::PLAYER_TOUCOUILLE_UUID, 200],
            'Get non existing player riot accounts' => ['00000000-0000-0000-0000-000000000000', 404],
        ];
    }
}


text:
package magefortress.input;

/**
 *
 */
public interface MFIMouseListener
{
  public void mouseClicked(int x, int y);
  public void mouseMoved(int x, int y);
}


text:
SYNONYM

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

#### Published in
Fl. N. Amer. 1(3):393. 1840

#### Original name
null

### Remarks
null


text:
package com.sevenre.trackre.parent.fragment;

import com.blunderer.materialdesignlibrary.handlers.ViewPagerHandler;
import com.sevenre.trackre.parent.R;

public class HomeFragment extends com.blunderer.materialdesignlibrary.fragments.ViewPagerWithTabsFragment {

    @Override
    protected boolean expandTabs() {
        return false;
    }

    @Override
    public ViewPagerHandler getViewPagerHandler() {
        return new ViewPagerHandler(getActivity())
                .addPage(R.string.children, ChildrenFragment.newInstance())
                .addPage(R.string.tracking, TrackingFragment.newInstance())
                .addPage(R.string.notification, NotificationFragment.newInstance());
    }

    @Override
    public int defaultViewPagerPageSelectedPosition() {
        return 0;
    }
}


text:
import six

from heat.common import exception
from heat.common.i18n import _
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine import support

class Order(resource.Resource):

    support_status = support.SupportStatus(version='2014.2')

    default_client_name = 'barbican'

    PROPERTIES = (
        NAME, PAYLOAD_CONTENT_TYPE, MODE, EXPIRATION,
        ALGORITHM, BIT_LENGTH, TYPE, REQUEST_TYPE, SUBJECT_DN,
        SOURCE_CONTAINER_REF, CA_ID, PROFILE, REQUEST_DATA,
        PASS_PHRASE
    ) = (
        'name', 'payload_content_type', 'mode', 'expiration',
        'algorithm', 'bit_length', 'type', 'request_type', 'subject_dn',
        'source_container_ref', 'ca_id', 'profile', 'request_data',
        'pass_phrase'
    )

    ATTRIBUTES = (
        STATUS, ORDER_REF, SECRET_REF, PUBLIC_KEY, PRIVATE_KEY,
        CERTIFICATE, INTERMEDIATES, CONTAINER_REF
    ) = (
        'status', 'order_ref', 'secret_ref', 'public_key', 'private_key',
        'certificate', 'intermediates', 'container_ref'
    )

    properties_schema = {
        NAME: properties.Schema(
            properties.Schema.STRING,
            _('Human readable name for the secret.'),
        ),
        PAYLOAD_CONTENT_TYPE: properties.Schema(
            properties.Schema.STRING,
            _('The type/format the secret data is provided in.'),
        ),
        EXPIRATION: properties.Schema(
            properties.Schema.STRING,
            _('The expiration date for the secret in ISO-8601 format.'),
            constraints=[
                constraints.CustomConstraint('iso_8601'),
            ],
        ),
        ALGORITHM: properties.Schema(
            properties.Schema.STRING,
            _('The algorithm type used to generate the secret.'),
        ),
        BIT_LENGTH: properties.Schema(
            properties.Schema.INTEGER,
            _('The bit-length of the secret.'),
        ),
        MODE: properties.Schema(
            properties.Schema.STRING,
            _('The type/mode of the algorithm associated with the secret '
              'information.'),
        ),
        TYPE: properties.Schema(
            properties.Schema.STRING,
            _('The type of the order.'),
            constraints=[
                constraints.AllowedValues([
                    'key', 'asymmetric', 'certificate'
                ]),
            ],
            support_status=support.SupportStatus(version='5.0.0'),
        ),
        REQUEST_TYPE: properties.Schema(
            properties.Schema.STRING,
            _('The type of the certificate request.'),
            support_status=support.SupportStatus(version='5.0.0'),
        ),
        SUBJECT_DN: properties.Schema(
            properties.Schema.STRING,
            _('The subject of the certificate request.'),
            support_status=support.SupportStatus(version='5.0.0'),
        ),
        SOURCE_CONTAINER_REF: properties.Schema(
            properties.Schema.STRING,
            _('The source of certificate request.'),
            support_status=support.SupportStatus(version='5.0.0'),
        ),
        CA_ID: properties.Schema(
            properties.Schema.STRING,
            _('The identifier of the CA to use.'),
            support_status=support.SupportStatus(version='5.0.0'),
        ),
        PROFILE: properties.Schema(
            properties.Schema.STRING,
            _('The profile of certificate to use.'),
            support_status=support.SupportStatus(version='5.0.0'),
        ),
        REQUEST_DATA: properties.Schema(
            properties.Schema.STRING,
            _('The content of the CSR.'),
            support_status=support.SupportStatus(version='5.0.0'),
        ),
        PASS_PHRASE: properties.Schema(
            properties.Schema.STRING,
            _('The passphrase the created key.'),
            support_status=support.SupportStatus(version='5.0.0'),
        ),
    }

    attributes_schema = {
        STATUS: attributes.Schema(
            _('The status of the order.'),
            type=attributes.Schema.STRING
        ),
        ORDER_REF: attributes.Schema(
            _('The URI to the order.'),
            type=attributes.Schema.STRING
        ),
        SECRET_REF: attributes.Schema(
            _('The URI to the created secret.'),
            type=attributes.Schema.STRING
        ),
        CONTAINER_REF: attributes.Schema(
            _('The URI to the created container.'),
            support_status=support.SupportStatus(version='5.0.0'),
            type=attributes.Schema.STRING
        ),
        PUBLIC_KEY: attributes.Schema(
            _('The payload of the created public key, if available.'),
            support_status=support.SupportStatus(version='5.0.0'),
            type=attributes.Schema.STRING
        ),
        PRIVATE_KEY: attributes.Schema(
            _('The payload of the created private key, if available.'),
            support_status=support.SupportStatus(version='5.0.0'),
            type=attributes.Schema.STRING
        ),
        CERTIFICATE: attributes.Schema(
            _('The payload of the created certificate, if available.'),
            support_status=support.SupportStatus(version='5.0.0'),
            type=attributes.Schema.STRING
        ),
        INTERMEDIATES: attributes.Schema(
            _('The payload of the created intermediates, if available.'),
            support_status=support.SupportStatus(version='5.0.0'),
            type=attributes.Schema.STRING
        ),
    }

    def handle_create(self):
        info = dict((k, v) for k, v in self.properties.items()
                    if v is not None)
        order = self.client().orders.create(**info)
        order_ref = order.submit()
        self.resource_id_set(order_ref)
        # NOTE(pshchelo): order_ref is HATEOAS reference, i.e a string
        # need not to be fixed re LP bug #1393268
        return order_ref

    def check_create_complete(self, order_href):
        order = self.client().orders.get(order_href)

        if order.status == 'ERROR':
            reason = order.error_reason
            code = order.error_status_code
            msg = (_("Order '%(name)s' failed: %(code)s - %(reason)s")
                   % {'name': self.name, 'code': code, 'reason': reason})
            raise exception.Error(msg)

        return order.status == 'ACTIVE'

    def handle_delete(self):
        if not self.resource_id:
            return

        client = self.client()
        try:
            client.orders.delete(self.resource_id)
        except Exception as exc:
            # This is the only exception the client raises
            # Inspecting the message to see if it's a 'Not Found'
            if 'Not Found' not in six.text_type(exc):
                raise

    def _resolve_attribute(self, name):
        client = self.client()
        order = client.orders.get(self.resource_id)
        if name in (
                self.PUBLIC_KEY, self.PRIVATE_KEY, self.CERTIFICATE,
                self.INTERMEDIATES):
            container = client.containers.get(order.container_ref)
            secret = getattr(container, name)
            return secret.payload

        return getattr(order, name)

def resource_mapping():
    return {
        'OS::Barbican::Order': Order,
    }


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

<meta name="generator" content="JDiff v1.1.0">

<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
Constructor Differences Index
</TITLE>
<link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" />

    Filter the Index:

Constructors

Removals

Additions

Changes

Listed as: Added,  Removed,  Changed

C
D
F
G
M
N
P
R
S
T
W
 TOP

<nobr>ClipData
(ClipData)</nobr> constructor

ClipData.Item

  <nobr>ClipData.Item
(CharSequence, String)</nobr> constructor

  <nobr>ClipData.Item
(CharSequence, String, Intent, Uri)</nobr> constructor

D
C
F
G
M
N
P
R
S
T
W
 TOP

<nobr>DrmStore
()</nobr> constructor

<nobr>DrmStore.Action
()</nobr> constructor

<nobr>DrmStore.DrmObjectType
()</nobr> constructor

<nobr>DrmStore.Playback
()</nobr> constructor

<nobr>DrmStore.RightsStatus
()</nobr> constructor

F
C
D
G
M
N
P
R
S
T
W
 TOP

<nobr>FormatException
(String, Throwable)</nobr> constructor

G
C
D
F
M
N
P
R
S
T
W
 TOP

<nobr>GeolocationPermissions
()</nobr> constructor

M
C
D
F
G
N
P
R
S
T
W
 TOP

<nobr>Mesh.AllocationBuilder
(RenderScript)</nobr> constructor

<nobr>Mesh.Builder
(RenderScript, int)</nobr> constructor

<nobr>Mesh.TriangleMeshBuilder
(RenderScript, int, int)</nobr> constructor

N
C
D
F
G
M
P
R
S
T
W
 TOP

<nobr>NdefMessage
(NdefRecord, )</nobr> constructor

<nobr>NdefRecord
(byte[])</nobr> constructor

P
C
D
F
G
M
N
R
S
T
W
 TOP

<nobr>ProgramFragment.Builder
(RenderScript)</nobr> constructor

<nobr>ProgramFragmentFixedFunction.Builder
(RenderScript)</nobr> constructor

<nobr>ProgramRaster.Builder
(RenderScript)</nobr> constructor

<nobr>ProgramVertex.Builder
(RenderScript)</nobr> constructor

<nobr>ProgramVertexFixedFunction.Builder
(RenderScript)</nobr> constructor

<nobr>ProgramVertexFixedFunction.Constants
(RenderScript)</nobr> constructor

R
C
D
F
G
M
N
P
S
T
W
 TOP

<nobr>RemoteViews
(RemoteViews, RemoteViews)</nobr> constructor

<nobr>RenderScriptGL
(Context, SurfaceConfig)</nobr> constructor

RenderScriptGL.SurfaceConfig

  <nobr>RenderScriptGL.SurfaceConfig
()</nobr> constructor

  <nobr>RenderScriptGL.SurfaceConfig
(SurfaceConfig)</nobr> constructor

RSSurfaceView

  <nobr>RSSurfaceView
(Context)</nobr> constructor

  <nobr>RSSurfaceView
(Context, AttributeSet)</nobr> constructor

RSTextureView

  <nobr>RSTextureView
(Context)</nobr> constructor

  <nobr>RSTextureView
(Context, AttributeSet)</nobr> constructor

S
C
D
F
G
M
N
P
R
T
W
 TOP

<nobr>SQLException
(String, Throwable)</nobr> constructor

<nobr>SQLiteException
(String, Throwable)</nobr> constructor

T
C
D
F
G
M
N
P
R
S
W
 TOP

TestSuite

  <nobr>TestSuite
(Class)</nobr> constructor

  <nobr>TestSuite
(Class, String)</nobr> constructor

  <nobr><A HREF="junit.framework.TestSuite.html#junit.framework.TestSuite.ctor_added(java.lang.Class<? extends junit.framework.TestCase>, java.lang.String)" class="hiddenlink" target="rightframe">TestSuite
(Class<TestCase>, String)</nobr> constructor

  <nobr><A HREF="junit.framework.TestSuite.html#junit.framework.TestSuite.ctor_added(java.lang.Class<? extends junit.framework.TestCase>[], java.lang.String)" class="hiddenlink" target="rightframe">TestSuite
(Class<TestCase>, String)</nobr> constructor

  <nobr><A HREF="junit.framework.TestSuite.html#junit.framework.TestSuite.ctor_added(java.lang.Class<?>)" class="hiddenlink" target="rightframe">TestSuite
(Class<?>)</nobr> constructor

  <nobr><A HREF="junit.framework.TestSuite.html#junit.framework.TestSuite.ctor_added(java.lang.Class<?>...)" class="hiddenlink" target="rightframe">TestSuite
(Class<?>)</nobr> constructor

W
C
D
F
G
M
N
P
R
S
T
 TOP

<nobr>WebStorage
()</nobr> constructor


text:
package com.webcohesion.enunciate.modules.jaxb.api.impl;

import com.webcohesion.enunciate.api.datatype.*;
import com.webcohesion.enunciate.javac.decorations.element.ElementUtils;
import com.webcohesion.enunciate.javac.javadoc.JavaDoc;
import com.webcohesion.enunciate.metadata.Label;
import com.webcohesion.enunciate.modules.jaxb.model.TypeDefinition;

import javax.lang.model.element.AnnotationMirror;
import java.util.List;
import java.util.Map;

/**
 * @author Ryan Heaton
 */
public abstract class DataTypeImpl implements DataType {

  private final TypeDefinition typeDefinition;

  protected DataTypeImpl(TypeDefinition typeDefinition) {
    this.typeDefinition = typeDefinition;
  }

  @Override
  public String getLabel() {
    Label label = this.typeDefinition.getAnnotation(Label.class);
    if (label != null) {
      return label.value();
    }

    JavaDoc.JavaDocTagList tags = this.typeDefinition.getJavaDoc().get("label");
    if (tags != null && tags.size() > 0) {
      String tag = tags.get(0).trim();
      if (!tag.isEmpty()) {
        return tag;
      }
    }

    return this.typeDefinition.isAnonymous() ? this.typeDefinition.getSimpleName() + " (Anonymous)" : this.typeDefinition.getName();
  }

  @Override
  public String getSlug() {
    String ns = this.typeDefinition.getContext().getNamespacePrefixes().get(this.typeDefinition.getNamespace());
    return "xml_" + ns + "_" + (this.typeDefinition.isAnonymous() ? "anonymous_" + this.typeDefinition.getSimpleName() : this.typeDefinition.getName());
  }

  @Override
  public String getDescription() {
    return this.typeDefinition.getJavaDoc().toString();
  }

  @Override
  public String getDeprecated() {
    return ElementUtils.findDeprecationMessage(this.typeDefinition);
  }

  @Override
  public Namespace getNamespace() {
    return new NamespaceImpl(this.typeDefinition.getContext().getSchemas().get(this.typeDefinition.getNamespace()));
  }

  @Override
  public Syntax getSyntax() {
    return this.typeDefinition.getContext();
  }

  @Override
  public List<DataTypeReference> getSupertypes() {
    return null;
  }

  @Override
  public String getSince() {
    JavaDoc.JavaDocTagList tags = this.typeDefinition.getJavaDoc().get("since");
    return tags == null ? null : tags.toString();
  }

  @Override
  public String getVersion() {
    JavaDoc.JavaDocTagList tags = this.typeDefinition.getJavaDoc().get("version");
    return tags == null ? null : tags.toString();
  }

  @Override
  public Example getExample() {
    return null;
  }

  @Override
  public Map<String, AnnotationMirror> getAnnotations() {
    return this.typeDefinition.getAnnotations();
  }

  @Override
  public JavaDoc getJavaDoc() {
    return this.typeDefinition.getJavaDoc();
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>My AngularJS App</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="app/bower_components/datatables/media/css/jquery.dataTables.css" />
    <link rel="stylesheet" href="app/bower_components/bootstrap/dist/css/bootstrap.css" />

    <link rel="stylesheet" href="app/styles/search.css" />


text:
using std::cout;
using std::endl;
using std::make_shared;
using std::shared_ptr;

// @include
shared_ptr<ListNode<int>> InsertionSort(const shared_ptr<ListNode<int>>& L) {
  auto dummy_head = make_shared<ListNode<int>>(ListNode<int>{0, L});
  auto iter = L;
  // The sublist consisting of nodes up to and including iter is sorted in
  // increasing order. We need to ensure that after we move to iter->next
  // this property continues to hold. We do this by swapping iter->next
  // with its predecessors in the list till it's in the right place.
  while (iter && iter->next) {
    if (iter->data > iter->next->data) {
      auto target = iter->next, pre = dummy_head;
      while (pre->next->data < target->data) {
        pre = pre->next;
      }
      auto temp = pre->next;
      pre->next = target;
      iter->next = target->next;
      target->next = temp;
    } else {
      iter = iter->next;
    }
  }
  return dummy_head->next;
}
// @exclude

int main(int argc, char** argv) {
  shared_ptr<ListNode<int>> L;
  L = make_shared<ListNode<int>>(ListNode<int>{
      1, make_shared<ListNode<int>>(ListNode<int>{
             4, make_shared<ListNode<int>>(ListNode<int>{
                    3, make_shared<ListNode<int>>(ListNode<int>{
                           2, make_shared<ListNode<int>>(
                                  ListNode<int>{5, nullptr})})})})});
  auto result = InsertionSort(L);
  shared_ptr<ListNode<int>> pre = nullptr;
  while (result) {
    assert(!pre || pre->data <= result->data);
    pre = result;
    cout << result->data << endl;
    result = result->next;
  }
  return 0;
}


text:
input[type=radio   ]:not(old) + label{
  display      : inline-block;
  margin-left  : 2em;
  line-height  : 1.5em;
}

#palette-container ul {
  list-style-type: none;
  margin: 20px;
  padding: 0;
}

#palette-container li {
  font: 200 20px/1.5 Helvetica, Verdana, sans-serif;
  border-bottom: 1px solid #ccc;
}

#palette-container li:last-child {
  border: none;
}

#palette-container li a {
  text-decoration: none;
  color: #000;

  -webkit-transition: font-size 0.3s ease, background-color 0.3s ease;
  -moz-transition: font-size 0.3s ease, background-color 0.3s ease;
  -o-transition: font-size 0.3s ease, background-color 0.3s ease;
  -ms-transition: font-size 0.3s ease, background-color 0.3s ease;
  transition: font-size 0.3s ease, background-color 0.3s ease;
  display: block;
  width: 200px;
}

#palette-container li a:hover {
  font-size: 30px;
  background: #f6f6f6;
}

.node-table {
    stroke: rgb(93, 114, 145);
    stroke-width: 1;
    border: 5px solid #4CAF50;
    border-collapse: collapse;
}

.node-table th, td {
    text-align: left;
    padding: 8px;
}

.node-table th {
    background-color: #4CAF50;
    color: white;
}

#sidebar {
    margin-top:20px;
}


text:
package com.nianticproject.ingress.common.assets;

public class AssetFinder {

    public ScreenDensity screenDensity;
}


text:
systemctl disable squid.service

#
# Stop squid.service if currently running
#
systemctl stop squid.service


text:
package com.lucythemoocher.FX;

import com.lucythemoocher.Globals.Globals;
import com.lucythemoocher.graphics.Animation;
import com.lucythemoocher.graphics.Drawable;

/**
 * Class for FX.<br/>
 * Represents a visual and sound effects
 */
public class FX implements Drawable {
	private Animation anim_;
	private boolean ended_ = false;
	private float x_;
	private float y_;

	/**
	 * Constructor
	 * @param resourceImg : resource of the image
	 * @param resourceSound : resource of the sound to play at the construction TODO
	 * @param x : pos x
	 * @param y : pos y
	 */
	public FX(int resourceImg, int resourceSound, float x, float y) {
		anim_ = new Animation(resourceImg, true);
		x_ = x;
		y_ = y;
		Globals.getInstance().getGame().getFXManager().add(this);
	}

	/**
	 * Update
	 */
	public void update() {
		anim_.update();
		if ( anim_.cycleEnded() ) {
			ended_ = true;
		}
	}

	/**
	 * Drawing the FX
	 */
	public void draw() {
		anim_.draw(x_, y_);
	}

	/**
	 * If the FX is ended (and need to be destroyed)
	 * @return if the animation is ended
	 */
	public boolean ended() {
		return ended_;
	}

	/**
	 * Getter
	 * @return x
	 */
	public float getX() {
		return x_;
	}

	/**
	 * Getter
	 * @return y
	 */
	public float getY() {
		return y_;
	}
}


text:
+++
title = "Communal Computing on Urbit"
date = "2022-02-17"
[taxonomies]
grant_type = ["Proposal"]
grant_category = ["other"]
[extra]
image = ""
description = "User research, domain research/synthesis, white paper creation and publicity effort around Urbit ID as a solution to questions of IoT identity sharing and privacy"
reward = "4.6 stars"
assignee = ["~pilwyc-fastec"]
mentor = ["~simfur-ritwed"]
grant_id = "P0113"
completed = true
link = ""
+++

## Communal Identities for the Urbit Smart Home

Today's smart home, IoT, and other communal devices should be for the people living in a home but are really surveillance systems for large corporations and governments. In this project we will make Urbit the best OS to tackle the identity, security, privacy, experience, and ownership issues with communal computing.

## Overview

There are a record number of devices being placed in the home and office that are meant for everyone to use. This includes smart home devices like video doorbells, internet of things (IoT) devices like light bulbs, and home assistants like the Amazon Echo. However, they are framed and built wrong due to their focus on a single user context from the days of mainframe time-sharing. They are built for the person that sets up the device rather than all of the people that may have access like partners, children, and guests. This causes problems with identity, privacy, security, experience, and ownership.

For example, the Amazon Ring video doorbell or connected security camera collect lots of video information. It attaches it to the identity of the owner and then makes it available to local police forces. It doesn't ask anyone that comes into view to opt-in or consent to having their image captured. There are many privacy and safety issues with automatically collecting this information without consent. There are reasons that someone would want to be identified though like a member of the home that would automatically be let into the front door when they are seen. This isn't the same as the random delivery person leaving a package as their identity isn't needed for the task of detecting a package is there.

In Urbit, the identity model (Azimuth) is key to running the OS and it has a great opportunity to rethink the paradigms of communal identities. The strong identity model for Urbit is beneficial but needs to figure out how to allow for other people besides the owner of the device to use the home's infrastructure.

From an identity point-of-view, we are made up of many different pseudo-identities: as part of a family, a work organization, a set of friends, a hobbyist community, and a neighborhood. All pseudo-identities that make up a person are interlocking with other people's identities through association (aka p2p). This includes a family member, a co-worker, a friend from school, a guest in your house or your nextdoor neighbor. This leads to the intersection of various reputation systems that overlap with Urbit and other reputational institutions (some of which may not exist yet).

I propose that I embark on an ethnographic study of the intersection between Urbit, identity, IoT, and smarthomes. Then create a whitepaper describing a way forward for Urbit.

## Scope

We will complete the proposed project with the following artifacts:

- Ethnographic research synthesis - and potential prototypes used to discuss

- Whitepaper describing how communal devices could leverage Urbit - this will include an outline of key problems identified during research, Urbit use of identity for communal devices, any Urbit feature recommendations, and a concrete case study like an open source video doorbell

- Blog post summarizing the whitepaper

- Talk and workshop regarding the whitepaper open to the public

To get to these artifacts the following work will be done:

- At least 10 compensated interviews with Urbit users or similar proxy profile focused on IoT and smart home - see the appendix interview guide for more information

- Prototyping sessions to show/discuss with interviewees to make their feedback grounded in a concrete case - this could point to an additional round of interviews after the initial ones

- Syntheses sessions to pull themes out of the research

- Ideation sessions to consider various IoT and smart home scenarios

- Technical sessions to discuss identity and Azimuth

- Design sessions for concrete case studies

- Drafting, review, and editing of whitepaper, blog post, and talk

All work is open to developers and other members of Urbit.

Key scenarios for the identity model with regards to communal use cases which may expand during research:

- Adding comets for devices to push content to the planet (or other storage locations and APIs)

- Auto-provisioning (and collecting consent from) identities for joining the home (both people living in the home and guests) to comets

- Auto-de-provisioning identities when people leave the home (and removing other data collected for their identity)

- Attaching biometrics to identities for automation

- External reputation system integration for local governance

- Existence of Urbit-based IoT alongside other smart home devices

- Linking current smart home platforms (e.g. Google Assistant and Smart Home) to Urbit IoT devices - for example, to allow a video doorbell to show it's video feed on a Google Home Hub

- Use of DID (and VCs), SSI, W3C (e.g. WoT), and other identity, IoT, etc. standards to integrate with next generation of identity services

## My experience and why I'm the right person for this project

I have over 20 years of product management experience in building B2C and B2B products, apps, services, etc. This includes product and business development leadership at Microsoft, Waze, KAYAK, Facebook Reality Labs, and most recently Cognizant. I've also founded a startup in the restaurant tech space, ran innovation for a venture capital firm, and directed AI/ML research projects for a design consultancy. I have experience in starting projects from zero and taking them through research, deployment, and maintenance. This happens because of my focus on connecting execution to a strong strategy and future vision.

Regarding communal computing, I've written and evangelised the concept of as a way to solve the current problems with home and office devices (see the appendix below). I'm an IoT hobbyist, smart home enthusiast, Alexa skill builder, and most recently was product manager for the identity platform, biometric recognition machine learning, and voice assistant integration for Facebook's Portal.

I'm interested in finding models that make sense for the smart home that don't give all of a person's data away and give them the control to keep it working the way they want, regardless of company boom and bust (or M&A) cycles.
[Google Docs version with links](https://docs.google.com/document/d/11RhvBUQ-kp-N8C_lwSIMr5v6ISHoZEa2b0OjooAHEpQ/edit#heading=h.2ks2kbs3fwmh)

## Milestones

### Milestone 1: Research
Payout: 1 star and .15 WSTR
Due Date: 3/11/22

The first milestone is after research into the problem area of communal use of Urbit systems. This includes interview guide drafting, recruiting, interviewing (at least 10 45-minute interviews), analysis, and synthesis of research.

The handoff is a research report (3-5 pages) with themes and important nuggets (~50 nuggets).

As compensation for the interviews we will give out specific Goras to people that participate in this study.

### Milestone 2: Concept Development
Payout: 1 star and .15 WSTR
Due Date: 4/11/22

The second milestone is to turn the research into actionable recommendations. This includes working sessions (at least 5) with the Urbit community to refine problems, ideate, design solutions, and situate in the context of Urbit's current systems. This will include 5-8 people in a synchronous meeting to workshop.

The handoff is a compilation of ideas with any recommendations from the working sessions. This will most likely be a journey map format with problems and possible solutions.

### Milestone 3: Report Creation + Sharing
Payout: 2 stars and .3 WSTR
Due Date: 5/27/22

The final milestone is the completion of a whitepaper (10-20 pages). This includes the whitepaper drafting and editing. As well as, authoring a blog post (1,000-2,000 words) and live talk for the Urbit YouTube account (45-60 minutes).

This will be shared out with the wider boomer web distribution like blogs, podcasts, newsletters, conferences, meetups, Twitter, and LinkedIn focused on topics including identity, privacy, crypto, IoT, and smart home (10-20 to be identified).

Here is a short list of possible groups:

- O'Reilly Radar blog
- Building the Metaverse Medium publication
- Inside Blockchain newsletter
- NYC Media Lab Data Download newsletter
- The IoT podcast
- VerseTech SF Metaverse | AI | Blockchain | XR VR AR meetup
- Vienna Digital Identity meetup
- Privacy Engineering SF meetup
- MLUX meetup
- IIW unconference