text:
from datetime import datetime
from sqlalchemy.ext.declarative import declared_attr

from flask_login import UserMixin as _UserMixin
from flask_login import login_user, logout_user
from werkzeug.security import check_password_hash, generate_password_hash

from flask_maple.models import ModelMixin, db
from flask_maple.mail import MailMixin

user_group = db.Table(
    'user_group', db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('group_id', db.Integer, db.ForeignKey('group.id')))

class GroupMixin(ModelMixin):
    @declared_attr
    def id(cls):
        return db.Column(db.Integer, primary_key=True)

    @declared_attr
    def name(cls):
        return db.Column(db.String(512), nullable=False, unique=True)

    @declared_attr
    def parent_id(cls):
        return db.Column(db.Integer, db.ForeignKey('group.id'))

    @declared_attr
    def parent_group(cls):
        return db.relationship(
            'Group',
            remote_side=[cls.id],
            backref=db.backref(
                'child_groups', remote_side=[cls.parent_id], lazy='dynamic'),
            lazy='joined',
            uselist=False)

    def get_child_groups(self, depth=1):
        child_groups = self.child_groups.all()
        depth -= 1
        if depth > 0:
            child_groups.extend([
                g for group in child_groups
                for g in group.get_child_groups(depth)
            ])
        return list(set(child_groups))

    def __str__(self):
        return self.name

    def __repr__(self):
        return '<Group %r>' % self.name

class UserMixin(_UserMixin, MailMixin, ModelMixin):
    @declared_attr
    def id(cls):
        return db.Column(db.Integer, primary_key=True)

    @declared_attr
    def username(cls):
        return db.Column(db.String(512), nullable=False, unique=True)

    @declared_attr
    def email(cls):
        return db.Column(db.String(512), nullable=False, unique=True)

    @declared_attr
    def password(cls):
        return db.Column(db.String(512), nullable=False)

    @declared_attr
    def is_superuser(cls):
        return db.Column(db.Boolean, default=False)

    @declared_attr
    def is_confirmed(cls):
        return db.Column(db.Boolean, default=False)

    @declared_attr
    def register_time(cls):
        return db.Column(db.DateTime, default=datetime.now)

    @declared_attr
    def last_login(cls):
        return db.Column(db.DateTime, default=datetime.now)

    @declared_attr
    def groups(cls):
        return db.relationship(
            'Group',
            secondary=user_group,
            backref=db.backref('users', lazy='dynamic'),
            lazy='dynamic')

    def set_password(self, raw_password):
        self.password = generate_password_hash(raw_password)
        return self.password

    def check_password(self, raw_password):
        return check_password_hash(self.password, raw_password)

    @property
    def is_logined(self):
        return self.is_authenticated

    def login(self, remember=True):
        login_user(self, remember)

    def logout(self):
        logout_user()

    def __str__(self):
        return self.username

    def __repr__(self):
        return '<User %r>' % self.username


text:
<?php
/**
* @package janitor.member
*/

class SuperMemberCore extends Member {

	/**
	*
	*/
	function __construct() {

		parent::__construct(get_class());

	}

	/**
	 * Get members (by user_id, member_id, item_id or all)
	 *
	 * Passing no parameters in $_options will return all members, including cancelled members
	 * Passing 'only_active_members' will exclude cancelled members (when getting multiple members)
	 *
	 * @param array|false $_options
	 * * user_id – get member object for user_id
	 * * member_id – get specific member object
	 * * item_id – get all members with specific membership
	 *
	 * @return array|false One or several membership objects. False on error.
	 */
	function getMembers($_options = false) {
		$IC = new Items();

		$member_id = false;
		$user_id = false;
		$item_id = false;
		$only_active_members = false;

		if($_options !== false) {
			foreach($_options as $_option => $_value) {
				switch($_option) {
					case "user_id"                   : $user_id                     = $_value; break;
					case "member_id"                 : $member_id                   = $_value; break;
					case "item_id"                   : $item_id                     = $_value; break;
					case "only_active_members"       : $only_active_members         = $_value; break;
				}
			}
		}

		$query = new Query();
		include_once("classes/shop/supershop.class.php");
		include_once("classes/users/superuser.class.php");
		$SC = new SuperShop();
		$UC = new SuperUser();

		// get membership by member_id
		if($member_id !== false) {

			// membership with subscription
			$sql = "SELECT members.id as id, subscriptions.id as subscription_id, subscriptions.item_id as item_id, subscriptions.order_id as order_id, members.user_id as user_id, members.created_at as created_at, members.modified_at as modified_at, subscriptions.renewed_at as renewed_at, subscriptions.expires_at as expires_at FROM ".$this->db_subscriptions." as subscriptions, ".$this->db_members." as members WHERE members.id = $member_id AND members.subscription_id = subscriptions.id LIMIT 1";
			if($query->sql($sql)) {

				$member = $query->result(0);
				$member["user"] = $UC->getUsers(["user_id" => $member["user_id"]]);
				$member["item"] = $IC->getItem(["id" => $member["item_id"], "extend" => ["subscription_method" => true, "prices" => true]]);

				if($member["order_id"]) {
					// payment status
					$member["order"] = $SC->getOrders(["order_id" => $member["order_id"]]);
				}
				else {
					$member["order"] = false;
				}

				return $member;
			}
			// membership without subscription
			else {
				$sql = "SELECT * FROM ".$this->db_members." WHERE id = $member_id LIMIT 1";
				if($query->sql($sql)) {
					$member = $query->result(0);
					$member["user"] = $UC->getUsers(["user_id" => $member["user_id"]]);
					$member["item"] = false;
					$member["order"] = false;
					$member["order_id"] = false;
					$member["item_id"] = false;
					$member["expires_at"] = false;
					$member["renewed_at"] = false;

					return $member;
				}
			}

		}

		// get membership by user_id
		else if($user_id !== false) {

			// membership with subscription
			$sql = "SELECT members.id as id, subscriptions.id as subscription_id, subscriptions.item_id as item_id, subscriptions.order_id as order_id, members.user_id as user_id, members.created_at as created_at, members.modified_at as modified_at, subscriptions.renewed_at as renewed_at, subscriptions.expires_at as expires_at FROM ".$this->db_subscriptions." as subscriptions, ".$this->db_members." as members WHERE members.user_id = $user_id AND members.subscription_id = subscriptions.id LIMIT 1";
			if($query->sql($sql)) {

				$member = $query->result(0);
				$member["item"] = $IC->getItem(["id" => $member["item_id"], "extend" => ["subscription_method" => true, "prices" => true]]);

				// payment status
				$member["order"] = $SC->getOrders(["order_id" => $member["order_id"]]);
				return $member;
			}
			// membership without subscription
			else {
				$sql = "SELECT * FROM ".$this->db_members." WHERE user_id = $user_id LIMIT 1";
				if($query->sql($sql)) {
					$member = $query->result(0);
					$member["item"] = false;
					$member["order"] = false;
					$member["order_id"] = false;
					$member["item_id"] = false;
					$member["expires_at"] = false;
					$member["renewed_at"] = false;

					return $member;
				}
			}

		}

		// get all members with specific membership
		else if($item_id !== false) {

			$sql = "SELECT members.id as id, subscriptions.id as subscription_id, subscriptions.item_id as item_id, subscriptions.order_id as order_id, members.user_id as user_id, members.created_at as created_at, members.modified_at as modified_at, subscriptions.renewed_at as renewed_at, subscriptions.expires_at as expires_at FROM ".$this->db_subscriptions." as subscriptions, ".$this->db_members." as members WHERE subscriptions.item_id = $item_id AND subscriptions.id = members.subscription_id";
			// get members with subscription
			if($query->sql($sql)) {
				$members = $query->results();

				foreach($members as $i => $member) {
					$members[$i]["user"] = $UC->getUsers(["user_id" => $member["user_id"]]);
					$members[$i]["item"] = $IC->getItem(["id" => $member["item_id"], "extend" => ["subscription_method" => true, "prices" => true]]);

					// payment status
					$members[$i]["order"] = $SC->getOrders(["order_id" => $member["order_id"]]);
				}

				return $members;
			}

		}

		// get list of all members
		else {

			$members = false;
			$cancelled_members = false;

			$sql = "SELECT members.id as id, subscriptions.id as subscription_id, subscriptions.item_id as item_id, subscriptions.order_id as order_id, members.user_id as user_id, members.created_at as created_at, members.modified_at as modified_at, subscriptions.renewed_at as renewed_at, subscriptions.expires_at as expires_at FROM ".$this->db_subscriptions." as subscriptions, ".$this->db_members." as members WHERE subscriptions.id = members.subscription_id";
			if($query->sql($sql)) {
				$members = $query->results();

				foreach($members as $i => $member) {
					$members[$i]["user"] = $UC->getUsers(["user_id" => $member["user_id"]]);
					$members[$i]["item"] = $IC->getItem(["id" => $member["item_id"], "extend" => ["subscription_method" => true, "prices" => true]]);

					// payment status
					$members[$i]["order"] = $SC->getOrders(["order_id" => $member["order_id"]]);
				}

			}

			if(!$only_active_members) {

				// also include "cancelled" members
				$sql = "SELECT members.id as id, members.user_id as user_id, members.subscription_id as subscription_id, members.created_at as created_at, members.modified_at as modified_at FROM ".$this->db_members." as members WHERE members.subscription_id IS NULL";
				if($query->sql($sql)) {
					$cancelled_members = $query->results();

					foreach($cancelled_members as $i => $cancelled_member) {
						$cancelled_members[$i]["user"] = $UC->getUsers(["user_id" => $cancelled_member["user_id"]]);
						$cancelled_members[$i]["item"] = false;
						$cancelled_members[$i]["order"] = false;
						$cancelled_members[$i]["order_id"] = false;
						$cancelled_members[$i]["renewed_at"] = false;
						$cancelled_members[$i]["expires_at"] = false;
					}

				}

				if($members && $cancelled_members) {
					// append cancelled members to members array
					$members = array_merge($members, $cancelled_members);
				}
				else if($cancelled_members) {
					$members = $cancelled_members;
				}
			}

			return $members;

		}

		return false;
	}

	// SEARCH

