text:
package organization

import (
	"errors"
	"net/http"
	"strings"

	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"

	"github.com/itsyouonline/identityserver/db"
)

const (
	mongoCollectionName       = "organizations"
	logoCollectionName        = "organizationLogos"
	last2FACollectionName     = "last2falogin"
	descriptionCollectionName = "organizationdescriptions"
)

//InitModels initialize models in mongo, if required.
func InitModels() {
	// TODO: Use model tags to ensure indices/constraints.
	index := mgo.Index{
		Key:    []string{"globalid"},
		Unique: true,
	}

	db.EnsureIndex(mongoCollectionName, index)

	// Index the logo collection
	index = mgo.Index{
		Key:    []string{"globalid"},
		Unique: true,
	}

	db.EnsureIndex(logoCollectionName, index)

	index = mgo.Index{
		Key:    []string{"globalid", "username"},
		Unique: true,
	}

	db.EnsureIndex(last2FACollectionName, index)

	// remove last2fa entries after 31 days
	automatic2FAExpiration := mgo.Index{
		Key:         []string{"last2fa"},
		ExpireAfter: time.Second * 3600 * 24 * 31,
		Background:  true,
	}
	db.EnsureIndex(last2FACollectionName, automatic2FAExpiration)

	// Index the info texts
	index = mgo.Index{
		Key:    []string{"globalid"},
		Unique: true,
	}

	db.EnsureIndex(descriptionCollectionName, index)
}

//Manager is used to store organizations
type Manager struct {
	session    *mgo.Session
	collection *mgo.Collection
}

//LogoManager is used to save the logo for an organization
type LogoManager struct {
	session    *mgo.Session
	collection *mgo.Collection
}

//Last2FAManager is used to save the date for the last 2FA login for an organization through the authorization code grant flow
type Last2FAManager struct {
	session    *mgo.Session
	collection *mgo.Collection
}

//DescriptionManager is used to store info texts for an organization
type DescriptionManager struct {
	session    *mgo.Session
	collection *mgo.Collection
}

func getCollection(session *mgo.Session) *mgo.Collection {
	return db.GetCollection(session, mongoCollectionName)
}

//get the logo collection
func getLogoCollection(session *mgo.Session) *mgo.Collection {
	return db.GetCollection(session, logoCollectionName)
}

//get the last 2FA collection
func getLast2FACollection(session *mgo.Session) *mgo.Collection {
	return db.GetCollection(session, last2FACollectionName)
}

//get the info text collection
func getDescriptionManager(session *mgo.Session) *mgo.Collection {
	return db.GetCollection(session, descriptionCollectionName)
}

//NewManager creates and initializes a new Manager
func NewManager(r *http.Request) *Manager {
	session := db.GetDBSession(r)
	return &Manager{
		session:    session,
		collection: getCollection(session),
	}
}

//NewLogoManager creates and initializes a new LogoManager
func NewLogoManager(r *http.Request) *LogoManager {
	session := db.GetDBSession(r)
	return &LogoManager{
		session:    session,
		collection: getLogoCollection(session),
	}
}

// NewLast2FAManager creates and initializes a new Last2FAManager
func NewLast2FAManager(r *http.Request) *Last2FAManager {
	session := db.GetDBSession(r)
	return &Last2FAManager{
		session:    session,
		collection: getLast2FACollection(session),
	}
}

// NewDescriptionManager creates and initializes a new DescriptionManager
func NewDescriptionManager(r *http.Request) *DescriptionManager {
	session := db.GetDBSession(r)
	return &DescriptionManager{
		session:    session,
		collection: getDescriptionManager(session),
	}
}

// GetOrganizations gets a list of organizations.
func (m *Manager) GetOrganizations(organizationIDs []string) ([]Organization, error) {
	var organizations []Organization

	err := m.collection.Find(bson.M{"globalid": bson.M{"$in": organizationIDs}}).All(&organizations)

	return organizations, err
}

// GetSubOrganizations returns all organizations which have {globalID} as parent (including the organization with {globalID} as globalid)
//TODO: validate globalID since it is appended in the query
//TODO: put an index on the globalid field
func (m *Manager) GetSubOrganizations(globalID string) ([]Organization, error) {
	var organizations = make([]Organization, 0, 0)
	var qry = bson.M{"globalid": bson.M{"$regex": bson.RegEx{"^" + globalID + `\.`, ""}}}
	if err := m.collection.Find(qry).All(&organizations); err != nil {
		return nil, err
	}

	return organizations, nil
}

//isDirectOwner checks if a specific user is in the owners list of an organization
func (m *Manager) isDirectOwner(globalID, username string) (isowner bool, err error) {
	matches, err := m.collection.Find(bson.M{"globalid": globalID, "owners": username}).Count()
	isowner = (matches > 0)
	return
}

func (m *Manager) isOwnerOrMember(globalID, username string, excludelist map[string]bool) (result bool, err error) {
	result, err = m.isDirectOwner(globalID, username)
	if result || err != nil {
		return
	}
	result, err = m.isDirectMember(globalID, username)
	if result || err != nil {
		return
	}
	// If not a direct owner or member, iterate through the list of owner/member organizations
	var org Organization
	err = m.collection.Find(bson.M{"globalid": globalID}).Select(bson.M{"orgowners": 1, "orgmembers": 1, "includesuborgsof": 1}).One(&org)
	if err != nil {
		return
	}
	excludelist[globalID] = true
	// Add the suborganizations from the includelist
	var includesuborgs []string
	for _, owner := range append(org.OrgOwners, org.OrgMembers...) {
		for _, include := range org.IncludeSubOrgsOf {
			if owner == include {
				includesuborgs = append(includesuborgs, include)
			}
		}
	}
	var subOrgs []Organization
	for _, subOrg := range includesuborgs {
		subOrganizations, err := m.GetSubOrganizations(subOrg)
		if err != nil && err != mgo.ErrNotFound {
			return false, err
		}
		subOrgs = append(subOrgs, subOrganizations...)
	}
	var orgs []string
	for _, suborganization := range subOrgs {
		orgs = append(orgs, suborganization.Globalid)
	}
	orgs = append(orgs, org.OrgMembers...)

	for _, owningOrganization := range append(org.OrgOwners, orgs...) {
		if _, excluded := excludelist[owningOrganization]; excluded {
			continue
		}
		result, err = m.isOwnerOrMember(owningOrganization, username, excludelist)
		if result || err != nil {
			return
		}
	}

	return
}

//IsOwner checks if a specific user is in the owners list of an organization
// or belongs to an organization that is in the owner list
// It also checks this for the parentorganizations
func (m *Manager) IsOwner(globalID, username string) (isowner bool, err error) {
	isowner, err = m.isDirectOwner(globalID, username)
	if isowner || err != nil {
		return
	}
	// If not a direct owner, check the ownership in the parent organization
	lastSubOrgSeparator := strings.LastIndex(globalID, ".")
	if lastSubOrgSeparator > 0 {
		isowner, err = m.IsOwner(globalID[:lastSubOrgSeparator], username)
		if isowner || err != nil {
			return
		}
	}
	// If not a direct or inherited owner, iterate through the list of owning organizations
	var org Organization
	err = m.collection.Find(bson.M{"globalid": globalID}).Select(bson.M{"orgowners": 1, "includesuborgsof": 1}).One(&org)
	if err != nil {
		if mgo.ErrNotFound == err {
			err = nil
		}
		return
	}
	excludelist := make(map[string]bool)
	excludelist[globalID] = true

	// Also get the suborganizations if they have been added
	var includesuborgs []string
	for _, owner := range org.OrgOwners {
		for _, include := range org.IncludeSubOrgsOf {
			if owner == include {
				includesuborgs = append(includesuborgs, include)
			}
		}
	}
	var subOrgs []Organization
	for _, subOrg := range includesuborgs {
		subOrganizations, err := m.GetSubOrganizations(subOrg)
		if err != nil && err != mgo.ErrNotFound {
			return false, err
		}
		subOrgs = append(subOrgs, subOrganizations...)
	}
	var orgs []string
	for _, suborganization := range subOrgs {
		orgs = append(orgs, suborganization.Globalid)
	}

	for _, owningOrganization := range append(orgs, org.OrgOwners...) {
		isowner, err = m.isOwnerOrMember(owningOrganization, username, excludelist)
		if isowner || err != nil {
			return
		}
	}

	return
}

//OrganizationIsOwner checks if organization2 is an owner of organization1
func (m *Manager) OrganizationIsOwner(globalID, organization string) (isowner bool, err error) {
	matches, err := m.collection.Find(bson.M{"globalid": globalID, "orgowners": organization}).Count()
	isowner = (matches > 0)
	return
}

//isDirectMember checks if a specific user is in the members list of an organization
func (m *Manager) isDirectMember(globalID, username string) (ismember bool, err error) {
	matches, err := m.collection.Find(bson.M{"globalid": globalID, "members": username}).Count()
	ismember = (matches > 0)
	return
}

//IsMember checks if a specific user is in the members list of an organization
// or belongs to an organization that is in the member list
// it also checks this for the parentorganization
func (m *Manager) IsMember(globalID, username string) (result bool, err error) {
	result, err = m.isDirectMember(globalID, username)
	if result || err != nil {
		return
	}
	// If not a direct member, check the membership in the parent organization
	lastSubOrgSeperator := strings.LastIndex(globalID, ".")
	if lastSubOrgSeperator > 0 {
		result, err = m.IsMember(globalID[:lastSubOrgSeperator], username)
		if result || err != nil {
			return
		}
	}
	// If not a direct or inherited member, iterate through the list of member organizations
	var org Organization
	err = m.collection.Find(bson.M{"globalid": globalID}).Select(bson.M{"orgmembers": 1, "includesuborgsof": 1}).One(&org)
	if err != nil {
		if mgo.ErrNotFound == err {
			err = nil
		}
		return
	}
	excludelist := make(map[string]bool)
	excludelist[globalID] = true

	// Also get the suborganizations if they have been added
	var includesuborgs []string
	for _, member := range org.OrgMembers {
		for _, include := range org.IncludeSubOrgsOf {
			if member == include {
				includesuborgs = append(includesuborgs, include)
			}
		}
	}
	var subOrgs []Organization
	for _, subOrg := range includesuborgs {
		subOrganizations, err := m.GetSubOrganizations(subOrg)
		if err != nil && err != mgo.ErrNotFound {
			return false, err
		}
		subOrgs = append(subOrgs, subOrganizations...)
	}
	var orgs []string
	for _, suborganization := range subOrgs {
		orgs = append(orgs, suborganization.Globalid)
	}
	for _, owningOrganization := range append(org.OrgMembers, orgs...) {
		result, err = m.isOwnerOrMember(owningOrganization, username, excludelist)
		if result || err != nil {
			return
		}
	}

	return
}

//OrganizationIsMember checks if organization2 is a member of organization1
func (m *Manager) OrganizationIsMember(globalID, organization string) (ismember bool, err error) {
	matches, err := m.collection.Find(bson.M{"globalid": globalID, "orgmembers": organization}).Count()
	ismember = (matches > 0)
	return
}

//OrganizationIsPartOf checks if organization2 is a member or an owner of organization1
func (m *Manager) OrganizationIsPartOf(globalID, organization string) (bool, error) {
	condition := []interface{}{
		bson.M{"orgmembers": organization},
		bson.M{"orgowners": organization},
	}
	qry := []interface{}{
		bson.M{"globalid": globalID},
		bson.M{"$or": condition},
	}
	occurrences, err := m.collection.Find(bson.M{"$and": qry}).Count()
	return occurrences == 1, err
}

