text:
"""
This is a module to check the filesystem for the presence and
permissions of certain files.  It can also be used to correct the
permissions (but not existance) of those files.

Currently only supports Posix systems (with Posixy permissions).
Permission stuff can probably be stubbed out later.
"""
import os
import pwd
import grp

def read_perm_spec(spec):
    """
    Reads a spec like 'rw-r--r--' into a octal number suitable for
    chmod.  That is characters in groups of three -- first group is
    user, second for group, third for other (all other people).  The
    characters are r (read), w (write), and x (executable), though the
    executable can also be s (sticky).  Files in sticky directories
    get the directories permission setting.

    Examples::

      >>> print oct(read_perm_spec('rw-r--r--'))
      0644
      >>> print oct(read_perm_spec('rw-rwsr--'))
      02664
      >>> print oct(read_perm_spec('r-xr--r--'))
      0544
      >>> print oct(read_perm_spec('r--------'))
      0400
    """
    total_mask = 0
    # suid/sgid modes give this mask in user, group, other mode:
    set_bits = (04000, 02000, 0)
    pieces = (spec[0:3], spec[3:6], spec[6:9])
    for i, (mode, set_bit) in enumerate(zip(pieces, set_bits)):
        mask = 0
        read, write, exe = list(mode)
        if read == 'r':
            mask = mask | 4
        elif read != '-':
            raise ValueError, (
                "Character %r unexpected (should be '-' or 'r')"
                % read)
        if write == 'w':
            mask = mask | 2
        elif write != '-':
            raise ValueError, (
                "Character %r unexpected (should be '-' or 'w')"
                % write)
        if exe == 'x':
            mask = mask | 1
        elif exe not in ('s', '-'):
            raise ValueError, (
                "Character %r unexpected (should be '-', 'x', or 's')"
                % exe)
        if exe == 's' and i == 2:
            raise ValueError, (
                "The 'other' executable setting cannot be suid/sgid ('s')")
        mask = mask << ((2-i)*3)
        if exe == 's':
            mask = mask | set_bit
        total_mask = total_mask | mask
    return total_mask

modes = [
    (04000, 'setuid bit',
     'setuid bit: make contents owned by directory owner'),
    (02000, 'setgid bit',
     'setgid bit: make contents inherit permissions from directory'),
    (01000, 'sticky bit',
     'sticky bit: append-only directory'),
    (00400, 'read by owner', 'read by owner'),
    (00200, 'write by owner', 'write by owner'),
    (00100, 'execute by owner', 'owner can search directory'),
    (00040, 'allow read by group members',
     'allow read by group members',),
    (00020, 'allow write by group members',
     'allow write by group members'),
    (00010, 'execute by group members',
     'group members can search directory'),
    (00004, 'read by others', 'read by others'),
    (00002, 'write by others', 'write by others'),
    (00001, 'execution by others', 'others can search directory'),
    ]

exe_bits = [0100, 0010, 0001]
exe_mask = 0111
full_mask = 07777

def mode_diff(filename, mode, **kw):
    """
    Returns the differences calculated using ``calc_mode_diff``
    """
    cur_mode = os.stat(filename).st_mode
    return calc_mode_diff(cur_mode, mode, **kw)

def calc_mode_diff(cur_mode, mode, keep_exe=True,
                   not_set='not set: ',
                   set='set: '):
    """
    Gives the difference between the actual mode of the file and the
    given mode.  If ``keep_exe`` is true, then if the mode doesn't
    include any executable information the executable information will
    simply be ignored.  High bits are also always ignored (except
    suid/sgid and sticky bit).

    Returns a list of differences (empty list if no differences)
    """
    for exe_bit in exe_bits:
        if mode & exe_bit:
            keep_exe = False
    diffs = []
    isdir = os.path.isdir(filename)
    for bit, file_desc, dir_desc in modes:
        if keep_exe and bit in exe_bits:
            continue
        if isdir:
            desc = dir_desc
        else:
            desc = file_desc
        if (mode & bit) and not (cur_mode & bit):
            diffs.append(not_set + desc)
        if not (mode & bit) and (cur_mode & bit):
            diffs.append(set + desc)
    return diffs

def calc_set_mode(cur_mode, mode, keep_exe=True):
    """
    Calculates the new mode given the current node ``cur_mode`` and
    the mode spec ``mode`` and if ``keep_exe`` is true then also keep
    the executable bits in ``cur_mode`` if ``mode`` has no executable
    bits in it.  Return the new mode.

    Examples::

      >>> print oct(calc_set_mode(0775, 0644))
      0755
      >>> print oct(calc_set_mode(0775, 0744))
      0744
      >>> print oct(calc_set_mode(010600, 0644))
      010644
      >>> print oct(calc_set_mode(0775, 0644, False))
      0644
    """
    for exe_bit in exe_bits:
        if mode & exe_bit:
            keep_exe = False
    # This zeros-out full_mask parts of the current mode:
    keep_parts = (cur_mode | full_mask) ^ full_mask
    if keep_exe:
        keep_parts = keep_parts | (cur_mode & exe_mask)
    new_mode = keep_parts | mode
    return new_mode

def set_mode(filename, mode, **kw):
    """
    Sets the mode on ``filename`` using ``calc_set_mode``
    """
    cur_mode = os.stat(filename).st_mode
    new_mode = calc_set_mode(cur_mode, mode, **kw)
    os.chmod(filename, new_mode)

def calc_ownership_spec(spec):
    """
    Calculates what a string spec means, returning (uid, username,
    gid, groupname), where there can be None values meaning no
    preference.

    The spec is a string like ``owner:group``.  It may use numbers
    instead of user/group names.  It may leave out ``:group``.  It may
    use '-' to mean any-user/any-group.

    """
    user = group = None
    uid = gid = None
    if ':' in spec:
        user_spec, group_spec = spec.split(':', 1)
    else:
        user_spec, group_spec = spec, '-'
    if user_spec == '-':
        user_spec = '0'
    if group_spec == '-':
        group_spec = '0'
    try:
        uid = int(user_spec)
    except ValueError:
        uid = pwd.getpwnam(user_spec)
        user = user_spec
    else:
        if not uid:
            uid = user = None
        else:
            user = pwd.getpwuid(uid).pw_name
    try:
        gid = int(group_spec)
    except ValueError:
        gid = grp.getgrnam(group_spec)
        group = group_spec
    else:
        if not gid:
            gid = group = None
        else:
            group = grp.getgrgid(gid).gr_name
    return (uid, user, gid, group)

def ownership_diff(filename, spec):
    """
    Return a list of differences between the ownership of ``filename``
    and the spec given.
    """
    diffs = []
    uid, user, gid, group = calc_ownership_spec(spec)
    st = os.stat(filename)
    if uid and uid != st.st_uid:
        diffs.append('owned by %s (should be %s)' %
                     (pwd.getpwuid(st.st_uid).pw_name, user))
    if gid and gid != st.st_gid:
        diffs.append('group %s (should be %s)' %
                     (grp.getgrgid(st.st_gid).gr_name, group))
    return diffs

def set_ownership(filename, spec):
    """
    Set the ownership of ``filename`` given the spec.
    """
    uid, user, gid, group = calc_ownership_spec(spec)
    st = os.stat(filename)
    if not uid:
        uid = st.st_uid
    if not gid:
        gid = st.st_gid
    os.chmod(filename, uid, gid)

class PermissionSpec(object):
    """
    Represents a set of specifications for permissions.

    Typically reads from a file that looks like this::

      rwxrwxrwx user:group filename

    If the filename ends in /, then it expected to be a directory, and
    the directory is made executable automatically, and the contents
    of the directory are given the same permission (recursively).  By
    default the executable bit on files is left as-is, unless the
    permissions specifically say it should be on in some way.

    You can use 'nomodify filename' for permissions to say that any
    permission is okay, and permissions should not be changed.

    Use 'noexist filename' to say that a specific file should not
    exist.

    Use 'symlink filename symlinked_to' to assert a symlink destination

    The entire file is read, and most specific rules are used for each
    file (i.e., a rule for a subdirectory overrides the rule for a
    superdirectory).  Order does not matter.
    """

    def __init__(self):
        self.paths = {}

    def parsefile(self, filename):
        f = open(filename)
        lines = f.readlines()
        f.close()
        self.parselines(lines, filename=filename)

    commands = {}

    def parselines(self, lines, filename=None):
        for lineindex, line in enumerate(lines):
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            parts = line.split()
            command = parts[0]
            if command in self.commands:
                cmd = self.commands[command](*parts[1:])
            else:
                cmd = self.commands['*'](*parts)
            self.paths[cmd.path] = cmd

    def check(self):
        action = _Check(self)
        self.traverse(action)

    def fix(self):
        action = _Fixer(self)
        self.traverse(action)

    def traverse(self, action):
        paths = self.paths_sorted()
        checked = {}
        for path, checker in list(paths)[::-1]:
            self.check_tree(action, path, paths, checked)
        for path, checker in paths:
            if path not in checked:
                action.noexists(path, checker)

    def traverse_tree(self, action, path, paths, checked):
        if path in checked:
            return
        self.traverse_path(action, path, paths, checked)
        if os.path.isdir(path):
            for fn in os.listdir(path):
                fn = os.path.join(path, fn)
                self.traverse_tree(action, fn, paths, checked)

    def traverse_path(self, action, path, paths, checked):
        checked[path] = None
        for check_path, checker in paths:
            if path.startswith(check_path):
                action.check(check_path, checker)
                if not checker.inherit:
                    break

    def paths_sorted(self):
        paths = self.paths.items()
        paths.sort(lambda a, b: -cmp(len(a[0]), len(b[0])))

class _Rule(object):
    class __metaclass__(type):
        def __new__(meta, class_name, bases, d):
            cls = type.__new__(meta, class_name, bases, d)
            PermissionSpec.commands[cls.__name__] = cls
            return cls

    inherit = False
    def noexists(self):
        return ['Path %s does not exist' % path]

class _NoModify(_Rule):

    name = 'nomodify'

    def __init__(self, path):
        self.path = path

    def fix(self, path):
        pass

class _NoExist(_Rule):

    name = 'noexist'

    def __init__(self, path):
        self.path = path

    def check(self, path):
        return ['Path %s should not exist' % path]

    def noexists(self, path):
        return []

    def fix(self, path):
        # @@: Should delete?
        pass

class _SymLink(_Rule):

    name = 'symlink'
    inherit = True

    def __init__(self, path, dest):
        self.path = path
        self.dest = dest

    def check(self, path):
        assert path == self.path, (
            "_Symlink should only be passed specific path %s (not %s)"
            % (self.path, path))
        try:
            link = os.path.readlink(path)
        except OSError:
            if e.errno != 22:
                raise
            return ['Path %s is not a symlink (should point to %s)'
                    % (path, self.dest)]
        if link != self.dest:
            return ['Path %s should symlink to %s, not %s'
                    % (path, self.dest, link)]
        return []

    def fix(self, path):
        assert path == self.path, (
            "_Symlink should only be passed specific path %s (not %s)"
            % (self.path, path))
        if not os.path.exists(path):
            os.symlink(path, self.dest)
        else:
            # @@: This should correct the symlink or something:
            print 'Not symlinking %s' % path

class _Permission(_Rule):

    name = '*'

    def __init__(self, perm, owner, dir):
        self.perm_spec = read_perm_spec(perm)
        self.owner = owner
        self.dir = dir

    def check(self, path):
        return mode_diff(path, self.perm_spec)

    def fix(self, path):
        set_mode(path, self.perm_spec)

