text:
<?php defined('BX_DOL') or die('hack attempt');

/**
 * Database queries
 */
class BxMessengerDb extends BxBaseModTextDb
{
   private $CNF;

   function __construct(&$oConfig)
   {
		parent::__construct($oConfig);
		$this->CNF = &$oConfig -> CNF;
	}

	/**
	* Get all lot by class name
	*@param string $sClass
	*@return array lot info
	*/
	public function getLotByClass($sClass){
		$sQuery = $this -> prepare("SELECT * FROM `{$this->CNF['TABLE_ENTRIES']}` WHERE `{$this->CNF['FIELD_CLASS']}` = ? LIMIT 1", $sClass);
		return $this -> getRow($sQuery);
	}

	/**
	* Get all lot by page url
	*@param string $sUrl or the page
	*@return array lot info
	*/
	public function getLotByUrl($sUrl)
	{
		$sQuery = $this -> prepare("SELECT * FROM `{$this->CNF['TABLE_ENTRIES']}` WHERE `{$this->CNF['FIELD_URL']}` = ? LIMIT 1", $sUrl);
		return $this -> getRow($sQuery);
	}

	/**
	* Get all lot by id
	*@param int $iId lot id
	*@return array lot info
	*/
	public function getLotInfoById($iId)
	{
		$sQuery = $this -> prepare("SELECT * FROM `{$this->CNF['TABLE_ENTRIES']}` WHERE `{$this->CNF['FIELD_ID']}` = ? LIMIT 1", (int)$iId);
		return $this -> getRow($sQuery);
	}

	/**
	* Get lot by id or url
	*@param int $iId lot id
	*@param string $sUrl url or url of the page with talk
	*@param int $iAuthor profile id
	*@return array lot info
	*/
	public function getLotByIdOrUrl($iId, $sUrl, $iAuthorId = 0){
		if ($iId)
			return $this -> getLotInfoById($iId);

		if ($sUrl)
			return $this -> getLotByUrl($sUrl);

		return array();
	}

	/**
	* Check if is the member author of the lot or jot
	*@param int $iId lot id
	*@param int $iAuthor profile id
	*@param boolean $bLotAuthor if true checks Lot, otherwise jot
	*@return boolean
	*/
	public function isAuthor($iId, $iAuthorId, $bLotAuthor = true){
		if (!$iAuthorId)
			return false;

		if ($bLotAuthor)
			$sQuery = $this -> prepare("SELECT COUNT(*) FROM `{$this->CNF['TABLE_ENTRIES']}` WHERE `{$this->CNF['FIELD_ID']}` = ? AND `{$this->CNF['FIELD_AUTHOR']}` = ? LIMIT 1", (int)$iId, (int)$iAuthorId);
		else
			$sQuery = $this -> prepare("SELECT COUNT(*) FROM `{$this->CNF['TABLE_MESSAGES']}` WHERE `{$this->CNF['FIELD_MESSAGE_ID']}` = ? AND `{$this->CNF['FIELD_MESSAGE_AUTHOR']}` = ? LIMIT 1", (int)$iId, (int)$iAuthorId);

		return $this -> getOne($sQuery) == 1;
	}

	/**
	* Deletes lot by lot Id
	*@param int $iLotId lot id
	*@return int affected rows
	*/
	public function deleteLot($iLotId){
		$aJots = $this -> getJotsByLotId($iLotId);
		foreach($aJots as $iKey => $aJot)
			$this -> removeFilesByJotId($aJot[$this->CNF['FIELD_MESSAGE_ID']]);

		$iResult = $this -> query("DELETE FROM `{$this->CNF['TABLE_ENTRIES']}` WHERE `{$this->CNF['FIELD_ID']}` = :id", array('id' => $iLotId));
		$iResult += $this -> query("DELETE FROM `{$this->CNF['TABLE_MESSAGES']}` WHERE `{$this->CNF['FIELD_MESSAGE_FK']}` = :id", array('id' => $iLotId));
		return $iResult;
	}