	function search($_options = false) {
		// debug(["search", $_options]);

		$pattern = false;

		$query_string = "";

		if($_options !== false) {
			foreach($_options as $_option => $_value) {
				switch($_option) {

					case "pattern"           : $pattern            = $_value; break;

					case "query"             : $query_string       = $_value; break;

				}
			}
		}

		$query = new Query();

		include_once("classes/users/superuser.class.php");
		$UC = new SuperUser();
		include_once("classes/shop/supershop.class.php");
		$SC = new SuperShop();

		$IC = new Items();
		$membership_model = $IC->typeObject("membership");

		global $page;

		// Prepare query parts
		$SELECT = array();
		$FROM = array();
		$LEFTJOIN = array();
		$WHERE = array();
		$GROUP_BY = "";
		$HAVING = "";
		$ORDER = array();
		$LIMIT = false;

		// Add base select properties
		$SELECT[] = "m.id";
		$SELECT[] = "m.user_id";
		$SELECT[] = "m.subscription_id";

		$SELECT[] = "s.expires_at";
		$SELECT[] = "s.custom_price";

		$SELECT[] = "p.price";
		$SELECT[] = "p.currency";

		$SELECT[] = "mi.name as membership";

		$SELECT[] = "o.payment_status";

		$SELECT[] = "GROUP_CONCAT(DISTINCT un.username SEPARATOR ', ') AS usernames";

		$SELECT[] = "u.nickname";

		$FROM[] = $this->db_members." AS m";

		if(isset($pattern["item_id"])) {
			$WHERE[] = "s.item_id = ".$pattern["item_id"];
		}

		$LEFTJOIN[] = $UC->db." AS u ON m.user_id = u.id";
		$LEFTJOIN[] = $UC->db_usernames." AS un ON m.user_id = un.user_id";
		$LEFTJOIN[] = $this->db_subscriptions." AS s ON m.subscription_id = s.id";
		$LEFTJOIN[] = $SC->db_orders." AS o ON s.order_id = o.id";
		$LEFTJOIN[] = $membership_model->db." AS mi ON s.item_id = mi.item_id";
		$LEFTJOIN[] = UT_ITEMS_PRICES." AS p ON s.item_id = p.item_id AND p.currency = '".$page->currency()."'";

		if($query_string) {
			$WHERE[] = "(o.order_no LIKE '%".$query_string."%' OR u.nickname LIKE '%".$query_string."%' OR u.firstname LIKE '%".$query_string."%' OR u.lastname LIKE '%".$query_string."%' OR un.username LIKE '%".$query_string."%' OR mi.name LIKE '%".$query_string."%')";
		}

		// Use order by from pattern or default order
		$ORDER[] = isset($pattern["order"]) ? $pattern["order"] : "o.id DESC";

		// Use limit from pattern
		if(isset($pattern["limit"]) && $pattern["limit"]) {
			$LIMIT = $pattern["limit"];
		}

		$GROUP_BY = "m.id";

		$sql = $query->compileQuery($SELECT, $FROM, array("LEFTJOIN" => $LEFTJOIN, "WHERE" => $WHERE, "HAVING" => $HAVING, "GROUP_BY" => $GROUP_BY, "ORDER" => $ORDER, "LIMIT" => $LIMIT));

		// debug(["sql", $sql]);
		$query->sql($sql);
		$results = $query->results();

		// print_r($results);
		return $results;

	}

	// PAGINATION STUFF

	/**
	* Get next member(s)
	*
	* Can receive members array to use for finding next member(s)
	* or receive query syntax to perform getItems request on it own
	*
	* @param $member_id member_id to get next from
	*/
	function getNext($member_id, $_options = false) {

		$members = false;
		$limit = 1;

		if($_options !== false) {
			foreach($_options as $_option => $_value) {
				switch($_option) {

					case "members"   : $members    = $_value; break;
					case "limit"   : $limit    = $_value; break;

				}
			}
		}

		// debug(["getNext", $member_id, $_options]);

		// filtering variables
		$next_members = array();
		$member_found = false;
		$counted = 0;

		// loop through all members, looking for starting point
		for($i = 0; $i < count($members); $i++) {

			// wait until we find starting point
			if($member_found) {

				// keep an eye on counter
				$counted++;

				// add to next scope
				$next_members[] = $members[$i];

				// end when enough members have been collected
				if($counted == $limit) {
					break;
				}
			}

			// found starting point
			else if($member_id === $members[$i]["id"]) {
				$member_found = true;
			}
		}

		// return set of next members
		return $next_members;
	}

	/**
	* Get previous member(s)
	*
	* Can receive members array to use for finding previous member(s)
	* or receive query syntax to perform getItems request on it own
	* TODO: This implementation is far from performance optimized, but works - consider alternate implementations
	*/
	function getPrev($member_id, $_options = false) {

		$members = false;
		$limit = 1;

		// Other getItems patters properties may also be passed

		if($_options !== false) {
			foreach($_options as $_option => $_value) {
				switch($_option) {
					case "members"  : $members    = $_value; break;
					case "limit"   : $limit    = $_value; break;
				}
			}
		}

		// filtering variables
		$prev_members = array();
		$member_found = false;
		$counted = 0;
		// loop backwards through all members, looking for starting point
		for($i = count($members)-1; $i >= 0; $i--) {

			// wait until we find starting point
			if($member_found) {

				// keep an eye on counter
				$counted++;

				// add to beginning of prev scope
				array_unshift($prev_members, $members[$i]);

				// end when enough members have been collected
				if($counted == $limit) {
					break;
				}
			}

			// found starting point
			else if($member_id === $members[$i]["id"]) {
				$member_found = true;
			}
		}

		// return set of prev members
		return $prev_members;
	}

	/**
	 * Paginate a list of members
	 *
	 * Splits a list of members into smaller fragments and returns information required to create meaningful pagination
	 *
	 * @param array $_options
	 * * pattern – array of options to be sent to SuperShop::search, which returns the members to be paginated
	 * * limit – maximal number of members per page. Default: 5.
	 *
	 *
	 * @return array
	 * * range_members (list of members in specified range)
	 * * next members
	 * * previous members
	 * * first id in range
	 * * last id in range
	 */
	function paginate($_options) {

		// Items selected for this pagination range
		$range_members = false;

		// Start range_members from page – Default false
		$page = false;

		// Search and extend pattern for range_members / pagination
		$pattern = false;

		// Search query
		$query_string = false;

		// Limit for range_members - Default 5
		$limit = 20;

		if($_options !== false) {
			foreach($_options as $_option => $_value) {
				switch($_option) {
					case "pattern"              : $pattern         = $_value; break;

					case "limit"                : $limit           = $_value; break;
					case "page"                 : $page            = $_value; break;

					case "query"                : $query_string    = $_value; break;
				}
			}
		}

		// get all members sorted as base for pagination
		$members = $this->search(["query" => $query_string, "pattern" => $pattern]);

		// if there is no user_id or page to start from beginning
		// Select first N posts
		if(!$page) {

			// simply add limit to members query
			$pattern["limit"] = $limit;
			$range_members = $this->search(["query" => $query_string, "pattern" => $pattern]);

		}
		// Starting point exists
		else {

			$start_index = ($page-1) * $limit;
			if(count($members) >= $start_index) {

				// Find user_id of first element of page
				$index_user = $members[$start_index];

				// Include index user (specified by passed sindex or user_id)
				// Reduce limit to make room
				// (for page based pagination it doesn't make sense to exclude user)
				$range_members = $this->getNext($index_user["id"], ["members" => $members, "limit" => $limit-1]);
				array_unshift($range_members, $index_user);

			}

		}

		// Page information
		$total_count = count($members);

		// Include page count and current page number
		$page_count = intval(ceil($total_count / $limit));
		$current_page = false;

		$first_id = false;
		// $first_sindex = false;
		$last_id = false;
		// $last_sindex = false;
		$prev = false;
		$next = false;

		if($range_members) {

			if(isset($range_members[0])) {

				$first_id = $range_members[0]["id"];
				// $first_sindex = $range_members[0]["sindex"];

				$prev = $this->getPrev($first_id, ["members" => $members, "limit" => 1]);
				if($prev) {
					$prev = $prev[0];
				}

				// If there is a first id, then there must be a last id (which might be the same, though)
				$last_id = $range_members[count($range_members)-1]["id"];
				// $last_sindex = $range_members[count($range_members)-1]["sindex"];

				$next = $this->getNext($last_id, ["members" => $members, "limit" => 1]);
				if($next) {
					$next = $next[0];
				}

				// Locate first_id in page stack
				$current_position = arrayKeyValue($members, "id", $first_id);
				$current_page = intval(floor($current_position / $limit)+1);

			}

		}

		// return all pagination info
		// range_members = list of members in specified range
		// next user
		// previous user
		// first id in range
		// last id in range
		return array("range_members" => $range_members, "next" => $next, "prev" => $prev, "first_id" => $first_id, "last_id" => $last_id, "total" => $total_count, "page_count" => $page_count, "current_page" => $current_page);
	}

	/**
	 * Get member count
	 *
	 * A shorthand function to get member count for UI
	 * Can return the total member count, or member count for a specific membership type.
	 *
	 * @param array|false $_options
	 * – item_id
	 *
	 * @return string Member count
	 */
	function getMemberCount($_options = false) {

		// get all count of members of item_id
		$item_id = false;

		if($_options !== false) {
			foreach($_options as $_option => $_value) {
				switch($_option) {
					case "item_id"             : $item_id              = $_value; break;
				}
			}
		}

		$query = new Query();

		if($item_id !== false) {

			$sql = "SELECT count(*) as member_count, members.id as id, subscriptions.id as subscription_id, subscriptions.item_id as item_id, subscriptions.order_id as order_id, members.user_id as user_id, members.created_at as created_at, members.modified_at as modified_at, subscriptions.renewed_at as renewed_at, subscriptions.expires_at as expires_at FROM ".$this->db_subscriptions." as subscriptions, ".$this->db_members." as members WHERE subscriptions.item_id = $item_id AND subscriptions.id = members.subscription_id";
			if($query->sql($sql)) {
				return $query->result(0, "member_count");
			}

		}
		else {

			$sql = "SELECT count(*) as member_count FROM ".$this->db_members;
			if($query->sql($sql)) {
				return $query->result(0, "member_count");
			}

		}

		return 0;
	}