// AllByUser get organizations for certain user.
func (m *Manager) AllByUser(username string) ([]Organization, error) {
	var organizations []Organization
	//TODO: handle this a bit smarter, select only the ones where the user is owner first, and take select only the org name
	//do the same for the orgs where the username is member but not owners
	//No need to pull in 1000's of records for this

	condition := []interface{}{
		bson.M{"members": username},
		bson.M{"owners": username},
	}

	err := m.collection.Find(bson.M{"$or": condition}).All(&organizations)

	return organizations, err
}

// AllByUserChain returns all organizations where the user is involved, explicitly or implicit
func (m *Manager) AllByUserChain(username string) ([]string, error) {
	var ownedOrgs []string

	// Get organization names where this user is an explicit owner or member
	userOrgs, err := m.AllByUser(username)
	if err != nil {
		if err != mgo.ErrNotFound {
			return nil, err
		}
		err = nil
	}

	// Now load all suborganizations to account for owner- and member-heritance
	var suborganizations []Organization
	for _, org := range userOrgs {
		orgs, err := m.GetSubOrganizations(org.Globalid)
		if err != nil {
			if err != mgo.ErrNotFound {
				return nil, err
			}
			err = nil
		}
		suborganizations = append(suborganizations, orgs...)
	}

	newOrgsFound := true
	var orgs []string

	var parentOrgs []string

	// We only want the globalids. Also remove possible duplicates
	for _, org := range append(userOrgs, suborganizations...) {
		exists := false
		for _, value := range orgs {
			if org.Globalid == value {
				exists = true
				break
			}
		}
		if !exists {
			orgs = append(orgs, org.Globalid)
		}
	}

	// Copy the elements in the slice
	for _, org := range orgs {
		ownedOrgs = append(ownedOrgs, org)
	}

	var orgsFoundThisIteration []string

	// while we find new organizations
	for newOrgsFound {

		// Get the organizations where our currently know organizations are owners or members.
		for _, org := range orgs {
			ownedbyorg, err := m.AllByOrg(org)
			if err != nil {
				if err != mgo.ErrNotFound {
					return nil, err
				}
				err = nil
			}
			for _, obOrg := range ownedbyorg {
				alreadyFound := false
				for _, knownOrg := range ownedOrgs {
					if obOrg.Globalid == knownOrg {
						alreadyFound = true
						break
					}
				}
				if !alreadyFound {
					ownedOrgs = append(ownedOrgs, obOrg.Globalid)
					orgs = append(orgs, obOrg.Globalid)
					orgsFoundThisIteration = append(orgsFoundThisIteration, obOrg.Globalid)
				}
			}
		}

		// Now get the subOrganizations we haven't discovered yet
		for _, org := range orgsFoundThisIteration {
			subOrgs, err := m.GetSubOrganizations(org)
			if err != nil {
				if err != mgo.ErrNotFound {
					return nil, err
				}
				err = nil
			}
			for _, subOrg := range subOrgs {
				alreadyFound := false
				for _, knownOrg := range ownedOrgs {
					if subOrg.Globalid == knownOrg {
						alreadyFound = true
						break
					}
				}
				if !alreadyFound {
					ownedOrgs = append(ownedOrgs, subOrg.Globalid)
					orgs = append(orgs, subOrg.Globalid)
					orgsFoundThisIteration = append(orgsFoundThisIteration, subOrg.Globalid)
				}
			}
		}

		// Get parent orgs
		for _, possibleChild := range orgs {
			subOrgSeperator := strings.LastIndex(possibleChild, ".")
			for subOrgSeperator > 0 {
				alreadyFoud := false
				for _, parentOrg := range parentOrgs {
					if parentOrg == possibleChild[:subOrgSeperator] {
						alreadyFoud = true
						break
					}
				}
				if !alreadyFoud {
					for _, knownOrg := range ownedOrgs {
						if knownOrg == possibleChild[:subOrgSeperator] {
							alreadyFoud = true
							break
						}
					}
				}
				if !alreadyFoud {
					parentOrgs = append(parentOrgs, possibleChild[:subOrgSeperator])
				}
				subOrgSeperator = strings.LastIndex(possibleChild[:subOrgSeperator], ".")
			}
		}

		// Get orgs where parentorgs are owner or member and parentorgs are on the includechildren list.
		for _, parentOrg := range parentOrgs {
			includedOrgs, err := m.AllByOrg(parentOrg)
			if err != nil {
				if err != mgo.ErrNotFound {
					return nil, err
				}
				err = nil
			}
			for _, includedOrg := range includedOrgs {
				alreadyFound := false
				for _, org := range ownedOrgs {
					if includedOrg.Globalid == org {
						alreadyFound = true
						break
					}
				}
				if alreadyFound {
					break
				}
				for _, subOrgsIncludedOf := range includedOrg.IncludeSubOrgsOf {
					if parentOrg == subOrgsIncludedOf {
						ownedOrgs = append(ownedOrgs, includedOrg.Globalid)
						orgs = append(orgs, includedOrg.Globalid)
						orgsFoundThisIteration = append(orgsFoundThisIteration, includedOrg.Globalid)
					}
				}
			}
		}

		newOrgsFound = len(orgsFoundThisIteration) > 0

		// Copy orgsFoundThisIteration to orgs && clear orgsFoundThisIteration
		orgs = []string{}
		for _, org := range orgsFoundThisIteration {
			orgs = append(orgs, org)
		}
		orgsFoundThisIteration = []string{}
	}

	return ownedOrgs, nil
}

// AllByOrg get organizations where certain organization is a member/owner.
func (m *Manager) AllByOrg(globalID string) ([]Organization, error) {
	var organizations []Organization
	//TODO: handle this a bit smarter, select only the ones where the user is owner first, and take select only the org name
	//do the same for the orgs where the username is member but not owners
	//No need to pull in 1000's of records for this

	condition := []interface{}{
		bson.M{"orgmembers": globalID},
		bson.M{"orgowners": globalID},
	}

	err := m.collection.Find(bson.M{"$or": condition}).All(&organizations)

	return organizations, err
}

// Get organization by ID.
func (m *Manager) Get(id string) (*Organization, error) {
	var organization Organization

	objectID := bson.ObjectIdHex(id)

	if err := m.collection.FindId(objectID).One(&organization); err != nil {
		return nil, err
	}

	return &organization, nil
}

// GetByName gets an organization by Name.
func (m *Manager) GetByName(globalID string) (organization *Organization, err error) {
	err = m.collection.Find(bson.M{"globalid": globalID}).One(&organization)
	// Check if organization isnt a nullpointer in case no org was found with this globalID
	if organization != nil && organization.RequiredScopes == nil {
		organization.RequiredScopes = []RequiredScope{}
	}
	return
}

func (m *LogoManager) GetByName(globalID string) (organization *Organization, err error) {
	err = m.collection.Find(bson.M{"globalid": globalID}).One(&organization)
	return
}

// Exists checks if an organization exists.
func (m *Manager) Exists(globalID string) bool {
	count, _ := m.collection.Find(bson.M{"globalid": globalID}).Count()

	return count == 1
}

// Exists checks if an organization and logo entry exists.
func (m *LogoManager) Exists(globalID string) bool {
	count, _ := m.collection.Find(bson.M{"globalid": globalID}).Count()

	return count == 1
}

// Exists checks if an organization - user combination entry exists.
func (m *Last2FAManager) Exists(globalID string, username string) bool {
	condition := []interface{}{
		bson.M{"globalid": globalID},
		bson.M{"username": username},
	}
	count, _ := m.collection.Find(bson.M{"$and": condition}).Count()

	return count == 1
}

// Create a new organization.
func (m *Manager) Create(organization *Organization) error {
	// TODO: Validation!

	err := m.collection.Insert(organization)
	if mgo.IsDup(err) {
		return db.ErrDuplicate
	}
	return err
}

// Create a new organization entry in the organization logo collection
func (m *LogoManager) Create(organization *Organization) error {
	var orgLogo OrganizationLogo

	orgLogo.Globalid = organization.Globalid

	err := m.collection.Insert(orgLogo)
	if mgo.IsDup(err) {
		return db.ErrDuplicate
	}
	return err
}

// Save an organization.
func (m *Manager) Save(organization *Organization) error {
	// TODO: Validation!

	// TODO: Save
	return errors.New("Save is not implemented yet")
}

// SaveMember save or update member
func (m *Manager) SaveMember(organization *Organization, username string) error {
	return m.collection.Update(
		bson.M{"globalid": organization.Globalid},
		bson.M{"$addToSet": bson.M{"members": username}})
}

// RemoveMember remove member
func (m *Manager) RemoveMember(organization *Organization, username string) error {
	return m.collection.Update(
		bson.M{"globalid": organization.Globalid},
		bson.M{"$pull": bson.M{"members": username}})
}

// SaveOwner save or update owners
func (m *Manager) SaveOwner(organization *Organization, owner string) error {
	return m.collection.Update(
		bson.M{"globalid": organization.Globalid},
		bson.M{"$addToSet": bson.M{"owners": owner}})
}

// RemoveOwner remove owner
func (m *Manager) RemoveOwner(organization *Organization, owner string) error {
	return m.collection.Update(
		bson.M{"globalid": organization.Globalid},
		bson.M{"$pull": bson.M{"owners": owner}})
}

// SaveOrgMember save or update organization member
func (m *Manager) SaveOrgMember(organization *Organization, organizationID string) error {
	return m.collection.Update(
		bson.M{"globalid": organization.Globalid},
		bson.M{"$addToSet": bson.M{"orgmembers": organizationID}})
}

// RemoveOrgMember remove organization member
func (m *Manager) RemoveOrgMember(organization *Organization, organizationID string) error {
	return m.collection.Update(
		bson.M{"globalid": organization.Globalid},
		bson.M{"$pull": bson.M{"orgmembers": organizationID}})
}

// SaveOrgOwner save or update owners
func (m *Manager) SaveOrgOwner(organization *Organization, organizationID string) error {
	return m.collection.Update(
		bson.M{"globalid": organization.Globalid},
		bson.M{"$addToSet": bson.M{"orgowners": organizationID}})
}

// RemoveOrgOwner remove owner
func (m *Manager) RemoveOrgOwner(organization *Organization, organizationID string) error {
	return m.collection.Update(
		bson.M{"globalid": organization.Globalid},
		bson.M{"$pull": bson.M{"orgowners": organizationID}})
}

// AddIncludeSubOrgOf adds an organization to the list of orgs who's suborgs are included in the owner/member hierarchy
func (m *Manager) AddIncludeSubOrgOf(globalId, orgMemberId string) error {
	return m.collection.Update(
		bson.M{"globalid": globalId},
		bson.M{"$addToSet": bson.M{"includesuborgsof": orgMemberId}})
}

// RemoveIncludeSubOrgOf removes an organization from the list of orgs who's suborgs are included in the owner/member hierarchy
func (m *Manager) RemoveIncludeSubOrgOf(globalId, orgMemberId string) error {
	return m.collection.Update(
		bson.M{"globalid": globalId},
		bson.M{"$pull": bson.M{"includesuborgsof": orgMemberId}})
}

func (m *Manager) AddDNS(organization *Organization, dnsName string) error {
	return m.collection.Update(
		bson.M{"globalid": organization.Globalid},
		bson.M{"$addToSet": bson.M{"dns": dnsName}})
}

func (m *Manager) UpdateDNS(organization *Organization, oldDNSName string, newDNSName string) error {
	err := m.collection.Update(
		bson.M{"globalid": organization.Globalid},
		bson.M{"$pull": bson.M{"dns": oldDNSName}})
	if err != nil {
		return err
	}
	return m.collection.Update(
		bson.M{"globalid": organization.Globalid},
		bson.M{"$addToSet": bson.M{"dns": newDNSName}})
}