class _Strategy(object):

    def __init__(self, spec):
        self.spec = spec

class _Check(_Strategy):

    def noexists(self, path, checker):
        checker.noexists(path)

    def check(self, path, checker):
        checker.check(path)

class _Fixer(_Strategy):

    def noexists(self, path, checker):
        pass

    def check(self, path, checker):
        checker.fix(path)

if __name__ == '__main__':
    import doctest
    doctest.testmod()


text:
<?php

/** test hello model */
class JobModelTest extends DatabaseTestCase
{
    /** set up tests */
    public function setUp()
    {
        $db = Zend_Registry::get('dbAdapter');
        $configDatabase = Zend_Registry::get('configDatabase');
        if ($configDatabase->database->adapter == 'PDO_PGSQL') {
            $db->query(
                "SELECT setval('remoteprocessing_job_job_id_seq', (SELECT MAX(job_id) FROM remoteprocessing_job)+1);"
            );
        }
        $this->setupDatabase(array('default')); // core dataset
        $this->setupDatabase(array('default'), 'remoteprocessing'); // module dataset
        $this->enabledModules = array('remoteprocessing');
        parent::setUp();
    }

    /** test getRelatedJob($item)*/
    public function testGetRelatedJob()
    {
        /** @var Remoteprocessing_JobModel $jobModel */
        $jobModel = MidasLoader::loadModel('Job', 'remoteprocessing');

        /** @var ItemModel $itemModel */
        $itemModel = MidasLoader::loadModel('Item');

        $item = $itemModel->load(1000);

        $jobs = $jobModel->getRelatedJob($item);
        $this->assertEquals(1, count($jobs));
    }

    /** test getBy */
    public function testGetBy()
    {
        include BASE_PATH.'/modules/remoteprocessing/constant/module.php';

        /** @var Remoteprocessing_JobModel $jobModel */
        $jobModel = MidasLoader::loadModel('Job', 'remoteprocessing');

        $jobs = $jobModel->getBy(
            MIDAS_REMOTEPROCESSING_OS_WINDOWS,
            '',
            '2000-10-26 22:32:58',
            MIDAS_REMOTEPROCESSING_STATUS_WAIT
        );
        $this->assertEquals(1, count($jobs));

        $jobs = $jobModel->getBy(
            MIDAS_REMOTEPROCESSING_OS_LINUX,
            '',
            '2000-10-26 22:32:58',
            MIDAS_REMOTEPROCESSING_STATUS_WAIT
        );
        $this->assertEquals(0, count($jobs));

        $jobs = $jobModel->getBy(
            MIDAS_REMOTEPROCESSING_OS_WINDOWS,
            '',
            '2100-10-26 22:32:58',
            MIDAS_REMOTEPROCESSING_STATUS_WAIT
        );
        $this->assertEquals(0, count($jobs));
    }

    /** test addItemRelation */
    public function testAddItemRelation()
    {
        /** @var Remoteprocessing_JobModel $jobModel */
        $jobModel = MidasLoader::loadModel('Job', 'remoteprocessing');
        $itemsFile = $this->loadData('Item', 'default');
        $jobFile = $this->loadData('Job', 'default', 'remoteprocessing', 'remoteprocessing');

        $jobModel->addItemRelation($jobFile[0], $itemsFile[1]);
        $jobs = $jobModel->getRelatedJob($itemsFile[1]);
        $this->assertEquals(1, count($jobs));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<readable><title>239807547_4923efc821</title><content>
two dogs fight next to rocks
Two dogs playfully wrestle in a rocky setting .
Two dogs playing next to rocks .
two dogs play on the dry ground .
Two dogs sit in the shade and lick each other 's face .
</content></readable>


text:
package fixchain

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"sync"
	"sync/atomic"
	"time"

	"github.com/google/certificate-transparency/go/x509"
)

// Limiter is an interface to allow different rate limiters to be used with the
// Logger.
type Limiter interface {
	Wait()
}

// Logger contains methods to asynchronously log certificate chains to a
// Certificate Transparency log and properties to store information about each
// attempt that is made to post a certificate chain to said log.
type Logger struct {
	url    string
	client *http.Client
	roots  *x509.CertPool
	toPost chan *toPost
	errors chan<- *FixError

	active uint32

	posted        uint32 // How many chains have been queued to be posted.
	reposted      uint32 // How many chains for an already-posted cert have been queued.
	chainReposted uint32 // How many chains have been queued again.

	// Note that wg counts the number of active requests, not
	// active servers, because we can't close it to signal the
	// end, because of retries.
	wg      sync.WaitGroup
	limiter Limiter

	postCertCache  *lockedMap
	postChainCache *lockedMap
}

// IsPosted tells the caller whether a chain for the given certificate has
// already been successfully posted to the log by this Logger.
func (l *Logger) IsPosted(cert *x509.Certificate) bool {
	return l.postCertCache.get(hash(cert))
}

// QueueChain adds the given chain to the queue to be posted to the log.
func (l *Logger) QueueChain(chain []*x509.Certificate) {
	if chain == nil {
		return
	}

	atomic.AddUint32(&l.posted, 1)
	// Has a chain for the cert this chain if for already been successfully
	//posted to the log by this Logger?
	h := hash(chain[0]) // Chains are cert -> root
	if l.postCertCache.get(h) {
		atomic.AddUint32(&l.reposted, 1)
		return // Don't post chain for a cert that has already had a chain posted.
	}
	// If we assume all chains for the same cert are equally
	// likely to succeed, then we could mark the cert as posted
	// here. However, bugs might cause a log to refuse one chain
	// and accept another, so try each unique chain.

	// Has this Logger already tried to post this chain?
	h = hashChain(chain)
	if l.postChainCache.get(h) {
		atomic.AddUint32(&l.chainReposted, 1)
		return
	}
	l.postChainCache.set(h, true)

	p := &toPost{chain: chain, retries: 5}
	l.postToLog(p)
}

// Wait for all of the active requests to finish being processed.
func (l *Logger) Wait() {
	l.wg.Wait()
}

// RootCerts returns the root certificates that the log accepts.
func (l *Logger) RootCerts() *x509.CertPool {
	if l.roots == nil {
		l.roots = l.getRoots()
	}
	return l.roots
}

func (l *Logger) getRoots() *x509.CertPool {
	rootsJSON, err := l.client.Get(l.url + "/ct/v1/get-roots")
	if err != nil {
		log.Fatalf("can't get roots from %s: %s", l.url, err)
	}
	defer rootsJSON.Body.Close()
	if rootsJSON.StatusCode != 200 {
		log.Fatalf("can't deal with status other than 200 from %s: %d", l.url, rootsJSON.StatusCode)
	}
	j, err := ioutil.ReadAll(rootsJSON.Body)
	if err != nil {
		log.Fatalf("can't read roots from %s: %s", l.url, err)
	}
	type Certificates struct {
		Certificates [][]byte
	}
	var certs Certificates
	err = json.Unmarshal(j, &certs)
	if err != nil {
		log.Fatalf("can't parse json (%s) from %s: %s", err, l.url, j)
	}
	ret := x509.NewCertPool()
	for i := 0; i < len(certs.Certificates); i++ {
		r, err := x509.ParseCertificate(certs.Certificates[i])
		switch err.(type) {
		case nil, x509.NonFatalErrors:
			// ignore
		default:
			log.Fatalf("can't parse certificate from %s: %s %#v", l.url, err, certs.Certificates[i])
		}
		ret.AddCert(r)
	}
	return ret
}

type toPost struct {
	chain   []*x509.Certificate
	retries uint8
}

func (l *Logger) postToLog(p *toPost) {
	// Add post to toPost channel in a separate goroutine to avoid deadlock
	// during retries.  Without the separate goroutine, deadlock can occur in
	// the following situation:
	//
	// Suppose there is only one postServer() goroutine running, and it is
	// blocked waiting for a toPost on the toPost chan.  A toPost gets added to
	// the chan, which causes the following to happen:
	// - the postServer takes the toPost from the chan.
	// - the postServer calls l.postChain(toPost), and waits for l.postChain()
	//   to return before going back to the toPost chan for another toPost.
	// - l.postChain() begins execution.  Suppose the first post attempt of the
	//   toPost fails for some network-related reason.
	// - l.postChain retries and calls l.postToLog() to queue up the toPost to
	//   try to post it again.
	// - l.postToLog() tries to put the toPost on the toPost chan, and blocks
	//   until a postServer takes it off the chan.
	// But the one and only postServer is still waiting for l.postChain (and
	// therefore l.postToLog) to return, and will not go to take another toPost
	// off the toPost chan until that happens.
	// Thus, deadlock.
	//
	// Similar situations with multiple postServers can easily be imagined.
	l.wg.Add(1)
	go func() {
		l.toPost <- p
	}()
}

func (l *Logger) postChain(p *toPost) {
	h := hash(p.chain[0])
	if l.postCertCache.get(h) {
		atomic.AddUint32(&l.reposted, 1)
		return
	}

	l.limiter.Wait()
	ferr := PostChainToLog(p.chain, l.client, l.url)
	if ferr != nil {
		switch ferr.Type {
		case PostFailed:
			if p.retries == 0 {
				l.errors <- ferr
			} else {
				log.Printf(ferr.Error.Error())
				p.retries--
				l.postToLog(p)
			}
			return
		case LogPostFailed:
			// If the http error code is 502, we retry.
			// TODO(katjoyce): Are there any other error codes for which the
			// post should be retried?
			if p.retries == 0 || ferr.Code != 502 {
				l.errors <- ferr
			} else {
				p.retries--
				l.postToLog(p)
			}
			return
		default:
			log.Fatalf("Unexpected FixError type: %s", ferr.TypeString())
		}
	}

	// If the post was successful, cache.
	l.postCertCache.set(h, true)
}

func (l *Logger) postServer() {
	for {
		c := <-l.toPost
		atomic.AddUint32(&l.active, 1)
		l.postChain(c)
		atomic.AddUint32(&l.active, ^uint32(0))
		l.wg.Done()
	}
}

func (l *Logger) logStats() {
	t := time.NewTicker(time.Second)
	go func() {
		for _ = range t.C {
			log.Printf("posters: %d active, %d posted, %d reposted, %d chains reposted",
				l.active, l.posted, l.reposted, l.chainReposted)
		}
	}()
}

// NewLogger creates a new asynchronous logger to log chains to the
// Certificate Transparency log at the given url.  It starts up a pool of
// workerCount workers.  Errors are pushed to the errors channel.  client is
// used to post the chains to the log.
func NewLogger(workerCount int, url string, errors chan<- *FixError, client *http.Client, limiter Limiter, logStats bool) *Logger {
	l := &Logger{
		url:            url,
		client:         client,
		errors:         errors,
		toPost:         make(chan *toPost),
		postCertCache:  newLockedMap(),
		postChainCache: newLockedMap(),
		limiter:        limiter,
	}

	// Start post server pool.
	for i := 0; i < workerCount; i++ {
		go l.postServer()
	}

	if logStats {
		l.logStats()
	}
	return l
}


text:
using namespace megamol;
using namespace megamol::protein_calls;

bool megamol::protein_calls::computeRMSF(protein_calls::MolecularDataCall* mol) {
    if (mol == NULL)
        return false;

    // store current frame and calltime
    float currentCallTime = mol->Calltime();
    unsigned int currentFrame = mol->FrameID();

    // load first frame
    mol->SetFrameID(0, true);
    if (!(*mol)(MolecularDataCall::CallForGetData))
        return false;
    // check if atom count is zero
    if (mol->AtomCount() < 1)
        return false;

    // no frames available -> false
    if (mol->FrameCount() < 2)
        return false;

    // allocate mem
    vislib::Array<float> meanPos;
    meanPos.SetCount(mol->AtomCount() * 3);
    float* rmsf;
    rmsf = new float[mol->AtomCount()];
    // initialize rmsf to zero
    for (unsigned int i = 0; i < mol->AtomCount(); i++) {
        rmsf[i] = 0;
    }

    // get atom pos of first frame
    for (unsigned int atomIdx = 0; atomIdx < mol->AtomCount(); atomIdx++) {
        meanPos[atomIdx * 3 + 0] = mol->AtomPositions()[atomIdx * 3 + 0];
        meanPos[atomIdx * 3 + 1] = mol->AtomPositions()[atomIdx * 3 + 1];
        meanPos[atomIdx * 3 + 2] = mol->AtomPositions()[atomIdx * 3 + 2];
    }

    // sum up all atom positions
    for (unsigned int i = 1; i < mol->FrameCount(); i++) {
        // load frame
        mol->SetFrameID(i, true);
        if (!(*mol)(MolecularDataCall::CallForGetData))
            return false;
        // add atom pos
        for (unsigned int atomIdx = 0; atomIdx < mol->AtomCount(); atomIdx++) {
            meanPos[atomIdx * 3 + 0] += mol->AtomPositions()[atomIdx * 3 + 0];
            meanPos[atomIdx * 3 + 1] += mol->AtomPositions()[atomIdx * 3 + 1];
            meanPos[atomIdx * 3 + 2] += mol->AtomPositions()[atomIdx * 3 + 2];
        }
    }
    // compute average pos
    for (unsigned int i = 0; i < meanPos.Count(); i++) {
        meanPos[i] /= static_cast<float>(mol->FrameCount());
    }

    // compute RMSF
    vislib::math::Vector<float, 3> tmpVec;
    float len;
    for (unsigned int i = 0; i < mol->FrameCount(); i++) {
        // load frame
        mol->SetFrameID(i, true);
        if (!(*mol)(MolecularDataCall::CallForGetData))
            return false;
        // get deviation from mean pos for current atom pos
        for (unsigned int atomIdx = 0; atomIdx < mol->AtomCount(); atomIdx++) {
            tmpVec.SetX(mol->AtomPositions()[atomIdx * 3 + 0] - meanPos[atomIdx * 3 + 0]);
            tmpVec.SetY(mol->AtomPositions()[atomIdx * 3 + 1] - meanPos[atomIdx * 3 + 1]);
            tmpVec.SetZ(mol->AtomPositions()[atomIdx * 3 + 2] - meanPos[atomIdx * 3 + 2]);
            len = tmpVec.Length();
            rmsf[atomIdx] += len * len;
        }
    }

    // compute average pos
    float minRMSF = FLT_MAX, maxRMSF = 0.0f;
    for (unsigned int i = 0; i < mol->AtomCount(); i++) {
        rmsf[i] = sqrtf(rmsf[i] / static_cast<float>(mol->FrameCount()));
        minRMSF = rmsf[i] < minRMSF ? rmsf[i] : minRMSF;
        maxRMSF = rmsf[i] > maxRMSF ? rmsf[i] : maxRMSF;
    }

    // restore current frame
    mol->SetCalltime(currentCallTime);
    mol->SetFrameID(currentFrame);
    if (!(*mol)(MolecularDataCall::CallForGetData))
        return false;

    // write RMSF to B-Factor
    mol->SetAtomBFactors(rmsf, true);
    mol->SetBFactorRange(minRMSF, maxRMSF);

    return true;
}


text:
package com.intellij.lang.html.structureView;

import com.intellij.ide.IdeBundle;
import com.intellij.ide.structureView.StructureViewTreeElement;
import com.intellij.ide.structureView.impl.common.PsiTreeElementBase;
import com.intellij.ide.structureView.impl.xml.XmlTagTreeElement;
import com.intellij.navigation.LocationPresentation;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

class HtmlTagTreeElement extends PsiTreeElementBase<XmlTag> implements LocationPresentation {
  static final int MAX_TEXT_LENGTH = 50;