	/**
	* Deletes jot
	*@param int iJotId jot id
	*@param int iProfileId member who deleted jot
	*@param boolean $bCompletely if true totally remove from the site
	*@return int affected rows
	*/
	public function deleteJot($iJotId, $iProfileId, $bCompletely = false){
		$iJotId = (int)$iJotId;
		if ($bCompletely)
		{
			$this -> removeFilesByJotId($iJotId);
			return $this -> query("DELETE FROM `{$this->CNF['TABLE_MESSAGES']}` WHERE `{$this->CNF['FIELD_MESSAGE_ID']}` = :id", array('id' => $iJotId));
		}

		return $this -> query("UPDATE `{$this->CNF['TABLE_MESSAGES']}`
								SET
									`{$this->CNF['FIELD_MESSAGE_TRASH']}` = 1,
									`{$this->CNF['FIELD_MESSAGE_LAST_EDIT']}` = UNIX_TIMESTAMP(),
									`{$this->CNF['FIELD_MESSAGE_EDIT_BY']}` = :profile
								WHERE `{$this->CNF['FIELD_MESSAGE_ID']}` = :id", array('id' => $iJotId, 'profile' => $iProfileId));
	}

	/**
	* Removes participant from the participants list
	*@param int $iLotId lot id
	*@param int $iParticipant profile id
	*@return int/false
	*/
	public function leaveLot($iLotId, $iParticipant){
		return $this -> removeParticipant($iLotId, $iParticipant);
	}

	/**
	* Get Lot(Talk) settings for a member
	*@param int $iLotId lot id
	*@param int $iParticipant profile id
	*@param string $sName name the option
	*@param boolean $bParams get from params array, otherwise from table's field
	*@return mixed option value
	*/
	private function getParams($iLotId, $iParticipant, $sName = 0, $bParams = false){
		$sQuery = $this -> prepare("SELECT * FROM `{$this->CNF['TABLE_USERS_INFO']}`
									WHERE `{$this->CNF['FIELD_INFO_LOT_ID']}` = ? AND `{$this->CNF['FIELD_INFO_USER_ID']}` = ?
									LIMIT 1", (int)$iLotId, (int)$iParticipant);
		$aInfo = $this -> getRow($sQuery);
		if (empty($aInfo))
			return false;

		if (!$sName)
			return $aInfo;

		if (!$bParams){
			$aParams = unserialize($aInfo[$this->CNF['FIELD_INFO_PARAMS']]);
			return isset($aParams[$sName]) ? $aParams[$sName] : 0;
		}

		return $aInfo[$sName];
	}

	/**
	* Save Lot(Talk) settings for a member
	*@param int $iLotId lot id
	*@param int $iParticipant profile id
	*@param array $aParams options list
	*@param boolean $bParams get from  params array otherwise as table field
	*@return int affected rows
	*/
	private function setParams($iLotId, $iParticipant, $sName, $sValue, $bParams = false){
		$aParams = $this -> getParams($iLotId, $iParticipant);

		if (!$bParams)
		{
			if (empty($aParams))
				return $this -> query("INSERT INTO `{$this->CNF['TABLE_USERS_INFO']}` SET `{$this->CNF['FIELD_INFO_PARAMS']}` = :values, `{$this->CNF['FIELD_INFO_LOT_ID']}` = :id, `{$this->CNF['FIELD_INFO_USER_ID']}` = :user", array('user' => $iParticipant, 'id' => $iLotId, 'values' => serialize(array($sName => $sValue))));

			return $this -> query("UPDATE `{$this->CNF['TABLE_USERS_INFO']}` SET `{$this->CNF['FIELD_INFO_PARAMS']}` = :values WHERE `{$this->CNF['FIELD_INFO_LOT_ID']}` = :id AND `{$this->CNF['FIELD_INFO_USER_ID']}` = :user", array('user' => $iParticipant, 'id' => $iLotId, 'values' => serialize(array($sName => $sValue))));
		}

		if (empty($aParams))
			return $this -> query("INSERT INTO `{$this->CNF['TABLE_USERS_INFO']}` SET `{$sName}` = :value, `{$this->CNF['FIELD_INFO_LOT_ID']}` = :id, `{$this->CNF['FIELD_INFO_USER_ID']}` = :user", array('user' => $iParticipant, 'id' => $iLotId, 'value' => $sValue));

		return $this -> query("UPDATE `{$this->CNF['TABLE_USERS_INFO']}` SET `{$sName}` = :value WHERE `{$this->CNF['FIELD_INFO_LOT_ID']}` = :id AND `{$this->CNF['FIELD_INFO_USER_ID']}` = :user", array('user' => $iParticipant, 'id' => $iLotId, 'value' => $sValue));
	}

	/**
	* Make the lot mute for a member
	*@param int $iLotId lot id
	*@param int $iParticipant profile id
	*@return int set value
	*/
	public function muteLot($iLotId, $iParticipant){
		$iCurrentNotification = (int)$this -> getParams($iLotId, $iParticipant, 'notification');
		$iNotification = (int)!$iCurrentNotification;

		$this -> setParams($iLotId, $iParticipant, 'notification', $iNotification);
		return $iNotification;
	}

	/**
	* Mark the lot with star
	*@param int $iLotId lot id
	*@param int $iParticipant profile id
	*@return int set
	*/
	public function starLot($iLotId, $iParticipant){
		$iCurrent = (int)$this -> getParams($iLotId, $iParticipant, 'star', true);
		$iNew = (int)!$iCurrent;

		$this -> setParams($iLotId, $iParticipant, 'star', $iNew, true);
		return $iNew;
	}

	public function isStarred($iLotId, $iParticipant){
		return $this -> getParams($iLotId, $iParticipant, 'star', true);
	}
	/**
	* Check if the lot is mute for a member
	*@param int $iLotId lot id
	*@param int $iParticipant profile id
	*@return boolean
	*/
	public function isMuted($iLotId, $iParticipant){
		$iMute = $this -> getParams($iLotId, $iParticipant, 'notification');
		return $iMute;
	}

	/**
	* Save participants list for the lot
	*@param int $iLotId lot id
	*@param array $aParticipants
	*@return int affected rows
	*/
	public function savePariticipantsList($iLotId, $aParticipants){
		$sParticipants = '';
		if (!empty($aParticipants))
		{
			$aParticipants = array_map('intval', $aParticipants);
			$sParticipants = implode(',', $aParticipants);
		}

		return $this -> query("UPDATE `{$this->CNF['TABLE_ENTRIES']}` SET `{$this->CNF['FIELD_PARTICIPANTS']}` = :parts WHERE `{$this->CNF['FIELD_ID']}` = :id", array('parts' => $sParticipants, 'id' => $iLotId));
	}

	/**
	* Save message for participants to database
	*@param array $aData lot settings
	*@param array $aParticipants participants list, if it empty then used default for lot
	*@return int affected rows
	*/
	public function saveMessage($aData, $aParticipants = array()) {
		$aLot = array();
		if ((int)$aData['lot'])
			$aLot = $this -> getLotInfoById($aData['lot']);

		if (($aData['type'] != BX_IM_TYPE_PRIVATE || $this -> isAuthor($aData['lot'], $aData['member_id'])) && !$this -> isParticipant($aData['lot'], $aData['member_id'], true))
			$this -> addMemberToParticipantsList($aData['lot'], $aData['member_id']);

		if (empty($aParticipants) && (int)$aData['lot'])
			$aParticipants = $this -> getParticipantsList($aData['lot']);

		$aLot = !empty($aLot) ? $aLot : $this -> getLotByUrlAndPariticipantsList($aData['url'], $aParticipants, $aData['type']);
		if (empty($aLot)){
			$iLotID = $this -> createNewLot($aData['member_id'], $aData['title'], $aData['type'], $aData['url'], $aParticipants);
		} else
			$iLotID = $aLot[$this->CNF['FIELD_ID']];

		return $this -> addNewJot($iLotID, $aData['message'], $aData['member_id']);
	}

	/**
	* Save message for participants to database
	*@param string $sUrl of the page with lot
	*@param array $aParticipants participants list
	*@param int $iType lot type
	*@return array Lot info
	*/
	public function getLotByUrlAndPariticipantsList($sUrl = '', $aParicipants = array(), $iType = BX_IM_TYPE_PRIVATE){
		if ($iType != BX_IM_TYPE_PRIVATE && $sUrl && $aLot = $this -> getLotByUrl($sUrl))
			return $aLot;

		$aResult = array();
		if (!empty($aParicipants)){
			$sWhere = " AND `{$this->CNF['FIELD_AUTHOR']}` IN (" . $this -> implode_escape($aParicipants) . ")";

			$aLots = $this -> getAll("SELECT * FROM `{$this->CNF['TABLE_ENTRIES']}` WHERE `type` = :type {$sWhere}", array('type' => $iType));

			if (!empty($aLots))
			{
				foreach($aLots as $iKey => $aValue)
				{
					 $aPerticipantsList = $this -> getParticipantsList($aValue[$this->CNF['FIELD_ID']]);
					 if (empty($aPerticipantsList) || count($aPerticipantsList) != count($aParicipants)) continue;

					 sort($aPerticipantsList);
					 sort($aParicipants);

					 if (array_values($aPerticipantsList) == array_values($aParicipants)){
						$aResult = $aValue;
					 }
				}
			}
		}

		return $aResult;
	}

	/**
	* Mark message as read in lot history
	*@param int $iJotId message id
	*@param int iProfileId
	*/
	public function readMessage($iJotId, $iProfileId){
		$sNotViewed = $this -> getOne("SELECT `{$this->CNF['FIELD_MESSAGE_NEW_FOR']}`
										FROM `{$this->CNF['TABLE_MESSAGES']}`
										WHERE `{$this->CNF['FIELD_MESSAGE_ID']}` = :id", array('id' => $iJotId));
		$sNewList = '';
		if ($sNotViewed)
		{
			$aParticipants = explode(',', $sNotViewed);
			$iKey = array_search($iProfileId, $aParticipants);
			if ($iKey !== FALSE)
			{
				unset($aParticipants[$iKey]);
				$sNewList = count($aParticipants) > 0 ? implode(',', $aParticipants) : '';
				$this -> query("UPDATE `{$this->CNF['TABLE_MESSAGES']}` SET `{$this->CNF['FIELD_MESSAGE_NEW_FOR']}` = :part WHERE `{$this->CNF['FIELD_MESSAGE_ID']}` = :id", array('part' => $sNewList, 'id' => $iJotId));
			}
		}
	}

	/**
	* Mark all message as read in lot history for member
	*@param int $iLot  lot id
	*@param int iProfileId
	*/
	public function readAllMessages($iLot, $iProfileId){
		$aAll = $this-> getAll("SELECT * FROM `{$this->CNF['TABLE_MESSAGES']}` WHERE `{$this->CNF['FIELD_MESSAGE_FK']}` = :id AND FIND_IN_SET(:user, `{$this->CNF['FIELD_MESSAGE_NEW_FOR']}`)", array('id' => $iLot, 'user' => $iProfileId));
		foreach($aAll as $iKey => $aValue){
			$sNewList = '';
			$aParticipants = explode(',', $aValue[$this->CNF['FIELD_MESSAGE_NEW_FOR']]);
			$iPos = array_search($iProfileId, $aParticipants);
			if ($iPos !== FALSE){
				unset($aParticipants[$iPos]);
				$sNewList = count($aParticipants) > 0 ? implode(',', $aParticipants) : '';
				$this -> query("UPDATE `{$this->CNF['TABLE_MESSAGES']}` SET `{$this->CNF['FIELD_MESSAGE_NEW_FOR']}` = :part WHERE `{$this->CNF['FIELD_MESSAGE_ID']}` = :id", array('part' => $sNewList, 'id' => $aValue[$this->CNF['FIELD_MESSAGE_ID']]));
			}
		}
	}

	/**
	*Add new new jot to database
	*@param int $iLotID  lot id
	*@param string $sMessage posted message
	*@param int iProfile Id	owner of the message
	*@return  int affected rows
	*/
	private function addNewJot($iLotID, $sMessage, $iProfileId)
	{
		$sParticipants = $this -> getParticipantsList($iLotID, false /* as  string list*/, $iProfileId);
		$sQuery = $this->prepare("INSERT INTO `{$this->CNF['TABLE_MESSAGES']}`
												SET  `{$this->CNF['FIELD_MESSAGE']}` = ?,
													 `{$this->CNF['FIELD_MESSAGE_FK']}` = ?,
													 `{$this->CNF['FIELD_MESSAGE_AUTHOR']}` = ?,
													 `{$this->CNF['FIELD_MESSAGE_NEW_FOR']}` = ?,
													 `{$this->CNF['FIELD_MESSAGE_ADDED']}` = UNIX_TIMESTAMP()", $sMessage, $iLotID, $iProfileId, $sParticipants);

		return $this->query($sQuery) ? $this -> lastId() : false;
	}

	/**
	*Create new chat/lot with list of participants
	*@param int iProfileId owner of the lot
	*@param string $sTitle lot title
	*@param int $iType type of the lot
	*@param string $sUrl url of the page
	*@param array $aParticipants list of participants
	*@return  int affected rows
	*/
	public function createNewLot($iProfileId, $sTitle, $iType, $sUrl = '', &$aParticipants = array())
	{
		$mixedParticipants = !empty($aParticipants) ? implode(',', $aParticipants) : $iProfileId;
		$sQuery = $this->prepare("INSERT INTO `{$this->CNF['TABLE_ENTRIES']}`
												SET  `{$this->CNF['FIELD_TITLE']}` = ?,
													 `{$this->CNF['FIELD_TYPE']}` = ?,
													 `{$this->CNF['FIELD_AUTHOR']}` = ?,
													 `{$this->CNF['FIELD_ADDED']}` = UNIX_TIMESTAMP(),
													 `{$this->CNF['FIELD_PARTICIPANTS']}` = ?,
													 `{$this->CNF['FIELD_URL']}` = ?", $sTitle, $iType, $iProfileId, $mixedParticipants, $sUrl);

		return $this->query($sQuery) ? $this -> lastId() : false;
	}

	/**
	*Get list of types of member lots
	*@param int iProfileId
	*@param string $sParam keyword to filter lots
	*@return  array found lots types with lots count per each type
	*/
	public function getMemberLotsTypes($iProfileId, $sParam = ''){
		$sWhere = '';
		$aWhere = array();

		if ($iProfileId){
			$aSWhere[] = "FIND_IN_SET(:profile, `{$this->CNF['FIELD_PARTICIPANTS']}`)";
			$aWhere = array('profile' => $iProfileId);
		}

		if ($sParam){
			$sParam = "%{$sParam}%";
			$aSWhere[] = " (`{$this->CNF['FIELD_TITLE']}` LIKE :title OR `{$this->CNF['FIELD_URL']}` LIKE :url OR `{$this->CNF['FIELD_TYPE']}` LIKE :type)";
			$aWhere = array_merge($aWhere, array('title' => $sParam, 'url' => $sParam, 'type' => $sParam));
		}

		if (!empty($aWhere))
			$sWhere = "WHERE (" . implode(' AND ', $aSWhere) . ')';

		return $this-> getPairs("SELECT `{$this->CNF['FIELD_TYPE']}`, COUNT(*) as `count`
			FROM `{$this->CNF['TABLE_ENTRIES']}`
			{$sWhere}
			GROUP BY `{$this->CNF['FIELD_TYPE']}`", $this->CNF['FIELD_TYPE'], 'count', $aWhere);
	}

	/**
	*Get list of all existed types
	*@return  array types
	*/
	public function getAllLotsTypes(){
		return $this -> getAll("SELECT * FROM `{$this->CNF['TABLE_TYPES']}` ORDER BY `{$this->CNF['FIELD_TYPE_ID']}` ASC");
	}

	/**
	*Get list of all existed types as pairs: Id - Value
	*@return  array types
	*/
	public function getLotsTypesPairs(){
		return $this -> getPairs("SELECT * FROM `{$this->CNF['TABLE_TYPES']}` ORDER BY `{$this->CNF['FIELD_TYPE_ID']}`", $this->CNF['FIELD_TYPE_ID'], $this->CNF['FIELD_TYPE_NAME']);
	}

	/**
	* Check if this ype of lot exists
	*@param int $iType type of the lot
	*@return boolean
	*/
	public function isLotType($iType){
		return $this -> getOne("SELECT COUNT(*) FROM `{$this->CNF['TABLE_TYPES']}` WHERE `{$this->CNF['FIELD_TYPE_ID']}` = :type LIMIT 1", array('type' => $iType)) == 1;
	}

	/**
	* Get lot's participant list
	*@param int $iLotId lot id
	*@param boolean $bArray if true, returns result as array, otherwise string with ids separated commas
	*@param int $bExcludeProfile allows to exclude profile from the list, usually it is owner
	*@return string/array
	*/
	public function getParticipantsList($iLotId, $bArray = true, $bExcludeProfile = 0){
		$aParticipants = array();
		$sParticipants = $this -> getOne("SELECT `{$this->CNF['FIELD_PARTICIPANTS']}` FROM `{$this->CNF['TABLE_ENTRIES']}` WHERE `{$this->CNF['FIELD_ID']}` = :value", array('value' => $iLotId));

		if (!$sParticipants)
				return array();

		$aParticipants = explode(',', $sParticipants);

		if ($bExcludeProfile && ($iId = array_search($bExcludeProfile, $aParticipants)) !== FALSE)
			unset($aParticipants[$iId]);

		return !$bArray ? implode(',', $aParticipants) : $aParticipants;
	}

	/**
	* Check if it is participant of the lot
	*@param int $iLotId lot id
	*@param int $iParticipantId profile id
	*@param boolean $bAsParticipant if true to check only participants list without lot owner
	*@return boolean
	*/
	public function isParticipant($iLotId, $iParticipantId, $bAsParticipant = false)
	{
		$aParticipants = $this -> getParticipantsList($iLotId);
		if (array_search($iParticipantId, $aParticipants) !== FALSE)
			return true;

		return !$bAsParticipant ? $this -> getOne("SELECT COUNT(*) FROM `{$this->CNF['TABLE_ENTRIES']}` WHERE `{$this->CNF['FIELD_ID']}` = :lot AND `{$this->CNF['FIELD_AUTHOR']}` = :author LIMIT 1", array('lot' => (int)$iLotId, 'author' => (int)$iParticipantId)) == 1 : false;
	}

	/**
	* Add profile to lot's participants list
	*@param int $iLotId lot id
	*@param int $iParticipantId profile id
	*@return int affected rows
	*/
	private function addMemberToParticipantsList($iLotId, $iParticipantId){
		$sParticipants = $this -> getParticipantsList($iLotId, false /* as string list */);
		$sParticipants = $sParticipants ? "{$sParticipants},{$iParticipantId}" : $iParticipantId;
		return $this -> query("UPDATE `{$this->CNF['TABLE_ENTRIES']}` SET `{$this->CNF['FIELD_PARTICIPANTS']}` = :parts WHERE `{$this->CNF['FIELD_ID']}` = :id", array('parts' => $sParticipants, 'id' => $iLotId));
	}

	/**
	* Remove profile from participants list
	*@param int $iLotId lot id
	*@param int $iParticipantId profile id
	*@return mixed false or affected rows
	*/
	private function removeParticipant($iLotId, $iParticipantId){
		$aParticipants = $this -> getParticipantsList($iLotId);
		$iKey = array_search($iParticipantId, $aParticipants);

		if ($iKey !== FALSE){
			unset($aParticipants[$iKey]);
			return $this -> savePariticipantsList($iLotId, $aParticipants);
		}

		return false;
	}

	/**
	* Get jots list for specified lot
	*@param int $iLotId lot id
	*@param int $iStart jot id from which start to get jots
	*@param string $sMode just posted or old jots from history
	*@param int $iLimit number of jots to get
	*@return array of the jots
	*/
	public function getJotsByLotId($iLotId, $iStart = 0, $sMode = 'new', $iLimit = 0){
		$sLimit = '';
		$aSWhere[] = "`{$this->CNF['FIELD_MESSAGE_FK']}` = :lot_id ";
		$aBindings['lot_id'] = (int)$iLotId;

		if ($iStart)
		{
			$aSWhere[] = "`{$this->CNF['FIELD_MESSAGE_ID']}` " . ($sMode == 'new' ? '>' : '<') . " :start ";
			$aBindings['start'] = (int)$iStart;
		}

		if ($iLimit)
		{
			$sLimit = "LIMIT :limit";
			$aBindings['limit'] = (int)$iLimit;
		}

		if (!empty($aBindings))
			$sWhere = 'WHERE ' . implode(' AND ', $aSWhere);

		return $this -> getAll("(
									SELECT * FROM `{$this->CNF['TABLE_MESSAGES']}`
									{$sWhere}
									ORDER BY `{$this->CNF['FIELD_MESSAGE_ADDED']}` DESC
									$sLimit
								) ORDER BY `{$this->CNF['FIELD_MESSAGE_ADDED']}` ASC", $aBindings);

	}

	/**
	* Get lot it by jot id
	*@param int $iJotId jot id
	*@param boolean bIdOnly return id or array with info
	*@return mixed lot id or lot info in array
	*/
	public function getLotByJotId($iJotId, $bIdOnly = true){
		$iLotId = $this -> getOne("SELECT `{$this->CNF['FIELD_MESSAGE_FK']}`
						FROM `{$this->CNF['TABLE_MESSAGES']}`
						WHERE `{$this->CNF['FIELD_MESSAGE_ID']}` = :jot LIMIT 1", array('jot' => $iJotId));

		if (!$iLotId)
			return array();

		return $bIdOnly ? $iLotId : $this -> getRow("SELECT * FROM `{$this->CNF['TABLE_ENTRIES']}`
						WHERE `{$this->CNF['FIELD_ID']}` = :lot LIMIT 1", array('lot' => $iLotId));
	}

	/**
	* Get the latest posted jot(message)
	*@param int $iLotId lot id
	*@param int $iProfileId if not specified the just latest jot of any member
	*@param boolean $bNotTrash don't show trash message
	*@return array with jot info
	*/
	public function getLatestJot($iLotId, $iProfileId = 0, $bNotTrash = true){
		$sWhere = '';
		$aWhere['lot'] = $iLotId;

		if ($iProfileId)
		{
			$sWhere = " AND `{$this->CNF['FIELD_MESSAGE_AUTHOR']}` = :profile";
			$aWhere['profile'] = $iProfileId;
		}

		if ($bNotTrash)
			$sWhere .= " AND `{$this->CNF['FIELD_MESSAGE_TRASH']}` = 0";

		return $this -> getRow("SELECT *
			FROM `{$this->CNF['TABLE_MESSAGES']}`
			WHERE  `{$this->CNF['FIELD_MESSAGE_FK']}` = :lot {$sWhere}
			ORDER BY `{$this->CNF['FIELD_MESSAGE_ADDED']}` DESC
			LIMIT 1", $aWhere);
	}

	/**
	* Get the latest posted jot(message)
	*@param int $iLotId lot id
	*@param int $iProfileId if not specified the just latest jot of any member
	*@return array with jot info
	*/
	public function getJotById($iJotId){
		$sQuery = $this -> prepare("SELECT *
			FROM `{$this->CNF['TABLE_MESSAGES']}`
			WHERE  `{$this->CNF['FIELD_MESSAGE_ID']}` = ?
			ORDER BY `{$this->CNF['FIELD_MESSAGE_ADDED']}` DESC
			LIMIT 1", $iJotId);

		return $this -> getRow($sQuery);
	}

	/**
	* Get all pages with comments block
	*@return array list with pages
	*/
	public function getPagesWithComments(){
		return $this -> getPairs("SELECT * FROM `sys_objects_cmts`", 'Name', 'BaseUrl');
	}

	/**
	* Check if the page already contains messenger block
	*@param $sPage page name
	*@return boolean
	*/
	public function isBlockAdded($sPage){
		$sPage = bx_process_input($sPage);
		$sQuery = $this -> prepare("SELECT COUNT(*) FROM `sys_pages_blocks` WHERE `object` = ? AND `title` = '_bx_messenger_page_block_title_messenger'", $sPage);

		return $this -> getOne($sQuery) == 1;
	}

	/**
	* Add messenger block to the page
	*@param $sPage page name
	*@return affected rows
	*/
	public function addMessengerBlock($sPage){
		$sPage = bx_process_input($sPage);
		$aInfo = $this -> findCommentsBlock($sPage);

		if (!empty($aInfo))
				return $this -> query("INSERT INTO `sys_pages_blocks` (`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`, `active`) VALUES
							  (:page, :cell, 'bx_messenger', '_bx_messenger_page_block_title_messenger', 0, 2147483647, 'service', 'a:3:{s:6:\"module\";s:12:\"bx_messenger\";s:6:\"method\";s:19:\"get_block_messenger\";s:6:\"params\";a:1:{i:0;s:6:\"{type}\";}}', 0, 0, :order, 0)",
							  array('page' => $sPage, 'cell' => $aInfo['cell_id'], 'order' => $aInfo['order'] + 1));

		return $this -> query("INSERT INTO `sys_pages_blocks` (`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`, `active`) VALUES
							  (:page, 1, 'bx_messenger', '_bx_messenger_page_block_title_messenger', 0, 2147483647, 'service', 'a:3:{s:6:\"module\";s:12:\"bx_messenger\";s:6:\"method\";s:19:\"get_block_messenger\";s:6:\"params\";a:1:{i:0;s:6:\"{type}\";}}', 0, 0, 0, 0)",
							   array('page' => $sPage));
	}

	/**
	* Find comments block on the page
	*@param $sPage page name
	*@return array block info
	*/
	private function findCommentsBlock($sPage){
		$sPage = bx_process_input($sPage);

		$sQuery = $this -> prepare("SELECT * FROM `sys_pages_blocks` WHERE `object` = ? AND `title` LIKE '%comments%'", $sPage);
		return $this -> getRow($sQuery);
	}

	public function getUnreadJotsMessagesCount($iProfileId, $iLotId){
		if (!(int)$iLotId) return false;

		$aJots = $this -> getMyJots($iProfileId, true, $iLotId);
		return count($aJots);
	}

	/**
	* Get all jots of the member
	*@param int $iProfileId
	*@param boolean $bUnread return only unread member
	*@return array list of jots
	*/
	public function getMyJots($iProfileId, $bUnread = false, $iLotId = 0){
		$sWhere = '';
		$aWhere['profile'] = $iProfileId;

		if ($bUnread){
			$sWhere = " AND FIND_IN_SET(:parts, `j`.`{$this->CNF['FIELD_MESSAGE_NEW_FOR']}`)";
			$aWhere['parts'] = $iProfileId;
		}

		if ($iLotId){
			$sWhere .= " AND `l`.`{$this->CNF['FIELD_ID']}` = :lot";
			$aWhere['lot'] = $iLotId;
		}

		return $this-> getAll("SELECT `j`.*
			FROM `{$this->CNF['TABLE_ENTRIES']}` as `l`
			LEFT JOIN `{$this->CNF['TABLE_MESSAGES']}` as `j` ON `l`.`{$this->CNF['FIELD_ID']}` = `j`.`{$this->CNF['FIELD_MESSAGE_FK']}`
			WHERE FIND_IN_SET(:profile, `l`.`{$this->CNF['FIELD_PARTICIPANTS']}`) {$sWhere}
			ORDER BY `j`.`{$this->CNF['FIELD_MESSAGE_ADDED']}` DESC", $aWhere);
	}

	/**
	* Get all member's lots
	*@param int $iProfileId
	*@param int $iType
	*@param string $sParam search keyword
	*@param boolean $bUnread get lots with unread jots only
	*@param int $iLotId lot id
	*@return array list of lots
	*/
	public function getMyLots($iProfileId, $iType = 0, $sParam = '', $bUnread = false, $iLotId = 0, $iStar = 0){
		$sJOIN = $sHaving = $sWhere = '';
		$aSWhere = array();
		$aWhere['parts'] = $aWhere['profile'] = $iProfileId;

		if ($sParam){
			$aSWhere[] = "(`j`.`{$this->CNF['FIELD_MESSAGE']}` LIKE :message OR `l`.`{$this->CNF['FIELD_TITLE']}` LIKE :title)";
			$aWhere['title'] = "%{$sParam}%";
			$aWhere['message'] = "%{$sParam}%";
		}

		if ($iType){
			$aSWhere[] = " `l`.`{$this->CNF['FIELD_TYPE']}` = :type ";
			$aWhere['type'] = $iType;
		}

		if ($bUnread){
			$sHaving = "HAVING `unread_jot_id` != 0";
		}

		if ($iLotId){
			$aSWhere[] = " `l`.`{$this->CNF['FIELD_ID']}` = :id ";
			$aWhere['id'] = $iLotId;
		}

		if ($iStar){
			$sJOIN = "INNER JOIN `{$this->CNF['TABLE_USERS_INFO']}` as `u` ON `u`.`{$this->CNF['FIELD_INFO_LOT_ID']}` = `l`.`{$this->CNF['FIELD_ID']}`";
			$aSWhere[] = "`u`.`{$this->CNF['FIELD_INFO_STAR']}` = 1";
		}

		if (!empty($aSWhere))
				$sWhere = ' AND ' . implode(' AND ', $aSWhere);

		return $this-> getAll("SELECT
			`l`.*,
			`p`.`count` as `unread_num`,
			`p`.`{$this->CNF['FIELD_MESSAGE_ADDED']}` as `last_created`,
			MAX(`j`.`{$this->CNF['FIELD_MESSAGE_ADDED']}`) as `last_jot_created`
			FROM `{$this->CNF['TABLE_ENTRIES']}` as `l`
			{$sJOIN}
			LEFT JOIN `{$this->CNF['TABLE_MESSAGES']}` as `j` ON `l`.`{$this->CNF['FIELD_ID']}` = `j`.`{$this->CNF['FIELD_MESSAGE_FK']}`
			LEFT JOIN (
						SELECT
							`{$this->CNF['FIELD_MESSAGE_FK']}`,
							COUNT(*) as `count`,
							MAX(`{$this->CNF['FIELD_MESSAGE_ADDED']}`) as `{$this->CNF['FIELD_MESSAGE_ADDED']}`
						FROM `{$this->CNF['TABLE_MESSAGES']}`
						WHERE FIND_IN_SET(:parts, `{$this->CNF['FIELD_MESSAGE_NEW_FOR']}`)
						GROUP BY `{$this->CNF['FIELD_MESSAGE_FK']}`
					  ) as `p` ON `p`.`{$this->CNF['FIELD_MESSAGE_FK']}` = `l`.`{$this->CNF['FIELD_ID']}`
			WHERE (FIND_IN_SET(:profile, `l`.`{$this->CNF['FIELD_PARTICIPANTS']}`) OR `l`.`{$this->CNF['FIELD_AUTHOR']}`=:profile) {$sWhere}
			GROUP BY `l`.`{$this->CNF['FIELD_ID']}`
			{$sHaving}
			ORDER BY `last_created` DESC, `last_jot_created` DESC", $aWhere);
	}

	/**
	* Get member's unread messages number
	*@param int $iProfileId
	*@return int number
	*/
	public function getNewMessagesNum($iProfileId){
		$aJots = $this -> getMyJots($iProfileId, true);
		return count($aJots);
	}

	/**
	* Check if the title of the lot type must contain link
	*@param int $iType
	*@return boolean
	*/
	public function isLinkedTitle($iType){
		$sQuery = $this -> prepare("SELECT `{$this->CNF['FIELD_TYPE_LINKED']}` FROM `{$this->CNF['TABLE_TYPES']}` WHERE `{$this->CNF['FIELD_TYPE_ID']}` = ? LIMIT 1", $iType);
		return (int)$this -> getOne($sQuery) == 1;
	}

	/**
	* Get time when member was online
	*@param int  $iProfileId
	*@return boolean
	*/
	public function lastOnline($iProfileId)
	{
	   $sSql = $this -> prepare("SELECT
				IF (`ts`.`date` != '', `ts`.`date`, `ta`.`logged`) as `logged`
			FROM `sys_profiles` AS `tp`
			INNER JOIN `sys_accounts` AS `ta` ON `tp`.`account_id`=`ta`.`id`
			LEFT JOIN `sys_sessions` AS `ts` ON `tp`.`account_id`=`ts`.`user_id`
			WHERE
				`tp`.`id` = ? AND
				`ta`.`profile_id`=`tp`.`id`
			LIMIT 1", $iProfileId);

		return $this -> getOne($sSql);
	}

	/**
	* Delete all profiles info from lots and jots
	*@param int  $iProfileId
	*@return int affected rows
	*/
	public function deleteProfileInfo($iProfileId){
		$bResult = true;

		$aWhere['profile'] = (int)$iProfileId;

		$bResult &= $this-> query("DELETE
			FROM `{$this->CNF['TABLE_ENTRIES']}`
			WHERE `{$this->CNF['FIELD_AUTHOR']}`=:profile", $aWhere);

		$aJots = $this-> getAll("SELECT *
			FROM `{$this->CNF['TABLE_MESSAGES']}`
			WHERE `{$this->CNF['FIELD_MESSAGE_AUTHOR']}`=:profile", $aWhere);

		foreach($aJots as $iKey => $aJot)
			$this -> removeFilesByJotId($aJot[$this->CNF['FIELD_MESSAGE_ID']]);

		$bResult &= $this-> query("DELETE
			FROM `{$this->CNF['TABLE_MESSAGES']}`
			WHERE `{$this->CNF['FIELD_MESSAGE_AUTHOR']}`=:profile", $aWhere);

		$aJots = $this-> getAll("SELECT *
			FROM `{$this->CNF['TABLE_ENTRIES']}`
			WHERE FIND_IN_SET(:profile, `{$this->CNF['FIELD_PARTICIPANTS']}`)", $aWhere);

		if (empty($aJots))
				return $bResult;

		foreach($aJots as $iKey => $aJot){
			$bResult &= $this -> removeParticipant($aJot[$this->CNF['FIELD_ID']], $iProfileId);
		}

		return $bResult;
	}

	/**
	* Add attachment to the jot
	*@param int  $iJotId jot id
	*@param text mixedContent attachment content
	*@param type sType attachment type
	*@return affected rows
	*/
	public function addAttachment($iJotId, $mixedContent, $sType = BX_ATT_TYPE_REPOST){
		$iJotId = (int)$iJotId;
		$aJotInfo = array();

		if (!$iJotId || !($aJotInfo = $this -> getJotById($iJotId)) || !$mixedContent)
			return false;

		if ($aJotInfo[$this->CNF['FIELD_MESSAGE_AT_TYPE']] && $aJotInfo[$this->CNF['FIELD_MESSAGE_AT_TYPE']] != BX_ATT_TYPE_REPOST) /* don't update attachment if it is already exists and it is not a repost */
			return false;

		$sQuery = $this->prepare("UPDATE `{$this->CNF['TABLE_MESSAGES']}`
												SET  `{$this->CNF['FIELD_MESSAGE_AT_TYPE']}` = ?,
													 `{$this->CNF['FIELD_MESSAGE_AT']}` = ?
												WHERE `{$this->CNF['FIELD_MESSAGE_ID']}` = ?", $sType, $mixedContent, $iJotId);

		return $this -> query($sQuery);
	}

	/**
	* Add attachment to the jot
	*@param int  $iJotId jot id
	*@param int  $iProfileId profile id
	*@param text $sMessage
	*@return affected rows
	*/
	public function editJot($iJotId, $iProfileId, $sMessage){
		$iJotId = (int)$iJotId;
		$aJotInfo = array();

		if (!$iJotId || !($aJotInfo = $this -> getJotById($iJotId)) || !$sMessage)
			return false;

		$sWhere = '';
		if ($aJotInfo[$this->CNF['FIELD_MESSAGE_AT_TYPE']] == BX_ATT_TYPE_REPOST)
			$sWhere = ",`{$this->CNF['FIELD_MESSAGE_AT_TYPE']}` = '', `{$this->CNF['FIELD_MESSAGE_AT']}` = ''";

		$sQuery = $this->prepare("UPDATE `{$this->CNF['TABLE_MESSAGES']}`
												SET  `{$this->CNF['FIELD_MESSAGE']}` = ?,
													 `{$this->CNF['FIELD_MESSAGE_LAST_EDIT']}` = UNIX_TIMESTAMP(),
													 `{$this->CNF['FIELD_MESSAGE_EDIT_BY']}` = ?
													 {$sWhere}
												WHERE `{$this->CNF['FIELD_MESSAGE_ID']}` = ?", $sMessage, $iProfileId, $iJotId);

		return $this -> query($sQuery);
	}

	/**
	* Check if the Jot already has attachment
	*@param int  $iJotId jot id
	*@param string $sType attachment type
	*@return int original attachment Id
	*/
	public function hasAttachment($iJotId, $sType='repost'){
		$iResult = $this->getOne("SELECT
									`{$this->CNF['FIELD_MESSAGE_AT']}`
									FROM `{$this->CNF['TABLE_MESSAGES']}`
									WHERE `{$this->CNF['FIELD_MESSAGE_ID']}` = :id AND `{$this->CNF['FIELD_MESSAGE_AT_TYPE']}`= :type", array('id' => $iJotId, 'type' => $sType));

		return $iResult ? $iResult : $iJotId;
	}

	public function updateFiles($iJotId, $sField = 'jot_id', $sValue){
		$sQuery = $this->prepare("UPDATE `{$this->CNF['OBJECT_STORAGE']}`
									SET  `{$sField}` = ?
									WHERE `{$this->CNF['FIELD_ST_ID']}` = ?", $sValue, $iJotId);

		return $this -> query($sQuery);
	}

	public function getJotFiles($iJot, $bCount = false){
		return !$bCount ? $this->getAll("SELECT * FROM `{$this->CNF['OBJECT_STORAGE']}` WHERE `{$this->CNF['FIELD_ST_JOT']}` = :id", array('id' => $iJot)) : $this->getOne("SELECT COUNT(*) FROM `{$this->CNF['OBJECT_STORAGE']}` WHERE `{$this->CNF['FIELD_ST_JOT']}` = :id", array('id' => $iJot));
	}

	private function removeFilesByJotId($iJotId){
		 $aFiles = $this -> getJotFiles($iJotId);
		 if (empty($aFiles))
			 return false;

		 $oStorage = BxDolStorage::getObjectInstance($this->CNF['OBJECT_STORAGE']);
		 $bResult = true;
		 foreach($aFiles as $iKey => $aFile)
			$bResult &= $oStorage -> deleteFile($aFile[$this->CNF['FIELD_ST_ID']], $aFile[$this->CNF['FIELD_ST_AUTHOR']]);

		  return $bResult;
	}

	public function isFileVendor($iFileId, $iProfileId){
		$oStorage = BxDolStorage::getObjectInstance($this->CNF['OBJECT_STORAGE']);
		$aFile = $oStorage -> getFile($iFileId);
		return $aFile[$this->CNF['FIELD_ST_AUTHOR']] == $iProfileId;
	}

	public function isEmptyJotMessage($iJotId){
		$aJotInfo = $this -> getJotById($iJotId);

		return empty($aJotInfo) || !$aJotInfo['FIELD_MESSAGE'];
	}
}

/** @} */


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

<TITLE>
Uses of Class edu.wpi.first.wpilibj.command.Command (2013 FRC Java API)
</TITLE>

<META NAME="date" CONTENT="2013-01-03">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
edu.wpi.first.wpilibj.command.Command

Packages that use Command

edu.wpi.first.wpilibj.buttons

edu.wpi.first.wpilibj.command

Uses of Command in edu.wpi.first.wpilibj.buttons

Methods in edu.wpi.first.wpilibj.buttons with parameters of type Command

 void
Trigger.whenActive(Command command)

          Starts the given command whenever the trigger just becomes active.

 void
Trigger.whenInactive(Command command)

          Starts the command when the trigger becomes inactive

 void
Button.whenPressed(Command command)

          Starts the given command whenever the button is newly pressed.

 void
Button.whenReleased(Command command)

          Starts the command when the button is released

 void
Trigger.whileActive(Command command)

          Constantly starts the given command while the button is held.

 void
Button.whileHeld(Command command)

          Constantly starts the given command while the button is held.

Uses of Command in edu.wpi.first.wpilibj.command

Subclasses of Command in edu.wpi.first.wpilibj.command

 class
CommandGroup

          A CommandGroup is a list of commands which are executed in sequence.

 class
PIDCommand

          This class defines a Command which interacts heavily with a PID loop.

 class
PrintCommand

          A PrintCommand is a command which prints out a string when it is initialized, and then immediately finishes.

 class
StartCommand

          A StartCommand will call the start() method of another command when it is initialized
 and will finish immediately.

 class
WaitCommand

          A WaitCommand will wait for a certain amount of time before finishing.

 class
WaitForChildren

          This command will only finish if whatever CommandGroup it is in has no active children.

 class
WaitUntilCommand

          WaitUntilCommand - waits until an absolute game time.

Methods in edu.wpi.first.wpilibj.command that return Command

 Command
Subsystem.getCurrentCommand()

          Returns the command which currently claims this subsystem.

protected  Command
Subsystem.getDefaultCommand()

          Returns the default command (or null if there is none).

Methods in edu.wpi.first.wpilibj.command with parameters of type Command

 void
Scheduler.add(Command command)

          Adds the command to the Scheduler.

 void
CommandGroup.addParallel(Command command)

          Adds a new child Command to the group.

 void
CommandGroup.addParallel(Command command,
            double timeout)

          Adds a new child Command to the group with the given timeout.

 void
CommandGroup.addSequential(Command command)

          Adds a new Command to the group.

 void
CommandGroup.addSequential(Command command,
              double timeout)

          Adds a new Command to the group with a given timeout.

protected  void
Subsystem.setDefaultCommand(Command command)

          Sets the default command.

Constructors in edu.wpi.first.wpilibj.command with parameters of type Command

StartCommand(Command commandToStart)

          Instantiates a StartCommand which will start the
 given command whenever its initialize() is called.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

"For updated information see the Java FRC site"

redpajama_set_name: RedPajamaGithub


text:
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'

$MatricesPath = './!matrices.txt'

Push-Location "$PSScriptRoot/roslyn-branches"
try {
    if (Test-Path $MatricesPath) {
        Remove-Item $MatricesPath
    }
    $env:GITHUB_OUTPUT=$MatricesPath

    npm run generate-matrix
    $matrices = Get-Content $MatricesPath -Raw
    $matrices -match 'update=(.+)' | Out-Null; $update = (ConvertFrom-Json $matches[1]).include
    $matrices -match 'cleanup=(.+)' | Out-Null; $cleanup = (ConvertFrom-Json $matches[1]).include

    $update
    $cleanup

    # TODO: new processing

    <#
    $matrix.include | % {
        $row = $_
        try {
            npm run build-branch -- $row.branch
        }
        catch {
            if (!$row.required) {
                Write-Warning "Branch $($row.branch) failed: $_"
                return
            }
            Write-Error "Branch $($row.branch) failed: $_"
        }
    }#>
}
finally {
    Pop-Location
}


text:
    #define countof(x) (sizeof(x) / sizeof(x[0]))
#endif // !countof

namespace clr
{
    namespace fs
    {
        class Dir
        {
        public:
            static inline bool Exists(
                LPCWSTR wzDirPath)
            {
                DWORD attrs = WszGetFileAttributes(wzDirPath);
                return (attrs != INVALID_FILE_ATTRIBUTES) && (attrs & FILE_ATTRIBUTE_DIRECTORY);
            }

            //-----------------------------------------------------------------------------------------
            // Creates new directory indicated by wzDirPath.
            //
            // Returns:
            //                          S_OK - on success directory creation
            //                       S_FALSE - when directory previously existed
            //      HR(ERROR_PATH_NOT_FOUND) - when creation of dir fails.
            static inline HRESULT Create(
                LPCWSTR wzDirPath)
            {
                HRESULT hr = S_OK;

                if (!WszCreateDirectory(wzDirPath, nullptr))
                {
                    hr = HRESULT_FROM_GetLastError();
                    if (hr == HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS))
                    {
                        hr = S_FALSE;
                    }
                }
                return hr;
            }

            //-----------------------------------------------------------------------------------------
            // Creates the specified directory and all required subdirectories. wzDirPath will be
            // temporarily modified in the process.
            //
            // Returns:
            //                          S_OK - on success directory creation
            //                       S_FALSE - when directory previously existed
            //      HR(ERROR_PATH_NOT_FOUND) - when creation of any dir fails.
            static inline HRESULT CreateRecursively(
                __inout_z LPWSTR wzDirPath,
                size_t cchDirPath = 0)
            {
                HRESULT hr = S_OK;

                if (wzDirPath == nullptr)
                {
                    return E_POINTER;
                }

                if (cchDirPath == 0)
                {
                    cchDirPath = wcslen(wzDirPath);
                }

                // Try to create the path. If it fails, assume that's because the parent folder does
                // not exist. Try to create the parent then re-attempt.
                WCHAR chOrig = wzDirPath[cchDirPath];
                hr = Create(wzDirPath);
                if (hr == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND))
                {
                    for (WCHAR* pCurCh = wzDirPath + cchDirPath - 1; pCurCh != wzDirPath; --pCurCh)
                    {
                        if (*pCurCh == W('\\') || *pCurCh == W('\0'))
                        {
                            WCHAR chOrig = *pCurCh;
                            *pCurCh = W('\0');
                            IfFailRet(CreateRecursively(wzDirPath, pCurCh - wzDirPath));
                            *pCurCh = chOrig;
                            break;
                        }
                    }
                    IfFailRet(Create(wzDirPath));
                }

                return hr;
            }

            //-----------------------------------------------------------------------------------------
            // Creates the specified directory and all required subdirectories.
            static inline HRESULT CreateRecursively(
                LPCWSTR wzDirPath)
            {
                HRESULT hr = S_OK;

                if (wzDirPath == nullptr)
                {
                    return E_POINTER;
                }

                // Make a writable copy of wzDirPath
                size_t cchDirPath = wcslen(wzDirPath);
                CQuickWSTR wzBuffer;
                IfFailRet(wzBuffer.ReSizeNoThrow(cchDirPath + 1));
                wcscpy_s(wzBuffer.Ptr(), wzBuffer.Size(), wzDirPath);
                IfFailRet(CreateRecursively(wzBuffer.Ptr(), cchDirPath));

                return hr;
            }
        };
    }
}

#endif // _clr_fs_Dir_h_


text:
package edu.duke.cabig.c3pr.webservice.iso21090;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for QSS_REAL complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="QSS_REAL">
 *   <complexContent>
 *     <extension base="{uri:iso.org:21090}QSET_REAL">
 *       <sequence>
 *         <element name="term" type="{uri:iso.org:21090}REAL" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "QSS_REAL", propOrder = {
    "term"
})
public class QSSREAL
    extends QSETREAL
{

    protected List<REAL> term;

    /**
     * Gets the value of the term property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the term property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getTerm().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link REAL }
     *
     *
     */
    public List<REAL> getTerm() {
        if (term == null) {
            term = new ArrayList<REAL>();
        }
        return this.term;
    }

}


text:
package io.squark.activemq.consuldiscovery;

public class ConsulDiscoveryException extends RuntimeException {
  public ConsulDiscoveryException(String message) {
    super(message);
  }

  public ConsulDiscoveryException(Throwable cause) {
    super(cause);
  }

  public ConsulDiscoveryException(String message, Throwable cause) {
    super(message, cause);
  }
}


text:
package org.mockito.internal.stubbing.answers;

import static junit.framework.TestCase.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;

import java.io.IOException;
import java.nio.charset.CharacterCodingException;

import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.invocation.InvocationBuilder;
import org.mockito.invocation.Invocation;

public class ThrowsExceptionTest {
    @Test
    public void should_raise_wanted_throwable() {
        try {
            new ThrowsException(new IllegalStateException("my dear throwable"))
                    .answer(createMethodInvocation());
            Assertions.fail("should have raised wanted exception");
        } catch (Throwable throwable) {
            assertThat(throwable)
                    .isInstanceOf(IllegalStateException.class)
                    .hasMessage("my dear throwable");
        }
    }

    @Test
    public void should_throw_mock_exception_without_stacktrace() {
        try {
            new ThrowsException(mock(Exception.class)).answer(createMethodInvocation());
            Assertions.fail("should have raised wanted exception");
        } catch (Throwable throwable) {
            assertThat(throwable.getStackTrace()).describedAs("no stack trace, it's mock").isNull();
        }
    }

    @Test
    public void should_fill_in_exception_stacktrace() {
        // given
        Exception throwableToRaise = new Exception();
        throwableToRaise.fillInStackTrace();
        assertThat(throwableToRaise.getStackTrace()[0].getClassName())
                .isEqualTo(this.getClass().getName());
        assertThat(throwableToRaise.getStackTrace()[0].getMethodName())
                .isEqualTo("should_fill_in_exception_stacktrace");
        try {

            // when
            new ThrowsException(throwableToRaise).answer(createMethodInvocation());
            Assertions.fail("should have raised wanted exception");
        } catch (Throwable throwable) {
            // then
            throwable.printStackTrace();
            assertThat(throwableToRaise.getStackTrace()[0].getClassName())
                    .isEqualTo(AbstractThrowsException.class.getName());
            assertThat(throwableToRaise.getStackTrace()[0].getMethodName()).isEqualTo("answer");
        }
    }

    @Test
    public void should_invalidate_null_throwable() {
        try {
            Invocation invocation = createMethodInvocation();
            new ThrowsException(null).validateFor(invocation);
            Assertions.fail("should have raised a MockitoException");
        } catch (MockitoException expected) {
        }
    }

    @Test
    public void should_throw_illegal_state_exception_if_null_answer() throws Throwable {
        Invocation invocation = createMethodInvocation();
        try {
            new ThrowsException(null).answer(invocation);
            fail();
        } catch (IllegalStateException expected) {
        }
    }

    @Test
    public void should_pass_proper_checked_exception() {
        new ThrowsException(new CharacterCodingException()).validateFor(createMethodInvocation());
    }

    @Test
    public void should_fail_invalid_checked_exception() {
        assertThatThrownBy(
                        () -> {
                            new ThrowsException(new IOException())
                                    .validateFor(createMethodInvocation());
                        })
                .isInstanceOf(MockitoException.class)
                .hasMessageContainingAll(
                        "Checked exception is invalid for this method!",
                        "Invalid: java.io.IOException");
    }

    @Test
    public void should_pass_RuntimeExceptions() {
        new ThrowsException(new Error()).validateFor(createMethodInvocation());
        new ThrowsException(new RuntimeException()).validateFor(createMethodInvocation());
    }

    @Test
    public void should_return_expected_throwable() {
        Throwable expected = new Exception();
        ThrowsException throwsException = new ThrowsException(expected);

        assertSame(expected, throwsException.getThrowable());
    }

    @Test
    public void should_return_same_throwable() {
        ThrowsException throwsException = new ThrowsException(new Exception());

        Throwable first = throwsException.getThrowable();
        Throwable second = throwsException.getThrowable();
        assertSame(first, second);
    }

    /** Creates Invocation of a "canThrowException" method call. */
    private static Invocation createMethodInvocation() {
        return new InvocationBuilder().method("canThrowException").toInvocation();
    }
}


text:
export interface IMap {
  [key: string]: any;
}
/**
 *
 * @param keys
 */
export function arrayToMapFunc(keys: string[]): (results: any) => any {
  return (results: any[]) => {
    return results.reduce((acc: IMap, result: any, i: number) => {
      acc[keys[i]] = result;
      return acc;
    }, {});
  };
}

/**
 *
 * @param array
 * @param chunkSize
 */
export function split(array: any[], chunkSize: number) {
  if (chunkSize <= 0) {
    throw Error(`chunkSize(${chunkSize}) parameter should be > 0`);
  }
  return [].concat.apply(
    [],
    array.map((elem, i) => {
      return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
    }),
  );
}


text:
"""Base FPCore interpreter."""

import itertools
import traceback

from ..titanic import utils, digital
from ..fpbench import fpcast as ast
from .evalctx import EvalCtx
from ..titanic import ndarray

class EvaluatorError(utils.TitanicError):
    """Base Titanic evaluator error."""

class EvaluatorUnimplementedError(EvaluatorError):
    """Unimplemented feature in Titanic evaluator."""

class EvaluatorUnboundError(EvaluatorError, LookupError):
    """Unbound variable encountered during evaluation."""

class Evaluator(object):
    """FPCore evaluator.
    Dispatches on type of expressions in the AST.
    """

    ctype = EvalCtx

    def _eval_expr(self, e, ctx):
        raise EvaluatorUnimplementedError('expr {}: unimplemented'.format(str(e)))

    def _eval_data(self, e, ctx):
        raise EvaluatorUnimplementedError('data {}: unimplemented'.format(str(e)))

    def _eval_value(self, e, ctx):
        raise EvaluatorUnimplementedError('value {}: unimplemented'.format(str(e)))

    def _eval_var(self, e, ctx):
        raise EvaluatorUnimplementedError('var {}: unimplemented'.format(str(e)))

    def _eval_val(self, e, ctx):
        raise EvaluatorUnimplementedError('val {}: unimplemented'.format(str(e)))

    def _eval_ctx(self, e, ctx):
        # Note that let creates a new context, so the old one will
        # not be changed.
        return None, self.evaluate(e.body, ctx.let(props=e.props))

    def _eval_control(self, e, ctx):
        raise EvaluatorUnimplementedError('control {}: unimplemented'.format(str(e)))

    def _eval_op(self, e, ctx):
        raise EvaluatorUnimplementedError('op {}: unimplemented'.format(str(e)))

    def _eval_unknown(self, e, ctx):
        raise EvaluatorError('unknown operation {}'.format(e.name))

    _evaluator_dispatch = {
        # catch-all for otherwise unimplemented AST nodes
        ast.Expr: '_eval_expr',
        # structured data, which usually will only occur in properties
        ast.Data: '_eval_data',
        # the parent value class represents interned data that should be returned exactly
        ast.ValueExpr: '_eval_value',
        # variables are their own thing
        ast.Var: '_eval_var',
        # catch-all for all constant-valued expressions
        ast.Val: '_eval_val',
        # specific types of values
        ast.Constant: '_eval_constant',
        ast.Decnum: '_eval_decnum',
        ast.Hexnum: '_eval_hexnum',
        ast.Integer: '_eval_integer',
        ast.Rational: '_eval_rational',
        ast.Digits: '_eval_digits',
        # strings are special ValueExprs (not Vals) that won't normally be evaluated
        ast.String: '_eval_string',
        # rounding contexts
        ast.Ctx: '_eval_ctx',
        # control flow and tensors
        ast.ControlExpr: '_eval_control',
        ast.If: '_eval_if',
        ast.Let: '_eval_let',
        ast.LetStar: '_eval_letstar',
        ast.While: '_eval_while',
        ast.WhileStar: '_eval_whilestar',
        ast.For: '_eval_for',
        ast.ForStar: '_eval_forstar',
        ast.Tensor: '_eval_tensor',
        ast.TensorStar: '_eval_tensorstar',
        # catch-all for operations with some number of arguments
        ast.NaryExpr: '_eval_op',
        # arrays are like expressions, but they return a list of the inputs
        ast.Array: '_eval_array',
        # unknown operations are treated as function calls
        ast.UnknownOperator: '_eval_unknown',
        # specific operations
        ast.Cast: '_eval_cast',
        ast.Dim: '_eval_dim',
        ast.Size: '_eval_size',
        ast.Ref: '_eval_ref',
        ast.Add: '_eval_add',
        ast.Sub: '_eval_sub',
        ast.Mul: '_eval_mul',
        ast.Div: '_eval_div',
        ast.Sqrt: '_eval_sqrt',
        ast.Fma: '_eval_fma',
        ast.Neg: '_eval_neg',
        ast.Copysign: '_eval_copysign',
        ast.Fabs: '_eval_fabs',
        ast.Fdim: '_eval_fdim',
        ast.Fmax: '_eval_fmax',
        ast.Fmin: '_eval_fmin',
        ast.Fmod: '_eval_fmod',
        ast.Remainder: '_eval_remainder',
        ast.Ceil: '_eval_ceil',
        ast.Floor: '_eval_floor',
        ast.Nearbyint: '_eval_nearbyint',
        ast.Round: '_eval_round',
        ast.Trunc: '_eval_trunc',
        ast.Acos: '_eval_acos',
        ast.Acosh: '_eval_acosh',
        ast.Asin: '_eval_asin',
        ast.Asinh: '_eval_asinh',
        ast.Atan: '_eval_atan',
        ast.Atan2: '_eval_atan2',
        ast.Atanh: '_eval_atanh',
        ast.Cos: '_eval_cos',
        ast.Cosh: '_eval_cosh',
        ast.Sin: '_eval_sin',
        ast.Sinh: '_eval_sinh',
        ast.Tan: '_eval_tan',
        ast.Tanh: '_eval_tanh',
        ast.Exp: '_eval_exp',
        ast.Exp2: '_eval_exp2',
        ast.Expm1: '_eval_exmp1',
        ast.Log: '_eval_log',
        ast.Log10: '_eval_log10',
        ast.Log1p: '_eval_log1p',
        ast.Log2: '_eval_log2',
        ast.Cbrt: '_eval_cbrt',
        ast.Hypot: '_eval_hypot',
        ast.Pow: '_eval_pow',
        ast.Erf: '_eval_erf',
        ast.Erfc: '_eval_erfc',
        ast.Lgamma: '_eval_lgamma',
        ast.Tgamma: '_eval_tgamma',
        ast.LT: '_eval_lt',
        ast.GT: '_eval_gt',
        ast.LEQ: '_eval_leq',
        ast.GEQ: '_eval_geq',
        ast.EQ: '_eval_eq',
        ast.NEQ: '_eval_neq',
        ast.Isfinite: '_eval_isfinite',
        ast.Isinf: '_eval_isinf',
        ast.Isnan: '_eval_isnan',
        ast.Isnormal: '_eval_isnormal',
        ast.Signbit: '_eval_signbit',
        ast.And: '_eval_and',
        ast.Or: '_eval_or',
        ast.Not: '_eval_not',
    }

    _evaluator_cache = utils.ImmutableDict()

    def __init__(self):
        self.evals = 0
        self.max_evals = 0
        self.notify_evals = 0xfffff
        self.enable_analysis = True
        self.analyses = []

    def evaluate(self, e, ctx):
        try:
            method = self._evaluator_cache[type(e)]
        except KeyError:
            # initialize the cache for this class if it hasn't been initialized already
            if isinstance(self._evaluator_cache, utils.ImmutableDict):
                self._evaluator_cache = {}
            # walk up the mro and assign the evaluator for the first subtype to this type
            method = None
            ecls = type(e)
            for superclass in ecls.__mro__:
                method_name = self._evaluator_dispatch.get(superclass, None)
                if method_name is not None and hasattr(self, method_name):
                    method = getattr(self, method_name)
                    self._evaluator_cache[ecls] = method
                    break
            if method is None:
                raise EvaluatorError('Evaluator: unable to dispatch for expression {} with mro {}'
                                     .format(repr(e), repr(ecls.__mro__)))

        inputs, result = method(e, ctx)

        if self.enable_analysis:
            self.evals += 1
            if self.evals & self.notify_evals == self.notify_evals:
                print(',', end='', flush=True)

            if str(ctx.props.get('titanic-analysis')) != 'skip':
                for analysis in self.analyses:
                    analysis.track(e, ctx, inputs, result)
                if self.max_evals and self.evals > self.max_evals:
                    raise EvaluatorError('Evaluation limit {} reached on expression {}'
                                         .format(str(self.max_evals), str(e)))

        return result

class BaseInterpreter(Evaluator):
    """Base interpreter - only implements control flow."""

    # datatype conversion

    dtype = type(None)
    ctype = EvalCtx

    constants = {
        'TRUE': True,
        'FALSE': False,
    }

    def __init__(self):
        super().__init__()
        self.cores = {}

    def arg_to_digital(x, ctx):
        raise EvaluatorUnimplementedError('arg_to_digital({}): unimplemented'.format(repr(x)))

    def round_to_context(x, ctx):
        raise EvaluatorUnimplementedError('round_to_context({}): unimplemented'.format(repr(x)))

    # values

    def _eval_value(self, e, ctx):
        return None, e.value

    def _eval_var(self, e, ctx):
        try:
            return None, ctx.bindings[e.value]
        except KeyError as exn:
            raise EvaluatorUnboundError(exn.args[0])

    def _eval_val(self, e, ctx):
        return None, self.arg_to_digital(e.value, ctx)

    def _eval_constant(self, e, ctx):
        try:
            return None, self.constants[e.value]
        except KeyError as exn:
            raise EvaluatorUnimplementedError('unsupported constant {}'.format(repr(exn.args[0])))

    # Tensors

    def _eval_array(self, e, ctx):
        return None, ndarray.NDArray(self.evaluate(child, ctx) for child in e.children)

    def _eval_dim(self, e, ctx):
        nd = self.evaluate(e.children[0], ctx)
        if not isinstance(nd, ndarray.NDArray):
            raise EvaluatorError('{} must be a tensor to get its dimension'.format(repr(nd)))
        #return digital.Digital(m=len(nd.shape), exp=0)
        return None, self.arg_to_digital(len(nd.shape), ctx=ctx)

    def _eval_size(self, e, ctx):
        nd = self.evaluate(e.children[0], ctx)
        if not isinstance(nd, ndarray.NDArray):
            raise EvaluatorError('{} must be a tensor to get the size of a dimension'.format(repr(nd)))
        idx = self.evaluate(e.children[1], ctx)
        if not idx.is_integer():
            raise EvaluatorError('computed shape index {} must be an integer'.format(repr(idx)))
        i = int(idx)
        #return digital.Digital(m=nd.shape[i], exp=0)
        return None, self.arg_to_digital(nd.shape[i], ctx=ctx)

    def _eval_ref(self, e, ctx):
        nd = self.evaluate(e.children[0], ctx)
        if not isinstance(nd, ndarray.NDArray):
            raise EvaluatorError('{} must be a tensor to get an element'.format(repr(nd)))
        inputs = []
        pos = []
        for child in e.children[1:]:
            idx = self.evaluate(child, ctx)
            if not idx.is_integer():
                raise EvaluatorError('computed index {} must be an integer'.format(repr(idx)))
            inputs.append(idx)
            pos.append(int(idx))
        result = nd[pos]
        if result is None:
            raise EvaluatorError('index {} has not been computed'.format(repr(pos)))
        else:
            return inputs, result

    def _eval_tensor(self, e, ctx):
        inputs = []
        shape = []
        names = []
        for name, expr in e.dim_bindings:
            size = self.evaluate(expr, ctx)
            if not size.is_integer():
                raise EvaluatorError('dimension size {} must be an integer'.format(repr(size)))
            inputs.append(size)
            shape.append(int(size))
            names.append(name)

        # TODO: should coordinates be rounded?
        data = [self.evaluate(e.body, ctx.let(bindings=[(name, self.dtype(i))
                                                        for name, i in zip(names, ndarray.position(shape, idx))]))
                for idx in range(ndarray.calc_size(shape))]
        return inputs, ndarray.NDArrayView(shape=shape, data=data)

    def _eval_tensorstar(self, e, ctx):
        inputs = []
        shape = []
        names = []
        for name, expr in e.dim_bindings:
            size = self.evaluate(expr, ctx)
            if not size.is_integer():
                raise EvaluatorError('dimension size {} must be an integer'.format(repr(size)))
            inputs.append(size)
            shape.append(int(size))
            names.append(name)

        nd = ndarray.NDArray(shape=shape)

        if e.ident:
            ctx = ctx.let(bindings=[(e.ident, nd)])

        for name, init_expr, update_expr in e.while_bindings:
            new_binding = (name, self.evaluate(init_expr, ctx))
            ctx = ctx.let(bindings=[new_binding])

        for idx in range(ndarray.calc_size(shape)):
            # TODO: should coordinates be rounded?
            pos = ndarray.position(shape, idx)
            ctx = ctx.let(bindings=[(name, self.dtype(i))
                                    for name, i in zip(names, pos)])
            for name, init_expr, update_expr in e.while_bindings:
                new_binding = (name, self.evaluate(update_expr, ctx))
                ctx = ctx.let(bindings=[new_binding])
            nd[pos] = self.evaluate(e.body, ctx)

        return inputs, ndarray.NDArrayView(shape=nd.shape, data=nd.data)

    # control flow

    def _eval_if(self, e, ctx):
        if self.evaluate(e.cond, ctx):
            result = self.evaluate(e.then_body, ctx)
        else:
            result = self.evaluate(e.else_body, ctx)
        return None, result

    def _eval_let(self, e, ctx):
        bindings = [(name, self.evaluate(expr, ctx)) for name, expr in e.let_bindings]
        return None, self.evaluate(e.body, ctx.let(bindings=bindings))

    def _eval_letstar(self, e, ctx):
        for name, expr in e.let_bindings:
            new_binding = (name, self.evaluate(expr, ctx))
            ctx = ctx.let(bindings=[new_binding])
        return None, self.evaluate(e.body, ctx)

    def _eval_while(self, e, ctx):
        bindings = [(name, self.evaluate(init_expr, ctx)) for name, init_expr, update_expr in e.while_bindings]
        ctx = ctx.let(bindings=bindings)
        while self.evaluate(e.cond, ctx):
            bindings = [(name, self.evaluate(update_expr, ctx)) for name, init_expr, update_expr in e.while_bindings]
            ctx = ctx.let(bindings=bindings)
        return None, self.evaluate(e.body, ctx)

    def _eval_whilestar(self, e, ctx):
        for name, init_expr, update_expr in e.while_bindings:
            new_binding = (name, self.evaluate(init_expr, ctx))
            ctx = ctx.let(bindings=[new_binding])
        while self.evaluate(e.cond, ctx):
            for name, init_expr, update_expr in e.while_bindings:
                new_binding = (name, self.evaluate(update_expr, ctx))
                ctx = ctx.let(bindings=[new_binding])
        return None, self.evaluate(e.body, ctx)

    def _eval_for(self, e, ctx):
        inputs = []
        shape = []
        names = []
        for name, expr in e.dim_bindings:
            size = self.evaluate(expr, ctx)
            if not size.is_integer():
                raise EvaluatorError('dimension size {} must be an integer'.format(repr(size)))
            inputs.append(size)
            shape.append(int(size))
            names.append(name)

        bindings = [(name, self.evaluate(init_expr, ctx)) for name, init_expr, update_expr in e.while_bindings]
        ctx = ctx.let(bindings=bindings)

        for idx in range(ndarray.calc_size(shape)):
            # TODO: should coordinates be rounded?
            ctx = ctx.let(bindings=[(name, self.dtype(i))
                                    for name, i in zip(names, ndarray.position(shape, idx))])
            bindings = [(name, self.evaluate(update_expr, ctx)) for name, init_expr, update_expr in e.while_bindings]
            ctx = ctx.let(bindings=bindings)

        return inputs, self.evaluate(e.body, ctx)

    def _eval_forstar(self, e, ctx):
        inputs = []
        shape = []
        names = []
        for name, expr in e.dim_bindings:
            size = self.evaluate(expr, ctx)
            if not size.is_integer():
                raise EvaluatorError('dimension size {} must be an integer'.format(repr(size)))
            inputs.append(size)
            shape.append(int(size))
            names.append(name)

        for name, init_expr, update_expr in e.while_bindings:
            new_binding = (name, self.evaluate(init_expr, ctx))
            ctx = ctx.let(bindings=[new_binding])

        for idx in range(ndarray.calc_size(shape)):
            # TODO: should coordinates be rounded?
            ctx = ctx.let(bindings=[(name, self.dtype(i))
                                    for name, i in zip(names, ndarray.position(shape, idx))])
            for name, init_expr, update_expr in e.while_bindings:
                new_binding = (name, self.evaluate(update_expr, ctx))
                ctx = ctx.let(bindings=[new_binding])

        return inputs, self.evaluate(e.body, ctx)

    def _eval_unknown(self, e, ctx):
        ident = e.name
        if ident is not None and ident in self.cores:
            function_core = self.cores[ident]
        else:
            raise EvaluatorError('unknown function {}'.format(e.name))

        inputs = [self.evaluate(child, ctx) for child in e.children]

        # wrap in Value, to avoid rounding the inputs again
        args = [ast.ValueExpr(v) for v in inputs]

        return inputs, self.interpret(function_core, args, ctx=ctx, override=False)

    # interpreter interface

    def arg_ctx(self, core, args, ctx=None, override=True):
        if len(core.inputs) != len(args):
            raise ValueError('incorrect number of arguments: got {}, expecting {} ({})'.format(
                len(args), len(core.inputs), ' '.join((name for name, props in core.inputs))))

        if ctx is None:
            ctx = self.ctype(props=core.props)
        elif override:
            allprops = {}
            allprops.update(core.props)
            allprops.update(ctx.props)
            ctx = ctx.let(props=allprops)
        else:
            ctx = ctx.let(props=core.props)

        arg_bindings = []

        for arg, (name, props, shape) in zip(args, core.inputs):
            local_ctx = ctx.let(props=props)

            if isinstance(arg, self.dtype):
                argval = self.round_to_context(arg, ctx=local_ctx)
            elif isinstance(arg, ast.Expr):
                argval = self.evaluate(arg, local_ctx)
            elif isinstance(arg, ndarray.NDArray):
                rounded_data = [
                    self.round_to_context(d, ctx=local_ctx) if isinstance(arg, self.dtype) else self.arg_to_digital(d, local_ctx)
                    for d in arg.data
                ]
                argval = ndarray.NDArray(shape=arg.shape, data=rounded_data)
            elif isinstance(arg, list):
                nd_unrounded = ndarray.NDArray(shape=None, data=arg)
                rounded_data = [
                    self.round_to_context(d, ctx=local_ctx) if isinstance(arg, self.dtype) else self.arg_to_digital(d, local_ctx)
                    for d in nd_unrounded.data
                ]
                argval = ndarray.NDArray(shape=nd_unrounded.shape, data=rounded_data)
            else:
                argval = self.arg_to_digital(arg, local_ctx)

            if isinstance(argval, ndarray.NDArray):
                if not shape:
                    raise EvaluatorError('not expecting a tensor, got shape {}'.format(repr(argval.shape)))
                if len(shape) != len(argval.shape):
                    raise EvaluatorError('tensor input has wrong shape: expecting {}, got {}'.format(repr(shape), repr(argval.shape)))
                for dim, argdim in zip(shape, argval.shape):
                    if isinstance(dim, int) and dim != argdim:
                        raise EvaluatorError('tensor input has wrong shape: expecting {}, got {}'.format(repr(shape), repr(argval.shape)))
                    elif isinstance(dim, str):
                        arg_bindings.append((dim, self.dtype(argdim)))

            arg_bindings.append((name, argval))

        return ctx.let(bindings=arg_bindings)

    def register_function(self, core):
        if core.ident is not None:
            self.cores[core.ident] = core

    def interpret(self, core, args, ctx=None, override=True):
        ctx = self.arg_ctx(core, args, ctx=ctx, override=override)
        return self.evaluate(core.e, ctx)

    def interpret_pre(self, core, args, ctx=None, override=True):
        if core.pre is None:
            return True
        else:
            ctx = self.arg_ctx(core, args, ctx=ctx, override=override)
            return self.evaluate(core.pre, ctx)

class SimpleInterpreter(BaseInterpreter):
    """Simple FPCore interpreter.
    Override Interpreter.dtype with any class that supports
    simple arithmetic operators: a + b, a > b, abs(a).
    """

    def _eval_cast(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        # HACK to make sure that rounding to a wider type doesn't cause a precision error
        in0 = type(in0)(in0, inexact=False, rounded=False)
        return [in0], self.round_to_context(in0, ctx)

    def _eval_add(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0 + in1

    def _eval_sub(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0 - in1

    def _eval_mul(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0 * in1

    # Division may need to be overwritten for types that raise an exception on
    # division by 0 (such as Python floats).

    def _eval_div(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0 / in1

    def _eval_neg(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], -in0

    def _eval_fabs(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], abs(in0)

    # In the common case where nan isn't ordered, it will probably be necessary
    # to override these functions so that they do the right thing.

    def _eval_fmax(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], max(in0, in1)

    def _eval_fmin(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], min(in0, in1)

    # This ugly code is designed to cause comparison operators to short-circuit.
    # A more elegant implementation:
    #    inputs = [self.evaluate(child, ctx) for child in e.children]
    #    for x, y in zip(inputs, inputs[1:]):
    #        if not x < y:
    #            return inputs, False
    #    return inputs, True
    # does not short-circuit, which is inconsistent with the behavior of
    # _eval_and and _eval_or, which use the short-circuiting all and any builtins.

    # Note that comparisons report only the arguments they evaluated
    # as their inputs, due to short-circuiting.
    # This will be 0 (for a nullary / unary comparison) or 2+.
    # Logical operations do not report their inputs, as they are all boolean.

    def _eval_lt(self, e, ctx):
        if len(e.children) == 2:
            in0 = self.evaluate(e.children[0], ctx)
            in1 = self.evaluate(e.children[1], ctx)
            return [in0, in1], in0 < in1
        elif len(e.children) < 2:
            return [], True
        else:
            inputs = []
            a = self.evaluate(e.children[0], ctx)
            inputs.append(a)
            for child in e.children[1:]:
                b = self.evaluate(child, ctx)
                inputs.append(b)
                if not a < b:
                    return inputs, False
                a = b
            return inputs, True

    def _eval_gt(self, e, ctx):
        if len(e.children) == 2:
            in0 = self.evaluate(e.children[0], ctx)
            in1 = self.evaluate(e.children[1], ctx)
            return [in0, in1], in0 > in1
        elif len(e.children) < 2:
            return True
        else:
            inputs = []
            a = self.evaluate(e.children[0], ctx)
            inputs.append(a)
            for child in e.children[1:]:
                b = self.evaluate(child, ctx)
                inputs.append(b)
                if not a > b:
                    return inputs, False
                a = b
            return inputs, True

    def _eval_leq(self, e, ctx):
        if len(e.children) == 2:
            in0 = self.evaluate(e.children[0], ctx)
            in1 = self.evaluate(e.children[1], ctx)
            return [in0, in1], in0 <= in1
        elif len(e.children) < 2:
            return [], True
        else:
            inputs = []
            a = self.evaluate(e.children[0], ctx)
            inputs.append(a)
            for child in e.children[1:]:
                b = self.evaluate(child, ctx)
                inputs.append(b)
                if not a <= b:
                    return inputs, False
                a = b
            return inputs, True

    def _eval_geq(self, e, ctx):
        if len(e.children) == 2:
            in0 = self.evaluate(e.children[0], ctx)
            in1 = self.evaluate(e.children[1], ctx)
            return [in0, in1], in0 >= in1
        elif len(e.children) < 2:
            return [], True
        else:
            inputs = []
            a = self.evaluate(e.children[0], ctx)
            inputs.append(a)
            for child in e.children[1:]:
                b = self.evaluate(child, ctx)
                inputs.append(b)
                if not a >= b:
                    return inputs, False
                a = b
            return inputs, True

    def _eval_eq(self, e, ctx):
        if len(e.children) == 2:
            in0 = self.evaluate(e.children[0], ctx)
            in1 = self.evaluate(e.children[1], ctx)
            return [in0, in1], in0 == in1
        elif len(e.children) < 2:
            return [], True
        else:
            inputs = []
            a = self.evaluate(e.children[0], ctx)
            inputs.append(a)
            for child in e.children[1:]:
                b = self.evaluate(child, ctx)
                inputs.append(b)
                if not a == b:
                    return inputs, False
                a = b
            return inputs, True

    # This is particularly complicated, because we need to try every combination
    # to ensure that each element is distinct. To short-circuit but avoid recomputation,
    # we keep a cache of results we've already computed. Note that we can't just
    # index with the child expressions themselves, or we might notice that shared
    # subtrees are actually the same object and forget to re-evaluate some of them.

    def _eval_neq(self, e, ctx):
        if len(e.children) == 2:
            in0 = self.evaluate(e.children[0], ctx)
            in1 = self.evaluate(e.children[1], ctx)
            return [in0, in1], in0 != in1
        elif len(e.children) < 2:
            return [], True
        else:
            nchildren = len(e.children)
            inputs = []
            cached = [False] * nchildren
            cache = [None] * nchildren
            for i1, i2 in itertools.combinations(range(nchildren), 2):
                if cached[i1]:
                    a = cache[i1]
                else:
                    a = self.evaluate(e.children[i1], ctx)
                    inputs.append(a)
                    cache[i1] = a
                    cached[i1] = True
                if cached[i2]:
                    b = cache[i2]
                else:
                    b = self.evaluate(e.children[i2], ctx)
                    inputs.append(b)
                    cache[i2] = b
                    cached[i2] = True
                if not a != b:
                    return inputs, False
            return inputs, True

    def _eval_and(self, e, ctx):
        return None, all(self.evaluate(child, ctx) for child in e.children)

    def _eval_or(self, e, ctx):
        return None, any(self.evaluate(child, ctx) for child in e.children)

    def _eval_not(self, e, ctx):
        return None, not self.evaluate(e.children[0], ctx)

class StandardInterpreter(SimpleInterpreter):
    """Standard FPCore interpreter.
    Override Interpreter.dtype with a class derived from Digital
    all standard FPCore operations as methods: x.add(y), a.fma(y, z), etc.
    i.e. MPNum.
    """

    def _eval_add(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0.add(in1, ctx=ctx)

    def _eval_sub(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0.sub(in1, ctx=ctx)

    def _eval_mul(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0.mul(in1, ctx=ctx)

    def _eval_div(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0.div(in1, ctx=ctx)

    def _eval_sqrt(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.sqrt(ctx=ctx)

    def _eval_fma(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        in2 = self.evaluate(e.children[2], ctx)
        return [in0, in1, in2], in0.fma(in1, in2, ctx=ctx)

    def _eval_neg(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.neg(ctx=ctx)

    def _eval_copysign(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0.copysign(in1, ctx=ctx)

    def _eval_fabs(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.fabs(ctx=ctx)

    def _eval_fdim(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0.fdim(in1, ctx=ctx)

    def _eval_fmax(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0.fmax(in1, ctx=ctx)

    def _eval_fmin(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0.fmin(in1, ctx=ctx)

    def _eval_fmod(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0.fmod(in1, ctx=ctx)

    def _eval_remainder(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0.remainder(in1, ctx=ctx)

    def _eval_ceil(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.ceil(ctx=ctx)

    def _eval_floor(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.floor(ctx=ctx)

    def _eval_nearbyint(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.nearbyint(ctx=ctx)

    def _eval_round(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.round(ctx=ctx)

    def _eval_trunc(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.trunc(ctx=ctx)

    def _eval_acos(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.acos(ctx=ctx)

    def _eval_acosh(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.acosh(ctx=ctx)

    def _eval_asin(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.asin(ctx=ctx)

    def _eval_asinh(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.asinh(ctx=ctx)

    def _eval_atan(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.atan(ctx=ctx)

    def _eval_atan2(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0.atan2(in1, ctx=ctx)

    def _eval_atanh(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.atanh(ctx=ctx)

    def _eval_cos(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.cos(ctx=ctx)

    def _eval_cosh(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.cosh(ctx=ctx)

    def _eval_sin(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.sin(ctx=ctx)

    def _eval_sinh(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.sinh(ctx=ctx)

    def _eval_tan(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.tan(ctx=ctx)

    def _eval_tanh(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.tanh(ctx=ctx)

    def _eval_exp(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.exp(ctx=ctx)

    def _eval_exp2(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.exp2(ctx=ctx)

    def _eval_expm1(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.expm1(ctx=ctx)

    def _eval_log(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.log(ctx=ctx)

    def _eval_log10(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.log10(ctx=ctx)

    def _eval_log1p(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.log1p(ctx=ctx)

    def _eval_log2(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.log2(ctx=ctx)

    def _eval_cbrt(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.cbrt(ctx=ctx)

    def _eval_hypot(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0.hypot(in1, ctx=ctx)

    def _eval_pow(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        in1 = self.evaluate(e.children[1], ctx)
        return [in0, in1], in0.pow(in1, ctx=ctx)

    def _eval_erf(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.erf(ctx=ctx)

    def _eval_erfc(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.erfc(ctx=ctx)

    def _eval_lgamma(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.lgamma(ctx=ctx)

    def _eval_tgamma(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.tgamma(ctx=ctx)

    def _eval_isfinite(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.isfinite()

    def _eval_isinf(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.isinf

    def _eval_isnan(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.isnan

    def _eval_isnormal(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.isnormal()

    def _eval_signbit(self, e, ctx):
        in0 = self.evaluate(e.children[0], ctx)
        return [in0], in0.signbit()


text:
package auth

import (
	"io/ioutil"
	"net/http"
)

func GetIdpMetadata(endpoint string) ([]byte, error) {
	resp, err := http.Get(endpoint)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}