// RemoveDNS remove DNS
func (m *Manager) RemoveDNS(organization *Organization, dns string) error {
	return m.collection.Update(
		bson.M{"globalid": organization.Globalid},
		bson.M{"$pull": bson.M{"dns": dns}})
}

// Remove removes the organization
func (m *Manager) Remove(globalid string) error {
	return m.collection.Remove(bson.M{"globalid": globalid})
}

// Remove the organization logo
func (m *LogoManager) Remove(globalid string) error {
	return m.collection.Remove(bson.M{"globalid": globalid})
}

// Remove the Last2FA entries for this organization
func (m *Last2FAManager) RemoveByOrganization(globalid string) error {
	_, err := m.collection.RemoveAll(bson.M{"globalid": globalid})
	return err
}

//Remove the Last2FA entries for this user
func (m *Last2FAManager) RemoveByUser(username string) error {
	_, err := m.collection.RemoveAll(bson.M{"username": username})
	return err
}

// Remove removes the organization descriptions
func (m *DescriptionManager) Remove(globalid string) error {
	return m.collection.Remove(bson.M{"globalid": globalid})
}

// UpdateMembership Updates a user his role in an organization
func (m *Manager) UpdateMembership(globalid string, username string, oldrole string, newrole string) error {
	qry := bson.M{"globalid": globalid}
	pull := bson.M{
		"$pull": bson.M{oldrole: username},
	}
	push := bson.M{
		"$addToSet": bson.M{newrole: username},
	}
	err := m.collection.Update(qry, pull)
	if err != nil {
		return err
	}
	return m.collection.Update(qry, push)
}

// UpdateOrgMembership Updates an organization role in another organization
func (m *Manager) UpdateOrgMembership(globalid string, organization string, oldrole string, newrole string) error {
	qry := bson.M{"globalid": globalid}
	pull := bson.M{
		"$pull": bson.M{oldrole: organization},
	}
	push := bson.M{
		"$addToSet": bson.M{newrole: organization},
	}
	err := m.collection.Update(qry, pull)
	if err != nil {
		return err
	}
	return m.collection.Update(qry, push)
}

// CountByUser counts the amount of organizations by user
func (m *Manager) CountByUser(username string) (int, error) {
	qry := bson.M{"owners": username}
	return m.collection.Find(qry).Count()
}

// CountByOrganization counts the amount of organizations where the organization is an owner
func (m *Manager) CountByOrganization(organization string) (int, error) {
	qry := bson.M{"orgowners": organization}
	return m.collection.Find(qry).Count()
}

// RemoveUser Removes a user from an organization
func (m *Manager) RemoveUser(globalID string, username string) error {
	qry := bson.M{"globalid": globalID}
	update := bson.M{"$pull": bson.M{"owners": username, "members": username}}
	return m.collection.Update(qry, update)
}

// RemoveOrganization Removes an organization as member or owner from another organization
func (m *Manager) RemoveOrganization(globalID string, organization string) error {
	qry := bson.M{"globalid": globalID}
	update := bson.M{"$pull": bson.M{"orgowners": organization, "orgmembers": organization}}
	return m.collection.Update(qry, update)
}

// GetValidity gets the 2FA validity duration in seconds
func (m *Manager) GetValidity(globalID string) (int, error) {
	var org *Organization
	err := m.collection.Find(bson.M{"globalid": globalID}).One(&org)
	seconds := org.SecondsValidity
	if seconds == -1 { //special value to avoid confusion with mongo null
		return 0, err
	} else if seconds == 0 { //mongo null for int field, use default duration
		return 3600 * 24 * 7, err //7 days default duration
	} else {
		return seconds, err
	}
}

func (m *Manager) SetValidity(globalID string, secondsDuration int) error {
	if secondsDuration == 0 {
		secondsDuration = -1 //assign -1 if duration should be zero to avoid confusion with mongo null
	}
	return m.collection.Update(
		bson.M{"globalid": globalID},
		bson.M{"$set": bson.M{"secondsvalidity": secondsDuration}})
}

// SaveLogo save or update logo
func (m *LogoManager) SaveLogo(globalID string, logo string) (*mgo.ChangeInfo, error) {
	return m.collection.Upsert(
		bson.M{"globalid": globalID},
		bson.M{"$set": bson.M{"logo": logo}})
}

// GetLogo Gets the logo from an organization
func (m *LogoManager) GetLogo(globalID string) (string, error) {
	var org *OrganizationLogo
	err := m.collection.Find(bson.M{"globalid": globalID}).One(&org)
	if err != nil {
		return "", err
	}
	return org.Logo, err
}

// RemoveLogo Removes the logo from an organization
func (m *LogoManager) RemoveLogo(globalID string) error {
	qry := bson.M{"globalid": globalID}
	update := bson.M{"$unset": bson.M{"logo": 1}}
	return m.collection.Update(qry, update)
}

// SetLast2FA Set the last successful 2FA time
func (m *Last2FAManager) SetLast2FA(globalID string, username string) error {
	now := time.Now()
	condition := []interface{}{
		bson.M{"globalid": globalID},
		bson.M{"username": username},
	}
	_, err := m.collection.Upsert(
		bson.M{"$and": condition},
		bson.M{"$set": bson.M{"last2fa": now}})
	return err
}

// GetLast2FA Gets the date of the last successful 2FA login, if no failed login attempts have occurred since then
func (m *Last2FAManager) GetLast2FA(globalID string, username string) (db.DateTime, error) {
	var l2fa *UserLast2FALogin
	condition := []interface{}{
		bson.M{"globalid": globalID},
		bson.M{"username": username},
	}
	err := m.collection.Find(bson.M{"$and": condition}).One(&l2fa)
	return l2fa.Last2FA, err
}

// RemoveLast2FA Removes the entry of the last successful 2FA login for this organization - user combination
func (m *Last2FAManager) RemoveLast2FA(globalID string, username string) error {
	condition := []interface{}{
		bson.M{"globalid": globalID},
		bson.M{"username": username},
	}
	return m.collection.Remove(bson.M{"$and": condition})
}

// AddRequiredScope adds a required scope
func (m *Manager) AddRequiredScope(globalId string, requiredScope RequiredScope) error {
	qry := bson.M{"globalid": globalId}
	update := bson.M{"$push": bson.M{"requiredscopes": requiredScope}}
	return m.collection.Update(qry, update)
}

// UpdateRequiredScope updates a required scope
func (m *Manager) UpdateRequiredScope(globalId string, oldRequiredScope string, newRequiredScope RequiredScope) error {
	qry := bson.M{
		"globalid":             globalId,
		"requiredscopes.scope": oldRequiredScope,
	}
	update := bson.M{
		"$set": bson.M{
			"requiredscopes.$": newRequiredScope,
		},
	}
	return m.collection.Update(qry, update)
}

// DeleteRequiredScope deletes a required scope
func (m *Manager) DeleteRequiredScope(globalId string, requiredScope string) error {
	return m.collection.Update(bson.M{"globalid": globalId},
		bson.M{"$pull": bson.M{"requiredscopes": bson.M{"scope": requiredScope}}})
}

func (m *Manager) ListByUserOrGlobalID(username string, globalIds []string) (error, []Organization) {
	var organizations []Organization
	qry := bson.M{
		"$or": []bson.M{
			{"owners": username},
			{"members": username},
			{"globalid": bson.M{
				"$in": globalIds},
			},
		},
	}
	err := m.collection.Find(qry).All(&organizations)
	return err, organizations
}

// SaveDescription saves a description for an organization
func (m *DescriptionManager) SaveDescription(globalId string, text LocalizedInfoText) error {
	_, err := m.collection.Upsert(bson.M{"globalid": globalId}, bson.M{"$addToSet": bson.M{"infotexts": text}})
	return err
}

// UpdateDescription updates a description for an organization
func (m *DescriptionManager) UpdateDescription(globalId string, text LocalizedInfoText) error {
	err := m.collection.Update(bson.M{"globalid": globalId}, bson.M{"$pull": bson.M{"infotexts": bson.M{"langkey": text.LangKey}}})
	if err != nil {
		return err
	}
	_, err = m.collection.Upsert(bson.M{"globalid": globalId}, bson.M{"$addToSet": bson.M{"infotexts": text}})
	return err
}

// DeleteDescription deletes a (translated) description for an organization
func (m *DescriptionManager) DeleteDescription(globalId, langKey string) error {
	return m.collection.Update(bson.M{"globalid": globalId}, bson.M{"$pull": bson.M{"infotexts": bson.M{"langkey": langKey}}})
}

// GetDescription get all descriptions for an organization
func (m *DescriptionManager) GetDescription(globalId string) (OrganizationInfoText, error) {
	var info OrganizationInfoText
	err := m.collection.Find(bson.M{"globalid": globalId}).One(&info)
	return info, err
}


text:
Material Design

Based on Google Material design

Material Design for Bootstrap is a theme for Bootstrap 3 which lets you use the new
            Google Material Design in your favorite front-end framework.

If you like this project you can support me by donating something on Gittip, starring this repository, or
            reporting bugs and ideas.

Read more about Material Design for Bootstrap
            at the Github page.

            file_download
            DOWNLOAD

            favorite_border
            GITTIP

            info_outline
            ISSUES

redpajama_set_name: RedPajamaGithub


text:
package com.microsoft.azure.management.appconfiguration.v2019_11_01_preview.implementation;

import com.microsoft.azure.management.appconfiguration.v2019_11_01_preview.KeyValue;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import org.joda.time.DateTime;
import java.util.Map;

class KeyValueImpl extends WrapperImpl<KeyValueInner> implements KeyValue {
    private final AppConfigurationManager manager;
    KeyValueImpl(KeyValueInner inner, AppConfigurationManager manager) {
        super(inner);
        this.manager = manager;
    }

    @Override
    public AppConfigurationManager manager() {
        return this.manager;
    }

    @Override
    public String contentType() {
        return this.inner().contentType();
    }

    @Override
    public String eTag() {
        return this.inner().eTag();
    }

    @Override
    public String keyVal() {
        return this.inner().key();
    }

    @Override
    public String label() {
        return this.inner().label();
    }

    @Override
    public DateTime lastModified() {
        return this.inner().lastModified();
    }

    @Override
    public Boolean locked() {
        return this.inner().locked();
    }

    @Override
    public Map<String, String> tags() {
        return this.inner().tags();
    }

    @Override
    public String value() {
        return this.inner().value();
    }

}


text:
declare -a CT_SERVER_PIDS
CT_SERVERS=
CT_CFG=
CT_LIFECYCLE_CFG=
CT_COMBINED_CFG=
PROMETHEUS_CFGDIR=