  public HtmlTagTreeElement(final XmlTag tag) {
    super(tag);
  }

  @Override
  @NotNull
  public Collection<StructureViewTreeElement> getChildrenBase() {
    final XmlTag tag = getElement();
    if (tag == null || !tag.isValid()) return Collections.emptyList();

    return ContainerUtil.map2List(tag.getSubTags(), new Function<XmlTag, StructureViewTreeElement>() {
      @Override
      public StructureViewTreeElement fun(final XmlTag subTag) {
        return new HtmlTagTreeElement(subTag);
      }
    });
  }

  @Override
  public String getPresentableText() {
    final XmlTag tag = getElement();
    if (tag == null) {
      return IdeBundle.message("node.structureview.invalid");
    }
    return getTagPresentation(tag);
  }

  @Nullable
  @Override
  public String getLocationString() {
    final XmlTag tag = getElement();
    if (tag == null) {
      return null;
    }

    if (tag.getName().equalsIgnoreCase("img") || tag.getName().equalsIgnoreCase("script")) {
      return getPathDescription(tag.getAttributeValue("src"));
    }
    else if (tag.getName().equalsIgnoreCase("link")) {
      return getPathDescription(tag.getAttributeValue("href"));
    }
    else {
      return StringUtil.nullize(normalizeSpacesAndShortenIfLong(tag.getValue().getTrimmedText()));
    }
  }

  private static String getPathDescription(String src) {
    if (StringUtil.isEmpty(src)) {
      return null;
    }
    else {
      return StringUtil.shortenPathWithEllipsis(src, MAX_TEXT_LENGTH, true);
    }
  }

  @Override
  public boolean isSearchInLocationString() {
    return true;
  }

  public static String getTagPresentation(final @NotNull XmlTag tag) {
    StringBuilder builder = new StringBuilder(tag.getLocalName());

    String id = XmlTagTreeElement.toCanonicalForm(tag.getAttributeValue("id"));
    if (id != null) {
      builder.append('#').append(id);
    }

    String classValue = tag.getAttributeValue("class");
    List<String> classValues = classValue == null ? Collections.<String>emptyList() : StringUtil.split(classValue, " ");
    if (!classValues.isEmpty()) {
      builder.append('.');
      StringUtil.join(classValues, ".", builder);
    }

    return builder.toString();
  }

  @Nullable
  public static String normalizeSpacesAndShortenIfLong(final @NotNull String text) {
    StringBuilder builder = normalizeSpaces(text);
    return builder == null ? null : shortenTextIfLong(builder);
  }

  @Nullable
  private static StringBuilder normalizeSpaces(@NotNull String text) {
    if (text.isEmpty()) {
      return null;
    }

    final StringBuilder buf = new StringBuilder(text.length());
    for (int i = 0, length = text.length(); i < length; i++) {
      char c = text.charAt(i);
      if (c <= ' ' || Character.isSpaceChar(c)) {
        if (buf.length() == 0 || buf.charAt(buf.length() - 1) != ' ') {
          buf.append(' ');
        }
      }
      else {
        buf.append(c);
      }
    }
    return buf;
  }

  @Nullable
  private static String shortenTextIfLong(@NotNull StringBuilder text) {
    if (text.length() <= MAX_TEXT_LENGTH) {
      return text.toString();
    }

    int index;
    for (index = MAX_TEXT_LENGTH; index > MAX_TEXT_LENGTH - 20; index--) {
      if (!Character.isLetter(text.charAt(index))) {
        break;
      }
    }

    text.setLength(Character.isLetter(index) ? MAX_TEXT_LENGTH : index);
    return text.append("\u2026").toString();
  }

  @Override
  public String getLocationPrefix() {
    return "  ";
  }

  @Override
  public String getLocationSuffix() {
    return "";
  }
}


text:
static NSString *kMediaCellID = @"media_cell_id";

@interface VRMediaViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, weak) IBOutlet UITableView *tableView;

@end

@implementation VRMediaViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.activityViewVisible = YES;
    __weak typeof(self) weakSelf = self;
    [self.viewModel fetchModel:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView reloadData];
            weakSelf.view.activityViewVisible = NO;
        });
    }];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    UINavigationController *navController = segue.destinationViewController;
    id vc = navController.topViewController;
    if ([vc respondsToSelector:@selector(setModel:)]) {
        [vc setModel:sender];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.viewModel.model entries] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    VREntryAdapter *adapter = [VREntryAdapter adapterFromObject:[self.viewModel.model entries][indexPath.row]];

    VRMediaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kMediaCellID];
    cell.orderNumber = indexPath.row + 1;
    cell.model = adapter;

    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.navigationController.splitViewController.collapsed) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }

    VREntryAdapter *adapter = [VREntryAdapter adapterFromObject:[self.viewModel.model entries][indexPath.row]];
    [self performSegueWithIdentifier:@"showDetails" sender:adapter];
}

@end


text:
package rootsyncdeployment

import (
	"context"
	"flag"
	"fmt"
	"sync"

	porchapi "github.com/GoogleContainerTools/kpt/porch/api/porch/v1alpha1"
	configapi "github.com/GoogleContainerTools/kpt/porch/api/porchconfig/v1alpha1"
	"github.com/GoogleContainerTools/kpt/porch/controllers/rootsyncdeployments/api/v1alpha1"
	rssapi "github.com/GoogleContainerTools/kpt/porch/controllers/rootsyncsets/api/v1alpha1"
	"k8s.io/apimachinery/pkg/api/equality"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/klog/v2"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
	"sigs.k8s.io/controller-runtime/pkg/handler"
	"sigs.k8s.io/controller-runtime/pkg/reconcile"
	"sigs.k8s.io/controller-runtime/pkg/source"
)

const (
	rootSyncSetLabel = "config.porch.kpt.dev/rootsyncdeployment"
)

var (
	configConnectorContainerClusterGVK = schema.GroupVersionKind{
		Group:   "container.cnrm.cloud.google.com",
		Version: "v1beta1",
		Kind:    "ContainerCluster",
	}
	configConnectorConfigControllerClusterGVK = schema.GroupVersionKind{
		Group:   "configcontroller.cnrm.cloud.google.com",
		Version: "v1beta1",
		Kind:    "ConfigControllerInstance",
	}
	rootSyncSetGVK = schema.GroupVersionKind{
		Group:   "config.porch.kpt.dev",
		Version: "v1alpha1",
		Kind:    "RootSyncSet",
	}
)

type Options struct {
}

func (o *Options) InitDefaults() {
}

func (o *Options) BindFlags(prefix string, flags *flag.FlagSet) {
}

func NewRootSyncDeploymentReconciler() *RootSyncDeploymentReconciler {
	return &RootSyncDeploymentReconciler{
		clusterTargetCache: make(map[types.NamespacedName]labels.Selector),
	}
}

// RootSyncDeploymentReconciler reconciles a RootSyncDeployment object
type RootSyncDeploymentReconciler struct {
	Options

	client.Client

	mutex              sync.Mutex
	clusterTargetCache map[types.NamespacedName]labels.Selector
}