	/**
	 * Add membership
	 *
	 * @param integer $item_id
	 * @param integer $subscription_id
	 * @param array|false $_options
	 * – user_id (required)
	 *
	 * @return array|false Membership object. False on error.
	 */
	function addMembership($item_id, $subscription_id, $_options = false) {

		include_once("classes/shop/supersubscription.class.php");
		$SuperSubscriptionClass = new SuperSubscription();
		$query = new Query();

		$subscription = $SuperSubscriptionClass->getSubscriptions(["subscription_id" => $subscription_id]);
		$user_id = false;

		if($_options !== false) {
			foreach($_options as $_option => $_value) {
				switch($_option) {
					case "user_id"					:	$user_id					= $_value; break;
				}
			}
		}

		// user_id was passed and subscription is valid
		if($user_id && $subscription && $subscription["user_id"] == $user_id) {

			// safety valve
			// does user already have membership
			$membership = $this->getMembers(["user_id" => $user_id]);
			if($membership) {
				return $this->updateMembership(["updateMembership"]);
			}

			// create new membership
			$sql = "INSERT INTO ".$this->db_members." SET user_id = $user_id, subscription_id = $subscription_id";

			// creating sucess
			if($query->sql($sql)) {

				$membership = $this->getMembers(["user_id" => $user_id]);

				logger()->addLog("SuperMember->addMembership: member_id:".$membership["id"].", user_id:$user_id");

				return $membership;
			}
		}

		return false;
	}

	/**
	 * Add new membership to specified user
	 *
	 * /#controller#/addNewMembership/#user_id#
	 * info in $_POST
	 *
	 *
	 * @param array $action
	 *
	 * @return array|false Order object. False on error.
	 */
	function addNewMembership($action) {

		// get posted values to make them available for models
		$this->getPostedEntities();

		// values are valid
		if(count($action) == 2 && $this->validateList(["item_id"])) {

			include_once("classes/shop/supershop.class.php");
			include_once("classes/users/superuser.class.php");
			$query = new Query();
			$IC = new Items();
			$UC = new SuperUser();
			$SC = new SuperShop();

			$user_id = $action[1];
			$item_id = $this->getProperty("item_id", "value");

			$cart = $SC->addToNewInternalCart($item_id, ["user_id" => $user_id]);

			if($cart) {

				$cart_reference = $cart["cart_reference"];
				$cart_id = $cart["id"];

				$current_user = $UC->getUser();
				$_POST["order_comment"] = "New membership added by ".$current_user["nickname"];
				$order = $SC->newOrderFromCart(["newOrderFromCart", $cart_id, $cart_reference]);
				unset($_POST);

				if($order) {

					logger()->addLog("Member->addNewMembership: item_id:".$item_id.", user_id:$user_id");

					return $order;
				}
			}

		}

		return false;
	}

	/**
	 * Update membership for specified user
	 *
	 * @param array|false $_options
	 * – user_id (required)
	 * – subscription_id (to be used if reactivaing an inactive membership)
	 *
	 * @return array|false Membership object. False on non-existing membership. False on error.
	 */
	function updateMembership($_options = false) {

		include_once("classes/shop/supersubscription.class.php");
		$SuperSubscriptionClass = new SuperSubscription();
		$query = new Query();

		$user_id = false;
		$subscription_id = false;

		if($_options !== false) {
			foreach($_options as $_option => $_value) {
				switch($_option) {
					case "user_id"				:		$user_id 			= $_value; break;
					case "subscription_id"		:		$subscription_id 	= $_value; break;
				}
			}
		}

		$membership = $this->getMembers(["user_id" => $user_id]);
		if($membership) {

			$sql = "UPDATE ".$this->db_members." SET modified_at = CURRENT_TIMESTAMP";

			// Add subscription id if passed
			if($subscription_id) {

				// make sure subscription is valid
				$subscription = $SuperSubscriptionClass->getSubscriptions(["subscription_id" => $subscription_id, "user_id" => $user_id]);
				if($subscription && $subscription["user_id"] == $user_id) {

					$sql .= ", subscription_id = $subscription_id";

				}

			}

			// Add condition
			$sql .= " WHERE user_id = $user_id";

			// creation sucess
			if($query->sql($sql)) {

				logger()->addLog("SuperMember->updateMembership: member_id:".$membership["id"].", user_id:$user_id, subscription_id:".($subscription_id ? $subscription_id : "N/A"));

				$membership = $this->getMembers(["user_id" => $user_id]);
				return $membership;
			}
		}

		message()->addMessage("Membership could not be changed", ["type" => "error"]);
		return false;

	}

	/**
	 * Cancel membership for specified user
	 *
	 * Removes subscription_id from membership and deletes related subscription
	 *
	 * /#controller#/cancelMembership/#user_id#/#member_id#
	 *
	 * @param array $array
	 *
	 * @return boolean
	 */
	function cancelMembership($action) {

		// does values validate
		if(count($action) == 3) {
			$user_id = $action[1];
			$member_id = $action[2];

			include_once("classes/shop/supersubscription.class.php");
			$SuperSubscriptionClass = new SuperSubscription();
			include_once("classes/users/superuser.class.php");
			$UC = new SuperUser();
			$query = new Query();

			$user = $UC->getUsers(["user_id" => $user_id]);
			$member = $this->getMembers(["user_id" => $user_id]);
			if($user && $member && $member["user_id"] == $user_id) {

				// set subscription_id to NULL - maintains member in system
				$sql = "UPDATE ".$this->db_members. " SET subscription_id = NULL, modified_at = CURRENT_TIMESTAMP WHERE id = ".$member_id;
				if($query->sql($sql)) {

					// delete subscription
					$SuperSubscriptionClass->deleteSubscription(["deleteSubscription", $user_id, $member["subscription_id"]]);

					logger()->addLog("SuperMember->cancelMembership: member_id:".$member["id"]);

					message()->addMessage("Membership cancelled");
					return true;

				}
			}
		}

		message()->addMessage("Membership could not be cancelled", ["type" => "error"]);
		return false;
	}

	/**
	 * Switch membership for specified user
	 *
	 * /#controller#/switchMembership/#user_id#
	 * item_id in $_POST
	 *
	 * @param array $action
	 *
	 * @return array|false Order object. False on error.
	 */
	function switchMembership($action) {

		// get posted values to make them available for models
		$this->getPostedEntities();

		// values are valid
		if(count($action) == 2 && $this->validateList(array("item_id"))) {

			$query = new Query();
			$IC = new Items();
			include_once("classes/shop/supershop.class.php");
			$SC = new SuperShop();
			include_once("classes/users/superuser.class.php");
			$UC = new SuperUser();

			$user_id = $action[1];
			$item_id = $this->getProperty("item_id", "value");

			// user exists and has membership
			$user = $UC->getUsers(["user_id" => $user_id]);
			$member = $this->getMembers(["user_id" => $user_id]);
			if($user && $member && $member["user_id"] == $user_id) {

				// add item to cart
				$cart = $SC->addToNewInternalCart($item_id, ["user_id" => $user_id]);

				// convert to order
				// this will call Member::updateMembership via TypeMembership::ordered
				// this will call SuperSubscription::updateSubscription or SuperSubscription::addSubscription via TypeMembership::ordered

				$_POST["switch_membership"] = true;
				$order = $SC->newOrderFromCart(array("newOrderFromCart", $cart["id"], $cart["cart_reference"]));

				if($order) {

					logger()->addLog("SuperMember->switchMembership: member_id:".$member["id"].", user_id:$user_id)");

					return $order;
				}
			}
		}

		return false;
	}

	/**
	 * Upgrade membership for specified user
	 *
	 * Adds new order with custom price (new_price - current_price)
	 * Gets existing membership order and copies info to new membership order, then adds manual order line
	 *
	 * /#controller#/upgradeMembership/#user_id#
	 * item_id in $_POST
	 *
	 * @param array $action
	 *
	 * @return boolean True on successful upgrade. False on error.
	 *
	 * @todo The creation of a new custom order based on an existing order should be done by SuperShop class
	 */
	function upgradeMembership($action) {

		// get posted values to make them available for models
		$this->getPostedEntities();

		// values are valid
		if(count($action) == 2 && $this->validateList(array("item_id"))) {

			include_once("classes/shop/supershop.class.php");
			include_once("classes/shop/supersubscription.class.php");
			include_once("classes/users/superuser.class.php");
			$SC = new SuperShop();
			$UC = new SuperUser();
			$SuperSubscriptionClass = new SuperSubscription();
			$query = new Query();
			$IC = new Items();

			$user_id = $action[1];
			$item_id = $this->getProperty("item_id", "value");

			// user exists and has active membership
			$user = $UC->getUsers(["user_id" => $user_id]);
			$member = $this->getMembers(["user_id" => $user_id]);
			if($user && $member && $member["subscription_id"]) {

				// get existing membership price
				$current_price = $SC->getPrice($member["item_id"], ["user_id" => $user_id]);

				// get new item and price
				$item = $IC->getItem(["id" => $item_id, "extend" => ["subscription_method" => true]]);
				$new_price = $SC->getPrice($item_id, ["user_id" => $user_id]);

				$model = $IC->typeObject($item["itemtype"]);

				// only perform membership upgrade if it is an actual upgrade
				if($new_price["price"] > $current_price["price"]) {

					// find price difference
					$order_price["price"] = $new_price["price"] - $current_price["price"];
					$order_price["vat"] = $new_price["price"] * (1 - (1 / (1 + ($new_price["vatrate"]/100))));

					// Start creating custom difference order

					// get existing order to copy data for new order
					$sql = "SELECT * FROM ".$SC->db_orders." WHERE id = ".$member["order_id"]." LIMIT 1";
					if($query->sql($sql)) {
						$order = $query->result(0);

						// get new order number
						$order_no = $SC->getNewOrderNumber();
						if($order_no) {

							// create base data update sql
							$sql = "UPDATE ".$SC->db_orders." SET comment = 'Membership upgrade'";

							foreach($order as $key => $value) {
								//	print $key . " = " . $value . "<br>\n";
								// filter out order specific values
								if(!preg_match("/(^order_no$|^id$|status$|^comment$|ed_at$)/", $key) && $value) {
									$sql .= ", $key = '$value'";
								}

							}

							$sql .= " WHERE order_no = '$order_no'";

							if($query->sql($sql)) {

								// get the new order
								$order = $SC->getOrders(array("order_no" => $order_no));

								// add custom order line
								$sql = "INSERT INTO ".$SC->db_order_items." SET order_id=".$order["id"].", item_id=$item_id, name='".$item["name"]." (Upgrade)', quantity=1, unit_price=".$order_price["price"].", unit_vat=".$order_price["vat"].", total_price=".$order_price["price"].", total_vat=".$order_price["vat"];
								if($query->sql($sql)) {

									// get current subscription
									$subscription = $SuperSubscriptionClass->getSubscriptions(array("subscription_id" => $member["subscription_id"]));

									// update subscription data (item id, order_id, expires_at)
									$sql = "UPDATE ".$SuperSubscriptionClass->db_subscriptions. " SET item_id = $item_id, order_id = ".$order["id"].", custom_price = NULL";

									$expires_at = false;
									if($item["subscription_method"]) {
										// current subscription has no expiry
										if(!$subscription["expires_at"]) {

											// calculate expiry date based on current date
											$start_time = date("Y-m-d H:i", time());
											$expires_at = $SuperSubscriptionClass->calculateSubscriptionExpiry($item["subscription_method"]["duration"], $start_time);
										}
										else {

											// keep expiry date
											$expires_at = $subscription["expires_at"];
										}
									}

									if($expires_at) {
										$sql .= ", expires_at = '$expires_at'";
									}
									else {
										$sql .= ", expires_at = NULL";
									}

									// Reset custom price
									$sql .= ", custom_price = NULL";

									// Add condition
									$sql .= " WHERE id = ".$member["subscription_id"];

									if($query->sql($sql)) {

										// add callback to 'upgraded'
										if(method_exists($this, "upgraded")) {

											$this->upgraded($member, $item);
										}

										logger()->addLog("SuperMember->upgradeMembership: member_id:".$member["id"].",item_id:$item_id, subscription_id:".$member["subscription_id"]);

										return true;
									}
								}
							}
						}
					}
				}

			}
		}

		return false;
	}

}