# ct_prep_test prepares a set of running processes for a CT test.
# Parameters:
#   - number of log servers to run
#   - number of log signers to run
#   - number of CT personality instances to run
# Populates:
#  - CT_SERVERS         : list of HTTP addresses (comma separated)
#  - CT_SERVER_1        : first HTTP address
#  - CT_METRICS_SERVERS : list of HTTP addresses (comma separated) serving metrics
#  - CT_SERVER_PIDS     : bash array of CT HTTP server pids
# in addition to the variables populated by log_prep_test.
# If etcd and Prometheus are configured, it also populates:
#  - ETCDISCOVER_PID   : pid of etcd service watcher
#  - PROMETHEUS_PID    : pid of local Prometheus server
#  - PROMETHEUS_CFGDIR : Prometheus configuration directory
ct_prep_test() {
  # Default to one of everything.
  local rpc_server_count=${1:-1}
  local log_signer_count=${2:-1}
  local http_server_count=${3:-1}

  echo "Launching core Trillian log components"
  log_prep_test "${rpc_server_count}" "${log_signer_count}"

  echo "Building CT personality code"
  go build ${GOFLAGS} github.com/google/certificate-transparency-go/trillian/ctfe/ct_server

  echo "Provisioning logs for CT"
  ct_provision "${RPC_SERVER_1}"

  echo "Launching CT personalities"
  for ((i=0; i < http_server_count; i++)); do
    local port=$(pick_unused_port)
    CT_SERVERS="${CT_SERVERS},localhost:${port}"
    local metrics_port=$(pick_unused_port ${port})
    CT_METRICS_SERVERS="${CT_METRICS_SERVERS},localhost:${metrics_port}"
    if [[ $i -eq 0 ]]; then
      CT_SERVER_1="localhost:${port}"
    fi

    echo "Starting CT HTTP server on localhost:${port}, metrics on localhost:${metrics_port}"
    ./ct_server ${ETCD_OPTS} --log_config="${CT_COMBINED_CFG}" --log_rpc_server="${RPC_SERVERS}" --http_endpoint="localhost:${port}" --metrics_endpoint="localhost:${metrics_port}" &
    pid=$!
    CT_SERVER_PIDS+=(${pid})
    wait_for_server_startup ${port}
  done
  CT_SERVERS="${CT_SERVERS:1}"
  CT_METRICS_SERVERS="${CT_METRICS_SERVERS:1}"

  if [[ ! -z "${ETCD_OPTS}" ]]; then
    echo "Registered HTTP endpoints"
    ETCDCTL_API=3 etcdctl get trillian-ctfe-http/ --prefix
    ETCDCTL_API=3 etcdctl get trillian-ctfe-metrics-http/ --prefix
  fi

  if [[ -x "${PROMETHEUS_DIR}/prometheus" ]]; then
    if [[ ! -z "${ETCD_OPTS}" ]]; then
        PROMETHEUS_CFGDIR="$(mktemp -d ${TMPDIR}/ct-prometheus-XXXXXX)"
        local prom_cfg="${PROMETHEUS_CFGDIR}/config.yaml"
        local etcdiscovered="${PROMETHEUS_CFGDIR}/trillian.json"
        sed "s!@ETCDISCOVERED@!${etcdiscovered}!" ${GOPATH}/src/github.com/google/certificate-transparency-go/trillian/integration/prometheus.yml > "${prom_cfg}"
        echo "Prometheus configuration in ${prom_cfg}:"
        cat ${prom_cfg}

        echo "Building etcdiscover"
        go build github.com/google/trillian/monitoring/prometheus/etcdiscover

        echo "Launching etcd service monitor updating ${etcdiscovered}"
        ./etcdiscover ${ETCD_OPTS} --etcd_services=trillian-ctfe-metrics-http,trillian-logserver-http,trillian-logsigner-http -target=${etcdiscovered} --logtostderr &
        ETCDISCOVER_PID=$!
        echo "Launching Prometheus (default location localhost:9090)"
        ${PROMETHEUS_DIR}/prometheus --config.file=${prom_cfg} \
                           --web.console.templates=${GOPATH}/src/github.com/google/certificate-transparency-go/trillian/integration/consoles \
                           --web.console.libraries=${GOPATH}/src/github.com/google/certificate-transparency-go/third_party/prometheus/console_libs &
        PROMETHEUS_PID=$!
    fi
  fi
}

# ct_provision generates a CT configuration file and provisions the trees for it.
# Parameters:
#   - location of admin server instance
# Populates:
#   - CT_CFG           : configuration file for CT integration test
#   - CT_LIFECYCLE_CFG : configuration file for CT lifecycle test
#   - CT_COMBINED_CFG  : the above configs concatenated together
ct_provision() {
  local admin_server="$1"

  # Build config files with absolute paths
  CT_CFG=$(mktemp ${TMPDIR}/ct-XXXXXX)
  sed "s!@TESTDATA@!${GOPATH}/src/github.com/google/certificate-transparency-go/trillian/testdata!" ${GOPATH}/src/github.com/google/certificate-transparency-go/trillian/integration/ct_integration_test.cfg > "${CT_CFG}"

  CT_LIFECYCLE_CFG=$(mktemp ${TMPDIR}/ct-XXXXXX)
  sed "s!@TESTDATA@!${GOPATH}/src/github.com/google/certificate-transparency-go/trillian/testdata!" ${GOPATH}/src/github.com/google/certificate-transparency-go/trillian/integration/ct_lifecycle_test.cfg > "${CT_LIFECYCLE_CFG}"

  echo 'Building createtree'
  go build ${GOFLAGS} github.com/google/trillian/cmd/createtree/

  echo 'Provisioning Integration Logs'
  ct_provision_cfg ${admin_server} ${CT_CFG}
  echo 'Provisioning Lifecycle Logs'
  ct_provision_cfg ${admin_server} ${CT_LIFECYCLE_CFG}

  CT_COMBINED_CFG=$(mktemp ${TMPDIR}/ct-XXXXXX)
  cat ${CT_CFG} ${CT_LIFECYCLE_CFG} > ${CT_COMBINED_CFG}

  echo "CT Integration Configuration in ${CT_CFG}:"
  cat "${CT_CFG}"
  echo "CT Lifeycle Configuration in ${CT_LIFECYCLE_CFG}:"
  cat "${CT_LIFECYCLE_CFG}"
  echo
}

# ct_provision_cfg provisions trees for the logs in a specified config file.
# Parameters:
#   - location of admin server instance
#   - the config file to be provisioned for
ct_provision_cfg() {
  local admin_server="$1"
  local cfg="$2"

  num_logs=$(grep -c '@TREE_ID@' ${cfg})
  for i in $(seq ${num_logs}); do
    # TODO(daviddrysdale): Consider using distinct keys for each log
    tree_id=$(./createtree \
      --admin_server="${admin_server}" \
      --private_key_format=PrivateKey \
      --pem_key_path=${GOPATH}/src/github.com/google/certificate-transparency-go/trillian/testdata/log-rpc-server.privkey.pem \
      --pem_key_password=towel \
      --signature_algorithm=ECDSA)
    echo "Created tree ${tree_id}"
    # Need suffix for sed -i to cope with both GNU and non-GNU (e.g. OS X) sed.
    sed -i'.bak' "1,/@TREE_ID@/s/@TREE_ID@/${tree_id}/" "${cfg}"
    rm -f "${cfg}.bak"
  done
}

# ct_gosmin_config generates a gosmin configuration file.
# Parameters:
#   - CT http server address
# Populates:
#   - GOSMIN_CFG : configuration file for gosmin program.
ct_gosmin_config() {
  local server="$1"

  # Build config file with absolute paths
  GOSMIN_CFG=$(mktemp ${TMPDIR}/gosmin-XXXXXX)
  sed "s/@SERVER@/${server}/" ${GOPATH}/src/github.com/google/certificate-transparency-go/trillian/integration/gosmin.cfg > "${GOSMIN_CFG}"

  echo "gosmin configuration at ${GOSMIN_CFG}:"
  cat "${GOSMIN_CFG}"
  echo
}

# ct_start_gosmin starts a gosmin instance.
# Assumes the following variable is set:
#   - GOSMIN_CFG : config file for gosmin instance.
# Populates:
#   - GOSMIN_PID : pid for gosmin instance.
ct_start_gosmin() {
  go build ${GOFLAGS} github.com/google/certificate-transparency-go/gossip/minimal/gosmin
  ./gosmin --config="${GOSMIN_CFG}" --logtostderr &
  GOSMIN_PID=$!
}

# ct_stop_gosmin closes the running gosmin process for a CT test.
# Assumes the following variable is set:
#   - GOSMIN_PID : pid for gosmin instance.
ct_stop_gosmin() {
  if [[ "${GOSMIN_PID}" != "" ]]; then
    kill_pid ${GOSMIN_PID}
  fi
}

# ct_goshawk_config generates a gosmin configuration file.
# Parameters:
#   - CT http server address
# Populates:
#   - GOSHAWK_CFG : configuration file for gosmin program.
ct_goshawk_config() {
  local server="$1"

  # Build config file with absolute paths
  GOSHAWK_CFG=$(mktemp ${TMPDIR}/goshawk-XXXXXX)
  sed "s/@SERVER@/${server}/" ${GOPATH}/src/github.com/google/certificate-transparency-go/trillian/integration/goshawk.cfg > "${GOSHAWK_CFG}"

  echo "gosmin configuration at ${GOSHAWK_CFG}:"
  cat "${GOSHAWK_CFG}"
  echo
}

# ct_start_goshawk starts a goshawk instance.
# Assumes the following variable is set:
#   - GOSHAWK_CFG : config file for gosmin instance, shared with goshawk.
# Populates:
#   - GOSHAWK_PID : pid for gosmin instance.
ct_start_goshawk() {
  go build ${GOFLAGS} github.com/google/certificate-transparency-go/gossip/minimal/goshawk
  ./goshawk --config="${GOSHAWK_CFG}" --logtostderr &
  GOSHAWK_PID=$!
}

# ct_stop_goshawk closes the running goshawk process for a CT test.
# Assumes the following variable is set:
#   - GOSHAWK_PID : pid for gosmin instance.
ct_stop_goshawk() {
  if [[ "${GOSHAWK_PID}" != "" ]]; then
    kill_pid ${GOSHAWK_PID}
  fi
}