//go:generate go run sigs.k8s.io/controller-tools/cmd/controller-gen@v0.8.0 rbac:roleName=porch-controllers-rootsyncdeployments webhook paths="." output:rbac:artifacts:config=../../../config/rbac

//+kubebuilder:rbac:groups=config.porch.kpt.dev,resources=rootsyncdeployments,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=config.porch.kpt.dev,resources=rootsyncdeployments/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=config.porch.kpt.dev,resources=rootsyncdeployments/finalizers,verbs=update
//+kubebuilder:rbac:groups=porch.kpt.dev,resources=packagerevisions,verbs=get;list;watch
//+kubebuilder:rbac:groups=config.porch.kpt.dev,resources=repositories,verbs=get;list;watch
//+kubebuilder:rbac:groups=configcontroller.cnrm.cloud.google.com,resources=configcontrollerinstances,verbs=get;list;watch
//+kubebuilder:rbac:groups=container.cnrm.cloud.google.com,resources=containerclusters,verbs=get;list;watch

func (r *RootSyncDeploymentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	var rootsyncdeployment v1alpha1.RootSyncDeployment
	if err := r.Get(ctx, req.NamespacedName, &rootsyncdeployment); err != nil {
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}

	myFinalizerName := "config.porch.kpt.dev/rootsyncdeployments"
	if rootsyncdeployment.ObjectMeta.DeletionTimestamp.IsZero() {
		// Update the cache with mapping from rollouts to ClusterTargets. It allows the controller
		// to determine which Rollouts needs to be reconciled based on an event about a cluster.
		selector, err := metav1.LabelSelectorAsSelector(rootsyncdeployment.Spec.Targets.Selector)
		if err != nil {
			return ctrl.Result{}, fmt.Errorf("error converting targets selector to labels.Selector: %v", err)
		}
		func() {
			r.mutex.Lock()
			defer r.mutex.Unlock()
			r.clusterTargetCache[req.NamespacedName] = selector
		}()

		// The object is not being deleted, so if it does not have our finalizer,
		// then lets add the finalizer and update the object. This is equivalent
		// registering our finalizer.
		if !controllerutil.ContainsFinalizer(&rootsyncdeployment, myFinalizerName) {
			controllerutil.AddFinalizer(&rootsyncdeployment, myFinalizerName)
			if err := r.Update(ctx, &rootsyncdeployment); err != nil {
				return ctrl.Result{}, fmt.Errorf("error adding finalizer: %w", err)
			}
		}
	} else {
		// Clean up the cache.
		func() {
			r.mutex.Lock()
			defer r.mutex.Unlock()
			delete(r.clusterTargetCache, req.NamespacedName)
		}()

		// The object is being deleted
		if controllerutil.ContainsFinalizer(&rootsyncdeployment, myFinalizerName) {
			// remove our finalizer from the list and update it.
			controllerutil.RemoveFinalizer(&rootsyncdeployment, myFinalizerName)
			if err := r.Update(ctx, &rootsyncdeployment); err != nil {
				return ctrl.Result{}, fmt.Errorf("failed to update %s after delete finalizer: %w", req.Name, err)
			}
		}
		// Stop reconciliation as the item is being deleted
		return ctrl.Result{}, nil
	}

	res, err := r.syncRootSyncDeployment(ctx, &rootsyncdeployment)
	if err != nil {
		return ctrl.Result{}, err
	}

	if err := r.updateStatus(ctx, &rootsyncdeployment, res); err != nil {
		return ctrl.Result{}, err
	}

	return ctrl.Result{}, nil
}

func (r *RootSyncDeploymentReconciler) updateStatus(ctx context.Context, rds *v1alpha1.RootSyncDeployment, clusterRefStatuses []v1alpha1.ClusterRefStatus) error {
	if equality.Semantic.DeepEqual(rds.Status.ClusterRefStatuses, clusterRefStatuses) {
		klog.Infof("Status has not changed, update not needed.")
		return nil
	}
	rds.Status.ClusterRefStatuses = clusterRefStatuses
	return r.Status().Update(ctx, rds)
}

func (r *RootSyncDeploymentReconciler) syncRootSyncDeployment(ctx context.Context, rsd *v1alpha1.RootSyncDeployment) ([]v1alpha1.ClusterRefStatus, error) {
	var clusterRefStatuses []v1alpha1.ClusterRefStatus
	namespace := rsd.Spec.PackageRevision.Namespace
	if namespace == "" {
		namespace = rsd.Namespace
	}
	nn := types.NamespacedName{
		Name:      rsd.Spec.PackageRevision.Name,
		Namespace: namespace,
	}

	pkgRev, err := r.getPackageRevision(ctx, nn)
	if err != nil {
		return clusterRefStatuses, err
	}

	repo, err := r.getRepository(ctx, types.NamespacedName{
		Name:      pkgRev.Spec.RepositoryName,
		Namespace: pkgRev.Namespace,
	})
	if err != nil {
		return clusterRefStatuses, err
	}

	rootSyncSetSpec := toRootSyncSpec(pkgRev, repo)

	clusters, err := r.getClusters(ctx, rsd.Spec.Targets.Selector)
	if err != nil {
		return clusterRefStatuses, err
	}
	klog.Infof("Found clusters: %s", toClusterNames(clusters))

	rootsyncsets, err := r.listRootSyncSets(ctx, rsd.Name, rsd.Namespace)
	if err != nil {
		return clusterRefStatuses, err
	}
	klog.Infof("Found RootSyncSets: %s", toRootSyncSetNames(rootsyncsets))

	var clustersMissingRootSync []rssapi.ClusterRef
	var clustersToDeleteRootSync []*rssapi.RootSyncSet
	var clustersNeedingUpdate []*rssapi.RootSyncSet
	var clustersBeingUpdated []*rssapi.RootSyncSet
	var upToDateClusters []*rssapi.RootSyncSet

	for i := range rootsyncsets {
		rss := rootsyncsets[i]

		// TODO: See if we can remove this constraint. But it make things easier for now.
		// First remove RootSyncSets for clusters where it should no longer exist.
		if l := len(rss.Spec.ClusterRefs); l != 1 {
			return clusterRefStatuses,
				fmt.Errorf("RootSyncSet %s contains %d ClusterRefs, but it should be 1", rss.Name, l)
		}

		// If the RootSyncSet references a cluster that is no longer matches by the target selector,
		// we need to delete the RootSyncSet.
		clusterRef := rss.Spec.ClusterRefs[0]
		if !contains(clusters, clusterRef) {
			clustersToDeleteRootSync = append(clustersToDeleteRootSync, rss)
			continue
		}

		// If the RootSync template in the RootSyncSet doesn't match the spec from the
		// PackageRevision, it needs to be updated.
		if !equality.Semantic.DeepEqual(rootSyncSetSpec, rss.Spec.Template.Spec) {
			clustersNeedingUpdate = append(clustersNeedingUpdate, rss)
			continue
		}

		// If the RootSyncSet is not synced, we treat them as being the process of being updated.
		// This might not be correct in all situations.
		if !isRssSynced(rss) {
			clustersBeingUpdated = append(clustersBeingUpdated, rss)
			continue
		}
		upToDateClusters = append(upToDateClusters, rss)
	}

	// Find any clusters that are targeted by the label selector, but
	// where we don't have a RootSyncSet referencing the cluster.
	for i := range clusters {
		cluster := clusters[i]
		ref := rssapi.ClusterRef{
			Name:       cluster.GetName(),
			Namespace:  cluster.GetNamespace(),
			ApiVersion: cluster.GetAPIVersion(),
			Kind:       cluster.GetKind(),
		}
		var found bool
		for _, rss := range rootsyncsets {
			rssClusterRef := *rss.Spec.ClusterRefs[0]
			if equality.Semantic.DeepEqual(rssClusterRef, ref) {
				found = true
			}
		}
		if !found {
			clustersMissingRootSync = append(clustersMissingRootSync, ref)
		}
	}

	// TODO: We should keep track of the clusters and status until we know they have been removed
	// from the cluster.
	for _, rss := range clustersToDeleteRootSync {
		if err := r.Delete(ctx, rss); err != nil {
			klog.Warningf("Error removing RootSyncSet %s: %v", rss.Name, err)
		}
	}

	// If we have clusters that doesn't already have the package installed, we just
	// update them all. The limit to the number of clusters being updated
	// concurrently (currently that is 1) does not apply here.
	if len(clustersMissingRootSync) > 0 {
		for _, cr := range clustersMissingRootSync {
			rss := newRootSyncSet(rsd, cr, rootSyncSetSpec, pkgRev.Spec.PackageName)
			if err := r.Create(ctx, rss); err != nil {
				klog.Warningf("Error creating RootSyncSet %s: %v", rss.Name, err)
			}
			clustersBeingUpdated = append(clustersBeingUpdated, rss)
		}
	}

	// If no clusters are in the process of being updated and we have clusters
	// that needs to be updated, just update the corresponding RootSyncSet.
	if len(clustersBeingUpdated) == 0 && len(clustersNeedingUpdate) > 0 {
		rss := clustersNeedingUpdate[0]
		rss.Spec.Template.Spec = rootSyncSetSpec
		if err := r.Update(ctx, rss); err != nil {
			klog.Warningf("Error updating RootSyncSet %s: %v", rss.Name, err)
		}
		clustersNeedingUpdate = clustersNeedingUpdate[1:]
		clustersBeingUpdated = append(clustersBeingUpdated, rss)
	}

	for _, c := range upToDateClusters {
		clusterRefStatuses = append(clusterRefStatuses, newClusterRefStatus(c, true))
	}
	for _, c := range clustersBeingUpdated {
		clusterRefStatuses = append(clusterRefStatuses, newClusterRefStatus(c, false))
	}
	for _, c := range clustersNeedingUpdate {
		clusterRefStatuses = append(clusterRefStatuses, newClusterRefStatus(c, isRssSynced(c)))
	}

	return clusterRefStatuses, nil
}

func newClusterRefStatus(rss *rssapi.RootSyncSet, synced bool) v1alpha1.ClusterRefStatus {
	clusterRef := rss.Spec.ClusterRefs[0]
	return v1alpha1.ClusterRefStatus{
		ApiVersion: clusterRef.ApiVersion,
		Kind:       clusterRef.Kind,
		Name:       clusterRef.Name,
		Namespace:  clusterRef.Namespace,
		Revision:   rss.Spec.Template.Spec.Git.Revision,
		Synced:     synced,
	}
}

func (r *RootSyncDeploymentReconciler) getPackageRevision(ctx context.Context, nn types.NamespacedName) (*porchapi.PackageRevision, error) {
	var packageRevision porchapi.PackageRevision
	if err := r.Get(ctx, nn, &packageRevision); err != nil {
		return nil, err
	}
	return &packageRevision, nil
}

func (r *RootSyncDeploymentReconciler) getRepository(ctx context.Context, nn types.NamespacedName) (*configapi.Repository, error) {
	var repository configapi.Repository
	if err := r.Get(ctx, nn, &repository); err != nil {
		return nil, err
	}
	return &repository, nil
}