?>

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import steemAPI from '../steemAPI';
import Loading from '../components/Icon/Loading';
import Tag from './Tag';
import { getFavoriteCategories } from '../reducers';
import * as favoriteActions from '../favorites/favoritesActions';

const sortTags = tags =>
  Object.keys(tags)
    .sort((key1, key2) => tags[key1].comments - tags[key2].comments)
    .reverse()
    .map(tagKey => tags[tagKey]);

@connect(
  state => ({
    favorites: getFavoriteCategories(state),
  }),
  dispatch =>
    bindActionCreators(
      {
        addCategoryFavorite: favoriteActions.addCategoryFavorite,
        removeCategoryFavorite: favoriteActions.removeCategoryFavorite,
      },
      dispatch,
    ),
)
export default class Tags extends React.Component {
  static propTypes = {
    favorites: PropTypes.arrayOf(PropTypes.string),
    addCategoryFavorite: PropTypes.func,
    removeCategoryFavorite: PropTypes.func,
  };

  static defaultProps = {
    favorites: [],
    addCategoryFavorite: () => {},
    removeCategoryFavorite: () => {},
  };

  state = {
    tags: {},
  };

  componentDidMount() {
    steemAPI.getState('tags', (err, result) => {
      this.setState({ tags: result.tags });
    });
  }

  render() {
    const { tags } = this.state;
    const sortedTags = sortTags(tags);
    const isFetching = !sortedTags.length;

    return (

          {sortedTags.map(
            tag =>
              tag.name ? (
                <Tag
                  key={tag.name}
                  tag={tag}
                  favorited={this.props.favorites.includes(tag.name)}
                  addCategoryFavorite={this.props.addCategoryFavorite}
                  removeCategoryFavorite={this.props.removeCategoryFavorite}
                />
              ) : (
                []
              ),
          )}

        {isFetching && (

            <Loading />

        )}

    );
  }
}


text:
require "formula"

class Rmate < Formula
  desc "Edit files from an SSH session in TextMate"
  homepage "https://github.com/textmate/rmate"
  url "https://github.com/textmate/rmate/archive/v1.5.7.tar.gz"
  sha1 "2f139c88c128b89626da56a00441602e7121be62"
  head "https://github.com/textmate/rmate.git"

  def install
    bin.install "bin/rmate"
  end

  test do
    system "#{bin}/rmate", "--version"
  end
end


text:
package com.percolate.sdk.android.dto;

import android.os.Parcel;
import android.os.Parcelable;
import com.percolate.sdk.dto.ActivityStreamMetadata;
import com.percolate.sdk.dto.Mention;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Android version of {@link com.percolate.sdk.dto.ActivityStreamData}.  Implements {@link Parcelable}
 */
public class ActivityStreamData extends com.percolate.sdk.dto.ActivityStreamData implements Parcelable {

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeMap(this.metaDataMap);
        dest.writeString(this.relatedObjectUid);
        dest.writeString(this.relatedObjectPreview);
        dest.writeString(this.objectUid);
        dest.writeSerializable(this.user);
        dest.writeString(this.objectPreview);
        dest.writeValue(this.userId);
        dest.writeString(this.createdAt);
        dest.writeValue(this.licenseId);
        dest.writeString(this.type);
        dest.writeList(this.metadataList);
        dest.writeList(this.mentions);
        dest.writeMap(this.extraFields);
    }

    public ActivityStreamData() {
    }

    protected ActivityStreamData(Parcel in) {
        this.metaDataMap = new HashMap<>();
        in.readMap(this.metaDataMap, Map.class.getClassLoader());
        this.relatedObjectUid = in.readString();
        this.relatedObjectPreview = in.readString();
        this.objectUid = in.readString();
        this.user = (com.percolate.sdk.dto.User) in.readSerializable();
        this.objectPreview = in.readString();
        this.userId = (Integer) in.readValue(Integer.class.getClassLoader());
        this.createdAt = in.readString();
        this.licenseId = (Integer) in.readValue(Integer.class.getClassLoader());
        this.type = in.readString();
        this.metadataList = new ArrayList<ActivityStreamMetadata>();
        in.readList(this.metadataList, List.class.getClassLoader());
        this.mentions = new ArrayList<Mention>();
        in.readList(this.mentions, List.class.getClassLoader());
        this.extraFields = new HashMap<>();
        in.readMap(this.extraFields, HashMap.class.getClassLoader());
    }

    public static final Creator<ActivityStreamData> CREATOR = new Creator<ActivityStreamData>() {
        public ActivityStreamData createFromParcel(Parcel source) {
            return new ActivityStreamData(source);
        }

        public ActivityStreamData[] newArray(int size) {
            return new ActivityStreamData[size];
        }
    };
}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Autofac.Features.AttributeFilters;
using AzureStorage.Queue;
using Common.Log;
using Lykke.Service.EthereumCore.Core;
using Lykke.Service.EthereumCore.Core.Airlines;
using Lykke.Service.EthereumCore.Core.Exceptions;
using Lykke.Service.EthereumCore.Core.Repositories;
using Lykke.Service.EthereumCore.Core.Settings;
using Lykke.Service.EthereumCore.Core.Shared;
using Nethereum.Web3;

namespace Lykke.Service.EthereumCore.Services.Airlines
{
    public class AirlinesErc20DepositContractService : IAirlinesErc20DepositContractService
    {
        private readonly IErc223DepositContractRepository _contractRepository;
        private readonly IContractService _contractService;
        private readonly IErc20DepositContractQueueServiceFactory _poolFactory;
        private readonly ILog _log;
        private readonly IWeb3 _web3;
        private readonly AppSettings _appSettings;
        private readonly IQueueExt _transferQueue;
        private readonly IErcInterfaceService _ercInterfaceService;
        private readonly IHotWalletOperationRepository _operationsRepository;
        private readonly IUserTransferWalletRepository _userTransferWalletRepository;

        public AirlinesErc20DepositContractService(
            [KeyFilter(Constants.AirLinesKey)] IErc223DepositContractRepository contractRepository,
            [KeyFilter(Constants.AirLinesKey)] IHotWalletOperationRepository operationsRepository,
            IContractService contractService,
            IErc20DepositContractQueueServiceFactory poolFactory,
            ILog log,
            IWeb3 web3,
            AppSettings appSettings,
            IQueueFactory factory,
            IErcInterfaceService ercInterfaceService,
            IUserTransferWalletRepository userTransferWalletRepository)
        {
            _contractRepository = contractRepository;
            _contractService = contractService;
            _poolFactory = poolFactory;
            _appSettings = appSettings;
            _log = log;
            _web3 = web3;
            _appSettings = appSettings;
            _transferQueue = factory.Build(Constants.AirlinesErc223TransferQueue);
            _ercInterfaceService = ercInterfaceService;
            _operationsRepository = operationsRepository;
            _userTransferWalletRepository = userTransferWalletRepository;
        }

        public async Task<string> AssignContractAsync(string userAddress)
        {
            var contractAddress = await GetContractAddressAsync(userAddress);

            if (string.IsNullOrEmpty(contractAddress))
            {
                var pool = _poolFactory.Get(Constants.AirlinesErc20DepositContractPoolQueue);

                contractAddress = await pool.GetContractAddress();

                await _contractRepository.AddOrReplace(new Erc20DepositContract
                {
                    ContractAddress = contractAddress,
                    UserAddress = userAddress
                });
            }

            return contractAddress;
        }

        public async Task<string> CreateContractAsync()
        {
            var fromAddress = _appSettings.Airlines.AirlinesAddress;
            var abi = _appSettings.EthereumCore.Erc223DepositContract.Abi;
            var byteCode = _appSettings.EthereumCore.Erc223DepositContract.ByteCode;

            return await _contractService.CreateContractWithoutBlockchainAcceptanceFromSpecificAddress(fromAddress, abi, byteCode);
        }

        public async Task<IEnumerable<string>> GetContractAddressesAsync(IEnumerable<string> txHashes)
        {
            return await _contractService.GetContractsAddresses(txHashes);
        }

        public async Task<string> GetContractAddressAsync(string userAddress)
        {
            var contract = await _contractRepository.Get(userAddress);

            return contract?.ContractAddress;
        }

        public async Task ProcessAllAsync(Func<IErc20DepositContract, Task> processAction)
        {
            await _contractRepository.ProcessAllAsync(processAction);
        }

        public async Task<bool> ContainsAsync(string address)
        {
            var contains = await _contractRepository.Contains(address);

            return contains;
        }