# ct_stop_test closes the running processes for a CT test.
# Assumes the following variables are set, in addition to those needed by logStopTest:
#  - CT_SERVER_PIDS  : bash array of CT HTTP server pids
ct_stop_test() {
  if [[ "${PROMETHEUS_PID}" != "" ]]; then
    kill_pid ${PROMETHEUS_PID}
  fi
  if [[ "${ETCDISCOVER_PID}" != "" ]]; then
    kill_pid ${ETCDISCOVER_PID}
  fi
  for pid in "${CT_SERVER_PIDS[@]}"; do
    echo "Stopping CT HTTP server (pid ${pid})"
    kill_pid ${pid}
  done
  log_stop_test
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Axiom.Core;

namespace Multiverse.Toolbox
{
    public class ColorValue : PropertyValue
    {
        public ColorValue(ColorEx val) :
            base((object)val)
        {
        }

        override public string ToString()
        {
            return ((ColorEx)Value).ToString();
        }

        public ColorEx Parse(string val)
        {
            string commaSeparatedList = val.Substring(1, val.Length - 2);
            int startIndexR = 0;
            int rLength = commaSeparatedList.IndexOf(',');
            int startIndexG = rLength + 1;
            int gLength = commaSeparatedList.IndexOf(',', startIndexG) - startIndexG;
            int startIndexB = startIndexG + gLength + 1;
            int bLength = commaSeparatedList.IndexOf(',', startIndexB) - startIndexB;
            int startIndexA = startIndexB + bLength + 1;
            string r = commaSeparatedList.Substring(startIndexR, rLength);
            string g = commaSeparatedList.Substring(startIndexG, gLength);
            string b = commaSeparatedList.Substring(startIndexB, bLength);
            string a = commaSeparatedList.Substring(startIndexA);
            return new ColorEx(float.Parse(a), float.Parse(r), float.Parse(g), float.Parse(b));
        }

        override public int CompareTo(object val)
        {
            float magnitude1 = ((ColorEx)Value).r + ((ColorEx)Value).g + ((ColorEx)Value).b + ((ColorEx)Value).a;
            float magnitude2 = ((ColorEx)((ColorValue)val).Value).r + ((ColorEx)((ColorValue)val).Value).g + ((ColorEx)((ColorValue)val).Value).b + ((ColorEx)((ColorValue)val).Value).a;
            if(magnitude1 == magnitude2)
            {
                if (((ColorEx)Value).r != ((ColorEx)((ColorValue)val).Value).r)
                {
                    return (int)(((ColorEx)Value).r - ((ColorEx)((ColorValue)val).Value).r);
                }
                if (((ColorEx)Value).g != ((ColorEx)((ColorValue)val).Value).g)
                {
                    return (int)(((ColorEx)Value).g - ((ColorEx)((ColorValue)val).Value).g);
                }
                if (((ColorEx)Value).b != ((ColorEx)((ColorValue)val).Value).b)
                {
                    return (int)(((ColorEx)Value).b - ((ColorEx)((ColorValue)val).Value).b);
                }
                if (((ColorEx)Value).a != ((ColorEx)((ColorValue)val).Value).a)
                {
                    return (int)(((ColorEx)Value).a - ((ColorEx)((ColorValue)val).Value).a);
                }
            }
            else
            {
                return (int)(magnitude1 - magnitude2);
            }
            return 0;
        }

        public ColorEx GetValue()
        {
            return (ColorEx)Value;
        }
    }
}


text:
"""Module containing the various utilities to build Chrome with AFDO.

For a description of AFDO see gcc.gnu.org/wiki/AutoFDO.
"""

import datetime
import os
import re

from chromite.cbuildbot import failures_lib
from chromite.cbuildbot import constants
from chromite.lib import cros_build_lib
from chromite.lib import git
from chromite.lib import gs
from chromite.lib import osutils
from chromite.lib import timeout_util

# AFDO-specific constants.
# Chrome URL where AFDO data is stored.
AFDO_PROD_URL = 'gs://chromeos-prebuilt/afdo-job/canonicals/'
AFDO_TEST_URL = '%s/afdo-job/canonicals/' % constants.TRASH_BUCKET
AFDO_BASE_URL = AFDO_PROD_URL
AFDO_CHROOT_ROOT = os.path.join('%(build_root)s', constants.DEFAULT_CHROOT_DIR)
AFDO_LOCAL_DIR = os.path.join('%(root)s', 'tmp')
AFDO_BUILDROOT_LOCAL = AFDO_LOCAL_DIR % {'root': AFDO_CHROOT_ROOT}
CHROME_ARCH_VERSION = '%(package)s-%(arch)s-%(version)s'
CHROME_PERF_AFDO_FILE = '%s.perf.data' % CHROME_ARCH_VERSION
CHROME_PERF_AFDO_URL = '%s%s.bz2' % (AFDO_BASE_URL, CHROME_PERF_AFDO_FILE)
CHROME_AFDO_FILE = '%s.afdo' % CHROME_ARCH_VERSION
CHROME_AFDO_URL = '%s%s.bz2' % (AFDO_BASE_URL, CHROME_AFDO_FILE)
CHROME_ARCH_RELEASE = '%(package)s-%(arch)s-%(release)s'
LATEST_CHROME_AFDO_FILE = 'latest-%s.afdo' % CHROME_ARCH_RELEASE
LATEST_CHROME_AFDO_URL = AFDO_BASE_URL + LATEST_CHROME_AFDO_FILE
CHROME_DEBUG_BIN = os.path.join('%(root)s',
                                'build/%(board)s/usr/lib/debug',
                                'opt/google/chrome/chrome.debug')
CHROME_DEBUG_BIN_URL = '%s%s.debug.bz2' % (AFDO_BASE_URL, CHROME_ARCH_VERSION)

AFDO_GENERATE_GCOV_TOOL = '/usr/bin/create_gcov'

# regex to find AFDO file for specific architecture within the ebuild file.
CHROME_EBUILD_AFDO_EXP = r'^(?P<bef>AFDO_FILE\["%s"\]=")(?P<name>.*)(?P<aft>")'
# and corresponding replacement string.
CHROME_EBUILD_AFDO_REPL = r'\g<bef>%s\g<aft>'

# How old can the AFDO data be? (in days).
AFDO_ALLOWED_STALE = 7

# TODO(llozano): Figure out exact list of boards/architectures that
# can generate 'perf' suitable for AFDO (with LBR events).
# Set of boards that can generate the AFDO profile (can generate 'perf'
# data with LBR events).
AFDO_DATA_GENERATORS = ('lumpy',)
# Set of boards that are allowed to update the Chrome ebuild with the
# appropriate AFDO file name.
# TODO(llozano): is it possible that the canary build for "falco" be
# executed before the PFQ for lumpy?. Is there a problem with this?
AFDO_EBUILD_UPDATERS = ('lumpy', 'daisy', 'x86-alex')

# For a given architecture, which architecture is used to generate
# the AFDO profile. Some architectures are not able to generate their
# own profile.
AFDO_ARCH_GENERATORS = {'amd64': 'amd64',
                        'arm': 'amd64',
                        'x86': 'amd64'}

AFDO_ALERT_RECIPIENTS = ['chromeos-toolchain@google.com']

class MissingAFDOData(failures_lib.StepFailure):
  """Exception thrown when necessary AFDO data is missing."""

class MissingAFDOMarkers(failures_lib.StepFailure):
  """Exception thrown when necessary ebuild markers for AFDO are missing."""

def CompressAFDOFile(to_compress, buildroot):
  """Compress file used by AFDO process.

  Args:
    to_compress: File to compress.
    buildroot: buildroot where to store the compressed data.

  Returns:
    Name of the compressed data file.
  """
  local_dir = AFDO_BUILDROOT_LOCAL % {'build_root': buildroot}
  dest = os.path.join(local_dir, os.path.basename(to_compress)) + '.bz2'
  cros_build_lib.CompressFile(to_compress, dest)
  return dest

def UncompressAFDOFile(to_decompress, buildroot):
  """Decompress file used by AFDO process.

  Args:
    to_decompress: File to decompress.
    buildroot: buildroot where to store the decompressed data.
  """
  local_dir = AFDO_BUILDROOT_LOCAL % {'build_root': buildroot}
  basename = os.path.basename(to_decompress)
  dest_basename = basename.rsplit('.', 1)[0]
  dest = os.path.join(local_dir, dest_basename)
  cros_build_lib.UncompressFile(to_decompress, dest)
  return dest

def GSUploadIfNotPresent(gs_context, src, dest):
  """Upload a file to GS only if the file does not exist.

  Will not generate an error if the file already exist in GS. It will
  only emit a warning.

  I could use GSContext.Copy(src,dest,version=0) here but it does not seem
  to work for large files. Using GSContext.Exists(dest) instead. See
  crbug.com/395858.

  Args:
    gs_context: GS context instance.
    src: File to copy.
    dest: Destination location.

  Returns:
    True if file was uploaded. False otherwise.
  """
  if gs_context.Exists(dest):
    cros_build_lib.Warning('File %s already in GS', dest)
    return False
  else:
    gs_context.Copy(src, dest, acl='public-read')
    return True

def CheckAFDOPerfData(arch, cpv, buildroot, gs_context):
  """Check whether AFDO perf data exists for the given architecture.

  Check if 'perf' data file for this architecture and release is available
  in GS. If so, copy it into a temp directory in the buildroot.

  Args:
    arch: architecture we're going to build Chrome for.
    cpv: The portage_utilities.CPV object for chromeos-chrome.
    buildroot: buildroot where AFDO data should be stored.
    gs_context: GS context to retrieve data.

  Returns:
    True if AFDO perf data is available. False otherwise.
  """
  # The file name of the perf data is based only in the chrome version.
  # The test case that produces it does not know anything about the
  # revision number.
  # TODO(llozano): perf data filename should include the revision number.
  version_number = cpv.version_no_rev.split('_')[0]
  chrome_spec = {'package': cpv.package,
                 'arch': arch,
                 'version': version_number}
  url = CHROME_PERF_AFDO_URL % chrome_spec
  if not gs_context.Exists(url):
    cros_build_lib.Info('Could not find AFDO perf data')
    return False
  dest_dir = AFDO_BUILDROOT_LOCAL % {'build_root': buildroot}
  dest_path = os.path.join(dest_dir, url.rsplit('/', 1)[1])
  gs_context.Copy(url, dest_path)

  UncompressAFDOFile(dest_path, buildroot)
  cros_build_lib.Info('Found and retrieved AFDO perf data')
  return True

def WaitForAFDOPerfData(cpv, arch, buildroot, gs_context,
                        timeout=constants.AFDO_GENERATE_TIMEOUT):
  """Wait for AFDO perf data to show up (with an appropriate timeout).

  Args:
    arch: architecture we're going to build Chrome for.
    cpv: CPV object for Chrome.
    buildroot: buildroot where AFDO data should be stored.
    gs_context: GS context to retrieve data.
    timeout: How long to wait total, in seconds.

  Returns:
    True if found the AFDO perf data before the timeout expired.
    False otherwise.
  """
  try:
    timeout_util.WaitForReturnTrue(
        CheckAFDOPerfData,
        func_args=(arch, cpv, buildroot, gs_context),
        timeout=timeout, period=constants.SLEEP_TIMEOUT)
  except timeout_util.TimeoutError:
    return False
  return True

def PatchChromeEbuildAFDOFile(ebuild_file, arch_profiles):
  """Patch the Chrome ebuild with the dictionary of {arch: afdo_file} pairs.

  Args:
    ebuild_file: path of the ebuild file within the chroot.
    arch_profiles: {arch: afdo_file} pairs to put into the ebuild.
  """
  original_ebuild = cros_build_lib.FromChrootPath(ebuild_file)
  modified_ebuild = '%s.new' % original_ebuild

  arch_patterns = {}
  arch_repls = {}
  arch_markers = {}
  for arch in arch_profiles.keys():
    arch_patterns[arch] = re.compile(CHROME_EBUILD_AFDO_EXP % arch)
    arch_repls[arch] = CHROME_EBUILD_AFDO_REPL % arch_profiles[arch]
    arch_markers[arch] = False

  with open(original_ebuild, 'r') as original:
    with open(modified_ebuild, 'w') as modified:
      for line in original:
        for arch in arch_profiles.keys():
          matched = arch_patterns[arch].match(line)
          if matched:
            arch_markers[arch] = True
            modified.write(arch_patterns[arch].sub(arch_repls[arch], line))
            break
        else: # line without markers, just copy it.
          modified.write(line)

  for arch, found in arch_markers.iteritems():
    if not found:
      raise MissingAFDOMarkers('Chrome ebuild file does not have appropriate '
                               'AFDO markers for arch %s' % arch)

  os.rename(modified_ebuild, original_ebuild)

def UpdateChromeEbuildAFDOFile(board, arch_profiles):
  """Update chrome ebuild with the dictionary of {arch: afdo_file} pairs.

  Modifies the Chrome ebuild to set the appropriate AFDO file for each
  given architecture. Regenerates the associated Manifest file and
  commits the new ebuild and Manifest.

  Args:
    board: board we are building Chrome for.
    arch_profiles: {arch: afdo_file} pairs to put into the ebuild.
  """
  # Find the Chrome ebuild file.
  equery_prog = 'equery'
  ebuild_prog = 'ebuild'
  if board:
    equery_prog += '-%s' % board
    ebuild_prog += '-%s' % board

  equery_cmd = [equery_prog, 'w', 'chromeos-chrome']
  ebuild_file = cros_build_lib.RunCommand(equery_cmd,
                                          enter_chroot=True,
                                          redirect_stdout=True).output.rstrip()

  # Patch the ebuild file with the names of the available afdo_files.
  PatchChromeEbuildAFDOFile(ebuild_file, arch_profiles)

  # Also patch the 9999 ebuild. This is necessary because the uprev
  # process starts from the 9999 ebuild file and then compares to the
  # current version to see if the uprev is really necessary. We dont
  # want the names of the available afdo_files to show as differences.
  # It also allows developers to do USE=afdo_use when using the 9999
  # ebuild.
  ebuild_9999 = os.path.join(os.path.dirname(ebuild_file),
                             'chromeos-chrome-9999.ebuild')
  PatchChromeEbuildAFDOFile(ebuild_9999, arch_profiles)

  # Regenerate the Manifest file.
  ebuild_gs_dir = None
  # If using the GS test location, pass this location to the
  # chrome ebuild.
  if AFDO_BASE_URL == AFDO_TEST_URL:
    ebuild_gs_dir = {'AFDO_GS_DIRECTORY': AFDO_TEST_URL}
  gen_manifest_cmd = [ebuild_prog,  ebuild_file, 'manifest', '--force']
  cros_build_lib.RunCommand(gen_manifest_cmd, enter_chroot=True,
                            extra_env=ebuild_gs_dir, print_cmd=True)

  ebuild_dir = cros_build_lib.FromChrootPath(os.path.dirname(ebuild_file))
  git.RunGit(ebuild_dir, ['add', 'Manifest'])

  # Check if anything changed compared to the previous version.
  mod_files = ['Manifest', os.path.basename(ebuild_file),
               os.path.basename(ebuild_9999)]
  modifications = git.RunGit(ebuild_dir,
                             ['status', '--porcelain', '--'] + mod_files,
                             capture_output=True, print_cmd=True).output
  if not modifications:
    cros_build_lib.Info('AFDO info for the Chrome ebuild did not change. '
                        'Nothing to commit')
    return

  # If there are changes to ebuild or Manifest, commit them.
  commit_msg = ('"Set {arch: afdo_file} pairs %s and updated Manifest"'
                % arch_profiles)
  git.RunGit(ebuild_dir,
             ['commit', '-m', commit_msg, '--'] + mod_files,
             print_cmd=True)

def VerifyLatestAFDOFile(afdo_release_spec, buildroot, gs_context):
  """Verify that the latest AFDO profile for a release is suitable.

  Find the latest AFDO profile file for a particular release and check
  that it is not too stale. The latest AFDO profile name for a release
  can be found in a file in GS under the name
  latest-chrome-<arch>-<release>.afdo.

  Args:
    afdo_release_spec: architecture and release to find the latest AFDO
        profile for.
    buildroot: buildroot where AFDO data should be stored.
    gs_context: GS context to retrieve data.

  Returns:
    The name of the AFDO profile file if a suitable one was found.
    None otherwise.
  """
  latest_afdo_url = LATEST_CHROME_AFDO_URL % afdo_release_spec

  # Check if latest-chrome-<arch>-<release>.afdo exists.
  latest_detail = None
  if gs_context.Exists(latest_afdo_url):
    latest_detail = gs_context.LSWithDetails(latest_afdo_url)
  if not latest_detail:
    cros_build_lib.Info('Could not find latest AFDO info file %s' %
                        latest_afdo_url)
    return None

  # Verify the AFDO profile file is not too stale.
  mod_date = latest_detail[0][2]
  curr_date = datetime.datetime.now()
  allowed_stale_days = datetime.timedelta(days=AFDO_ALLOWED_STALE)
  if (curr_date - mod_date) > allowed_stale_days:
    cros_build_lib.Info('Found latest AFDO info file %s but it is too old' %
                        latest_afdo_url)
    return None

  # Then get the name of the latest valid AFDO profile file.
  local_dir = AFDO_BUILDROOT_LOCAL % {'build_root': buildroot }
  latest_afdo_file = LATEST_CHROME_AFDO_FILE % afdo_release_spec
  latest_afdo_path = os.path.join(local_dir, latest_afdo_file)
  gs_context.Copy(latest_afdo_url, latest_afdo_path)

  return osutils.ReadFile(latest_afdo_path).strip()

def GetLatestAFDOFile(cpv, arch, buildroot, gs_context):
  """Try to find the latest suitable AFDO profile file.

  Try to find the latest AFDO profile generated for current release
  and architecture. If there is none, check the previous release (mostly
  in case we have just branched).

  Args:
    cpv: cpv object for Chrome.
    arch: architecture for which we are looking for AFDO profile.
    buildroot: buildroot where AFDO data should be stored.
    gs_context: GS context to retrieve data.

  Returns:
    Name of latest suitable AFDO profile file if one is found.
    None otherwise.
  """
  generator_arch = AFDO_ARCH_GENERATORS[arch]
  version_number = cpv.version
  current_release = version_number.split('.')[0]
  afdo_release_spec = {'package': cpv.package,
                       'arch': generator_arch,
                       'release': current_release}
  afdo_file = VerifyLatestAFDOFile(afdo_release_spec, buildroot, gs_context)
  if afdo_file:
    return afdo_file

  # Could not find suitable AFDO file for the current release.
  # Let's see if there is one from the previous release.
  previous_release = str(int(current_release) - 1)
  prev_release_spec = {'package': cpv.package,
                       'arch': generator_arch,
                       'release': previous_release}
  return VerifyLatestAFDOFile(prev_release_spec, buildroot, gs_context)

def GenerateAFDOData(cpv, arch, board, buildroot, gs_context):
  """Generate AFDO profile data from 'perf' data.

  Given the 'perf' profile, generate an AFDO profile using create_gcov.
  It also creates a latest-chrome-<arch>-<release>.afdo file pointing
  to the generated AFDO profile.
  Uploads the generated data to GS for retrieval by the chrome ebuild
  file when doing an 'afdo_use' build.
  It is possible the generated data has previously been uploaded to GS
  in which case this routine will not upload the data again. Uploading
  again may cause verication failures for the ebuild file referencing
  the previous contents of the data.

  Args:
    cpv: cpv object for Chrome.
    arch: architecture for which we are looking for AFDO profile.
    board: board we are building for.
    buildroot: buildroot where AFDO data should be stored.
    gs_context: GS context to retrieve/store data.

  Returns:
    Name of the AFDO profile file generated if successful.
  """
  CHROME_UNSTRIPPED_NAME = 'chrome.unstripped'

  version_number = cpv.version
  afdo_spec = {'package': cpv.package,
               'arch': arch,
               'version': version_number}
  chroot_root = AFDO_CHROOT_ROOT % {'build_root': buildroot }
  local_dir = AFDO_LOCAL_DIR % {'root': chroot_root }
  in_chroot_local_dir = AFDO_LOCAL_DIR % {'root': '' }

  # Upload compressed chrome debug binary to GS for triaging purposes.
  # TODO(llozano): This simplifies things in case of need of triaging
  # problems but is it really necessary?
  debug_bin = CHROME_DEBUG_BIN % {'root': chroot_root,
                                  'board': board }
  comp_debug_bin_path = CompressAFDOFile(debug_bin, buildroot)
  GSUploadIfNotPresent(gs_context, comp_debug_bin_path,
                       CHROME_DEBUG_BIN_URL % afdo_spec)

  # create_gcov demands the name of the profiled binary exactly matches
  # the name of the unstripped binary or it is named 'chrome.unstripped'.
  # So create a symbolic link with the appropriate name.
  local_debug_sym = os.path.join(local_dir, CHROME_UNSTRIPPED_NAME)
  in_chroot_debug_bin = CHROME_DEBUG_BIN % {'root': '', 'board': board }
  osutils.SafeUnlink(local_debug_sym)
  os.symlink(in_chroot_debug_bin, local_debug_sym)

  # Call create_gcov tool to generated AFDO profile from 'perf' profile
  # and upload it to GS. Need to call from within chroot since this tool
  # was built inside chroot.
  debug_sym = os.path.join(in_chroot_local_dir, CHROME_UNSTRIPPED_NAME)
  # The name of the 'perf' file is based only on the version of chrome. The
  # revision number is not included.
  afdo_spec_no_rev = {'package': cpv.package,
                      'arch': arch,
                      'version': cpv.version_no_rev.split('_')[0]}
  perf_afdo_file = CHROME_PERF_AFDO_FILE % afdo_spec_no_rev
  perf_afdo_path = os.path.join(in_chroot_local_dir, perf_afdo_file)
  afdo_file = CHROME_AFDO_FILE % afdo_spec
  afdo_path = os.path.join(in_chroot_local_dir, afdo_file)
  afdo_cmd = [AFDO_GENERATE_GCOV_TOOL,
              '--binary=%s' % debug_sym,
              '--profile=%s' % perf_afdo_path,
              '--gcov=%s' % afdo_path]
  cros_build_lib.RunCommand(afdo_cmd, enter_chroot=True, capture_output=True,
                            print_cmd=True)

  afdo_local_path = os.path.join(local_dir, afdo_file)
  comp_afdo_path = CompressAFDOFile(afdo_local_path, buildroot)
  uploaded_afdo_file = GSUploadIfNotPresent(gs_context, comp_afdo_path,
                                            CHROME_AFDO_URL % afdo_spec)

  if uploaded_afdo_file:
    # Create latest-chrome-<arch>-<release>.afdo pointing to the name
    # of the AFDO profile file and upload to GS.
    current_release = version_number.split('.')[0]
    afdo_release_spec = {'package': cpv.package,
                         'arch': arch,
                         'release': current_release}
    latest_afdo_file = LATEST_CHROME_AFDO_FILE % afdo_release_spec
    latest_afdo_path = os.path.join(local_dir, latest_afdo_file)
    osutils.WriteFile(latest_afdo_path, afdo_file)
    gs_context.Copy(latest_afdo_path,
                    LATEST_CHROME_AFDO_URL % afdo_release_spec,
                    acl='public-read')

  return afdo_file

def CanGenerateAFDOData(board):
  """Does this board has the capability of generating its own AFDO data?."""
  return board in AFDO_DATA_GENERATORS

def CanUpdateEbuildAFDOData(board):
  """Is this board one of the designated to update the chrome ebuild?."""
  return board in AFDO_EBUILD_UPDATERS

def GenerateOrFindAFDOData(cpv, arch, board, buildroot):
  """Generate or find the appropriate AFDO profile for the given architecture.

  For the architectures that can generate a 'perf' tool profile, wait for
  it to be generated by the autotest AFDO_generate and generate an AFDO
  profile for it. In the generation of the 'perf' profile failed, use
  a previously generated AFDO profile that is not too stale.
  For the architectures that cannot generate a 'perf' tool profile, use
  the AFDO profile from another architecture (e.g.: ARM can use a profile
  from AMD64).
  Once we have an adequate AFDO profile, put this information in the
  chrome ebuild.

  Args:
    cpv: cpv object for Chrome.
    arch: architecture for which we are looking for AFDO profile.
    board: board we are building for.
    buildroot: buildroot where AFDO data should be stored.
  """
  if not CanUpdateEbuildAFDOData(board):
    return

  gs_context = gs.GSContext()
  afdo_file = None
  if CanGenerateAFDOData(board):
    # Generation of AFDO could fail for different reasons. Try to be
    # resilient about this and in case of failure just find an
    # older AFDO profile.
    try:
      if WaitForAFDOPerfData(cpv, arch, buildroot, gs_context):
        afdo_file = GenerateAFDOData(cpv, arch, board, buildroot, gs_context)
        assert afdo_file
        cros_build_lib.Info('Generated %s AFDO profile %s',
                            arch, afdo_file)
    # Will let system-exiting exceptions through.
    except Exception:
      cros_build_lib.PrintBuildbotStepWarnings()
      cros_build_lib.Warning('AFDO profile generation failed with exception ',
                             exc_info=True)
  if not afdo_file:
    cros_build_lib.Info('Trying to find previous appropriate AFDO profile')
    afdo_file = GetLatestAFDOFile(cpv, arch, buildroot, gs_context)
    if afdo_file:
      cros_build_lib.Info('Found previous %s AFDO profile %s',
                          arch, afdo_file)
  if not afdo_file:
    raise MissingAFDOData('Could not generate or find appropriate AFDO profile')

  # We found an AFDO profile. Lets put the info in the chrome ebuild.
  UpdateChromeEbuildAFDOFile(board, {arch: afdo_file})


text:
<?php

/**
 * Created by PhpStorm.
 * User: carri_000
 * Date: 23.09.2016
 * Time: 22:29
 */

namespace Pachisi\Exception;

class PachisiException extends \Exception {

}


text:
package com.planet_ink.coffee_mud.Abilities.Common;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class PlayInstrument extends CommonSkill implements Wand.WandUsage
{
	@Override
	public String ID()
	{
		return "PlayInstrument";
	}

	private final static String	localizedName	= CMLib.lang().L("Play Instrument");

	@Override
	public String name()
	{
		return localizedName;
	}

	private static final String[]	triggerStrings	= I(new String[] { "PLAY", "PLAYINSTRUMENT", "PLAYSONG"});

	@Override
	public String supportedResourceString()
	{
		return "MISC";
	}

	@Override
	public String[] triggerStrings()
	{
		return triggerStrings;
	}

	@Override
	public int classificationCode()
	{
		return Ability.ACODE_COMMON_SKILL | Ability.DOMAIN_ARTISTIC;
	}

	@Override
	protected boolean canBeDoneSittingDown()
	{
		return true;
	}

	public PlayInstrument()
	{
		super();
		displayText=L("You are playing...");
		verb=L("playing");
	}

	protected volatile String				lastInstrType	= "";
	protected volatile MusicalInstrument	instrument		= null;

	@Override
	public int getEnchantType()
	{
		return Ability.ACODE_SONG;
	}

	@Override
	public void unInvoke()
	{
		super.unInvoke();
	}

	@Override
	protected String getAlmostDoneMessage()
	{
		return null;
	}

	@Override
	protected String getYouContinueMessage()
	{
		final String sound=(playSound!=null)?CMLib.protocol().msp(playSound,10):"";
		return L("<S-NAME> continue(s) @x1.@x2",verb,sound);
	}

	@Override
	protected String getOthersContinueMessage()
	{
		final String sound=(playSound!=null)?CMLib.protocol().msp(playSound,10):"";
		return L("<S-NAME> continue(s) @x1.@x2",verb,sound);
	}

	protected Map<String,int[]> proficiencies = new Hashtable<String,int[]>();

	@Override
	public void setMiscText(final String text)
	{
		proficiencies.clear();
		final Map<String,String> map= CMParms.parseStrictEQParms(text);
		for(final String key : map.keySet())
			proficiencies.put(key, new int[] {CMath.s_int(map.get(key))});
	}

	@Override
	public String text()
	{
		proficiency();
		final Map<String,String> strMap=new HashMap<String,String>();
		for(final String key : proficiencies.keySet())
			strMap.put(key, ""+proficiencies.get(key)[0]);
		return CMParms.toEqListString(strMap);
	}

	@Override
	public int proficiency()
	{
		final MusicalInstrument instrument = this.instrument;
		if(instrument != null)
		{
			final String typeName = instrument.getInstrumentTypeName();
			final int[] profSave;
			if(proficiencies.size()==0)
			{
				profSave = new int[] {super.proficiency};
				proficiencies.put(typeName, profSave);
			}
			else
			if(!proficiencies.containsKey(typeName))
			{
				profSave = new int[] {0};
				proficiencies.put(typeName, profSave);
			}
			else
				profSave = proficiencies.get(typeName);
			if(lastInstrType.equals(typeName))
				profSave[0] = super.proficiency();
			else
			{
				super.proficiency = profSave[0];
				lastInstrType = typeName;
			}
		}
		return super.proficiency();
	}

	@Override
	public void affectPhyStats(final Physical affected, final PhyStats affectableStats)
	{
		if((affected instanceof MOB)&&(instrument != null))
			affectableStats.addAmbiance("playing "+instrument.name());
		super.affectPhyStats(affected, affectableStats);
	}

	public static boolean usingInstrument(final MusicalInstrument I, final MOB mob)
	{
		if((I==null)||(mob==null))
			return false;
		if(I instanceof Rideable)
		{
			return (((Rideable)I).amRiding(mob)
					&&(mob.fetchFirstWornItem(Wearable.WORN_WIELD)==null)
					&&(mob.fetchHeldItem()==null));
		}
		return mob.isMine(I)&&(!I.amWearingAt(Wearable.IN_INVENTORY));
	}

	@Override
	public boolean tick(final Tickable ticking, final int tickID)
	{
		final Physical affected=this.affected;
		if(!(affected instanceof MOB))
			return false;
		if(tickID==Tickable.TICKID_MOB)
		{
			final MOB mob=(MOB)affected;
			if(!usingInstrument(this.instrument,mob))
			{
				aborted=true;
				unInvoke();
				return false;
			}
			this.activityRoom = mob.location();
		}
		return super.tick(ticking, tickID);
	}

	protected MusicalInstrument getInstrumentPlayed(final MOB mob)
	{
		for(int i=0;i<mob.numItems();i++)
		{
			final Item I=mob.getItem(i);
			if((I!=null)
			&&(I instanceof MusicalInstrument)
			&&(I.container()==null)
			&&(usingInstrument((MusicalInstrument)I,mob)))
			{
				return (MusicalInstrument) I;
			}
		}
		if((mob.riding()!=null)&&(mob.riding() instanceof MusicalInstrument))
			return (MusicalInstrument)mob.riding();
		return null;
	}

	@Override
	public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
	{
		if(super.checkStop(mob, commands))
		{
			final MusicalInstrument target=this.getInstrumentPlayed(mob);
			if((target != null)
			&&(usingInstrument(target, mob))
			&&(mob.fetchEffect(ID())==null))
			{
				final CMMsg msg=CMClass.getMsg(mob,target,this,getActivityMessageType(),null,CMParms.combineQuoted(commands,0),null);
				if(mob.location().okMessage(mob,msg))
					mob.location().send(mob, msg);
			}
			return true;
		}

		if((commands.size()>0)&&(commands.get(0).equalsIgnoreCase("LIST")))
		{
			final StringBuilder str = new StringBuilder(L("You have some musical proficiency with: "));
			if(proficiencies.size()==0)
				str.append(L("Nothing!"));
			else
			{
				for(final String s : proficiencies.keySet())
				{
					str.append(CMStrings.capitalizeAndLower(s)+" ("+proficiencies.get(s)[0]+"%), ");
				}
				str.delete(str.length()-2,str.length());
			}
			commonTell(mob,str.toString());
			return false;
		}

		if(mob.fetchEffect(ID())!=null)
		{
			commonTell(mob,L("You are already playing an instrument.  Use PLAYINSTRUMENT STOP to stop."));
			return false;
		}

		MusicalInstrument target=null;
		if((mob.riding()!=null)&&(mob.riding() instanceof MusicalInstrument))
		{
			if(!usingInstrument((MusicalInstrument)mob.riding(),mob))
			{
				commonTell(mob,L("You need to free your hands to play @x1.",mob.riding().name()));
				return false;
			}
			target=(MusicalInstrument)mob.riding();
		}
		if(target==null)
			target=this.getInstrumentPlayed(mob);
		if(target==null)
		{
			commonTell(mob,L("You need an instrument to play one!"));
			return false;
		}

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;
		this.instrument=target; // necc for the proficiency checks
		verb=L("playing @x1",target.name());
		displayText=L("You are @x1",verb);
		if(!proficiencyCheck(mob,0,auto))
		{
			if(proficiency() < 25)
			{
				verb=L("making foul noises with @x1",target.name());
				displayText=L("You are @x1",verb);
			}
			else
			if(proficiency() < 50)
			{
				verb=L("trying to play @x1 and failing",target.name());
				displayText=L("You are @x1",verb);
			}
			else
			if(proficiency() < 75)
			{
				verb=L("playing @x1, but terribly",target.name());
				displayText=L("You are @x1",verb);
			}
			else
			{
				verb=L("playing @x1 pretty badly",target.name());
				displayText=L("You are @x1",verb);
			}
		}
		else
		if(proficiency() == 100)
		{
			verb=L("playing @x1 beautifully",target.name());
			displayText=L("You are @x1",verb);
		}

		final int duration=30;//getDuration(30,mob,1,3);
		final CMMsg msg=CMClass.getMsg(mob,target,this,getActivityMessageType(),
				L("<S-NAME> start(s) playing <T-NAME>."),CMParms.combineQuoted(commands,0),L("<S-NAME> start(s) playing <T-NAME>."));
		if(mob.location().okMessage(mob,msg))
		{
			instrument = target;
			mob.location().send(mob,msg);
			final PlayInstrument pA = (PlayInstrument)beneficialAffect(mob,mob,asLevel,duration);
			if(pA != null)
			{
				pA.proficiencies = this.proficiencies;
				pA.lastInstrType = this.lastInstrType;
				pA.instrument = this.instrument;
			}
		}
		return true;
	}
}


text:
package com.example.testcamera;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.List;

public class SilentCamera extends Activity {

    private SurfaceView mySurfaceView;
    private Camera myCamera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_camera);

        mySurfaceView = (SurfaceView) findViewById(R.id.mySurfaceView);

        // クリック時のコールバック(リスナ)を設定
        mySurfaceView.setOnClickListener(onSurfaceClickListener);

        SurfaceHolder holder = mySurfaceView.getHolder();

        holder.addCallback(SurfaceCallback);
    }

    private SurfaceHolder.Callback SurfaceCallback = new SurfaceHolder.Callback() {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            myCamera = Camera.open();
            myCamera.setDisplayOrientation(90);

            try {
                myCamera.setPreviewDisplay(holder);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            // 最適なサイズを取得
            // myCameraのパラメータを取得
            Camera.Parameters param = myCamera.getParameters();
            // プレビューで表示できる横幅、縦幅、縦横比を格納
            List<Camera.Size> previewSizes = myCamera.getParameters().getSupportedPreviewSizes();
            Camera.Size optimalSize = getOptimalPreviewSize(previewSizes, width, height);
            param.setPreviewSize(optimalSize.width, optimalSize.height);
            myCamera.setParameters(param);

            myCamera.startPreview();
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            myCamera.release();
            myCamera = null;
        }
    };

    // クリックしたとき
    private View.OnClickListener onSurfaceClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (myCamera != null)
                //オートフォーカス実行、実行時のコールバック設定
                myCamera.autoFocus(autoFocusCallback);
        }
    };

    // フォーカスしたとき
    private Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback() {
        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            // プレビューを一枚切り取る、コールバック設定
            camera.setOneShotPreviewCallback(previewCallback);
        }
    };

    // プレビューを一枚切り取ったとき
    private Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
            int w = camera.getParameters().getPreviewSize().width;
            int h = camera.getParameters().getPreviewSize().height;
            Toast.makeText(getApplicationContext(), "フォーカスが合い画像を切り取りました。" + w, Toast.LENGTH_SHORT).show();