func newRootSyncSet(rsd *v1alpha1.RootSyncDeployment, clusterRef rssapi.ClusterRef, rssSpec *rssapi.RootSyncSpec, pkgName string) *rssapi.RootSyncSet {
	t := true
	rootsyncset := &rssapi.RootSyncSet{
		ObjectMeta: metav1.ObjectMeta{
			Name:      fmt.Sprintf("%s-%s", pkgName, clusterRef.Name),
			Namespace: rsd.Namespace,
			Labels: map[string]string{
				rootSyncSetLabel: rsd.Name,
			},
			OwnerReferences: []metav1.OwnerReference{
				{
					APIVersion: rsd.APIVersion,
					Kind:       rsd.Kind,
					Name:       rsd.Name,
					UID:        rsd.UID,
					Controller: &t,
				},
			},
		},
		Spec: rssapi.RootSyncSetSpec{
			ClusterRefs: []*rssapi.ClusterRef{
				&clusterRef,
			},
			Template: &rssapi.RootSyncInfo{
				Spec: rssSpec,
			},
		},
	}
	return rootsyncset
}

func toRootSyncSpec(pkgRev *porchapi.PackageRevision, repo *configapi.Repository) *rssapi.RootSyncSpec {
	return &rssapi.RootSyncSpec{
		SourceFormat: "unstructured",
		Git: &rssapi.GitInfo{
			Repo:     repo.Spec.Git.Repo,
			Revision: fmt.Sprintf("%s/%s", pkgRev.Spec.PackageName, pkgRev.Spec.Revision),
			Dir:      pkgRev.Spec.PackageName,
			Branch:   repo.Spec.Git.Branch,
			Auth:     "none",
		},
	}
}

func isRssSynced(rss *rssapi.RootSyncSet) bool {
	if rss.Generation != rss.Status.ObservedGeneration {
		return false
	}

	for _, crs := range rss.Status.ClusterRefStatuses {
		if crs.SyncStatus == "Synced" {
			return true
		}
	}
	return false
}

func contains(clusters []*unstructured.Unstructured, clusterRef *rssapi.ClusterRef) bool {
	for _, cr := range clusters {
		if clusterRef.ApiVersion == cr.GetAPIVersion() &&
			clusterRef.Kind == cr.GetKind() &&
			clusterRef.Name == cr.GetName() &&
			clusterRef.Namespace == cr.GetNamespace() {
			return true
		}
	}
	return false
}

func (r *RootSyncDeploymentReconciler) listRootSyncSets(ctx context.Context, rsdName, rsdNamespace string) ([]*rssapi.RootSyncSet, error) {
	var list rssapi.RootSyncSetList
	if err := r.List(ctx, &list, client.MatchingLabels{rootSyncSetLabel: rsdName}, client.InNamespace(rsdNamespace)); err != nil {
		return nil, err
	}
	var rootsyncsets []*rssapi.RootSyncSet
	for i := range list.Items {
		item := &list.Items[i]
		rootsyncsets = append(rootsyncsets, item)
	}
	return rootsyncsets, nil
}

func (r *RootSyncDeploymentReconciler) getClusters(ctx context.Context, sel *metav1.LabelSelector) ([]*unstructured.Unstructured, error) {
	var clusters []*unstructured.Unstructured
	for _, gvk := range []schema.GroupVersionKind{configConnectorConfigControllerClusterGVK, configConnectorContainerClusterGVK} {
		c, err := r.getClustersByGVK(ctx, gvk, sel)
		if err != nil {
			return nil, err
		}
		clusters = append(clusters, c...)
	}
	return clusters, nil
}

func (r *RootSyncDeploymentReconciler) getClustersByGVK(ctx context.Context, gvk schema.GroupVersionKind, sel *metav1.LabelSelector) ([]*unstructured.Unstructured, error) {
	selector, err := metav1.LabelSelectorAsSelector(sel)
	if err != nil {
		return nil, err
	}
	var list unstructured.UnstructuredList
	list.SetGroupVersionKind(gvk)
	if err := r.List(ctx, &list, client.MatchingLabelsSelector{Selector: selector}); err != nil {
		return nil, err
	}

	var clusters []*unstructured.Unstructured
	for i := range list.Items {
		c := list.Items[i]
		clusters = append(clusters, &c)
	}
	return clusters, nil
}

func toRootSyncSetNames(rsss []*rssapi.RootSyncSet) []string {
	var names []string
	for _, rss := range rsss {
		names = append(names, rss.Name)
	}
	return names
}

func toClusterNames(clusters []*unstructured.Unstructured) []string {
	var names []string
	for _, c := range clusters {
		names = append(names, c.GetName())
	}
	return names
}

// SetupWithManager sets up the controller with the Manager.
func (r *RootSyncDeploymentReconciler) SetupWithManager(mgr ctrl.Manager) error {
	if err := v1alpha1.AddToScheme(mgr.GetScheme()); err != nil {
		return err
	}
	if err := porchapi.AddToScheme(mgr.GetScheme()); err != nil {
		return err
	}
	if err := configapi.AddToScheme(mgr.GetScheme()); err != nil {
		return err
	}

	r.Client = mgr.GetClient()

	var containerCluster unstructured.Unstructured
	containerCluster.SetGroupVersionKind(configConnectorContainerClusterGVK)
	var configController unstructured.Unstructured
	configController.SetGroupVersionKind(configConnectorConfigControllerClusterGVK)

	return ctrl.NewControllerManagedBy(mgr).
		For(&v1alpha1.RootSyncDeployment{}).
		Owns(&rssapi.RootSyncSet{}).
		Watches(
			&source.Kind{Type: &containerCluster},
			handler.EnqueueRequestsFromMapFunc(r.requestsFromMapFunc),
		).
		Watches(
			&source.Kind{Type: &configController},
			handler.EnqueueRequestsFromMapFunc(r.requestsFromMapFunc),
		).
		Complete(r)
}

func (r *RootSyncDeploymentReconciler) requestsFromMapFunc(cluster client.Object) []reconcile.Request {
	r.mutex.Lock()
	defer r.mutex.Unlock()

	var requests []reconcile.Request
	l := cluster.GetLabels()
	for nn, clusterTargetSelector := range r.clusterTargetCache {
		if clusterTargetSelector.Matches(labels.Set(l)) {
			requests = append(requests, reconcile.Request{NamespacedName: nn})
		}
	}
	return requests
}


text:
package org.slc.sli.api.security.context;

import com.sun.jersey.spi.container.ContainerRequest;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.lang.math.NumberUtils;
import org.slc.sli.api.config.EntityDefinition;
import org.slc.sli.api.constants.ResourceNames;
import org.slc.sli.api.resources.generic.util.ResourceHelper;
import org.slc.sli.api.security.SLIPrincipal;
import org.slc.sli.api.security.context.resolver.EdOrgHelper;
import org.slc.sli.api.security.context.validator.IContextValidator;
import org.slc.sli.api.service.EntityNotFoundException;
import org.slc.sli.api.util.SecurityUtil;
import org.slc.sli.common.constants.EntityNames;
import org.slc.sli.domain.Entity;
import org.slc.sli.domain.NeutralCriteria;
import org.slc.sli.domain.NeutralQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;

import javax.ws.rs.core.PathSegment;
import java.util.*;

/**
 * ContextValidator
 * Determines if the principal has context to a resource.
 * Verifies the requested endpoint is accessible by the principal
 */
@Component
public class ContextValidator implements ApplicationContextAware {

    private static final Logger LOG = LoggerFactory.getLogger(ContextValidator.class);

    protected static final Set<String> GLOBAL_RESOURCES = new HashSet<String>(
            Arrays.asList(ResourceNames.ASSESSMENTS,
            ResourceNames.CALENDAR_DATES,
            ResourceNames.COMPETENCY_LEVEL_DESCRIPTORS,
            ResourceNames.COURSES,
            ResourceNames.COURSE_OFFERINGS,
            ResourceNames.EDUCATION_ORGANIZATIONS,
            ResourceNames.GRADUATION_PLANS,
            ResourceNames.GRADING_PERIODS,
            ResourceNames.LEARNINGOBJECTIVES,
            ResourceNames.LEARNINGSTANDARDS,
            ResourceNames.PROGRAMS,
            ResourceNames.SCHOOLS,
            ResourceNames.SECTIONS,
            ResourceNames.SESSIONS,
            ResourceNames.STUDENT_COMPETENCY_OBJECTIVES,
            ResourceNames.CUSTOM,
            "parentLearningObjectives",
            "childLearningObjectives",
            ResourceNames.CLASS_PERIODS,
            ResourceNames.BELL_SCHEDULES));

    private List<IContextValidator> validators;

    @Autowired
    private ResourceHelper resourceHelper;

    @Autowired
    private PagingRepositoryDelegate<Entity> repo;

    @Autowired
    private EntityOwnershipValidator ownership;

    @Autowired
    private StudentAccessValidator studentAccessValidator;

    @Autowired
    private EdOrgHelper edOrgHelper;