        /// <param name="depositContractAddress"></param>
        /// <param name="erc20TokenAddress"></param>
        /// <param name="destinationAddress"></param>
        /// <returns>TransactionHash</returns>
        public async Task<string> RecievePaymentFromDepositContractAsync(string depositContractAddress,
           string erc20TokenAddress, string destinationAddress, string tokenAmount)
        {
            var depositContract = await _contractRepository.GetByContractAddress(depositContractAddress);
            if (depositContract == null)
            {
                throw new ClientSideException(ExceptionType.WrongParams, $"DepositContractAddress {depositContractAddress} does not exist");
            }

            var amount = System.Numerics.BigInteger.Parse(tokenAmount);
            var balance = await _ercInterfaceService.GetBalanceForExternalTokenAsync(depositContractAddress, erc20TokenAddress);
            if (balance == 0 || amount > balance)
            {
                throw new ClientSideException(ExceptionType.NotEnoughFunds,
                    $"Not enough tokens to proceed with withdrawal detected at deposit address {depositContractAddress}. " +
                    $"Current balance: {balance}");
            }

            var guidStr = Guid.NewGuid().ToString();

            var message = new Lykke.Service.EthereumCore.Core.Messages.LykkePay.LykkePayErc20TransferMessage()
            {
                OperationId = guidStr
            };

            var existingOperation = await _operationsRepository.GetAsync(guidStr);
            if (existingOperation != null)
            {
                throw new ClientSideException(ExceptionType.EntityAlreadyExists, "Try again later");
            }

            var transactionSenderAddress = _appSettings.Airlines.AirlinesAddress;
            var estimationResult = await Erc223SharedService.EstimateDepositTransferAsync(_web3,
                _appSettings.EthereumCore.Erc223DepositContract.Abi,
                transactionSenderAddress,
                depositContractAddress,
                erc20TokenAddress,
                destinationAddress,
                amount,
                _appSettings.EthereumCore,
                _log);

            if (!estimationResult)
            {
                throw new ClientSideException(ExceptionType.WrongDestination, $"Can't estimate transfer {depositContractAddress}, {erc20TokenAddress}, {destinationAddress}");
            }

            await _operationsRepository.SaveAsync(new HotWalletOperation()
            {
                Amount = amount,
                FromAddress = depositContractAddress,
                OperationId = guidStr,
                OperationType = HotWalletOperationType.Cashin,
                ToAddress = destinationAddress,
                TokenAddress = erc20TokenAddress
            });

            await _transferQueue.PutRawMessageAsync(Newtonsoft.Json.JsonConvert.SerializeObject(message));

            return guidStr;
        }

        public async Task<string> GetUserAddressAsync(string contractAddress)
        {
            var contract = await _contractRepository.GetByContractAddress(contractAddress);

            return contract?.UserAddress;
        }
    }
}


text:
package org.apache.camel.component.splunk;

public enum ConsumerType {
    NORMAL, REALTIME, SAVEDSEARCH;

    public static ConsumerType fromUri(String uri) {
        for (ConsumerType consumerType : ConsumerType.values()) {
            if (consumerType.name().equalsIgnoreCase(uri)) {
                return consumerType;
            }
        }
        throw new RuntimeException("Unable to construct consumerType from uri : " + uri);
    }

}


text:
title: getOrNull -
---
//[kotlin-util](../../index.md)/[it.czerwinski.kotlin.util](../index.md)/[Option](index.md)/[getOrNull](get-or-null.md)

# getOrNull
[Kotlin utilities]
Brief description
Gets the value of a [Some](../-some/index.md) or null if this is a [None](../-none/index.md).

#### Return
Value of a [Some](../-some/index.md) or null.

Content
abstract fun [getOrNull](get-or-null.md)(): [T](index.md)?


text:
using System.Threading.Tasks;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using BrumWithMe.Web.Models.Account;
using BrumWithMe.Data.Models.Entities;
using BrumWithMe.Auth.Identity.Contracts;
using System.Collections;
using BrumWithMe.Services.Providers.Mapping.Contracts;
using System.IO;
using Bytes2you.Validation;

namespace BrumWithMe.MVC.Controllers
{
    [Authorize]
    public class AccountController : BaseController
    {
        private const string XsrfKey = "XsrfId";
        private readonly IMappingProvider mappingProvider;
        private readonly IAuthService authService;

        public AccountController(IAuthService authService, IMappingProvider mappingProvider)
        {
            Guard.WhenArgument(authService, nameof(authService)).IsNull().Throw();
            Guard.WhenArgument(mappingProvider, nameof(mappingProvider)).IsNull().Throw();

            this.mappingProvider = mappingProvider;
            this.authService = authService;
        }

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var result = await this.authService.LogIn(model.Email, model.Password);

            switch (result)
            {
                case SignInStatus.Success:
                    return this.RedirectToAction(nameof(HomeController.Index), "Home");
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Грешно потребителско име или парола!");
                    return View(model);
            }
        }

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new User
                {
                    UserName = model.Email,
                    Email = model.Email,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    AvatarImageurl = "/UserAvatars/default.png"
                };

                IdentityResult result = await this.authService.Register(user, model.Password);

                if (result.Succeeded)
                {
                    await this.authService.LogIn(model.Email, model.Password);

                    var path = Server.MapPath($"~/UserAvatars/{model.Email}/Cars/");
                    Directory.CreateDirectory(path);

                    return RedirectToAction(nameof(HomeController.Index), "Home");
                }

                this.AddErrors(result);
            }

            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            this.authService.LogOff();
            return RedirectToAction("Index", "Home");
        }
    }
}


text:
.. _int: https://docs.python.org/2/library/stdtypes.html

.. _str: https://docs.python.org/2/library/stdtypes.html

.. _vmodl.DynamicData: ../../vmodl/DynamicData.rst

.. _DiagnosticPartitionType: ../../vim/host/DiagnosticPartition/DiagnosticType.rst

.. _vim.host.ScsiDisk.Partition: ../../vim/host/ScsiDisk/Partition.rst

.. _DiagnosticPartitionStorageType: ../../vim/host/DiagnosticPartition/StorageType.rst

vim.host.DiagnosticPartition
============================
  This data object type contains information about an available or active diagnostic partition.
:extends: vmodl.DynamicData_

Attributes:
    storageType (`str`_):

       Indicates the storage type of the diagnostic partition.See `DiagnosticPartitionStorageType`_
    diagnosticType (`str`_):

       Indicates the type of the diagnostic partition.See `DiagnosticPartitionType`_
    slots (`int`_):

       The number of slots in the diagnostic partition.
    id (`vim.host.ScsiDisk.Partition`_):

       Diagnostic partition identification information.


text:
<?xml version="1.0"?>
<data_managers>
    <data_manager tool_file="data_manager/bwameth_index_builder.xml" id="bwameth_index_builder">
        <data_table name="bwameth_indexes">
            <output>
                <column name="value" />
                <column name="dbkey" />
                <column name="name" />
                <column name="path" output_ref="out_file" >
                    <move type="directory" relativize_symlinks="True">
                        <target base="${GALAXY_DATA_MANAGER_DATA_PATH}">${dbkey}/bwameth_index/${value}</target>
                    </move>
                    <value_translation>${GALAXY_DATA_MANAGER_DATA_PATH}/${dbkey}/bwameth_index/${value}/${path}</value_translation>
                    <value_translation type="function">abspath</value_translation>
                </column>
            </output>
        </data_table>
    </data_manager>
</data_managers>


text:
<?php

namespace app\modules\admin\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\modules\admin\models\LoginForm;
use yii\filters\AccessControl;

/**
 * CategoryController implements the CRUD actions for Category model.
 */
class DefaultController extends Controller {

    public $layout = 'main';

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'allow' => true,
                        'roles' => ['admin'],
                    ],
                ],
                'denyCallback' => function($rule, $action) {
            $this->redirect('/admin/default/login');
        },
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * Lists all Category models.
     * @return mixed
     */
    public function actionIndex() {

        return $this->render('index');
    }

    public function actionLogin() {
//        var_dump(Yii::$app->user->identity);
//        die();

        if (!\Yii::$app->user->isGuest) {
            if (Yii::$app->user->can('admin'))
                return $this->render('index');
        }

        $model = new LoginForm();

        if ($model->load(Yii::$app->request->post()) && $model->login()) {

            # die('!');
            return $this->redirect('index');
        } else {
            return $this->render('login', [
                        'model' => $model,
            ]);
        }
    }

    public function actionLogout() {
        Yii::$app->user->logout();

        return $this->goHome();
    }

}