//            Bitmap bmp = BitmapFactory.decodeByteArray(data,0,data.length,null);
            Bitmap bmp = getBitmapImageFromYUV(data, w, h);

            //回転
            Matrix m = new Matrix();
            m.setRotate(90);

            //保存用 bitmap生成
            Bitmap rotated_bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), m, true);

            //保存
            MediaStore.Images.Media.insertImage(getContentResolver(), rotated_bmp, "0000.jpg", null);

        }
    };

    public static Bitmap getBitmapImageFromYUV(byte[] data, int width, int height) {
        YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, width, height, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        yuvimage.compressToJpeg(new Rect(0, 0, width, height), 80, baos);
        byte[] jdata = baos.toByteArray();
        BitmapFactory.Options bitmapFatoryOptions = new BitmapFactory.Options();
        bitmapFatoryOptions.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length, bitmapFatoryOptions);
        return bmp;
    }

    // 最適なサイズを取得
    private Camera.Size getOptimalPreviewSize(List<Camera.Size> previewSizes, int width, int height) {

        final double ASPECT_TOLERANCE = 0.1;

        double targetRatio = (double) height / width; // 画面の縦横比

        if (previewSizes == null) return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = height;

        // サポートされているサイズの中で最も最適なサイズを選ぶ
        for (Camera.Size size : previewSizes) {
            double ratio = (double) size.width / size.height; // プレビューの縦横比
            // 画面とプレビューの縦横比の差が大きい場合続行
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            // 画面とプレビューの縦幅の差が小さいとき
            if (Math.abs(size.height - targetHeight) < minDiff) {
                // 最適なサイズを更新
                optimalSize = size;
                // 最小の縦幅の差を更新
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : previewSizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }
}


text:
using Cake.Common.Tests.Fixtures.Tools;
using Xunit;

namespace Cake.Common.Tests.Unit.Tools.SignTool
{
    public sealed class SignToolResolverTests
    {
        public sealed class TheConstructor
        {
            [Fact]
            public void Should_Throw_If_File_System_Is_Null()
            {
                // Given
                var fixture = new SignToolResolverFixture();
                fixture.FileSystem = null;

                // When
                var result = Record.Exception(() => fixture.Resolve());

                // Then
                Assert.IsArgumentNullException(result, "fileSystem");
            }

            [Fact]
            public void Should_Throw_If_Environment_Is_Null()
            {
                // Given
                var fixture = new SignToolResolverFixture();
                fixture.Environment = null;

                // When
                var result = Record.Exception(() => fixture.Resolve());

                // Then
                Assert.IsArgumentNullException(result, "environment");
            }

            [Fact]
            public void Should_Throw_If_Registry_Is_Null()
            {
                // Given
                var fixture = new SignToolResolverFixture();
                fixture.Registry = null;

                // When
                var result = Record.Exception(() => fixture.Resolve());

                // Then
                Assert.IsArgumentNullException(result, "registry");
            }
        }

        public sealed class TheResolveMethod
        {
            [Theory]
            [InlineData(true)]
            [InlineData(false)]
            public void Should_Return_From_Disc_If_Found(bool is64Bit)
            {
                // Given
                var fixture = new SignToolResolverFixture(is64Bit);
                fixture.GivenThatToolExistInKnownPath();

                // When
                var result = fixture.Resolve();

                // Then
                Assert.NotNull(result);
            }

            [Fact]
            public void Should_Return_From_Registry_If_Found()
            {
                // Given
                var fixture = new SignToolResolverFixture();
                fixture.GivenThatToolHasRegistryKey();

                // When
                var result = fixture.Resolve();

                // Then
                Assert.NotNull(result);
            }

            [Fact]
            public void Should_Throw_If_Not_Found_On_Disc_And_SDK_Registry_Path_Cannot_Be_Resolved()
            {
                // Given
                var fixture = new SignToolResolverFixture();
                fixture.GivenThatNoSdkRegistryKeyExist();

                // When
                var result = Record.Exception(() => fixture.Resolve());

                // Then
                Assert.IsCakeException(result, "Failed to find signtool.exe.");
            }

            [Fact]
            public void Should_Throw_If_SignTool_Cannot_Be_Resolved()
            {
                // Given
                var fixture = new SignToolResolverFixture();

                // When
                var result = Record.Exception(() => fixture.Resolve());

                // Then
                Assert.IsCakeException(result, "Failed to find signtool.exe.");
            }
        }
    }
}


text:
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/cfd20465-d0f8-4a0a-8444-467f5b5f16ad/mini.png)](https://insight.sensiolabs.com/projects/cfd20465-d0f8-4a0a-8444-467f5b5f16ad) [![Slack](https://grav-chat.now.sh/badge.svg)](https://chat.getgrav.org) [![Build Status](https://travis-ci.org/getgrav/grav.svg?branch=develop)](https://travis-ci.org/getgrav/grav) [![OpenCollective](https://opencollective.com/grav/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/grav/sponsors/badge.svg)](#sponsors)

Grav is a **Fast**, **Simple**, and **Flexible**, file-based Web-platform.  There is **Zero** installation required.  Just extract the ZIP archive, and you are already up and running.  It follows similar principles to other flat-file CMS platforms, but has a different design philosophy than most. Grav comes with a powerful **Package Management System** to allow for simple installation and upgrading of plugins and themes, as well as simple updating of Grav itself.

The underlying architecture of Grav is designed to use well-established and _best-in-class_ technologies to ensure that Grav is simple to use and easy to extend. Some of these key technologies include:

* [Twig Templating](http://twig.sensiolabs.org/): for powerful control of the user interface
* [Markdown](http://en.wikipedia.org/wiki/Markdown): for easy content creation
* [YAML](http://yaml.org): for simple configuration
* [Parsedown](http://parsedown.org/): for fast Markdown and Markdown Extra support
* [Doctrine Cache](http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/caching.html): layer for performance
* [Pimple Dependency Injection Container](http://pimple.sensiolabs.org/): for extensibility and maintainability
* [Symfony Event Dispatcher](http://symfony.com/doc/current/components/event_dispatcher/introduction.html): for plugin event handling
* [Symfony Console](http://symfony.com/doc/current/components/console/introduction.html): for CLI interface
* [Gregwar Image Library](https://github.com/Gregwar/Image): for dynamic image manipulation

# Requirements

- PHP 5.5.9 or higher. Check the [required modules list](https://learn.getgrav.org/basics/requirements#php-requirements)
- Check the [Apache](https://learn.getgrav.org/basics/requirements#apache-requirements) or [IIS](https://learn.getgrav.org/basics/requirements#iis-requirements) requirements

# QuickStart

These are the options to get Grav:

### Downloading a Grav Package

You can download a **ready-built** package from the [Downloads page on https://getgrav.org](https://getgrav.org/downloads)

### With Composer

You can create a new project with the latest **stable** Grav release with the following command:

```
$ composer create-project getgrav/grav ~/webroot/grav
```

### From GitHub

1. Clone the Grav repository from [https://github.com/getgrav/grav]() to a folder in the webroot of your server, e.g. `~/webroot/grav`. Launch a **terminal** or **console** and navigate to the webroot folder:
   ```
   $ cd ~/webroot
   $ git clone https://github.com/getgrav/grav.git
   ```

2. Install the **plugin** and **theme dependencies** by using the [Grav CLI application](https://learn.getgrav.org/advanced/grav-cli) `bin/grav`:
   ```
   $ cd ~/webroot/grav
   $ bin/grav install
   ```

Check out the [install procedures](https://learn.getgrav.org/basics/installation) for more information.

# Adding Functionality

You can download [plugins](https://getgrav.org/downloads/plugins) or [themes](https://getgrav.org/downloads/themes) manually from the appropriate tab on the [Downloads page on https://getgrav.org](https://getgrav.org/downloads), but the preferred solution is to use the [Grav Package Manager](https://learn.getgrav.org/advanced/grav-gpm) or `GPM`:

```
$ bin/gpm index
```

This will display all the available plugins and then you can install one or more with:

```
$ bin/gpm install <plugin/theme>
```

# Updating

To update Grav you should use the [Grav Package Manager](https://learn.getgrav.org/advanced/grav-gpm) or `GPM`:

```
$ bin/gpm selfupgrade
```

To update plugins and themes:

```
$ bin/gpm update
```

# Contributing
We appreciate any contribution to Grav, whether it is related to bugs, grammar, or simply a suggestion or improvement.
However, we ask that any contributions follow our simple guidelines in order to be properly received.

All our projects follow the [GitFlow branching model][gitflow-model], from development to release. If you are not familiar with it, there are several guides and tutorials to make you understand what it is about.

You will probably want to get started by installing [this very good collection of git extensions][gitflow-extensions].

What you mainly want to know is that:

- All the main activity happens in the `develop` branch. Any pull request should be addressed only to that branch. We will not consider pull requests made to the `master`.
- It's very well appreciated, and highly suggested, to start a new feature whenever you want to make changes or add functionalities. It will make it much easier for us to just checkout your feature branch and test it, before merging it into `develop`

# Getting Started

* [What is Grav?](https://learn.getgrav.org/basics/what-is-grav)
* [Install](https://learn.getgrav.org/basics/installation) Grav in few seconds
* Understand the [Configuration](https://learn.getgrav.org/basics/grav-configuration)
* Take a peek at our available free [Skeletons](https://getgrav.org/downloads/skeletons)
* If you have questions, jump on our [Slack Room](https://getgrav.org/slack)!
* Have fun!

# Exploring More

* Have a look at our [Basic Tutorial](https://learn.getgrav.org/basics/basic-tutorial)
* Dive into more [advanced](https://learn.getgrav.org/advanced) functions

# Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/grav#backer)]

# Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/grav#sponsor)]

# License

See [LICENSE](LICENSE.txt)

[gitflow-model]: http://nvie.com/posts/a-successful-git-branching-model/
[gitflow-extensions]: https://github.com/nvie/gitflow

# Running Tests

First install the dev dependencies by running `composer update` from the Grav root.
Then `composer test` will run the Unit Tests, which should be always executed successfully on any site.

You can also run a single unit test file, e.g. `composer test tests/unit/Grav/Common/AssetsTest.php`


text:
namespace inet {

namespace visualizer {

NetworkNodeCanvasVisualization::Annotation::Annotation(cFigure *figure, cFigure::Point size) :
    figure(figure),
    size(size)
{
}

NetworkNodeCanvasVisualization::NetworkNodeCanvasVisualization(cModule *networkNode) :
    networkNode(networkNode)
{
    // TODO: determine size from icon
    // const char *icon = networkNode->getDisplayString().getTagArg("i", 0);
    size.x = 40;
    size.y = 40;
}

void NetworkNodeCanvasVisualization::updateAnnotationPositions()
{
    double spacing = 4;
    double totalHeight = 0;
    for (auto annotation : annotations) {
        double dx = -annotation.size.x / 2;
        double dy = -size.y / 2 - spacing - totalHeight - annotation.size.y;
        annotation.figure->setTransform(cFigure::Transform().translate(dx, dy));
        totalHeight += annotation.size.y + spacing;
    }
}

void NetworkNodeCanvasVisualization::addAnnotation(cFigure *figure, cFigure::Point size)
{
    annotations.push_back(Annotation(figure, size));
    addFigure(figure);
    updateAnnotationPositions();
}

void NetworkNodeCanvasVisualization::removeAnnotation(cFigure *figure)
{
    for (auto it = annotations.begin(); it != annotations.end(); it++) {
        if ((*it).figure == figure) {
            annotations.erase(it);
            break;
        }
    }
    removeFigure(figure);
    updateAnnotationPositions();
}

} // namespace visualizer

} // namespace inet