    @Autowired
    private ParentAccessValidator parentAccessValidator;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        validators = new ArrayList<IContextValidator>();
        validators.addAll(applicationContext.getBeansOfType(IContextValidator.class).values());
    }

    public void validateContextToUri(ContainerRequest request, SLIPrincipal principal) {
        validateUserHasContextToRequestedEntities(request, principal);
    }

    /**
     * white list student accessible URL. Can't do it in validateUserHasContextToRequestedEntity
     * because we must also block some url that only has 2 segment, i.e.
     * disciplineActions/disciplineIncidents
     *
     * @param request
     * @return if url is accessible to students principals
     */
    public boolean isUrlBlocked(ContainerRequest request) {
        List<PathSegment> segs = cleanEmptySegments(request.getPathSegments());

        if (isSystemCall(segs)) {
            // do not block system calls
            return false;
        }

        if (SecurityUtil.isStudent()) {
            return !studentAccessValidator.isAllowed(request);
        } else if (SecurityUtil.isParent()) {
            return !parentAccessValidator.isAllowed(request);
        }

        return false;
    }

    private boolean isSystemCall(List<PathSegment> pathSegments) {
        /**
         * assuming all resource endpoints are versioned
         */
        if (pathSegments == null || pathSegments.size() == 0) {
            // /api/rest/ root access?
            return false;
        }

        // all data model resources are versioned
        if (isVersionString(pathSegments.get(0).getPath())) {
            return false;
        }

        return true;
    }

    private boolean isVersionString(String path) {
        if (path != null && path.startsWith("v")) {
            return NumberUtils.isNumber(path.substring(1));
        }
        return false;
    }

    public List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments) {
        for (Iterator<PathSegment> i = pathSegments.iterator(); i.hasNext();) {
            if (i.next().getPath().isEmpty()) {
                i.remove();
            }
        }

        return pathSegments;
    }

    private void validateUserHasContextToRequestedEntities(ContainerRequest request, SLIPrincipal principal) {

        List<PathSegment> segs = request.getPathSegments();
        segs = cleanEmptySegments(segs);

        if (segs.size() < 3) {
            return;
        }

        /*
         * If the URI being requested is a GET full of global entities, we do
         * not need to attempt validation Global entities include: ASSESSMENT,
         * LEARNING_OBJECTIVE, LEARNING_STANDARD, COMPETENCY_LEVEL_DESCRIPTOR,
         * SESSION, COURSE_OFFERING, GRADING_PERIOD, COURSE,
         * EDUCATION_ORGANIZATION, SCHOOL, SECITON, PROGRAM, GRADUATION_PLAN,
         * STUDENT_COMPETENCY_OBJECTIVE, and CUSTOM (custom entity exists under
         * another entity, they should not prevent classification of a call
         * being global)
         */
        boolean isGlobal = true;
        for (PathSegment seg : segs) {
            // First segment is always API version, skip it
            // Third segment is always the ID, skip it
            if (seg.equals(segs.get(0)) || seg.equals(segs.get(2))) {
                continue;
            }
            // Check if the segment is not global, if so break
            if (!GLOBAL_RESOURCES.contains(seg.getPath())) {
                isGlobal = false;
                break;
            }
        }
        // Only skip validation if method is a get, updates may still require
        // validation
        if (isGlobal && request.getMethod().equals("GET")) {
            // The entity has global context, just return and don't call the
            // validators
            LOG.debug("Call to {} is of global context, skipping validation", request.getAbsolutePath().toString());
            return;
        }

        String rootEntity = segs.get(1).getPath();

        EntityDefinition def = resourceHelper.getEntityDefinition(rootEntity);
        if (def == null || def.skipContextValidation()) {
            return;
        }

        /*
         * e.g.
         * !isTransitive - /v1/staff/<ID>/disciplineActions
         * isTransitive - /v1/staff/<ID> OR /v1/staff/<ID>/custom
         */
        boolean isTransitive = segs.size() == 3
                || (segs.size() == 4 && segs.get(3).getPath().equals(ResourceNames.CUSTOM));

        validateContextToCallUri(segs);
        String idsString = segs.get(2).getPath();
        Set<String> ids = new HashSet<String>(Arrays.asList(idsString.split(",")));
        validateContextToEntities(def, ids, isTransitive);
    }

    /**
     * Validates the principal's context to call the given URI.
     *
     * @param segments
     *            List of Path Segments representing API call.
     */
    public void validateContextToCallUri(List<PathSegment> segments) {
        if (SecurityUtil.getSLIPrincipal().getEntity().getType().equals(EntityNames.TEACHER)
                && checkAccessOfStudentsThroughDisciplineIncidents(segments)) {
            throw new APIAccessDeniedException("Cannot access endpoint.");
        }
    }

    /**
     * Check for the path segments to match the following patterns:
     * /disciplineIncidents/{ids}/studentDisciplineIncidentAssociations,
     * /disciplineIncidents/{ids}/studentDisciplineIncidentAssociations/students
     *
     * @param segments
     *            List of Path Segments representing API call.
     * @return true if the URI exactly matches one of the enumerated patterns,
     *         false otherwise.
     */
    public boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments) {
        /*
         * Both /disciplineIncidents/{ids}/studentDisciplineIncidentAssociations and
         * /disciplineIncidents/{ids}/studentDisciplineIncidentAssociations/students
         * have the same pattern (first segment of discipline incident, third of
         * the association, so just check for those two conditions
         */
        if (segments.size() > 3) {
            return segments.get(1).getPath().equals(ResourceNames.DISCIPLINE_INCIDENTS)
                    && segments.get(3).getPath().equals(ResourceNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATIONS);
        }
        return false; // Num segments is 3, just return
    }

    /**
    * Validates entities, based upon entity definition and entity ids to validate.
    *
    * @param def - Definition of entities to validate
    * @param ids - Collection of ids of entities to validate
    * @param isTransitive - Determines whether validation is through another entity type
    *
    * @throws APIAccessDeniedException - When entities cannot be accessed
    */
    public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException {
        LOG.debug(">>>ContextValidator.validateContextToEntities()");
        LOG.debug("  def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE));
        LOG.debug("  ids: {}", (ids==null) ? "null" : ids.toArray().toString() );

        LOG.debug("  isTransitive" + isTransitive);

        IContextValidator validator = findValidator(def.getType(), isTransitive);
        LOG.debug("  loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE));

        if (validator != null) {
            NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids)));
            LOG.debug("  getIdsQuery: " + getIdsQuery.toString());

            Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery);
            LOG.debug("  entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE));

            Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids);
            LOG.debug("  idsToValidate: " + idsToValidate.toString());

            Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator);
            LOG.debug("  validatedIds: " + validatedIds.toString());

            if (!validatedIds.containsAll(idsToValidate)) {
                LOG.debug("    ...APIAccessDeniedException");
                throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate);
            }
        } else {
            throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids);
        }
    }

    /**
     * Validates entities, based upon entity definition and entity ids to validate.
     *
     * @param def - Definition of entities to validate
     * @param ids - Collection of ids of entities to validate
     * @param isTransitive - Determines whether validation is through another entity type
     *
     * @throws APIAccessDeniedException - When entities cannot be accessed
     */
    public Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive) throws APIAccessDeniedException {
        IContextValidator validator = findValidator(def.getType(), isTransitive);
        if (validator != null) {
            NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids)));
            Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery);
            Set<String> orphans = new HashSet<String>();
            for (Entity entity: entities) {
                if (isOrphanCreatedByUser(entity)) {
                    orphans.add(entity.getEntityId());
                }
            }
            Set<String> nonOrphanIds = new HashSet<String>();
            nonOrphanIds.addAll(ids);
            nonOrphanIds.removeAll(orphans);
            Set<String> validatedIds = validator.getValid(def.getType(), nonOrphanIds);

            validatedIds.addAll(orphans);
            return validatedIds;
        } else {
            throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids);
        }
    }

    /**
    * Returns a map of validated entity ids and their contexts, based upon entity definition and entities to validate.
    *
    * @param def - Definition of entities to validate
    * @param entities - Collection of entities to validate
    * @param isTransitive - Determines whether validation is through another entity type
    *
    * @return - Map of validated entity ids and their contexts, null if the validation is skipped
    *
    * @throws APIAccessDeniedException - When no entity validators can be found
    */
    public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException {

        if (skipValidation(def, isRead)) {
            return null;
        }

        Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>();

        List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive);
        Collection<String> ids = getEntityIds(entities);
        if (!contextValidators.isEmpty()) {
            Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive);
            for (IContextValidator validator : contextValidators) {
                // Add validated entity ids to the map.
                Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator);
                for (String id : validatedIds) {
                    if (!entityContexts.containsKey(id)) {
                        entityContexts.put(id, validator.getContext());
                    } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) ||
                               (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) {
                        entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT);
                    }
                }
            }

            // Add accessible, non-validated entity ids (orphaned and owned/self) to the map.
            Set<String> accessibleNonValidatedIds = new HashSet<String>(ids);
            accessibleNonValidatedIds.removeAll(idsToValidate);
            for (String id : accessibleNonValidatedIds) {
                entityContexts.put(id, SecurityUtil.getUserContext());
            }
        } else {
            throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids);
        }

        return entityContexts;
    }

    /**
    * Returns a set of entity ids to validate, based upon entity type and list of entities to filter for validation.
    *
    * @param def - Definition of entities to filter
    * @param entities - Collection of entities to filter for validation
    * @param isTransitive - Determines whether validation is through another entity type
    * @param ids - Original set of entity ids to validate
    *
    * @return - Set of entity ids to validate
    *
    * @throws APIAccessDeniedException - When an entity cannot be accessed
    * @throws EntityNotFoundException - When an entity cannot be located
    */
    protected Set<String> getEntityIdsToValidate(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, Collection<String> ids)
                          throws APIAccessDeniedException, EntityNotFoundException {
        Set<String> entityIdsToValidate = new HashSet<String>();
        for (Entity ent : entities) {
            Collection<String> userEdOrgs = edOrgHelper.getDirectEdorgs(ent);
            if (isOrphanCreatedByUser(ent)) {
                LOG.debug("Entity is orphaned: id {} of type {}", ent.getEntityId(), ent.getType());
            } else if (SecurityUtil.getSLIPrincipal().getEntity() != null
                        && SecurityUtil.getSLIPrincipal().getEntity().getEntityId().equals(ent.getEntityId())) {
                LOG.debug("Entity is themselves: id {} of type {}", ent.getEntityId(), ent.getType());
            } else {
                if (ownership.canAccess(ent, isTransitive)) {
                    entityIdsToValidate.add(ent.getEntityId());
                } else {
                    throw new APIAccessDeniedException("Access to " + ent.getEntityId() + " is not authorized", userEdOrgs);
                }
            }
        }

        // report an EntityNotFoundException on the id we find without a corresponding entity
        // so that we don't use the constructor for EntityNotFoundException incorrectly
        if (entities.size() != ids.size()) {
            for (String id : ids ) {
                boolean foundentity = false;
                for (Entity ent : entities) {
                    if (ent.getEntityId().contains(id)){
                    	foundentity = true;
                    	break;
                    }
                }
                if (!foundentity) {
                    LOG.debug("Invalid reference, an entity does not exist. collection: {} entities: {}",
                            def.getStoredCollectionName(), entities);
                    throw new EntityNotFoundException(id);
                }
            }
        }

        return entityIdsToValidate;
    }

    /**
     * Returns true if the entity is an orphan that is created by the user, false otherwise
     *
     * @param entity - Collection of entities to filter for validation
     *
     * @return
     */
    private boolean isOrphanCreatedByUser(Entity entity) {
         return SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy"))
                    && "true".equals(entity.getMetaData().get("isOrphaned"));
        }

    /**
     * This method forgivingly iterate through the input entities, returns a set of entity ids to validate,
     * based upon entity type and list of entities to filter for validation.
     *
     *
     * @param entities - Collection of entities to filter for validation
     * @param isTransitive - Determines whether validation is through another entity type
     *
     * @return - Set of entity ids to validate
     */
    protected Set<String> getEntityIdsToValidateForgiving(Collection<Entity> entities, boolean isTransitive){
        Set<String> entityIdsToValidate = new HashSet<String>();
        for (Entity ent : entities) {
            if (isOrphanCreatedByUser(ent)) {
                LOG.debug("Entity is orphaned: id {} of type {}", ent.getEntityId(), ent.getType());
            } else if (SecurityUtil.getSLIPrincipal().getEntity() != null
                    && SecurityUtil.getSLIPrincipal().getEntity().getEntityId().equals(ent.getEntityId())) {
                LOG.debug("Entity is themselves: id {} of type {}", ent.getEntityId(), ent.getType());
            } else {
                try{
                    if (ownership.canAccess(ent, isTransitive)) {
                        entityIdsToValidate.add(ent.getEntityId());
                    }
                } catch (AccessDeniedException aex) {
                    LOG.error(aex.getMessage());
                }
            }
        }

        return entityIdsToValidate;
    }

    /**
    * Returns a set of validated entity ids based upon entity type and list of entity ids to validate.
    *
    * @param def - Definition of entities to validate
    * @param idsToValidate - Collection of entity ids to validate
    * @param validator - Validator to use
    *
    * @return - Set of validated entities
    */
    protected Set<String> getValidatedIds(EntityDefinition def, Set<String> idsToValidate, IContextValidator validator) {
        LOG.debug(">>>ContextValidator.getValidatedIds()");
        Set<String> validatedIds = new HashSet<String>();
        if (!idsToValidate.isEmpty()) {
            validatedIds = validator.validate(def.getType(), idsToValidate);
        }

        return validatedIds;
    }

    /**
    * Returns a set of entity ids from a set of entities.
    *
    * @param entities - Collection of entities to validate
    *
    * @return - Set of entity ids
    */
    protected Set<String> getEntityIds(Collection<Entity> entities) {
        Set<String> entityIds = new HashSet<String>();
        for (Entity ent : entities) {
            entityIds.add(ent.getEntityId());
        }

        return entityIds;
    }

    /**
     * Returns a contextual validator based upon entity type.
     *
    * @param toType - Type of entity to validate
    * @param isTransitive - Determines whether validation is through another entity type
     *
     * @return - Validator applicable to given type
     *
     * @throws IllegalStateException - ???
     */
    public IContextValidator findValidator(String toType, boolean isTransitive) throws IllegalStateException {

        IContextValidator found = null;
        for (IContextValidator validator : this.validators) {
            if (validator.canValidate(toType, isTransitive)) {
                LOG.info("Using {} to validate {}", new Object[] { validator.getClass().toString(), toType });
                found = validator;
                break;
            }
        }

        if (found == null) {
            LOG.warn("No {} validator to {}.", isTransitive ? "TRANSITIVE" : "NOT TRANSITIVE", toType);
        }

        return found;
    }

    public static boolean isTransitive(List<PathSegment> segs) {
                /*
         * e.g.
         * !isTransitive - /v1/staff/<ID>/disciplineActions
         * isTransitive - /v1/staff/<ID> OR /v1/staff/<ID>/custom
         */
        return segs.size() == 3
                || (segs.size() == 4 && segs.get(3).getPath().equals(ResourceNames.CUSTOM));
    }

    /**
    * Returns a list of contextual validators based upon entity type.
    *
    * @param toType - Type of entity to validate
    * @param isTransitive - Determines whether validation is through another entity type
    *
    * @return - List of validators to use
    */
    public List<IContextValidator> findContextualValidators(String toType, boolean isTransitive) {

        List<IContextValidator> validators = new ArrayList<IContextValidator>();
        for (IContextValidator validator : this.validators) {
            if (validator.canValidate(toType, isTransitive)) {
                LOG.info("Using {} to validate {}", new Object[] { validator.getClass().toString(), toType });
                validators.add(validator);
            }
        }

        if (validators.isEmpty()) {
            LOG.warn("No {} validator to {}.", isTransitive ? "TRANSITIVE" : "NOT TRANSITIVE", toType);
        }

        return validators;
    }

    /**
     * Determines if the entity is global.
     *
     * @param type
     *            Type of entity to checked.
     * @return True if the entity is global, false otherwise.
     */
    public boolean isGlobalEntity(String type) {
        return EntityNames.isPublic(type);
    }

    private boolean skipValidation(EntityDefinition def, boolean isRead) {
        return def == null || def.skipContextValidation() || (GLOBAL_RESOURCES.contains(def.getResourceName()) && isRead);
    }

}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SetSerializer.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Implements the set serializer class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Quartz.Spi.MongoDbJobStore.Serializers
{
    using System.Collections.Generic;

    using MongoDB.Bson.Serialization;
    using MongoDB.Bson.Serialization.Serializers;

    internal class SetSerializer<T> : SerializerBase<ISet<T>>
    {
        private readonly IBsonSerializer serializer;

        public SetSerializer()
        {
            this.serializer = BsonSerializer.LookupSerializer(typeof(IEnumerable<T>));
        }

        public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, ISet<T> value)
            => this.serializer.Serialize(context, args, value);

        public override ISet<T> Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            var enumerable = (IEnumerable<T>)this.serializer.Deserialize(context, args);
            return new HashSet<T>(enumerable);
        }
    }
}