text:
{-# LANGUAGE PackageImports #-}

module Core.TypeCheck where

import Control.Applicative
import Control.Monad
import "mtl" Control.Monad.State
import Data.Either
import qualified Data.Map as M
import Data.Maybe
import Text.Printf

import Core.AST
import Core.PrettyPrinter

-- | Check types. Simple enough.
typecheck :: Module -> Module
typecheck m = let emptyState = TypeCheck M.empty M.empty []
                  (m', state) = runState (initMod m >> processModule m) emptyState
              in case errors state of
                [] -> m'
                es -> error $ unlines $ reverse es

data TypeCheck = TypeCheck { typeMap :: M.Map String Type, kindMap :: M.Map String Kind, errors :: [String] }

type TypeCheckM a = State TypeCheck a

-- | Run an action inside its own inner scope. All types mapped inside this scope will not be accessible outside.
subScope :: TypeCheckM a -> TypeCheckM a
subScope action = do
    oldTypes <- gets typeMap
    oldKinds <- gets kindMap
    r <- action
    modify (\state -> state { typeMap = oldTypes, kindMap = oldKinds })
    pure r

-- | Add a type to the typeMap.
addType :: String -> Type -> TypeCheckM ()
addType name ty = do
    oldMap <- gets typeMap
    modify (\state -> state { typeMap = M.insert name ty oldMap })

-- | Add a type to the kindMap.
addKind :: String -> Kind -> TypeCheckM ()
addKind name ty = do
    oldMap <- gets kindMap
    modify (\state -> state { kindMap = M.insert name ty oldMap })

-- | Add an id to the type or kind map.
addIdent :: Ident -> TypeCheckM ()
addIdent (Id name ty) = addType name ty
addIdent (TyId name ki) = addKind name ki

lookupType :: String -> TypeCheckM (Maybe Type)
lookupType name = M.lookup name <$> gets typeMap

-- | Add an error to the log.
reportError :: String -> TypeCheckM ()
reportError e = do
    es <- gets errors
    modify (\state -> state { errors = e:es })

-- | Extract types of top-level term identifiers and kinds of top-level types, and add them to the state..
initMod :: Module -> TypeCheckM ()
initMod (Module _ decls) = do
    addType "dumpInt" (TyInt ~> TyInt)
    forM_ decls $ \decl -> case decl of
        DTerm ident _ -> addIdent ident
        DType ident constrs -> do
            addIdent ident
            mapM_ addIdent constrs

processModule :: Module -> TypeCheckM Module
processModule (Module name decls) = Module name <$> mapM processDecl decls

processDecl :: Decl -> TypeCheckM Decl
processDecl decl@(DTerm ident expr) = do
    ty <- subScope $ calculateType expr
    case ty == typeOf ident of
        True -> pure decl
        False -> do
            reportError $ printf "Type mismatch in top-level decl. Expected %s, got %s." (ppType $ typeOf ident) (ppType ty)
            pure decl
processDecl (DType ident constructors) = pure $ (DType ident constructors)  -- TODO: should probably check kinds here.

checkIdent :: Ident -> Expr Ident -> TypeCheckM Type
checkIdent (Id name ty1) expr = do
    ty2 <- calculateType expr
    case ty1 == ty2 of
        True -> pure ty1
        False -> do
            reportError $ printf "Type mismatch. Identifier has type %s but the expression has type %s." (ppType ty1) (ppType ty2)
            pure ty1

-- | Calculate the type of the given expression.
calculateType :: Expr Ident -> TypeCheckM Type
calculateType (V ident) = do
    -- Lookup name in typeMap.
    mty <- lookupType $ name ident
    -- Make sure it's the same as the ident's.
    case mty of
        Just ty -> case ty == typeOf ident of
            True -> pure ty
            False -> do
                reportError $ printf "Type mismatch. Identifier has type %s but the value in scope has type %s." (ppType $ typeOf ident) (ppType ty)
                pure ty
        Nothing -> do
            reportError $ printf "Type lookup failed: %s." $ ppIdent ident
            pure $ typeOf ident
calculateType (L lit) = pure TyInt
calculateType (l :@ r) = do
    lTy <- calculateType l
    case lTy of
        -- Term application.
        TyFun lTy2 rTy2 -> do
            rTy <- calculateType r
            case lTy2 == rTy of
                True -> pure rTy2
                False -> do
                    reportError $ printf "Type mismatch. Function expecting value of type %s but got type %s." (ppType lTy2) (ppType rTy)
                    pure $ rTy2
        -- Type application.
        TyForAll ident ty1 -> case r of
            Type ty2 -> do
                ki <- calculateKind ty2
                case kindOf ident == ki of
                    True -> pure $ applyType (TyForAll ident ty1) ty2
                    False -> do
                        reportError $ printf "kind mismatch. Type application expecting type of kind %s but got kind %s." (ppKind $ kindOf ident) (ppKind ki)
                        pure ty2
            expr -> error $ printf "Syntax error. Expected type for application, got other expression instead: %s" (ppExpr expr)
calculateType (Lam ident@(Id name ty) expr) = subScope $ do
    addIdent ident
    ty2 <- calculateType expr
    pure $ ty ~> ty2
calculateType (Lam ident expr) = subScope $ do
    addIdent ident
    ty2 <- calculateType expr
    pure $ TyForAll ident ty2
calculateType (Let rec bindings expr) = subScope $ do
    forM_ bindings $ \(ident, bexpr) -> do
        addType (name ident) =<< checkIdent ident bexpr
    calculateType expr
calculateType (Case expr ty alts) = do
    forM_ alts $ \(tag, binders, body) -> subScope $ do
        mapM_ addIdent binders
        ty2 <- calculateType body
        unless (ty == ty2) $ reportError $ printf "Type mismatch. Case alt has type %s where %s is expected." (ppType ty2) (ppType ty)
    pure ty
calculateType (Constr tag ty exprs)
    | length exprs == getTypeArity ty = do
        passed <- and <$> checkTypes ty exprs
        if passed then pure $ returnType ty else error "Type mismatch in data constructor."
    | length exprs > getTypeArity ty = error "Data constructor over-saturated."
    | length exprs < getTypeArity ty = error "Unsaturated data constructor."
  where
    checkTypes :: Type -> [Expr Ident] -> TypeCheckM [Bool]
    checkTypes (TyFun l r) (v:vs) = do
        ety <- calculateType v
        rest <- checkTypes r vs
        pure $ (l == ety) : rest
    checkTypes ty' (v:[]) = do
        ety <- calculateType v
        pure $ (ty' == ety) : []
    checkTypes ty' [] = pure []  -- Nullary constructors.
    checkTypes ty' vs = error $ printf "Foo: %s -- %s" (show ty') (show vs)
calculateType (PrimFun pf) = pure $ getTypePF pf
calculateType (Type ty) = error $ printf "Found type (%s) where term was expected." $ ppType ty

getTypePF :: PrimFun -> Type
getTypePF (PrimBinOp op) = TyInt ~> TyInt ~> TyInt

-- | Calculate the kind of a type.
calculateKind :: Type -> TypeCheckM Kind
calculateKind (TyFun l r) = pure KiStar
calculateKind (TyInt) = pure KiStar
calculateKind (TyVar ident) = pure $ kindOf ident
calculateKind (TyForAll ident ty) = calculateKind ty
calculateKind (TyAp tyL tyR) = do
    kiL <- calculateKind tyL
    case kiL of
        KiFun l r -> do
            kiR <- calculateKind tyR
            case kiR == r of
                True -> pure l
                False -> do
                    reportError $ printf "Kind mismatch. Applying type of kind %s where %s is expected." (ppKind kiR) (ppKind r)
                    pure r
        kind -> do
            reportError $ printf "Attempting to apply type of kind %s to concrete type %s." (ppKind kind) (ppType tyL)
            pure kind


text:
__author__ = "Nick Isaacs"

import json
import logging
import multiprocessing

from src.utils.Envirionment import Envirionment
from src.stream.GnipRawStreamClient import GnipRawStreamClient

class GnipJsonStreamClient(object):
    def __init__(self, _streamURL, _streamName, _userName, _password,
                 _filePath, _rollDuration, compressed=True):
        self.gnip_raw_sream_client = GnipRawStreamClient(_streamURL, _streamName, _userName, _password,
                                                         _filePath, _rollDuration, compressed)
        self.environment = Envirionment()
        self.producer_queue = multiprocessing.Queue()
        self.logr = logging.getLogger("GnipJsonStreamClient")
        self.logr.addHandler(self.environment.rotating_handler)
        self._stop = multiprocessing.Event()
        self.run_thread = multiprocessing.Process(target=self.parse_string_buffer)
        self._started = False

    def started(self):
        return self._started

    def run(self):
        self.gnip_raw_sream_client.run()
        self.run_thread.start()
        self.logr.debug("Started application")

    def running(self):
        return not self.stopped()

    def stop(self):
        self._stop.set()
        self.gnip_raw_sream_client.stop()
        self.logr.debug("Cleanly stopped raw streaming client")

    def stopped(self):
        return self._stop.is_set()

    def queue(self):
        return self.producer_queue

    def parse_string_buffer(self):
        self.logr.debug("Starting to parse buffer")
        while not self.stopped():
            if not isinstance(self.gnip_raw_sream_client.get_string_buffer(), basestring):
                continue
            try:
                chunks = self.gnip_raw_sream_client.get_string_buffer().split("\n")
                for chunk in chunks:
                    if chunk.strip() is None or chunk.strip() == '':
                        continue
                    the_hash = json.loads(chunk)
                    self.producer_queue.put(the_hash)
                    if not self._started:
                        self._started = True
            except ValueError:
                self.logr.error("There was a ValueError in the chunk: " + chunk)
            except Exception, e:
                self.logr.error("There was an error: " + e.message)
                raise e


text:
/* @flow */
/* eslint
no-restricted-globals: 0
*/
import React from 'react';
import {
  lifecycle,
  compose,
  withState,
  withProps,
  mapProps,
  withHandlers,
} from 'recompose';
import OncoGrid from 'oncogrid';
import { uniqueId, get, debounce, isEqual } from 'lodash';
import { connect } from 'react-redux';
import withSize from '@ncigdc/utils/withSize';
import FullScreenIcon from 'react-icons/lib/md/fullscreen';

import {
  exitFullScreen,
  enterFullScreen,
  isFullScreen,
} from '@ncigdc/utils/fullscreen';
import { getFilterValue, replaceFilters } from '@ncigdc/utils/filters';
import {
  consequenceTypes,
  colorMap,
  cnvChangeTypes,
} from '@ncigdc/utils/filters/prepared/significantConsequences';
import withRouter from '@ncigdc/utils/withRouter';

import Loader from '@ncigdc/uikit/Loaders/Loader';
import Button from '@ncigdc/uikit/Button';
import { Row, Column } from '@ncigdc/uikit/Flex';
import { Tooltip } from '@ncigdc/uikit/Tooltip';

import { ToggleSwatchLegend } from '@ncigdc/components/Legends';
import DownloadVisualizationButton from '@ncigdc/components/DownloadVisualizationButton';
import Hidden from '@ncigdc/components/Hidden';

import { visualizingButton } from '@ncigdc/theme/mixins';
import wrapSvg from '@ncigdc/utils/wrapSvg';
import { performanceTracker } from '@ncigdc/utils/analytics';
import { withTooltip } from '@ncigdc/uikit/Tooltip/index';

import getQueries from './getQueries';
import oncoGridParams from './oncoGridParams';
import mouseEvents from './mouseEvents';
import { setModal } from '@ncigdc/dux/modal';
import ColorPickerModal from '@ncigdc/components/Modals/ColorPickerModal';
import DropDown from '@ncigdc/uikit/Dropdown';
import DropdownItem from '@ncigdc/uikit/DropdownItem';

import './oncogrid.css';

function refreshGridState({
  oncoGrid,
  setHeatMapMode,
  setShowGridLines,
  setCrosshairMode,
  setIsLoading,
}: {
  oncoGrid: Object,
  setHeatMapMode: Function,
  setShowGridLines: Function,
  setCrosshairMode: Function,
  setIsLoading: Function,
}): void {
  setIsLoading(true);
  oncoGrid.container.node().style.visibility = 'hidden';
  setHeatMapMode(oncoGrid.heatMapMode);
  setShowGridLines(oncoGrid.drawGridLines);
  setCrosshairMode(oncoGrid.crosshairMode);
}

const GRID_CLASS = 'oncogrid-wrapper';
const MAX_CASES = 200;
const MAX_GENES = 50;

const styles = {
  container: {
    overflow: 'visible',
    padding: '0 30px',
    background: 'white',
  },
  fullscreen: {
    maxWidth: '100%',
    width: '100%',
    marginLeft: 0,
    padding: '100px 100px 0',
    overflow: 'scroll',
    height: '100%',
  },
  button: {
    ...visualizingButton,
    marginBottom: 12,
  },
  buttonActive: {
    backgroundColor: '#e6e6e6',
    borderColor: '#adadad',
  },
  legends: {
    width: '80%',
    marginLeft: '100px',
    flexFlow: 'row wrap',
  },
};

const containerRefs = {};
const wrapperRefs = {};

type TProps = {
  oncoGrid: Object,
  setOncoGrid: Function,
  setOncoGridData: Function,
  oncoGridPadding: number,
  oncoGridHeight: number,
  setIsLoading: Function,
  projectId: string,
  setHeatMapMode: Function,
  setShowGridLines: Function,
  setCrosshairMode: Function,
  setTrackLegends: Function,
  currentFilters: Object,
  uniqueGridClass: string,
  dispatch: Function,
  push: Function,
  impacts: Array<string>,
  filteredConsequenceTypes: Array<string>,
};

const OncoGridWrapper = compose(
  withRouter,
  withState(
    'gridColors',
    'setGridColors',
    JSON.parse(localStorage.getItem('oncogridActiveTheme') || 'null') ||
      colorMap,
  ),
  withHandlers({
    resetColors: ({ setGridColors }) => () => {
      setGridColors(colorMap);
      localStorage.setItem('oncogridActiveTheme', JSON.stringify(colorMap));
    },
  }),
  withState('oncoGrid', 'setOncoGrid', {}),
  withState('oncoGridData', 'setOncoGridData', null),
  withState('crosshairMode', 'setCrosshairMode', false),
  withState('showGridLines', 'setShowGridLines', false),
  withState('heatMapMode', 'setHeatMapMode', false),
  withState('isLoading', 'setIsLoading', true),
  withState('caseCount', 'setCaseCount', 0),
  withState('lastRequest', 'setLastRequest', null),
  withState(
    'uniqueGridClass',
    'setUniqueGridClass',
    () => GRID_CLASS + uniqueId(),
  ),
  withState('trackLegends', 'setTrackLegends', []),
  withState('variationDataTypes', 'setVariationDataTypes', ['cnv', 'ssm']),
  withState('toggledCnvChanges', 'setToggledCnvChanges', cnvChangeTypes),
  withState('toggledConsequences', 'setToggledConsequences', consequenceTypes),
  withState('rankOncoGridBy', 'setRankOncoGridBy', 'ssm'),
  mapProps(
    ({
      title,
      impacts,
      toggledConsequences,
      variationDataTypes,
      toggledCnvChanges,
      rankOncoGridBy,
      gridColors,
      ...props
    }) => {
      const cases = props.oncoGridData
        ? props.oncoGridData.cases.length
        : MAX_CASES;
      const genes = props.oncoGridData
        ? props.oncoGridData.genes.length
        : MAX_GENES;

      const currentImpacts = getFilterValue({
        currentFilters: props.currentFilters.content,
        dotField: 'ssms.consequence.transcript.annotation.vep_impact',
      });

      const currentConsequenceTypes = get(
        getFilterValue({
          currentFilters: props.currentFilters.content,
          dotField: 'ssms.consequence.transcript.consequence_type',
        }),
        'content.value',
        consequenceTypes,
      );

      const currentCnvChanges = get(
        getFilterValue({
          currentFilters: props.currentFilters.content,
          dotField: 'cnv.cnv_change',
        }),
        'content.value',
        cnvChangeTypes,
      );
      // const filteredConsequenceTypes = consequenceTypes.filter((c: any) =>
      //   currentConsequenceTypes.includes(c),
      // );

      const filteredConsequenceTypes = toggledConsequences.filter((c: any) =>
        currentConsequenceTypes.includes(c),
      );

      const filteredCnvChanges = toggledCnvChanges.filter((c: any) =>
        currentCnvChanges.includes(c),
      );

      const currentFilters = props.currentFilters;
      const currentSSMFilters = replaceFilters(
        {
          op: 'and',
          content: [
            {
              op: 'in',
              content: {
                field: 'ssms.consequence.transcript.consequence_type',
                value: filteredConsequenceTypes,
              },
            },
          ],
        },
        props.currentFilters,
      );

      let currentCNVFilters = replaceFilters(
        {
          op: 'and',
          content: [
            {
              op: 'in',
              content: {
                field: 'cnv.cnv_change',
                value: filteredCnvChanges,
              },
            },
          ],
        },
        props.currentFilters,
      );

      return {
        ...props,
        title:
          title ||
          `${cases}${cases < props.caseCount
            ? ' Most'
            : ''} Mutated Cases and Top ${genes} Mutated Genes By SSM`,
        impacts:
          impacts || (currentImpacts && currentImpacts.content.value) || [],
        filteredConsequenceTypes,
        currentFilters,
        toggledConsequences,
        variationDataTypes,
        toggledCnvChanges,
        currentCNVFilters,
        currentSSMFilters,
        rankOncoGridBy,
        gridColors,
      };
    },
  ),
  withTooltip,
  withProps({
    oncoGridHeight: 150,
    oncoGridPadding: 306,
    oncoGridWrapper: null,
    heatMapColor: '#2E7D32',
    async getQueries(
      {
        oncoGrid,
        setOncoGrid,
        setOncoGridData,
        oncoGridPadding,
        oncoGridHeight,
        setIsLoading,
        projectId,
        heatMapMode,
        setHeatMapMode,
        setShowGridLines,
        setCrosshairMode,
        setTrackLegends,
        currentFilters,
        impacts,
        uniqueGridClass,
        dispatch,
        push,
        filteredConsequenceTypes,
        setCaseCount,
        showGridLines,
        lastRequest,
        setLastRequest,
        setTooltip,
        variationDataTypes,
        setVariationDataTypes,
        currentCNVFilters,
        currentSSMFilters,
        toggledCnvChanges,
        rankOncoGridBy,
        heatMapColor,
        gridColors,
      }: TProps = {},
      previousResponses: Object,
    ): Promise<*> {
      if (!filteredConsequenceTypes.length) {
        if (oncoGrid.toggleGridLines) oncoGrid.destroy();
        setOncoGrid({});
        setOncoGridData(null);
        setIsLoading(false);
        return;
      }

      if (lastRequest) lastRequest.cancelled = true;
      const request = { cancelled: false };
      setLastRequest(request);
      performanceTracker.begin('oncogrid:fetch');
      const responses = await getQueries({
        currentFilters,
        maxCases: MAX_CASES,
        maxGenes: MAX_GENES,
        currentCNVFilters,
        currentSSMFilters,
        rankOncoGridBy,
        heatMapMode,
      });

      const performanceContext = {
        donors: responses.cases.length,
        genes: responses.genes.length,
        ssm_occurrences: responses.ssm_occurrences.length,
        cnv_occurrences: responses.cnv_occurrences.length,
        maxCases: MAX_CASES,
        maxGenes: MAX_GENES,
      };

      performanceTracker.end('oncogrid:fetch', performanceContext);
      if (!wrapperRefs[uniqueGridClass] || request.cancelled) return;

      performanceTracker.begin('oncogrid:process');
      const gridParams = oncoGridParams({
        grid: showGridLines,
        colorMap: gridColors,
        element: wrapperRefs[uniqueGridClass],
        donorData: responses.cases,
        geneData: responses.genes,
        ssmOccurrencesData: responses.ssm_occurrences,
        cnvOccurrencesData: responses.cnv_occurrences,
        width:
          (containerRefs[uniqueGridClass] || { offsetWidth: 0 }).offsetWidth -
          oncoGridPadding,
        height: oncoGridHeight,
        trackPadding: 30,
        impacts,
        consequenceTypes: filteredConsequenceTypes,
        heatMap: heatMapMode,
        heatMapColor,
      });

      performanceTracker.end('oncogrid:process', performanceContext);

      if (gridParams) {
        if (previousResponses && oncoGrid.toggleGridLines) oncoGrid.destroy();

        performanceTracker.begin('oncogrid:init');
        const grid = new OncoGrid(gridParams);

        performanceTracker.end('oncogrid:init', performanceContext);
        grid.resize = debounce(grid.resize.bind(grid), 200);

        performanceTracker.begin('oncogrid:render');
        grid.render();

        grid.container.node().style.visibility = 'hidden';
        grid.on('render:all:end', () => {
          setIsLoading(false);
          grid.container.node().style.visibility = 'visible';
          performanceTracker.end('oncogrid:render', performanceContext);
        });

        mouseEvents({
          grid,
          setTooltip,
          trackLegends: gridParams.trackLegends,
          push,
          dispatch,
          currentFilters,
        });

        setCaseCount(responses.totalCases);
        setOncoGrid(grid);
        setOncoGridData(responses);
        refreshGridState({
          oncoGrid: grid,
          setHeatMapMode,
          setShowGridLines,
          setCrosshairMode,
          setIsLoading,
        });
      } else {
        if (oncoGrid.toggleGridLines) oncoGrid.destroy();
        setOncoGridData(null);
        setIsLoading(false);
      }

      if (gridParams) {
        setTrackLegends(Object.values(gridParams.trackLegends));
      }
    },
  }),
  connect(),
  withSize(),
  lifecycle({
    componentWillReceiveProps(nextProps: Object): void {
      const {
        crosshairMode: lastCrosshairMode,
        showGridLines: lastShowGridLines,
        heatMapMode: lastHeadMapMode,
        size: { width: lastWidth },
      } = this.props;

      const {
        oncoGrid,
        oncoGridPadding,
        oncoGridHeight,
        crosshairMode,
        showGridLines,
        heatMapMode,
        size: { width },
        uniqueGridClass,
      } = nextProps;

      if (oncoGrid.toggleGridLines) {
        if (lastCrosshairMode !== crosshairMode) {
          oncoGrid.setCrosshair(crosshairMode);
        }
        if (lastShowGridLines !== showGridLines) {
          oncoGrid.setGridLines(showGridLines);
        }
        if (lastHeadMapMode !== heatMapMode) oncoGrid.setHeatmap(heatMapMode);
        if (width !== lastWidth) {
          oncoGrid.resize(
            wrapperRefs[uniqueGridClass].offsetWidth - oncoGridPadding,
            oncoGridHeight,
          );
        }
      }

      if (
        JSON.stringify(this.props.currentCNVFilters) !==
          JSON.stringify(nextProps.currentCNVFilters) ||
        JSON.stringify(this.props.currentSSMFilters) !==
          JSON.stringify(nextProps.currentSSMFilters) ||
        !isEqual(this.props.gridColors, nextProps.gridColors) ||
        this.props.heatMapMode !== nextProps.heatMapMode
      ) {
        this.props.setIsLoading(true);
        this.props.getQueries(nextProps, this.props.oncoGridData);
      }
    },
    componentDidMount(): void {
      this.props.getQueries(this.props);
    },
    componentWillUnmount(): void {
      const { uniqueGridClass, oncoGrid } = this.props;
      if (oncoGrid.toggleGridLines) oncoGrid.destroy();
      delete containerRefs[uniqueGridClass];
      delete wrapperRefs[uniqueGridClass];
    },
  }),
)(
  ({
    oncoGrid,
    oncoGridData,
    heatMapMode,
    setHeatMapMode,
    showGridLines,
    setShowGridLines,
    crosshairMode,
    setCrosshairMode,
    isLoading,
    setIsLoading,
    uniqueGridClass,
    trackLegends,
    title,
    toggledCnvChanges,
    setToggledCnvChanges,
    toggledConsequences,
    setToggledConsequences,
    variationDataTypes,
    setVariationDataTypes,
    heatMapColor,
    setGridColors,
    gridColors,
    dispatch,
    resetColors,
  }) => (
    <Loader loading={isLoading} height="800px">

 {
          containerRefs[uniqueGridClass] = r;
        }}
      >
        <Row
          style={{
            display: 'flex',
            justifyContent: oncoGridData ? 'space-between' : 'flex-end',
          }}
        >
          {oncoGridData &&
{title}
}
          {!isLoading && (

              <Row
                style={{
                  justifyContent: 'flex-start',
                  marginRight: '12px',
                  flexWrap: 'wrap',
                  paddingBottom: 15,
                }}
                spacing="1rem"
              >
                <DropDown
                  isDisabled={!oncoGridData || isFullScreen()}
                  button={
                    <Tooltip Component="Customize Colors">
                      <Button
                        style={visualizingButton}
                        disabled={!oncoGridData || isFullScreen()}
                      >

                        <Hidden>Customize Colors</Hidden>
                      </Button>
                    </Tooltip>
                  }
                >
                  <DropdownItem
                    onClick={() => {
                      dispatch(
                        setModal(
                          <ColorPickerModal
                            onSave={colors => {
                              setGridColors(colors);
                              localStorage.setItem(
                                'oncogridActiveTheme',
                                JSON.stringify(colors),
                              );
                              dispatch(setModal(null));
                            }}
                            onClose={() => dispatch(setModal(null))}
                            colors={gridColors}
                          />,
                        ),
                      );
                    }}
                  >
                    Customize Colors
                  </DropdownItem>
                  <DropdownItem onClick={resetColors}>
                    Reset to Default
                  </DropdownItem>
                </DropDown>
                <DownloadVisualizationButton
                  svg={() => {
                    const elementsAfter = trackLegends.map(html => {
                      const div = document.createElement('div');
                      div.innerHTML = html;
                      div.style.position = 'absolute';
                      div.style.left = '-99999px';
                      document.body.appendChild(div);
                      return div;
                    });

                    const wrappedSvg = wrapSvg({
                      selector: `.${uniqueGridClass} svg`,
                      title,
                      className: GRID_CLASS,
                      embed: {
                        top: {
                          elements: [
                            containerRefs[uniqueGridClass].querySelector(
                              '.oncogrid-legend',
                            ),
                          ],
                        },
                        bottom: {
                          elements: elementsAfter,
                          styles:
                            'display: inline-block; width: 200px; vertical-align: top; ',
                        },
                      },
                    });

                    elementsAfter.forEach(el => document.body.removeChild(el));
                    return wrappedSvg;
                  }}
                  data={oncoGridData}
                  stylePrefix={`.${GRID_CLASS}`}
                  slug="oncogrid"
                  noText
                  tooltipHTML="Download"
                  disabled={!oncoGridData}
                />
                <Tooltip Component="Reload Grid">
                  <Button
                    style={styles.button}
                    onClick={() => {
                      oncoGrid.reload();
                      setToggledConsequences(consequenceTypes);
                      setToggledCnvChanges(cnvChangeTypes);
                      refreshGridState({
                        oncoGrid,
                        setHeatMapMode,
                        setShowGridLines,
                        setCrosshairMode,
                        setIsLoading,
                      });
                    }}
                    disabled={!oncoGridData}
                  >

                    <Hidden>Reload</Hidden>
                  </Button>
                </Tooltip>
                <Tooltip Component="Cluster Data">
                  <Button
                    style={styles.button}
                    onClick={() => oncoGrid.cluster()}
                    disabled={!oncoGridData}
                  >

                    <Hidden>Cluster</Hidden>
                  </Button>
                </Tooltip>
                <Tooltip Component="Toggle Heatmap View">
                  <Button
                    style={{
                      ...styles.button,
                      ...(heatMapMode && styles.buttonActive),
                    }}
                    disabled={toggledConsequences.length === 0 || !oncoGridData}
                    onClick={() => setHeatMapMode(!heatMapMode)}
                  >

                    <Hidden>Heatmap</Hidden>
                  </Button>
                </Tooltip>
                <Tooltip Component="Toggle Gridlines">
                  <Button
                    style={{
                      ...styles.button,
                      ...(showGridLines && styles.buttonActive),
                    }}
                    onClick={() => setShowGridLines(!showGridLines)}
                    disabled={!oncoGridData}
                  >

                    <Hidden>Lines</Hidden>
                  </Button>
                </Tooltip>
                <Tooltip Component="Toggle Crosshairs">
                  <Button
                    style={{
                      ...styles.button,
                      ...(crosshairMode && styles.buttonActive),
                    }}
                    onClick={() => setCrosshairMode(!crosshairMode)}
                    disabled={!oncoGridData}
                  >

                    <Hidden>Crosshair</Hidden>
                  </Button>
                </Tooltip>
                <Tooltip Component="Fullscreen">
                  <Button
                    style={{
                      ...styles.button,
                      ...(isFullScreen() && styles.buttonActive),
                      marginRight: 0,
                    }}
                    onClick={() => {
                      if (isFullScreen()) {
                        exitFullScreen();
                        oncoGrid.reload();
                        refreshGridState({
                          oncoGrid,
                          setHeatMapMode,
                          setShowGridLines,
                          setCrosshairMode,
                          setIsLoading,
                        });
                      } else {
                        enterFullScreen(containerRefs[uniqueGridClass]);
                        oncoGrid.resize(
                          screen.width - 400,
                          screen.height - 400,
                          true,
                        );
                      }
                    }}
                    disabled={!oncoGridData}
                  >
                    <FullScreenIcon />
                    <Hidden>Fullscreen</Hidden>
                  </Button>
                </Tooltip>
              </Row>
              {crosshairMode && (

                  Click and drag to select a region on the OncoGrid to zoom in.

              )}

          )}
        </Row>
        <Row style={styles.legends}>

Mutations

              <ToggleSwatchLegend
                toggledValues={toggledConsequences}
                toggle={key => {
                  if (toggledConsequences.includes(key)) {
                    setToggledConsequences(
                      toggledConsequences.filter(c => c !== key),
                    );
                  } else {
                    setToggledConsequences([...toggledConsequences, key]);
                  }
                }}
                toggleAll={() => {
                  if (toggledConsequences.length > 0) {
                    setToggledConsequences([]);
                  } else {
                    setToggledConsequences(consequenceTypes);
                  }
                }}
                colorMap={gridColors.mutation}
                type={'mutations'}
                heatMapMode={heatMapMode}
                heatMapColor={heatMapColor}
              />

          {!heatMapMode && (

CNV Changes

              <ToggleSwatchLegend
                toggledValues={toggledCnvChanges}
                toggle={key => {
                  if (toggledCnvChanges.includes(key)) {
                    setToggledCnvChanges(
                      toggledCnvChanges.filter(c => c !== key),
                    );
                  } else {
                    setToggledCnvChanges([...toggledCnvChanges, key]);
                  }
                }}
                toggleAll={() => {
                  if (toggledCnvChanges.length > 0) {
                    setToggledCnvChanges([]);
                  } else {
                    setToggledCnvChanges(cnvChangeTypes);
                  }
                }}
                colorMap={gridColors.cnv}
                type={'copy number variations'}
              />

          )}
        </Row>
        {!oncoGridData &&
          !isLoading && (
            <Column style={{ padding: '2rem 0' }}>
              {toggledConsequences.length === 0 && (

                  The current selection has no results. Please select more
                  mutation types or reload the page to continue exploration.

              )}
              {toggledConsequences.length > 0 &&
No result found.
}
            </Column>
          )}
        <div
          className={`${GRID_CLASS} ${uniqueGridClass}`}
          ref={n => {
            wrapperRefs[uniqueGridClass] = n;
          }}
          style={{
            cursor: crosshairMode ? 'crosshair' : 'pointer',
            visibility: isLoading ? 'hidden' : 'visible',
            paddingTop: 15,
          }}
        />

    </Loader>
  ),
);

export default OncoGridWrapper;


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="MdlGlossaryEntriesCategories" table="mdl_glossary_entries_categories">
    <indexes>
      <index name="mdl_glosentrcate_cat_ix" columns="categoryid"/>
      <index name="mdl_glosentrcate_ent_ix" columns="entryid"/>
    </indexes>
    <id name="id" type="bigint" column="id">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="categoryid" type="bigint" column="categoryid" nullable="false"/>
    <field name="entryid" type="bigint" column="entryid" nullable="false"/>
  </entity>
</doctrine-mapping>