text:
require 'spec_helper'

# Generators are not automatically loaded by Rails
require 'generators/rspec/controller/controller_generator'

describe Rspec::Generators::ControllerGenerator do
  # Tell the generator where to put its output (what it thinks of as Rails.root)
  destination File.expand_path("../../../../../tmp", __FILE__)

  before { prepare_destination }

  describe 'controller specs' do
    subject { file('spec/controllers/posts_controller_spec.rb') }
    describe 'generated by default' do
      before do
        run_generator %w(posts)
      end

      describe 'the spec' do
        it { should exist }
        it { should contain(/require 'spec_helper'/) }
        it { should contain(/describe PostsController/) }
      end
    end
    describe 'skipped with a flag' do
      before do
        run_generator %w(posts --no-controller_specs)
      end
      it { should_not exist }
    end
  end

  describe 'view specs' do
    describe 'are not generated' do
      describe 'with no-view-spec flag' do
        before do
          run_generator %w(posts index show --no-view-specs)
        end
        describe 'index.html.erb' do
          subject { file('spec/views/posts/index.html.erb_spec.rb') }
          it { should_not exist }
        end
      end
      describe 'with no actions' do
        before do
          run_generator %w(posts)
        end
        describe 'index.html.erb' do
          subject { file('spec/views/posts/index.html.erb_spec.rb') }
          it { should_not exist }
        end
      end

      describe 'with --no-template-engine' do
        before do
          run_generator %w(posts index --no-template-engine)
        end

        describe 'index.html.erb' do
          subject { file('spec/views/posts/index.html._spec.rb') }
          it { should_not exist }
        end
      end
    end

    describe 'are generated' do
      describe 'with default template engine' do
        before do
          run_generator %w(posts index show)
        end
        describe 'index.html.erb' do
          subject { file('spec/views/posts/index.html.erb_spec.rb') }
          it { should exist }
          it { should contain(/require 'spec_helper'/) }
          it { should contain(/describe "posts\/index.html.erb"/) }
        end
        describe 'show.html.erb' do
          subject { file('spec/views/posts/show.html.erb_spec.rb') }
          it { should exist }
          it { should contain(/require 'spec_helper'/) }
          it { should contain(/describe "posts\/show.html.erb"/) }
        end
      end
      describe 'with haml' do
        before do
          run_generator %w(posts index --template_engine haml)
        end
        describe 'index.html.haml' do
          subject { file('spec/views/posts/index.html.haml_spec.rb') }
          it { should exist }
          it { should contain(/require 'spec_helper'/) }
          it { should contain(/describe "posts\/index.html.haml"/) }
        end
      end
    end
  end
end


text:
#pragma once
#include "GLRendertarget.h"
#include "GLTexture.h"
#include "GL.h"

class GLRenderTexture2D : public GLRendertarget
{
public:
	static GLRenderTexture2D *New(int width, int height,
		int internalformat, int format, int type);

	virtual ~GLRenderTexture2D();

	GLTexture* GetTexture() { return tex; }
	const GLTexture* GetTexture() const { return tex; }

	bool Resize(int width, int height);

protected:
	GLTexture *tex;

	GLRenderTexture2D(int width, int height);

	virtual void AttachToBoundFBO(int attachment);

	virtual bool Allocate(int internalformat, int format, int type);

private:
	// Not implemented
	GLRenderTexture2D(const GLRenderTexture2D&);
	void operator=(const GLRenderTexture2D&);
};


text:
default_target: all
.PHONY : default_target

#=============================================================================
# Special targets provided by cmake.

# Disable implicit rules so canonical targets will work.
.SUFFIXES:

# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =

.SUFFIXES: .hpux_make_needs_suffix_list

# Suppress display of executed commands.
$(VERBOSE).SILENT:

# A target that is always out of date.
cmake_force:
.PHONY : cmake_force

#=============================================================================
# Set environment variables for the build.

# The shell in which to execute make rules.
SHELL = /bin/sh

# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake

# The command to remove a file.
RM = /usr/bin/cmake -E remove -f

# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/vadim/projects/qpid-proton-0.7

# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/vadim/projects/qpid-proton-0.7/build

#=============================================================================
# Targets provided globally by CMake.

# Special rule for the target edit_cache
edit_cache:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running interactive CMake command-line interface..."
	/usr/bin/cmake -i .
.PHONY : edit_cache

# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast

# Special rule for the target install
install: preinstall
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
	/usr/bin/cmake -P cmake_install.cmake
.PHONY : install

# Special rule for the target install
install/fast: preinstall/fast
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
	/usr/bin/cmake -P cmake_install.cmake
.PHONY : install/fast

# Special rule for the target install/local
install/local: preinstall
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..."
	/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake
.PHONY : install/local

# Special rule for the target install/local
install/local/fast: install/local
.PHONY : install/local/fast

# Special rule for the target install/strip
install/strip: preinstall
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..."
	/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake
.PHONY : install/strip

# Special rule for the target install/strip
install/strip/fast: install/strip
.PHONY : install/strip/fast

# Special rule for the target list_install_components
list_install_components:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Python\" \"Ruby\" \"Unspecified\""
.PHONY : list_install_components

# Special rule for the target list_install_components
list_install_components/fast: list_install_components
.PHONY : list_install_components/fast

# Special rule for the target rebuild_cache
rebuild_cache:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
	/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache

# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast

# Special rule for the target test
test:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running tests..."
	/usr/bin/ctest --force-new-ctest-process $(ARGS)
.PHONY : test

# Special rule for the target test
test/fast: test
.PHONY : test/fast

# The main all target
all: cmake_check_build_system
	cd /home/vadim/projects/qpid-proton-0.7/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/vadim/projects/qpid-proton-0.7/build/CMakeFiles /home/vadim/projects/qpid-proton-0.7/build/proton-c/bindings/ruby/CMakeFiles/progress.marks
	cd /home/vadim/projects/qpid-proton-0.7/build && $(MAKE) -f CMakeFiles/Makefile2 proton-c/bindings/ruby/all
	$(CMAKE_COMMAND) -E cmake_progress_start /home/vadim/projects/qpid-proton-0.7/build/CMakeFiles 0
.PHONY : all

# The main clean target
clean:
	cd /home/vadim/projects/qpid-proton-0.7/build && $(MAKE) -f CMakeFiles/Makefile2 proton-c/bindings/ruby/clean
.PHONY : clean

# The main clean target
clean/fast: clean
.PHONY : clean/fast

# Prepare targets for installation.
preinstall: all
	cd /home/vadim/projects/qpid-proton-0.7/build && $(MAKE) -f CMakeFiles/Makefile2 proton-c/bindings/ruby/preinstall
.PHONY : preinstall

# Prepare targets for installation.
preinstall/fast:
	cd /home/vadim/projects/qpid-proton-0.7/build && $(MAKE) -f CMakeFiles/Makefile2 proton-c/bindings/ruby/preinstall
.PHONY : preinstall/fast

# clear depends
depend:
	cd /home/vadim/projects/qpid-proton-0.7/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend

# Convenience name for target.
proton-c/bindings/ruby/CMakeFiles/cproton-ruby.dir/rule:
	cd /home/vadim/projects/qpid-proton-0.7/build && $(MAKE) -f CMakeFiles/Makefile2 proton-c/bindings/ruby/CMakeFiles/cproton-ruby.dir/rule
.PHONY : proton-c/bindings/ruby/CMakeFiles/cproton-ruby.dir/rule

# Convenience name for target.
cproton-ruby: proton-c/bindings/ruby/CMakeFiles/cproton-ruby.dir/rule
.PHONY : cproton-ruby

# fast build rule for target.
cproton-ruby/fast:
	cd /home/vadim/projects/qpid-proton-0.7/build && $(MAKE) -f proton-c/bindings/ruby/CMakeFiles/cproton-ruby.dir/build.make proton-c/bindings/ruby/CMakeFiles/cproton-ruby.dir/build
.PHONY : cproton-ruby/fast

rubyRUBY_wrap.o: rubyRUBY_wrap.c.o
.PHONY : rubyRUBY_wrap.o

# target to build an object file
rubyRUBY_wrap.c.o:
	cd /home/vadim/projects/qpid-proton-0.7/build && $(MAKE) -f proton-c/bindings/ruby/CMakeFiles/cproton-ruby.dir/build.make proton-c/bindings/ruby/CMakeFiles/cproton-ruby.dir/rubyRUBY_wrap.c.o
.PHONY : rubyRUBY_wrap.c.o

rubyRUBY_wrap.i: rubyRUBY_wrap.c.i
.PHONY : rubyRUBY_wrap.i

# target to preprocess a source file
rubyRUBY_wrap.c.i:
	cd /home/vadim/projects/qpid-proton-0.7/build && $(MAKE) -f proton-c/bindings/ruby/CMakeFiles/cproton-ruby.dir/build.make proton-c/bindings/ruby/CMakeFiles/cproton-ruby.dir/rubyRUBY_wrap.c.i
.PHONY : rubyRUBY_wrap.c.i

rubyRUBY_wrap.s: rubyRUBY_wrap.c.s
.PHONY : rubyRUBY_wrap.s

# target to generate assembly for a file
rubyRUBY_wrap.c.s:
	cd /home/vadim/projects/qpid-proton-0.7/build && $(MAKE) -f proton-c/bindings/ruby/CMakeFiles/cproton-ruby.dir/build.make proton-c/bindings/ruby/CMakeFiles/cproton-ruby.dir/rubyRUBY_wrap.c.s
.PHONY : rubyRUBY_wrap.c.s

# Help Target
help:
	@echo "The following are some of the valid targets for this Makefile:"
	@echo "... all (the default if no target is provided)"
	@echo "... clean"
	@echo "... depend"
	@echo "... cproton-ruby"
	@echo "... edit_cache"
	@echo "... install"
	@echo "... install/local"
	@echo "... install/strip"
	@echo "... list_install_components"
	@echo "... rebuild_cache"
	@echo "... test"
	@echo "... rubyRUBY_wrap.o"
	@echo "... rubyRUBY_wrap.i"
	@echo "... rubyRUBY_wrap.s"
.PHONY : help

#=============================================================================
# Special targets to cleanup operation of make.

# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
	cd /home/vadim/projects/qpid-proton-0.7/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system


text: Utility for detecting breaking changes between library versions


text:
<?php

namespace Duo\ModelBundle\Repository;

/**
 * StatusRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class StatusRepository extends \Doctrine\ORM\EntityRepository
{
	public function findAll()
	{
	    $qb = $this->getEntityManager()
        ->createQueryBuilder()
        ->select('sta.status_id,sta.title')
        ->from('DuoModelBundle:Status','sta');
	    return $qb->getQuery()->getResult();

	}
}


text:
Table List

The following tables are available in your application.

		<?php foreach ($tables as $table) { ?>

<?php echo linkTo(Schema::displayName($table), array("table"=>$table)) ?>

		<?php } ?>


text:
The place for holding all information about zsh

# Presentations & Blogs
1. [Why zsh is cooler than your shell](http://www.slideshare.net/jaguardesignstudio/why-zsh-is-cooler-than-your-shell-16194692)


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

package org.chromium.base.test.params;

import org.junit.Test;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.Suite;
import org.junit.runners.model.FrameworkField;
import org.junit.runners.model.Statement;
import org.junit.runners.model.TestClass;

import org.chromium.base.test.params.ParameterAnnotations.ClassParameter;
import org.chromium.base.test.params.ParameterAnnotations.UseMethodParameter;
import org.chromium.base.test.params.ParameterAnnotations.UseRunnerDelegate;
import org.chromium.base.test.params.ParameterizedRunnerDelegateFactory.ParameterizedRunnerDelegateInstantiationException;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

/**
 * ParameterizedRunner generates a list of runners for each of class parameter set in a test class.
 *
 * ParameterizedRunner looks for {@code @ClassParameter} annotation in test class and
 * generates a list of ParameterizedRunnerDelegate runners for each ParameterSet.
 */
public final class ParameterizedRunner extends Suite {
    private final List<Runner> mRunners;

    /**
     * Create a ParameterizedRunner to run test class
     *
     * @param klass the Class of the test class, test class should be atomic
     *              (extends only Object)
     */
    public ParameterizedRunner(Class<?> klass) throws Throwable {
        super(klass, Collections.emptyList()); // pass in empty list of runners
        validate();
        mRunners = createRunners(getTestClass());
    }

    @Override
    protected List<Runner> getChildren() {
        return mRunners;
    }

    /**
     * ParentRunner calls collectInitializationErrors() to check for errors in Test class.
     * Parameterized tests are written in unconventional ways, therefore, this method is
     * overridden and validation is done seperately.
     */
    @Override
    protected void collectInitializationErrors(List<Throwable> errors) {
        // Do not call super collectInitializationErrors
    }

    private void validate() throws Throwable {
        validateNoNonStaticInnerClass();
        validateOnlyOneConstructor();
        validateInstanceMethods();
        validateOnlyOneClassParameterField();
        validateAtLeastOneParameterSetField();
    }

    private void validateNoNonStaticInnerClass() throws Exception {
        if (getTestClass().isANonStaticInnerClass()) {
            throw new Exception("The inner class " + getTestClass().getName() + " is not static.");
        }
    }

    private void validateOnlyOneConstructor() throws Exception {
        if (!hasOneConstructor()) {
            throw new Exception("Test class should have exactly one public constructor");
        }
    }

    private boolean hasOneConstructor() {
        return getTestClass().getJavaClass().getConstructors().length == 1;
    }

    private void validateOnlyOneClassParameterField() {
        if (getTestClass().getAnnotatedFields(ClassParameter.class).size() > 1) {
            throw new IllegalParameterArgumentException(String.format(Locale.getDefault(),
                    "%s class has more than one @ClassParameter, only one is allowed",
                    getTestClass().getName()));
        }
    }

    private void validateAtLeastOneParameterSetField() {
        if (getTestClass().getAnnotatedFields(ClassParameter.class).isEmpty()
                && getTestClass().getAnnotatedMethods(UseMethodParameter.class).isEmpty()) {
            throw new IllegalArgumentException(String.format(Locale.getDefault(),
                    "%s has no field annotated with @ClassParameter or method annotated with"
                            + "@UseMethodParameter; it should not use ParameterizedRunner",
                    getTestClass().getName()));
        }
    }

    private void validateInstanceMethods() throws Exception {
        if (getTestClass().getAnnotatedMethods(Test.class).size() == 0) {
            throw new Exception("No runnable methods");
        }
    }

    /**
     * Return a list of runner delegates through ParameterizedRunnerDelegateFactory.
     *
     * For class parameter set: each class can only have one list of class parameter sets.
     * Each parameter set will be used to create one runner.
     *
     * For method parameter set: a single list method parameter sets is associated with
     * a string tag, an immutable map of string to parameter set list will be created and
     * passed into factory for each runner delegate to create multiple tests. Only one
     * Runner will be created for a method that uses @UseMethodParameter, regardless of the
     * number of ParameterSets in the associated list.
     *
     * @return a list of runners
     * @throws ParameterizedRunnerDelegateInstantiationException if runner delegate can not
     *         be instantiated with constructor reflectively
     * @throws IllegalAccessError if the field in tests are not accessible
     */
    static List<Runner> createRunners(TestClass testClass)
            throws IllegalAccessException, ParameterizedRunnerDelegateInstantiationException {
        List<ParameterSet> classParameterSetList;
        if (testClass.getAnnotatedFields(ClassParameter.class).isEmpty()) {
            classParameterSetList = new ArrayList<>();
            classParameterSetList.add(null);
        } else {
            classParameterSetList = getParameterSetList(
                    testClass.getAnnotatedFields(ClassParameter.class).get(0), testClass);
            validateWidth(classParameterSetList);
        }

        Class<? extends ParameterizedRunnerDelegate> runnerDelegateClass =
                getRunnerDelegateClass(testClass);
        ParameterizedRunnerDelegateFactory factory = new ParameterizedRunnerDelegateFactory();
        List<Runner> runnersForTestClass = new ArrayList<>();
        for (ParameterSet classParameterSet : classParameterSetList) {
            BlockJUnit4ClassRunner runner = (BlockJUnit4ClassRunner) factory.createRunner(
                    testClass, classParameterSet, runnerDelegateClass);
            runnersForTestClass.add(runner);
        }
        return runnersForTestClass;
    }

    /**
     * Return an unmodifiable list of ParameterSet through a FrameworkField
     */
    private static List<ParameterSet> getParameterSetList(FrameworkField field, TestClass testClass)
            throws IllegalAccessException {
        field.getField().setAccessible(true);
        if (!Modifier.isStatic(field.getField().getModifiers())) {
            throw new IllegalParameterArgumentException(String.format(Locale.getDefault(),
                    "ParameterSetList fields must be static, this field %s in %s is not",
                    field.getName(), testClass.getName()));
        }
        if (!(field.get(testClass.getJavaClass()) instanceof List)) {
            throw new IllegalArgumentException(String.format(Locale.getDefault(),
                    "Fields with @ClassParameter annotations must be an instance of List, "
                            + "this field %s in %s is not list",
                    field.getName(), testClass.getName()));
        }
        @SuppressWarnings("unchecked") // checked above
        List<ParameterSet> result = (List<ParameterSet>) field.get(testClass.getJavaClass());
        return Collections.unmodifiableList(result);
    }

    static void validateWidth(Iterable<ParameterSet> parameterSetList) {
        int lastSize = -1;
        for (ParameterSet set : parameterSetList) {
            if (set.size() == 0) {
                throw new IllegalParameterArgumentException(
                        "No parameter is added to method ParameterSet");
            }
            if (lastSize == -1 || set.size() == lastSize) {
                lastSize = set.size();
            } else {
                throw new IllegalParameterArgumentException(String.format(Locale.getDefault(),
                        "All ParameterSets in a list of ParameterSet must have equal"
                                + " length. The current ParameterSet (%s) contains %d parameters,"
                                + " while previous ParameterSet contains %d parameters",
                        Arrays.toString(set.getValues().toArray()), set.size(), lastSize));
            }
        }
    }

    /**
     * Get the runner delegate class for the test class if {@code @UseRunnerDelegate} is used.
     * The default runner delegate is BaseJUnit4RunnerDelegate.class
     */
    private static Class<? extends ParameterizedRunnerDelegate> getRunnerDelegateClass(
            TestClass testClass) {
        if (testClass.getAnnotation(UseRunnerDelegate.class) != null) {
            return testClass.getAnnotation(UseRunnerDelegate.class).value();
        }
        return BaseJUnit4RunnerDelegate.class;
    }

    static class IllegalParameterArgumentException extends IllegalArgumentException {
        IllegalParameterArgumentException(String msg) {
            super(msg);
        }
    }

    public static class ParameterizedTestInstantiationException extends Exception {
        ParameterizedTestInstantiationException(
                TestClass testClass, String parameterSetString, Exception e) {
            super(String.format(
                          "Test class %s can not be initiated, the provided parameters are %s,"
                                  + " the required parameter types are %s",
                          testClass.getJavaClass().toString(), parameterSetString,
                          Arrays.toString(testClass.getOnlyConstructor().getParameterTypes())),
                    e);
        }
    }

    /**
     * We need to prevent the ParentRunner from running ClassRules or Before/AfterClass annotations,
     * or they'll run a second time (re-entrantly) when the child runners that actually run the
     * tests run.
     *
     * Do not call super.classBlock().
     */
    @Override
    protected Statement classBlock(final RunNotifier notifier) {
        Statement statement = childrenInvoker(notifier);
        return statement;
    }
}