text:
import sys, subprocess
import struct

# ===== STEP 0: Prepares function-ID maps ===== #
map_extfun = {
              "tosthread_sleep":0, "tosthread_create":1,

              "led0On":2, "led1On":3, "led2On":4,
              "led0Off":5, "led1Off":6, "led2Off":7,
              "led0Toggle":8, "led1Toggle":9, "led2Toggle":10,

              "amSerialStart":11, "amSerialStop":12, "amSerialReceive":13,
              "amSerialSend":14, "amSerialLocalAddress":15, "amSerialGetLocalGroup":16,
              "amSerialGetDestination":17, "amSerialGetSource":18, "amSerialSetDestination":19,
              "amSerialSetSource":20, "amSerialIsForMe":21, "amSerialGetType":22,
              "amSerialSetType":23, "amSerialGetGroup":24, "amSerialSetGroup":25,
              "serialClear":26, "serialGetPayloadLength":27, "serialSetPayloadLength":28,
              "serialMaxPayloadLength":29, "serialGetPayload":30, "serialRequestAck":31,
              "serialNoAck":32, "serialWasAcked":33,

              "amRadioStart":34, "amRadioStop":35, "amRadioReceive":36,
              "amRadioSend":37, "amRadioGetLocalAddress":38, "amRadioGetLocalGroup":39,
              "amRadioGetDestination":40, "amRadioGetSource":41, "amRadioSetDestination":42,
              "amRadioSetSource":43, "amRadioIsForMe":44, "amRadioGetType":45,
              "amRadioSetType":46, "amRadioGetGroup":47, "amRadioSetGroup":48,
              "radioClear":49, "radioGetPayloadLength":50, "radioSetPayloadLength":51,
              "radioMaxPayloadLength":52, "radioGetPayload":53, "radioRequestAck":54,
              "radioNoAck":55, "radioWasAcked":56,

              "semaphore_reset":57, "semaphore_acquire":58, "semaphore_release":59,

              "barrier_reset":60, "barrier_block":61, "barrier_isBlocking":62,

              "condvar_init":63, "condvar_wait":64, "condvar_signalNext":65,
              "condvar_signalAll":66, "condvar_isBlocking":67,

              "mutex_init":68, "mutex_lock":69, "mutex_unlock":70,

              "volumeBlockRead":71, "volumeBlockWrite":72, "volumeBlockCrc":73,
              "volumeBlockErase":74, "volumeBlockSync":75,

              "refcounter_init":76, "refcounter_increment":77, "refcounter_decrement":78,
              "refcounter_waitOnValue":79, "refcounter_count":80,

              "amRadioSnoop":81,

              "queue_init":82, "queue_clear":83, "queue_push":84,
              "queue_pop":85, "queue_remove":86, "queue_size":87,
              "queue_is_empty":88,

              "sensirionSht11_humidity_read":89, "sensirionSht11_humidity_getNumBits":90, "sensirionSht11_temperature_read":91,
              "sensirionSht11_temperature_getNumBits":92,

              "hamamatsuS10871_tsr_read":93, "hamamatsuS10871_tsr_readStream":94, "hamamatsuS10871_tsr_getNumBits":95,

              "hamamatsuS1087_par_read":96, "hamamatsuS1087_par_readStream":97, "hamamatsuS1087_par_getNumBits":98,

              "volumeLogRead":99, "volumeLogCurrentReadOffset":100, "volumeLogSeek":101,
              "volumeLogGetSize":102,

              "volumeLogAppend":103, "volumeLogCurrentWriteOffset":104, "volumeLogErase":105,
              "volumeLogSync":106,

              "getLeds":107, "setLeds":108,

              "__divmodhi4":109,

              "tosthread_join":110,

              "volumeConfigMount":111, "volumeConfigRead":112, "volumeConfigWrite":113,
              "volumeConfigCommit":114, "volumeConfigGetSize":115, "volumeConfigValid":116}


text:
package br.com.monitoringDiabeticsApi.models;

import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "usuario_grupo")
public class UsuarioGrupo {

	@EmbeddedId
	private UsuarioGrupoId id;

	public UsuarioGrupoId getId() {
		return id;
	}

	public void setId(UsuarioGrupoId id) {
		this.id = id;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		UsuarioGrupo other = (UsuarioGrupo) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}

}

redpajama_set_name: RedPajamaGithub


text:
from pyramid.response import Response
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
from pyramid.session import check_csrf_token
from pyramid.security import (
    remember,
    forget,
    )
from sqlalchemy.exc import DBAPIError, SQLAlchemyError
from sqlalchemy import desc
from passlib.hash import sha256_crypt
from .models import (
    DBSession,
    Entry,
    )

from wtforms import Form, StringField, TextAreaField, validators

class EntryForm(Form):
    """WTForm for adding or editing entries."""
    title = StringField(u'Title', [validators.required(),
                        validators.length(max=128)])
    text = TextAreaField(u'Entry', [validators.required()])

def good_login(request):
    """Return true if the request is a valid login."""
    username = request.params.get('username')
    password = request.params.get('password')
    settings = request.registry.settings
    if not (username and password):  # UN or PW is missing
        return False
    if username == settings.get('auth.username'):
        return sha256_crypt.verify(password, settings.get('auth.password'))
    return False

@view_config(route_name='list', renderer='templates/list_template.jinja2',
             permission='read')
def list_view(request):
    """View for home page."""
    entries = DBSession.query(Entry).order_by(desc(Entry.created))
    return {'entries': entries, 'title': "Kyle's Learning Journal"}

@view_config(route_name='detail', renderer='templates/detail_template.jinja2',
             permission='read')
def detail_view(request):
    """View for single entry."""
    id = request.matchdict['id']
    entry = DBSession.query(Entry).filter(
        Entry.id == id).first()
    title = "Learning Journal Entry {}".format(id)
    return {'entry': entry, 'entry_text': entry.markdown, 'title': title}

@view_config(route_name='add_entry',
             renderer='templates/add_entry_template.jinja2',
             permission='create')
def add_entry_view(request):
    """View for adding entry page."""
    entry_form = EntryForm(request.POST)
    if request.method == 'POST' and entry_form.validate():
        check_csrf_token(request)
        if DBSession.query(Entry).filter(
                Entry.title == entry_form.title.data).all():
            #import pdb; pdb.set_trace()
            return {'title': 'Add Entry', 'form': entry_form,
                    'error': 'Title Already Used'}
        new_entry = Entry(title=entry_form.title.data,
                          text=entry_form.text.data)
        DBSession.add(new_entry)
        return HTTPFound(request.route_url('list'))
    return {'title': 'Add Entry', 'form': entry_form}

@view_config(route_name='edit_entry',
             renderer='templates/edit_entry_template.jinja2',
             permission='edit')
def edit_entry_view(request):
    """View for page editing an entry"""
    id = request.matchdict['id']
    current_entry = DBSession.query(Entry).filter(Entry.id == id).first()
    edited_form = EntryForm(request.POST, current_entry)
    if request.method == 'POST' and edited_form.validate():
        check_csrf_token(request)
        # If we try to edit the title to something already in DB
        if (DBSession.query(Entry).filter(
                Entry.title == edited_form.title.data).all() and
                current_entry.title != edited_form.title.data):
            return {'title': 'Add Entry', 'form': edited_form,
                    'error': 'Title Already Used'}
        current_entry.title = edited_form.title.data
        current_entry.text = edited_form.text.data
        return HTTPFound(request.route_url("detail", id=current_entry.id))
    return {'title': 'Add Entry', 'form': edited_form}

@view_config(route_name='login', renderer='templates/login_template.jinja2',
             permission='read')
def login_view(request):
    """View for login page."""
    error = ''
    if request.method == 'POST':
        if good_login(request):
            headers = remember(request, request.params['username'])
            return HTTPFound(request.route_url('list'), headers=headers)
        error = 'Bad Login'
    return {'error': error}

@view_config(route_name='logout')
def logout_view(request):
    """Logout View."""
    headers = forget(request)
    return HTTPFound(request.route_url('list'), headers=headers)

conn_err_msg = """\
Pyramid is having a problem using your SQL database.  The problem
might be caused by one of the following things:

1.  You may need to run the "initialize_learning-journal_db" script
    to initialize your database tables.  Check your virtual
    environment's "bin" directory for this script and try to run it.

2.  Your database server may not be running.  Check that the
    database server referred to by the "sqlalchemy.url" setting in
    your "development.ini" file is running.

After you fix the problem, please restart the Pyramid application to
try it again.
"""


text:
import configparser
from .remote import cache_if_remote
from collections import namedtuple
import os
import stat
from binascii import hexlify, unhexlify
import shutil

from .key import PlaintextKey
from .logger import create_logger
logger = create_logger()
from .helpers import Error, get_cache_dir, decode_dict, int_to_bigint, \
    bigint_to_int, format_file_size, yes
from .locking import UpgradableLock
from .hashindex import ChunkIndex

import msgpack

class Cache:
    """Client Side cache
    """
    class RepositoryReplay(Error):
        """Cache is newer than repository, refusing to continue"""

    class CacheInitAbortedError(Error):
        """Cache initialization aborted"""

    class RepositoryAccessAborted(Error):
        """Repository access aborted"""

    class EncryptionMethodMismatch(Error):
        """Repository encryption method changed since last access, refusing to continue"""

    @staticmethod
    def break_lock(repository, path=None):
        path = path or os.path.join(get_cache_dir(), hexlify(repository.id).decode('ascii'))
        UpgradableLock(os.path.join(path, 'lock'), exclusive=True).break_lock()

    def __init__(self, repository, key, manifest, path=None, sync=True, do_files=False, warn_if_unencrypted=True,
                 lock_wait=None):
        self.lock = None
        self.timestamp = None
        self.lock = None
        self.txn_active = False
        self.repository = repository
        self.key = key
        self.manifest = manifest
        self.path = path or os.path.join(get_cache_dir(), hexlify(repository.id).decode('ascii'))
        self.do_files = do_files
        # Warn user before sending data to a never seen before unencrypted repository
        if not os.path.exists(self.path):
            if warn_if_unencrypted and isinstance(key, PlaintextKey):
                msg = ("Warning: Attempting to access a previously unknown unencrypted repository!" +
                       "\n" +
                       "Do you want to continue? [yN] ")
                if not yes(msg, false_msg="Aborting.", env_var_override='BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK'):
                    raise self.CacheInitAbortedError()
            self.create()
        self.open(lock_wait=lock_wait)
        try:
            # Warn user before sending data to a relocated repository
            if self.previous_location and self.previous_location != repository._location.canonical_path():
                msg = ("Warning: The repository at location {} was previously located at {}".format(repository._location.canonical_path(), self.previous_location) +
                       "\n" +
                       "Do you want to continue? [yN] ")
                if not yes(msg, false_msg="Aborting.", env_var_override='BORG_RELOCATED_REPO_ACCESS_IS_OK'):
                    raise self.RepositoryAccessAborted()

            if sync and self.manifest.id != self.manifest_id:
                # If repository is older than the cache something fishy is going on
                if self.timestamp and self.timestamp > manifest.timestamp:
                    raise self.RepositoryReplay()
                # Make sure an encrypted repository has not been swapped for an unencrypted repository
                if self.key_type is not None and self.key_type != str(key.TYPE):
                    raise self.EncryptionMethodMismatch()
                self.sync()
                self.commit()
        except:
            self.close()
            raise

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    def __str__(self):
        fmt = """\
All archives:   {0.total_size:>20s} {0.total_csize:>20s} {0.unique_csize:>20s}

                       Unique chunks         Total chunks
Chunk index:    {0.total_unique_chunks:20d} {0.total_chunks:20d}"""
        return fmt.format(self.format_tuple())

    def format_tuple(self):
        # XXX: this should really be moved down to `hashindex.pyx`
        Summary = namedtuple('Summary', ['total_size', 'total_csize', 'unique_size', 'unique_csize', 'total_unique_chunks', 'total_chunks'])
        stats = Summary(*self.chunks.summarize())._asdict()
        for field in ['total_size', 'total_csize', 'unique_csize']:
            stats[field] = format_file_size(stats[field])
        return Summary(**stats)

    def create(self):
        """Create a new empty cache at `self.path`
        """
        os.makedirs(self.path)
        with open(os.path.join(self.path, 'README'), 'w') as fd:
            fd.write('This is a Borg cache')
        config = configparser.ConfigParser(interpolation=None)
        config.add_section('cache')
        config.set('cache', 'version', '1')
        config.set('cache', 'repository', hexlify(self.repository.id).decode('ascii'))
        config.set('cache', 'manifest', '')
        with open(os.path.join(self.path, 'config'), 'w') as fd:
            config.write(fd)
        ChunkIndex().write(os.path.join(self.path, 'chunks').encode('utf-8'))
        os.makedirs(os.path.join(self.path, 'chunks.archive.d'))
        with open(os.path.join(self.path, 'files'), 'wb') as fd:
            pass  # empty file

    def destroy(self):
        """destroy the cache at `self.path`
        """
        self.close()
        os.remove(os.path.join(self.path, 'config'))  # kill config first
        shutil.rmtree(self.path)

    def _do_open(self):
        self.config = configparser.ConfigParser(interpolation=None)
        config_path = os.path.join(self.path, 'config')
        self.config.read(config_path)
        try:
            cache_version = self.config.getint('cache', 'version')
            wanted_version = 1
            if cache_version != wanted_version:
                raise Exception('%s has unexpected cache version %d (wanted: %d).' % (
                    config_path, cache_version, wanted_version))
        except configparser.NoSectionError:
            raise Exception('%s does not look like a Borg cache.' % config_path) from None
        self.id = self.config.get('cache', 'repository')
        self.manifest_id = unhexlify(self.config.get('cache', 'manifest'))
        self.timestamp = self.config.get('cache', 'timestamp', fallback=None)
        self.key_type = self.config.get('cache', 'key_type', fallback=None)
        self.previous_location = self.config.get('cache', 'previous_location', fallback=None)
        self.chunks = ChunkIndex.read(os.path.join(self.path, 'chunks').encode('utf-8'))
        self.files = None

    def open(self, lock_wait=None):
        if not os.path.isdir(self.path):
            raise Exception('%s Does not look like a Borg cache' % self.path)
        self.lock = UpgradableLock(os.path.join(self.path, 'lock'), exclusive=True, timeout=lock_wait).acquire()
        self.rollback()

    def close(self):
        if self.lock is not None:
            self.lock.release()
            self.lock = None

    def _read_files(self):
        self.files = {}
        self._newest_mtime = 0
        logger.info('reading files cache')
        with open(os.path.join(self.path, 'files'), 'rb') as fd:
            u = msgpack.Unpacker(use_list=True)
            while True:
                data = fd.read(64 * 1024)
                if not data:
                    break
                u.feed(data)
                for path_hash, item in u:
                    item[0] += 1
                    # in the end, this takes about 240 Bytes per file
                    self.files[path_hash] = msgpack.packb(item)

    def begin_txn(self):
        # Initialize transaction snapshot
        txn_dir = os.path.join(self.path, 'txn.tmp')
        os.mkdir(txn_dir)
        shutil.copy(os.path.join(self.path, 'config'), txn_dir)
        shutil.copy(os.path.join(self.path, 'chunks'), txn_dir)
        shutil.copy(os.path.join(self.path, 'files'), txn_dir)
        os.rename(os.path.join(self.path, 'txn.tmp'),
                  os.path.join(self.path, 'txn.active'))
        self.txn_active = True

    def commit(self):
        """Commit transaction
        """
        if not self.txn_active:
            return
        if self.files is not None:
            with open(os.path.join(self.path, 'files'), 'wb') as fd:
                for path_hash, item in self.files.items():
                    # Discard cached files with the newest mtime to avoid
                    # issues with filesystem snapshots and mtime precision
                    item = msgpack.unpackb(item)
                    if item[0] < 10 and bigint_to_int(item[3]) < self._newest_mtime:
                        msgpack.pack((path_hash, item), fd)
        self.config.set('cache', 'manifest', hexlify(self.manifest.id).decode('ascii'))
        self.config.set('cache', 'timestamp', self.manifest.timestamp)
        self.config.set('cache', 'key_type', str(self.key.TYPE))
        self.config.set('cache', 'previous_location', self.repository._location.canonical_path())
        with open(os.path.join(self.path, 'config'), 'w') as fd:
            self.config.write(fd)
        self.chunks.write(os.path.join(self.path, 'chunks').encode('utf-8'))
        os.rename(os.path.join(self.path, 'txn.active'),
                  os.path.join(self.path, 'txn.tmp'))
        shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
        self.txn_active = False

    def rollback(self):
        """Roll back partial and aborted transactions
        """
        # Remove partial transaction
        if os.path.exists(os.path.join(self.path, 'txn.tmp')):
            shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
        # Roll back active transaction
        txn_dir = os.path.join(self.path, 'txn.active')
        if os.path.exists(txn_dir):
            shutil.copy(os.path.join(txn_dir, 'config'), self.path)
            shutil.copy(os.path.join(txn_dir, 'chunks'), self.path)
            shutil.copy(os.path.join(txn_dir, 'files'), self.path)
            os.rename(txn_dir, os.path.join(self.path, 'txn.tmp'))
            if os.path.exists(os.path.join(self.path, 'txn.tmp')):
                shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
        self.txn_active = False
        self._do_open()

    def sync(self):
        """Re-synchronize chunks cache with repository.

        Maintains a directory with known backup archive indexes, so it only
        needs to fetch infos from repo and build a chunk index once per backup
        archive.
        If out of sync, missing archive indexes get added, outdated indexes
        get removed and a new master chunks index is built by merging all
        archive indexes.
        """
        archive_path = os.path.join(self.path, 'chunks.archive.d')

        def mkpath(id, suffix=''):
            id_hex = hexlify(id).decode('ascii')
            path = os.path.join(archive_path, id_hex + suffix)
            return path.encode('utf-8')

        def cached_archives():
            if self.do_cache:
                fns = os.listdir(archive_path)
                # filenames with 64 hex digits == 256bit
                return set(unhexlify(fn) for fn in fns if len(fn) == 64)
            else:
                return set()

        def repo_archives():
            return set(info[b'id'] for info in self.manifest.archives.values())

        def cleanup_outdated(ids):
            for id in ids:
                os.unlink(mkpath(id))

        def fetch_and_build_idx(archive_id, repository, key):
            chunk_idx = ChunkIndex()
            cdata = repository.get(archive_id)
            data = key.decrypt(archive_id, cdata)
            chunk_idx.add(archive_id, 1, len(data), len(cdata))
            archive = msgpack.unpackb(data)
            if archive[b'version'] != 1:
                raise Exception('Unknown archive metadata version')
            decode_dict(archive, (b'name',))
            unpacker = msgpack.Unpacker()
            for item_id, chunk in zip(archive[b'items'], repository.get_many(archive[b'items'])):
                data = key.decrypt(item_id, chunk)
                chunk_idx.add(item_id, 1, len(data), len(chunk))
                unpacker.feed(data)
                for item in unpacker:
                    if not isinstance(item, dict):
                        logger.error('Error: Did not get expected metadata dict - archive corrupted!')
                        continue
                    if b'chunks' in item:
                        for chunk_id, size, csize in item[b'chunks']:
                            chunk_idx.add(chunk_id, 1, size, csize)
            if self.do_cache:
                fn = mkpath(archive_id)
                fn_tmp = mkpath(archive_id, suffix='.tmp')
                try:
                    chunk_idx.write(fn_tmp)
                except Exception:
                    os.unlink(fn_tmp)
                else:
                    os.rename(fn_tmp, fn)
            return chunk_idx

        def lookup_name(archive_id):
            for name, info in self.manifest.archives.items():
                if info[b'id'] == archive_id:
                    return name

        def create_master_idx(chunk_idx):
            logger.info('Synchronizing chunks cache...')
            cached_ids = cached_archives()
            archive_ids = repo_archives()
            logger.info('Archives: %d, w/ cached Idx: %d, w/ outdated Idx: %d, w/o cached Idx: %d.' % (
                len(archive_ids), len(cached_ids),
                len(cached_ids - archive_ids), len(archive_ids - cached_ids), ))
            # deallocates old hashindex, creates empty hashindex:
            chunk_idx.clear()
            cleanup_outdated(cached_ids - archive_ids)
            if archive_ids:
                chunk_idx = None
                for archive_id in archive_ids:
                    archive_name = lookup_name(archive_id)
                    if archive_id in cached_ids:
                        archive_chunk_idx_path = mkpath(archive_id)
                        logger.info("Reading cached archive chunk index for %s ..." % archive_name)
                        archive_chunk_idx = ChunkIndex.read(archive_chunk_idx_path)
                    else:
                        logger.info('Fetching and building archive index for %s ...' % archive_name)
                        archive_chunk_idx = fetch_and_build_idx(archive_id, repository, self.key)
                    logger.info("Merging into master chunks index ...")
                    if chunk_idx is None:
                        # we just use the first archive's idx as starting point,
                        # to avoid growing the hash table from 0 size and also
                        # to save 1 merge call.
                        chunk_idx = archive_chunk_idx
                    else:
                        chunk_idx.merge(archive_chunk_idx)
            logger.info('Done.')
            return chunk_idx

        def legacy_cleanup():
            """bring old cache dirs into the desired state (cleanup and adapt)"""
            try:
                os.unlink(os.path.join(self.path, 'chunks.archive'))
            except:
                pass
            try:
                os.unlink(os.path.join(self.path, 'chunks.archive.tmp'))
            except:
                pass
            try:
                os.mkdir(archive_path)
            except:
                pass

        self.begin_txn()
        with cache_if_remote(self.repository) as repository:
            legacy_cleanup()
            # TEMPORARY HACK: to avoid archive index caching, create a FILE named ~/.cache/borg/REPOID/chunks.archive.d -
            # this is only recommended if you have a fast, low latency connection to your repo (e.g. if repo is local disk)
            self.do_cache = os.path.isdir(archive_path)
            self.chunks = create_master_idx(self.chunks)

    def add_chunk(self, id, data, stats):
        if not self.txn_active:
            self.begin_txn()
        size = len(data)
        if self.seen_chunk(id, size):
            return self.chunk_incref(id, stats)
        data = self.key.encrypt(data)
        csize = len(data)
        self.repository.put(id, data, wait=False)
        self.chunks[id] = (1, size, csize)
        stats.update(size, csize, True)
        return id, size, csize

    def seen_chunk(self, id, size=None):
        refcount, stored_size, _ = self.chunks.get(id, (0, None, None))
        if size is not None and stored_size is not None and size != stored_size:
            # we already have a chunk with that id, but different size.
            # this is either a hash collision (unlikely) or corruption or a bug.
            raise Exception("chunk has same id [%r], but different size (stored: %d new: %d)!" % (
                            id, stored_size, size))
        return refcount

    def chunk_incref(self, id, stats):
        if not self.txn_active:
            self.begin_txn()
        count, size, csize = self.chunks[id]
        self.chunks[id] = (count + 1, size, csize)
        stats.update(size, csize, False)
        return id, size, csize

    def chunk_decref(self, id, stats):
        if not self.txn_active:
            self.begin_txn()
        count, size, csize = self.chunks[id]
        if count == 1:
            del self.chunks[id]
            self.repository.delete(id, wait=False)
            stats.update(-size, -csize, True)
        else:
            self.chunks[id] = (count - 1, size, csize)
            stats.update(-size, -csize, False)

    def file_known_and_unchanged(self, path_hash, st):
        if not (self.do_files and stat.S_ISREG(st.st_mode)):
            return None
        if self.files is None:
            self._read_files()
        entry = self.files.get(path_hash)
        if not entry:
            return None
        entry = msgpack.unpackb(entry)
        if entry[2] == st.st_size and bigint_to_int(entry[3]) == st.st_mtime_ns and entry[1] == st.st_ino:
            # reset entry age
            entry[0] = 0
            self.files[path_hash] = msgpack.packb(entry)
            return entry[4]
        else:
            return None

    def memorize_file(self, path_hash, st, ids):
        if not (self.do_files and stat.S_ISREG(st.st_mode)):
            return
        # Entry: Age, inode, size, mtime, chunk ids
        mtime_ns = st.st_mtime_ns
        self.files[path_hash] = msgpack.packb((0, st.st_ino, st.st_size, int_to_bigint(mtime_ns), ids))
        self._newest_mtime = max(self._newest_mtime, mtime_ns)


text:
package monitor

// system captures build diagnostics
type build struct {
	Version string
	Commit  string
	Branch  string
}

func (b *build) Diagnostics() (*Diagnostic, error) {
	diagnostics := map[string]interface{}{
		"Version": b.Version,
		"Commit":  b.Commit,
		"Branch":  b.Branch,
	}

	return DiagnosticFromMap(diagnostics), nil
}


text:
Objective-LINQ
=============

Objective-LINQ makes it easy to perform query operations on NSArray objects.


text:
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <string.h>
#include "driver/spi_master.h"
#include "soc/gpio_sig_map.h"
#include "soc/spi_reg.h"
#include "soc/dport_reg.h"
#include "soc/spi_struct.h"
#include "rom/ets_sys.h"
#include "esp_types.h"
#include "esp_attr.h"
#include "esp_intr.h"
#include "esp_intr_alloc.h"
#include "esp_log.h"
#include "esp_err.h"
#include "soc/soc.h"
#include "soc/dport_reg.h"
#include "rom/lldesc.h"
#include "driver/gpio.h"
#include "driver/periph_ctrl.h"
#include "esp_heap_caps.h"

#include "driver/spi_common.h"

static const char *SPI_TAG = "spi";

#define SPI_CHECK(a, str, ret_val) \
    if (!(a)) { \
        ESP_LOGE(SPI_TAG,"%s(%d): %s", __FUNCTION__, __LINE__, str); \
        return (ret_val); \
    }

typedef struct spi_device_t spi_device_t;

/*
 Stores a bunch of per-spi-peripheral data.
*/
typedef struct {
    const uint8_t spiclk_out;       //GPIO mux output signals
    const uint8_t spiclk_in;
    const uint8_t spid_out;
    const uint8_t spiq_out;
    const uint8_t spiwp_out;
    const uint8_t spihd_out;
    const uint8_t spid_in;          //GPIO mux input signals
    const uint8_t spiq_in;
    const uint8_t spiwp_in;
    const uint8_t spihd_in;
    const uint8_t spics_out[3];     // /CS GPIO output mux signals
    const uint8_t spics_in;
    const uint8_t spiclk_native;    //IO pins of IO_MUX muxed signals
    const uint8_t spid_native;
    const uint8_t spiq_native;
    const uint8_t spiwp_native;
    const uint8_t spihd_native;
    const uint8_t spics0_native;
    const uint8_t irq;              //irq source for interrupt mux
    const uint8_t irq_dma;          //dma irq source for interrupt mux
    const periph_module_t module;   //peripheral module, for enabling clock etc
    spi_dev_t *hw;              //Pointer to the hardware registers
} spi_signal_conn_t;

/*
 Bunch of constants for every SPI peripheral: GPIO signals, irqs, hw addr of registers etc
*/
static const spi_signal_conn_t io_signal[3] = {
    {
        .spiclk_out = SPICLK_OUT_IDX,
        .spiclk_in = SPICLK_IN_IDX,
        .spid_out = SPID_OUT_IDX,
        .spiq_out = SPIQ_OUT_IDX,
        .spiwp_out = SPIWP_OUT_IDX,
        .spihd_out = SPIHD_OUT_IDX,
        .spid_in = SPID_IN_IDX,
        .spiq_in = SPIQ_IN_IDX,
        .spiwp_in = SPIWP_IN_IDX,
        .spihd_in = SPIHD_IN_IDX,
        .spics_out = {SPICS0_OUT_IDX, SPICS1_OUT_IDX, SPICS2_OUT_IDX},
        .spics_in = SPICS0_IN_IDX,
        .spiclk_native = 6,
        .spid_native = 8,
        .spiq_native = 7,
        .spiwp_native = 10,
        .spihd_native = 9,
        .spics0_native = 11,
        .irq = ETS_SPI1_INTR_SOURCE,
        .irq_dma = ETS_SPI1_DMA_INTR_SOURCE,
        .module = PERIPH_SPI_MODULE,
        .hw = &SPI1
    }, {
        .spiclk_out = HSPICLK_OUT_IDX,
        .spiclk_in = HSPICLK_IN_IDX,
        .spid_out = HSPID_OUT_IDX,
        .spiq_out = HSPIQ_OUT_IDX,
        .spiwp_out = HSPIWP_OUT_IDX,
        .spihd_out = HSPIHD_OUT_IDX,
        .spid_in = HSPID_IN_IDX,
        .spiq_in = HSPIQ_IN_IDX,
        .spiwp_in = HSPIWP_IN_IDX,
        .spihd_in = HSPIHD_IN_IDX,
        .spics_out = {HSPICS0_OUT_IDX, HSPICS1_OUT_IDX, HSPICS2_OUT_IDX},
        .spics_in = HSPICS0_IN_IDX,
        .spiclk_native = 14,
        .spid_native = 13,
        .spiq_native = 12,
        .spiwp_native = 2,
        .spihd_native = 4,
        .spics0_native = 15,
        .irq = ETS_SPI2_INTR_SOURCE,
        .irq_dma = ETS_SPI2_DMA_INTR_SOURCE,
        .module = PERIPH_HSPI_MODULE,
        .hw = &SPI2
    }, {
        .spiclk_out = VSPICLK_OUT_IDX,
        .spiclk_in = VSPICLK_IN_IDX,
        .spid_out = VSPID_OUT_IDX,
        .spiq_out = VSPIQ_OUT_IDX,
        .spiwp_out = VSPIWP_OUT_IDX,
        .spihd_out = VSPIHD_OUT_IDX,
        .spid_in = VSPID_IN_IDX,
        .spiq_in = VSPIQ_IN_IDX,
        .spiwp_in = VSPIWP_IN_IDX,
        .spihd_in = VSPIHD_IN_IDX,
        .spics_out = {VSPICS0_OUT_IDX, VSPICS1_OUT_IDX, VSPICS2_OUT_IDX},
        .spics_in = VSPICS0_IN_IDX,
        .spiclk_native = 18,
        .spid_native = 23,
        .spiq_native = 19,
        .spiwp_native = 22,
        .spihd_native = 21,
        .spics0_native = 5,
        .irq = ETS_SPI3_INTR_SOURCE,
        .irq_dma = ETS_SPI3_DMA_INTR_SOURCE,
        .module = PERIPH_VSPI_MODULE,
        .hw = &SPI3
    }
};

//Periph 1 is 'claimed' by SPI flash code.
static bool spi_periph_claimed[3] = {true, false, false};

//Returns true if this peripheral is successfully claimed, false if otherwise.
bool spicommon_periph_claim(spi_host_device_t host)
{
    bool ret = __sync_bool_compare_and_swap(&spi_periph_claimed[host], false, true);
    if (ret) periph_module_enable(io_signal[host].module);
    return ret;
}

//Returns true if this peripheral is successfully freed, false if otherwise.
bool spicommon_periph_free(spi_host_device_t host)
{
    bool ret = __sync_bool_compare_and_swap(&spi_periph_claimed[host], true, false);
    if (ret) periph_module_disable(io_signal[host].module);
    return ret;
}

int spicommon_irqsource_for_host(spi_host_device_t host)
{
    return io_signal[host].irq;
}

spi_dev_t *spicommon_hw_for_host(spi_host_device_t host)
{
    return io_signal[host].hw;
}

/*
Do the common stuff to hook up a SPI host to a bus defined by a bunch of GPIO pins. Feed it a host number and a
bus config struct and it'll set up the GPIO matrix and enable the device. It will set is_native to 1 if the bus
config can be done using the IOMUX instead of using the GPIO matrix.
*/
esp_err_t spicommon_bus_initialize_io(spi_host_device_t host, const spi_bus_config_t *bus_config, int dma_chan, int flags, bool *is_native)
{
    bool native = true;
    bool use_quad = (flags & SPICOMMON_BUSFLAG_QUAD) != 0;

    SPI_CHECK(bus_config->mosi_io_num < 0 || GPIO_IS_VALID_OUTPUT_GPIO(bus_config->mosi_io_num), "spid pin invalid", ESP_ERR_INVALID_ARG);
    SPI_CHECK(bus_config->sclk_io_num < 0 || GPIO_IS_VALID_OUTPUT_GPIO(bus_config->sclk_io_num), "spiclk pin invalid", ESP_ERR_INVALID_ARG);
    SPI_CHECK(bus_config->miso_io_num < 0 || GPIO_IS_VALID_GPIO(bus_config->miso_io_num), "spiq pin invalid", ESP_ERR_INVALID_ARG);
    if (use_quad) {
        SPI_CHECK(bus_config->quadwp_io_num < 0 || GPIO_IS_VALID_OUTPUT_GPIO(bus_config->quadwp_io_num), "spiwp pin invalid", ESP_ERR_INVALID_ARG);
        SPI_CHECK(bus_config->quadhd_io_num < 0 || GPIO_IS_VALID_OUTPUT_GPIO(bus_config->quadhd_io_num), "spihd pin invalid", ESP_ERR_INVALID_ARG);
    }

    //Check if the selected pins correspond to the native pins of the peripheral
    if (bus_config->mosi_io_num >= 0 && bus_config->mosi_io_num != io_signal[host].spid_native) native = false;
    if (bus_config->miso_io_num >= 0 && bus_config->miso_io_num != io_signal[host].spiq_native) native = false;
    if (bus_config->sclk_io_num >= 0 && bus_config->sclk_io_num != io_signal[host].spiclk_native) native = false;
    if (use_quad) {
        if (bus_config->quadwp_io_num >= 0 && bus_config->quadwp_io_num != io_signal[host].spiwp_native) native = false;
        if (bus_config->quadhd_io_num >= 0 && bus_config->quadhd_io_num != io_signal[host].spihd_native) native = false;
    }

    *is_native = native;

    if (native) {
        //All SPI native pin selections resolve to 1, so we put that here instead of trying to figure
        //out which FUNC_GPIOx_xSPIxx to grab; they all are defined to 1 anyway.
        if (bus_config->mosi_io_num > 0) PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[bus_config->mosi_io_num], 1);
        if (bus_config->miso_io_num > 0) PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[bus_config->miso_io_num], 1);
        if (use_quad && bus_config->quadwp_io_num > 0) PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[bus_config->quadwp_io_num], 1);
        if (use_quad && bus_config->quadhd_io_num > 0) PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[bus_config->quadhd_io_num], 1);
        if (bus_config->sclk_io_num > 0) PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[bus_config->sclk_io_num], 1);
    } else {
        //Use GPIO
        if (bus_config->mosi_io_num > 0) {
            PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[bus_config->mosi_io_num], PIN_FUNC_GPIO);
            gpio_set_direction(bus_config->mosi_io_num, GPIO_MODE_INPUT_OUTPUT);
            gpio_matrix_out(bus_config->mosi_io_num, io_signal[host].spid_out, false, false);
            gpio_matrix_in(bus_config->mosi_io_num, io_signal[host].spid_in, false);
        }
        if (bus_config->miso_io_num > 0) {
            PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[bus_config->miso_io_num], PIN_FUNC_GPIO);
            gpio_set_direction(bus_config->miso_io_num, GPIO_MODE_INPUT_OUTPUT);
            gpio_matrix_out(bus_config->miso_io_num, io_signal[host].spiq_out, false, false);
            gpio_matrix_in(bus_config->miso_io_num, io_signal[host].spiq_in, false);
        }
        if (use_quad && bus_config->quadwp_io_num > 0) {
            PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[bus_config->quadwp_io_num], PIN_FUNC_GPIO);
            gpio_set_direction(bus_config->quadwp_io_num, GPIO_MODE_INPUT_OUTPUT);
            gpio_matrix_out(bus_config->quadwp_io_num, io_signal[host].spiwp_out, false, false);
            gpio_matrix_in(bus_config->quadwp_io_num, io_signal[host].spiwp_in, false);
        }
        if (use_quad && bus_config->quadhd_io_num > 0) {
            PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[bus_config->quadhd_io_num], PIN_FUNC_GPIO);
            gpio_set_direction(bus_config->quadhd_io_num, GPIO_MODE_INPUT_OUTPUT);
            gpio_matrix_out(bus_config->quadhd_io_num, io_signal[host].spihd_out, false, false);
            gpio_matrix_in(bus_config->quadhd_io_num, io_signal[host].spihd_in, false);
        }
        if (bus_config->sclk_io_num > 0) {
            PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[bus_config->sclk_io_num], PIN_FUNC_GPIO);
            gpio_set_direction(bus_config->sclk_io_num, GPIO_MODE_INPUT_OUTPUT);
            gpio_matrix_out(bus_config->sclk_io_num, io_signal[host].spiclk_out, false, false);
            gpio_matrix_in(bus_config->sclk_io_num, io_signal[host].spiclk_in, false);
        }
    }

    //Select DMA channel.
    DPORT_SET_PERI_REG_BITS(DPORT_SPI_DMA_CHAN_SEL_REG, 3, dma_chan, (host * 2));

    return ESP_OK;
}

//Find any pin with output muxed to ``func`` and reset it to GPIO
static void reset_func_to_gpio(int func)
{
    for (int x = 0; x < GPIO_PIN_COUNT; x++) {
        if (GPIO_IS_VALID_GPIO(x) && (READ_PERI_REG(GPIO_FUNC0_OUT_SEL_CFG_REG + (x * 4))&GPIO_FUNC0_OUT_SEL_M) == func)  {
            gpio_matrix_out(x, SIG_GPIO_OUT_IDX, false, false);
        }
    }
}

esp_err_t spicommon_bus_free_io(spi_host_device_t host)
{
    if (REG_GET_FIELD(GPIO_PIN_MUX_REG[io_signal[host].spid_native], MCU_SEL) == 1) PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[io_signal[host].spid_native], PIN_FUNC_GPIO);
    if (REG_GET_FIELD(GPIO_PIN_MUX_REG[io_signal[host].spiq_native], MCU_SEL) == 1) PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[io_signal[host].spiq_native], PIN_FUNC_GPIO);
    if (REG_GET_FIELD(GPIO_PIN_MUX_REG[io_signal[host].spiclk_native], MCU_SEL) == 1) PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[io_signal[host].spiclk_native], PIN_FUNC_GPIO);
    if (REG_GET_FIELD(GPIO_PIN_MUX_REG[io_signal[host].spiwp_native], MCU_SEL) == 1) PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[io_signal[host].spiwp_native], PIN_FUNC_GPIO);
    if (REG_GET_FIELD(GPIO_PIN_MUX_REG[io_signal[host].spihd_native], MCU_SEL) == 1) PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[io_signal[host].spihd_native], PIN_FUNC_GPIO);
    reset_func_to_gpio(io_signal[host].spid_out);
    reset_func_to_gpio(io_signal[host].spiq_out);
    reset_func_to_gpio(io_signal[host].spiclk_out);
    reset_func_to_gpio(io_signal[host].spiwp_out);
    reset_func_to_gpio(io_signal[host].spihd_out);
    return ESP_OK;
}

void spicommon_cs_initialize(spi_host_device_t host, int cs_io_num, int cs_num, int force_gpio_matrix)
{
    if (!force_gpio_matrix && cs_io_num == io_signal[host].spics0_native && cs_num == 0) {
        //The cs0s for all SPI peripherals map to pin mux source 1, so we use that instead of a define.
        PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[cs_io_num], 1);
    } else {
        //Use GPIO matrix
        PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[cs_io_num], PIN_FUNC_GPIO);
        gpio_matrix_out(cs_io_num, io_signal[host].spics_out[cs_num], false, false);
        if (cs_num == 0) gpio_matrix_in(cs_io_num, io_signal[host].spics_in, false);
    }
}

void spicommon_cs_free(spi_host_device_t host, int cs_io_num)
{
    if (cs_io_num == 0 && REG_GET_FIELD(GPIO_PIN_MUX_REG[io_signal[host].spics0_native], MCU_SEL) == 1) {
        PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[io_signal[host].spics0_native], PIN_FUNC_GPIO);
    }
    reset_func_to_gpio(io_signal[host].spics_out[cs_io_num]);
}

//Set up a list of dma descriptors. dmadesc is an array of descriptors. Data is the buffer to point to.
void spicommon_setup_dma_desc_links(lldesc_t *dmadesc, int len, const uint8_t *data, bool isrx)
{
    int n = 0;
    while (len) {
        int dmachunklen = len;
        if (dmachunklen > SPI_MAX_DMA_LEN) dmachunklen = SPI_MAX_DMA_LEN;
        if (isrx) {
            //Receive needs DMA length rounded to next 32-bit boundary
            dmadesc[n].size = (dmachunklen + 3) & (~3);
            dmadesc[n].length = (dmachunklen + 3) & (~3);
        } else {
            dmadesc[n].size = dmachunklen;
            dmadesc[n].length = dmachunklen;
        }
        dmadesc[n].buf = (uint8_t *)data;
        dmadesc[n].eof = 0;
        dmadesc[n].sosf = 0;
        dmadesc[n].owner = 1;
        dmadesc[n].qe.stqe_next = &dmadesc[n + 1];
        len -= dmachunklen;
        data += dmachunklen;
        n++;
    }
    dmadesc[n - 1].eof = 1; //Mark last DMA desc as end of stream.
    dmadesc[n - 1].qe.stqe_next = NULL;
}

/*
Code for workaround for DMA issue in ESP32 v0/v1 silicon
*/

static volatile int dmaworkaround_channels_busy[2] = {0, 0};
static dmaworkaround_cb_t dmaworkaround_cb;
static void *dmaworkaround_cb_arg;
static portMUX_TYPE dmaworkaround_mux = portMUX_INITIALIZER_UNLOCKED;
static int dmaworkaround_waiting_for_chan = 0;

bool IRAM_ATTR spicommon_dmaworkaround_req_reset(int dmachan, dmaworkaround_cb_t cb, void *arg)
{
    int otherchan = (dmachan == 1) ? 2 : 1;
    bool ret;
    portENTER_CRITICAL(&dmaworkaround_mux);
    if (dmaworkaround_channels_busy[otherchan-1]) {
        //Other channel is busy. Call back when it's done.
        dmaworkaround_cb = cb;
        dmaworkaround_cb_arg = arg;
        dmaworkaround_waiting_for_chan = otherchan;
        ret = false;
    } else {
        //Reset DMA
        DPORT_SET_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI_DMA_RST);
        DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI_DMA_RST);
        ret = true;
    }
    portEXIT_CRITICAL(&dmaworkaround_mux);
    return ret;
}

bool IRAM_ATTR spicommon_dmaworkaround_reset_in_progress()
{
    return (dmaworkaround_waiting_for_chan != 0);
}

void IRAM_ATTR spicommon_dmaworkaround_idle(int dmachan)
{
    portENTER_CRITICAL(&dmaworkaround_mux);
    dmaworkaround_channels_busy[dmachan-1] = 0;
    if (dmaworkaround_waiting_for_chan == dmachan) {
        //Reset DMA
        DPORT_SET_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI_DMA_RST);
        DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI_DMA_RST);
        dmaworkaround_waiting_for_chan = 0;
        //Call callback
        dmaworkaround_cb(dmaworkaround_cb_arg);

    }
    portEXIT_CRITICAL(&dmaworkaround_mux);
}

void IRAM_ATTR spicommon_dmaworkaround_transfer_active(int dmachan)
{
    portENTER_CRITICAL(&dmaworkaround_mux);
    dmaworkaround_channels_busy[dmachan-1] = 1;
    portEXIT_CRITICAL(&dmaworkaround_mux);
}


text:
using System;
using NUnit.Framework;
using Xamarin.Forms;

namespace UISleuth.Tests.SurfaceManager
{
    [TestFixture]
    public class TestDesignSurfaceManager
    {
        [Test]
        public void ContentView_HasContentProperty()
        {
            var cv = new ContentView();
            var page = new ContentPage { Content = cv };
            var mgr = new DefaultSurfaceManager();
            var root = mgr.SetInspectorSurface(page);

            var pair = mgr[cv.Id.ToString()];
            Assert.IsTrue(pair.UIWidget.HasContentProperty);
            Assert.IsTrue(pair.UIWidget.IsContentPropertyViewType);
            Assert.AreEqual(pair.UIWidget.ContentPropertyTypeName, typeof(View).FullName);
        }

        [Test]
        public void StackLayout_IsLayout_no_ContentProperty()
        {
            var stack = new StackLayout();
            var page = new ContentPage { Content = stack };
            var mgr = new DefaultSurfaceManager();
            var root = mgr.SetInspectorSurface(page);

            var pair = mgr[stack.Id.ToString()];
            Assert.AreEqual("System.Collections.IEnumerable<Xamarin.Forms.View>", pair.UIWidget.ContentPropertyTypeName);
            Assert.IsTrue(pair.UIWidget.IsLayout);
            Assert.IsTrue(pair.UIWidget.IsContentPropertyViewType);
            Assert.IsTrue(pair.UIWidget.HasContentProperty);
        }

        [Test]
        public void String_Content_isnt_Layout()
        {
            var label = new Label { Text = "value" };
            var page = new ContentPage { Content = label };
            var mgr = new DefaultSurfaceManager();
            var root = mgr.SetInspectorSurface(page);

            var pair = mgr[label.Id.ToString()];
            Assert.IsFalse(pair.UIWidget.IsLayout);
            Assert.IsTrue(pair.UIWidget.HasContentProperty);
            Assert.IsFalse(pair.UIWidget.IsContentPropertyViewType);
            Assert.AreEqual(typeof (string).FullName, pair.UIWidget.ContentPropertyTypeName);
        }

        [Test]
        public void Button_has_no_children_and_no_ContentProperty()
        {
            var btn = new Button { Text = "value" };
            var page = new ContentPage { Content = btn };
            var mgr = new DefaultSurfaceManager();
            var root = mgr.SetInspectorSurface(page);

            var pair = mgr[btn.Id.ToString()];
            Assert.IsFalse(pair.UIWidget.IsLayout);
            Assert.IsFalse(pair.UIWidget.HasContentProperty);
            Assert.IsFalse(pair.UIWidget.IsContentPropertyViewType);
            Assert.AreEqual(null, pair.UIWidget.ContentPropertyTypeName);
        }

        [Test]
        public void When_setting_design_surface_Root_is_set_and_returned()
        {
            var mgr = new DefaultSurfaceManager();
            var page = new ContentPage();

            var root = mgr.SetInspectorSurface(page);

            Assert.AreEqual(root, mgr.Root);
        }

        [Test]
        public void When_setting_design_surface_the_page_becomes_the_root_widget()
        {
            var mgr = new DefaultSurfaceManager();
            var page = new ContentPage();

            var root = mgr.SetInspectorSurface(page);

            Assert.AreEqual(page.Id.ToString(), root.Id, "Ids aren't equal.");
        }

        [Test]
        public void When_setting_design_surface_the_UIWidget_type_properties_are_set()
        {
            const string title = "Some title.";
            var mgr = new DefaultSurfaceManager();

            var page = new ContentPage
            {
                Title = title
            };

            var root = mgr.SetInspectorSurface(page);

            Assert.AreEqual(root.Id, page.Id.ToString(), "Ids aren't equal.");
            Assert.AreEqual(root.FullTypeName, page.GetType().FullName, "Full type names aren't equal.");
            Assert.AreEqual(root.Type, page.GetType().Name, "Short type names aren't equal.");
            Assert.AreEqual(root.Name, title, "The titles aren't equal.");
        }

        [Test]
        public void Can_lookup_UIWidget_by_id()
        {
            var label = new Label {Text = "textvalue"};
            var page = new ContentPage
            {
                Content = label
            };

            var mgr = new DefaultSurfaceManager();
            var root = mgr.SetInspectorSurface(page);

            var pagePair = mgr[page.Id.ToString()];
            var labelPair = mgr[label.Id.ToString()];

            Assert.AreEqual(root, pagePair.UIWidget, "The root and page aren't equal.");
            Assert.AreEqual(pagePair.VisualElement, page, "The page wasn't returned.");
            Assert.AreEqual(labelPair.VisualElement, label, "The label wasn't returned.");
            Assert.AreEqual(labelPair.UIWidget.Id, label.Id.ToString(), "The label Ids aren't equal.");
        }

        [Test]
        public void Can_lookup_UIWidget_by_guid()
        {
            var page = new ContentPage();
            var mgr = new DefaultSurfaceManager();

            mgr.SetInspectorSurface(page);
            var match = mgr[page.Id];

            Assert.IsNotNull(match, "Match was null.");
            Assert.AreEqual(match.UIWidget.Id, page.Id.ToString());
        }

        [Test]
        public void When_widget_isnt_found_during_lookup_return_null()
        {
            var page = new ContentPage();
            var mgr = new DefaultSurfaceManager();
            mgr.SetInspectorSurface(page);

            var pair = mgr["12345"];
            Assert.IsNull(pair);
        }

        [Test]
        public void Should_return_null_on_invalid_input()
        {
            var traverser = new DefaultSurfaceManager();

            // Act
            var nullArg = traverser[null];
            Assert.IsNull(nullArg, "Null returns null.");

            var empty = traverser[""];
            Assert.IsNull(empty, "Empty returns null.");

            var whitespace = traverser[" "];
            Assert.IsNull(whitespace, "Whitespace returns null.");
        }

        [Test]
        [Description("The client should prevent this action from happening.")]
        public void Removing_root_UIWidget()
        {
            var page = new ContentPage();
            var mgr = new DefaultSurfaceManager();
            var root = mgr.SetInspectorSurface(page);

            Assert.Throws<InvalidOperationException>(() => mgr.Remove(root));
        }

        [Test]
        public void Should_remove_only_design_surface_child_by_using_its_UIWidget()
        {
            var label = new Label {Text = "value"};
            var page = new ContentPage {Content = label};
            var mgr = new DefaultSurfaceManager();
            var root = mgr.SetInspectorSurface(page);

            var labelPair = mgr[label.Id.ToString()];
            var removed = mgr.Remove(labelPair.UIWidget);

            Assert.IsTrue(removed, "Removed wasn't true.");
            Assert.IsEmpty(mgr.Root.Children, "mgr.Root.Children should be empty.");
            Assert.IsEmpty(root.Children, "root.Children should be empty.");
            Assert.IsNull(page.Content, "Page content should be null.");
        }

        [Test]
        public void Should_remove_child_of_stacklayout_by_using_its_UIWidget()
        {
            var child = new Entry {Placeholder = "text"};
            var layout = new StackLayout();
            layout.Children.Add(child);
            var page = new ContentPage {Content = layout};

            var mgr = new DefaultSurfaceManager();
            mgr.SetInspectorSurface(page);

            var childPair = mgr[child.Id.ToString()];
            var layoutPair = mgr[layout.Id.ToString()];

            Assert.IsNotEmpty(layoutPair.UIWidget.Children, "The stacklayouts UIWidget should have children.");

            var removed = mgr.Remove(childPair.UIWidget);

            Assert.IsTrue(removed, "Removed wasn't true.");
            Assert.IsEmpty(layout.Children, "The stacklayout has children.");
            Assert.IsEmpty(layoutPair.UIWidget.Children, "The stacklayout has children.");
        }

        [Test]
        public void Calling_Contains_should_return_true_when_UIWidget_is_a_descendant_of_root()
        {
            var label = new Label();
            var child = new Entry { Placeholder = "text" };
            var layout = new StackLayout();
            layout.Children.Add(child);
            var page = new ContentPage { Content = layout };

            var mgr = new DefaultSurfaceManager();
            mgr.SetInspectorSurface(page);

            var childPair = mgr[child.Id.ToString()];
            var containsWidget = mgr.Contains(childPair.UIWidget);
            var containsVisual = mgr.Contains(childPair.VisualElement);
            var containsLabel = mgr.Contains(label);

            Assert.IsTrue(containsWidget, "UIWidget not found.");
            Assert.IsTrue(containsVisual, "VisualElement not found.");
            Assert.IsFalse(containsLabel, "Label was not added to the page.");
        }

        [Test]
        public void SetParent_page_is_parent_and_label_is_child()
        {
            var label = new Label {Text = "value"};
            var page = new ContentPage();
            var mgr = new DefaultSurfaceManager();

            mgr.SetInspectorSurface(page);

            var parented = mgr.SetParent(label, page);
            Assert.IsTrue(parented, "SetParent returned false.");
            Assert.AreEqual(1, mgr.Root.Children.Count, "Expected one child.");
            Assert.AreEqual(label.Id.ToString(), mgr.Root.Children[0].Id, "The label widget wasn't added to the children collection.");
        }

        [Test]
        public void SetParent_stacklayout_is_parent_and_entry_is_child()
        {
            var child = new Entry();
            var layout = new StackLayout();
            var page = new ContentPage();
            var mgr = new DefaultSurfaceManager();

            page.Content = layout;
            mgr.SetInspectorSurface(page);

            var parented = mgr.SetParent(child, layout);

            Assert.IsTrue(parented, "Parented returned false.");

            var layoutWidget = mgr[layout.Id.ToString()];
            Assert.IsNotEmpty(layoutWidget.UIWidget.Children, "UIWidget did not have any children.");
            Assert.IsNotEmpty(layout.Children, "StackLayout view did not contain children.");
        }

        [Test]
        public void SetParent_entry_is_parent_and_label_is_child()
        {
            var child = new Label();
            var entry = new Entry();
            var page = new ContentPage();
            var mgr = new DefaultSurfaceManager();

            page.Content = entry;
            mgr.SetInspectorSurface(page);

            var parented = mgr.SetParent(child, entry);
            Assert.IsFalse(parented, "Parented should be false.");
            Assert.AreEqual(mgr.Root.Children[0].Id, entry.Id.ToString(), "The content view has changed.");
        }

        [Test]
        public void SetParent_ContentView_is_parent_and_label_is_child()
        {
            var child = new Label();
            var content = new ContentView();
            var page = new ContentPage {Content = content};
            var mgr = new DefaultSurfaceManager();

            mgr.SetInspectorSurface(page);
            var parented = mgr.SetParent(child, content);

            Assert.IsTrue(parented, "Parented should be true.");

            var contentPair = mgr[content.Id.ToString()];
            Assert.IsNotEmpty(contentPair.UIWidget.Children, "Content children should have an element.");
            Assert.AreEqual(contentPair.UIWidget.Children[0].Id, child.Id.ToString(), "The wrong child was attached.");
        }

        [Test]
        public void SetParent_ScrollView_is_parent_and_entry_is_child()
        {
            var child = new Label();
            var content = new ScrollView();
            var page = new ContentPage { Content = content };
            var mgr = new DefaultSurfaceManager();

            mgr.SetInspectorSurface(page);
            var parented = mgr.SetParent(child, content);

            Assert.IsTrue(parented, "Parented should be true.");

            var contentPair = mgr[content.Id.ToString()];
            Assert.IsNotEmpty(contentPair.UIWidget.Children, "Content children should have an element.");
            Assert.AreEqual(contentPair.UIWidget.Children[0].Id, child.Id.ToString(), "The wrong child was attached.");
        }

        [Test]
        public void ListView_should_have_three_children_returned()
        {
            var lv = new ListView
            {
                ItemsSource = new[]
                {
                    "1",
                    "2",
                    "3"
                }
            };

            var page = new ContentPage { Content = lv };

            var mgr = new DefaultSurfaceManager();
            mgr.SetInspectorSurface(page);

            var pair = mgr[lv.Id];

            Assert.AreEqual(3, pair.UIWidget.Children.Count);
            Assert.AreEqual(typeof(TextCell).FullName, pair.UIWidget.Children[0].FullTypeName);
        }

        [Test]
        public void ListView_Cells_should_be_recognized()
        {
            var lv = new ListView
            {
                ItemsSource = new[]
                {
                    "1",
                    "2",
                    "3"
                }
            };

            var page = new ContentPage { Content = lv };

            var mgr = new DefaultSurfaceManager();
            mgr.SetInspectorSurface(page);

            var pair = mgr[lv.Id];
            Assert.AreEqual(3, pair.UIWidget.Children.Count);

            Assert.IsFalse(pair.UIWidget.IsCell);
            Assert.IsTrue(pair.UIWidget.Children[0].IsCell);
            Assert.IsTrue(pair.UIWidget.Children[1].IsCell);
            Assert.IsTrue(pair.UIWidget.Children[2].IsCell);
        }

        [Test]
        public void TableView_ImageCells_should_be_recognized()
        {
            var page = new ImageCellTableViewPage();
            var mgr = new DefaultSurfaceManager();
            mgr.SetInspectorSurface(page);

            var table = mgr[page.Table.Id];
            Assert.IsNotNull(table);

            var cell = table.UIWidget.Children[0];
            Assert.IsNotNull(cell);
            Assert.AreEqual(typeof(ImageCell).FullName, cell.FullTypeName);
        }

        [Test]
        public void ListView_Custom_cells_should_be_recognized()
        {
            var page = new ImageCellPage();
            var mgr = new DefaultSurfaceManager();
            mgr.SetInspectorSurface(page);

            var listview = mgr[page.ListView.Id];
            Assert.IsNotNull(listview);

            var cell = listview.UIWidget.Children[0];
            Assert.IsNotNull(cell);
            Assert.AreEqual(typeof(CustomCell).FullName, cell.FullTypeName);
        }

        [Test]
        public void ListView_ViewCell_children_recognized()
        {
            var page = new ImageCellPage();
            var mgr = new DefaultSurfaceManager();
            mgr.SetInspectorSurface(page);

            var listview = mgr[page.ListView.Id];
            Assert.IsNotNull(listview);

            var cell = listview.UIWidget.Children[0];

            Assert.IsNotNull(cell);
            Assert.IsTrue(cell.Children.Count > 0, "cell.Children.Count > 0");
            Assert.AreEqual("Xamarin.Forms.StackLayout", cell.Children[0].FullTypeName);
            Assert.IsTrue(cell.Children[0].Children.Count > 0, "cell.Children[0].Children.Count > 0");
        }

        [Test]
        public void ListView_ViewCells_in_StackLayout_recognized()
        {
            var page = new TestDataSelectorPage();
            var mgr = new DefaultSurfaceManager();
            mgr.SetInspectorSurface(page);

            var listview = mgr[page.ListView.Id];
            Assert.IsNotNull(listview);

            var cell = listview.UIWidget.Children[0];
            Assert.IsNotNull(cell);
            Assert.IsTrue(cell.Children.Count > 0, "cell.Children.Count > 0");
        }

        [Test]
        public void Cannot_delete_cells()
        {
            var page = new ImageCellPage();
            var mgr = new DefaultSurfaceManager();
            mgr.SetInspectorSurface(page);

            var listview = mgr[page.ListView.Id];
            Assert.IsNotNull(listview);

            var cell = listview.UIWidget.Children[0];
            Assert.IsNotNull(cell);
            Assert.AreEqual(typeof(CustomCell).FullName, cell.FullTypeName);

            foreach (var child in listview.UIWidget.Children)
            {
                Assert.IsFalse(child.CanDelete);
            }
        }

        [Test]
        public void Test_IsDatabound_True()
        {
            object ctx = new
            {
                Value1 = "123"
            };

            var page = new ContentPage
            {
                BindingContext = ctx
            };

            var mgr = new DefaultSurfaceManager();
            mgr.SetInspectorSurface(page);

            var pair = mgr[page.Id];

            Assert.IsNotNull(pair);
            Assert.IsTrue(pair.UIWidget.IsDatabound);
        }

        [Test]
        public void Test_IsDatabound_False()
        {
            var page = new ContentPage
            {
            };

            var mgr = new DefaultSurfaceManager();
            mgr.SetInspectorSurface(page);

            var pair = mgr[page.Id];

            Assert.IsNotNull(pair);
            Assert.IsFalse(pair.UIWidget.IsDatabound);
        }

        [Test]
        public void TableView_as_only_child_should_be_recognized()
        {
            var table = new TableView
            {
                Intent = TableIntent.Form,
                Root = new TableRoot
                {
                    new TableSection
                    {
                        new ImageCell(),
                        new SwitchCell(),
                        new EntryCell()
                    }
                }
            };

            var page = new ContentPage
            {
                Content = table
            };

            var mgr = new DefaultSurfaceManager();
            mgr.SetInspectorSurface(page);

            var pair = mgr[table.Id];

            Assert.IsNotNull(pair);
            Assert.AreEqual(3, pair.UIWidget.Children.Count);

            Assert.AreEqual(typeof(ImageCell).FullName, pair.UIWidget.Children[0].FullTypeName);
            Assert.AreEqual(typeof(SwitchCell).FullName, pair.UIWidget.Children[1].FullTypeName);
            Assert.AreEqual(typeof(EntryCell).FullName, pair.UIWidget.Children[2].FullTypeName);
        }
    }
}


text:
choco install android-sdk

choco install androidstudio

## This is also installed via Install-NodeTools.ps1

choco install yarn

yarn add global expo-cli

yarn add global react-native-cli


text:
namespace Quoteversation.Web.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    using Quoteversation.Data;

    public abstract class BaseController : Controller
    {
        public BaseController(IQuoteversationData data)
        {
            this.Data = data;
        }

        protected IQuoteversationData Data { get; set; }

        protected ApplicationUserManager CurrentUser { get; set; }
    }
}


text:
package io.cattle.platform.process.agent;

import com.netflix.config.DynamicBooleanProperty;
import io.cattle.platform.agent.AgentLocator;
import io.cattle.platform.agent.util.AgentUtils;
import io.cattle.platform.archaius.util.ArchaiusUtil;
import io.cattle.platform.core.constants.AccountConstants;
import io.cattle.platform.core.constants.AgentConstants;
import io.cattle.platform.core.constants.CredentialConstants;
import io.cattle.platform.core.constants.StoragePoolConstants;
import io.cattle.platform.core.dao.AccountDao;
import io.cattle.platform.core.model.Account;
import io.cattle.platform.core.model.Agent;
import io.cattle.platform.core.model.StoragePool;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.eventing.EventService;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.process.ObjectProcessManager;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.util.type.CollectionUtils;
import io.github.ibuildthecloud.gdapi.factory.SchemaFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import static io.cattle.platform.core.model.tables.AccountTable.*;
import static io.cattle.platform.core.model.tables.AgentTable.*;

public class AgentProcessManager {

    private static final DynamicBooleanProperty CREATE_ACCOUNT = ArchaiusUtil.getBoolean("process.agent.create.create.account");

    private static final Logger log = LoggerFactory.getLogger(AgentProcessManager.class);

    AccountDao accountDao;
    ObjectManager objectManager;
    ObjectProcessManager processManager;
    AgentLocator agentLocator;
    EventService eventService;
    SchemaFactory schemaFactory;

    public AgentProcessManager(AccountDao accountDao, ObjectManager objectManager, ObjectProcessManager processManager,
            AgentLocator agentLocator, EventService eventService, SchemaFactory schemaFactory) {
        this.accountDao = accountDao;
        this.objectManager = objectManager;
        this.processManager = processManager;
        this.agentLocator = agentLocator;
        this.eventService = eventService;
        this.schemaFactory = schemaFactory;
    }

    public HandlerResult create(ProcessState state, ProcessInstance process) {
        Agent agent = (Agent) state.getResource();
        Long accountId = agent.getAccountId();

        if (accountId != null || !CREATE_ACCOUNT.get()) {
            return new HandlerResult(AGENT.ACCOUNT_ID, accountId);
        }

        DataAccessor.fromMap(state.getData())
                .withScope(AccountConstants.class)
                .withKey(AccountConstants.OPTION_CREATE_APIKEY)
                .set(true);

        DataAccessor.fromMap(state.getData())
                .withScope(AccountConstants.class)
                .withKey(AccountConstants.OPTION_CREATE_APIKEY_KIND)
                .set(CredentialConstants.KIND_AGENT_API_KEY);

        List<? extends String> roles =
                DataAccessor.fromDataFieldOf(agent)
                        .withKey(AgentConstants.DATA_REQUESTED_ROLES)
                        .withDefault(Collections.EMPTY_LIST)
                        .asList(String.class);
        sortRoles(roles);

        String primaryRole = getPrimaryRole(roles); // note null is an acceptable value
        Account account = createPrimaryAccount(agent, primaryRole);
        processManager.executeCreateThenActivate(account, state.getData());

        Map<String, Object> data = new HashMap<>();
        data.put(AgentConstants.FIELD_ACCOUNT_ID, account.getId());

        List<? extends String> secondaryRoles = getSecondaryRoles(roles);
        List<Long> authedRoleAccounts = createSecondaryAccounts(agent, secondaryRoles, state);
        if (!authedRoleAccounts.isEmpty()) {
            data.put(AgentConstants.FIELD_AUTHORIZED_ROLE_ACCOUNTS, authedRoleAccounts);
        }

        return new HandlerResult(data);
    }

    public HandlerResult remove(ProcessState state, ProcessInstance process) {
        Agent agent = (Agent)state.getResource();

        for (String type : AgentUtils.AGENT_RESOURCES.get()) {
            Class<?> clz = schemaFactory.getSchemaClass(type);
            if (clz == null) {
                log.error("Failed to find class for [{}]", type);
                continue;
            }

            for (Object obj : objectManager.children(agent, clz)) {
                if (obj instanceof StoragePool) {
                    StoragePool sp = (StoragePool)obj;
                    if (StoragePoolConstants.TYPE.equals(sp.getKind())) {
                        // Don't automatically delete shared storage pools
                        continue;
                    }
                }
                processManager.executeDeactivateThenScheduleRemove(obj, null);
            }
        }

        if (agent.getAccountId() != null) {
            processManager.executeDeactivateThenScheduleRemove(objectManager.loadResource(Account.class, agent.getAccountId()), null);
        }

        List<Long> authedRoleAccountIds = DataAccessor.fieldLongList(agent, AgentConstants.FIELD_AUTHORIZED_ROLE_ACCOUNTS);
        for (Long accountId : authedRoleAccountIds) {
            processManager.executeDeactivateThenScheduleRemove(objectManager.loadResource(Account.class, accountId), null);
        }

        return null;
    }

    protected Account createPrimaryAccount(Agent agent, String role) {
        if (agent.getAccountId() != null) {
            return objectManager.loadResource(Account.class, agent.getAccountId());
        }

        String uuid = getAccountUuid(agent);
        Account account = accountDao.findByUuid(uuid);

        if (account == null) {
            Object data = createAccountDataWithActAsValue(role);
            account = objectManager.create(Account.class,
                    ACCOUNT.UUID, uuid,
                    ACCOUNT.DATA, data,
                    ACCOUNT.CLUSTER_ID, agent.getClusterId(),
                    ACCOUNT.KIND, "agent");
        }

        return account;
    }

    protected List<Long> createSecondaryAccounts(Agent agent, List<? extends String> roles, ProcessState state) {
        if (roles.isEmpty()) {
            return new ArrayList<>();
        }

        List<Long> authedRoleAccountIds = DataAccessor.fieldLongList(agent, AgentConstants.FIELD_AUTHORIZED_ROLE_ACCOUNTS);
        if (authedRoleAccountIds != null && !authedRoleAccountIds.isEmpty()) {
            return authedRoleAccountIds;
        }

        authedRoleAccountIds = new ArrayList<>();
        for (String role : roles) {
            String uuid = getAccountUuid(agent, role);
            Account account = accountDao.findByUuid(uuid);

            Map<String, Object> data = createAccountDataWithActAsValue(role);
            data.put(AccountConstants.DATA_AGENT_OWNER_ID, agent.getId());

            if (account == null) {
                account = objectManager.create(Account.class,
                        ACCOUNT.UUID, uuid,
                        ACCOUNT.DATA, data,
                        ACCOUNT.KIND, "agent");
            }
            processManager.executeCreateThenActivate(account, state.getData());
            authedRoleAccountIds.add(account.getId());
        }

        return authedRoleAccountIds;
    }

    Map<String, Object> createAccountDataWithActAsValue(String r) {
        if ("environment".equals(r)) {
            return CollectionUtils.asMap(AccountConstants.DATA_ACT_AS_RESOURCE_ACCOUNT, true);
        } else if ("environmentAdmin".equals(r)) {
            return CollectionUtils.asMap(AccountConstants.DATA_ACT_AS_RESOURCE_ADMIN_ACCOUNT, true);
        }
        return new HashMap<>();
    }

    private void sortRoles(List<? extends String> roles) {
        Collections.sort(roles, new Comparator<String>() {
            @Override
            public int compare(String lhs, String rhs) {
                if (lhs.equals(rhs)) {
                    return 0;
                }

                if ("agent".equals(lhs)) {
                    return -1;
                } else if ("agent".equals(rhs)) {
                    return 1;
                }

                if ("environmentAdmin".equals(lhs)) {
                    return -1;
                } else if ("environmentAdmin".equals(rhs)) {
                    return 1;
                }

                return 0;
            }
        });
    }

    private String getPrimaryRole(List<? extends String> roles) {
        if (roles.isEmpty()) {
            return null;
        }
        return roles.get(0);
    }

    private List<? extends String> getSecondaryRoles(List<? extends String> roles) {
        if (roles.isEmpty()) {
            return roles;
        } else if (roles.size() == 1){
            return new ArrayList<>();
        }
        return roles.subList(1, roles.size());
    }

    protected String getAccountUuid(Agent agent, String role) {
        return "agentAccount" + agent.getId() + "-" + role;
    }

    protected String getAccountUuid(Agent agent) {
        return "agentAccount" + agent.getId();
    }

    public AccountDao getAccountDao() {
        return accountDao;
    }

}


text:
"use strict"; // run code in ES5 strict mode

var expect = require("expect.js"),
    registry = require("../lib/node/registry.js");

describe("registry", function () {
    var descrA = {},
        descrB = {},
        descrC = {},
        constrA = function A() {},
        constrB = function B() {},
        constrC = function C() {},
        srcA = "A",
        srcB = "B",
        srcC = "C";

    describe(".setEntry()", function () {
        it("should throw no error", function () {
            registry.setEntry(descrA, constrA, srcA);
            registry.setEntry(descrB, constrB, srcB);
            registry.setEntry(descrC, constrC, srcC);
        });
    });
    describe(".getEntry()", function () {
        it("should return the requested entry", function () {
            var entry,
                expectedEntry;

            expectedEntry = {
                descriptor: descrA,
                constructorFunc: constrA,
                compiledSrc: srcA
            };
            entry = registry.getEntry(descrA);
            expect(entry).to.eql(expectedEntry);
            entry = registry.getEntry(constrA);
            expect(entry).to.eql(expectedEntry);

            expectedEntry = {
                descriptor: descrB,
                constructorFunc: constrB,
                compiledSrc: srcB
            };
            entry = registry.getEntry(descrB);
            expect(entry).to.eql(expectedEntry);
            entry = registry.getEntry(constrB);
            expect(entry).to.eql(expectedEntry);

            expectedEntry = {
                descriptor: descrC,
                constructorFunc: constrC,
                compiledSrc: srcC
            };
            entry = registry.getEntry(descrC);
            expect(entry).to.eql(expectedEntry);
            entry = registry.getEntry(constrC);
            expect(entry).to.eql(expectedEntry);
        });
        it("should return null if the component is unknown", function () {
            expect(registry.getEntry(function D() {})).to.be(null);
            expect(registry.getEntry({})).to.be(null);
        });
    });
});


text:
""" Code to load a class file compiled to native code in python memory space.
"""

import logging

from .io import read_class_file
from .class2ir import class_to_ir

def load_class(filename):
    """Load a compiled class into memory."""
    logger = logging.getLogger("jvm.io")
    with open(filename, "rb") as f:
        class_file = read_class_file(f)

    ir_module = class_to_ir(class_file)

    from ...api import ir_to_object, get_current_arch

    arch = get_current_arch()
    logger.info("Instantiating class as %s code", arch)
    obj = ir_to_object([ir_module], arch, debug=True)

    from ...utils.codepage import load_obj

    _code_module = load_obj(obj)
    return _code_module


text:
class A {

    constructor();
    constructor(a: string);
    constructor(a: number);
    constructor(a?: any) {

    }
}


text:
/*
   This structure is used by lib/interfaces.c to return the list of network
   interfaces on the machine
*/

struct iface_struct {
	char name[16];
	struct in_addr ip;
	struct in_addr netmask;
};


text:
            Order Review

            <button class="btn btn-default" ng-click="expressOrderReview.print()">Print</button>
            <button class="btn btn-info" ng-click="expressOrderReview.removeFromFavorites()" ng-if="expressOrderReview.submittedOrder.xp.favorite">
                  Remove from Favorites
            </button>
            <button class="btn btn-primary" ng-click="expressOrderReview.addToFavorites()" ng-if="!(expressOrderReview.submittedOrder.xp.favorite)">
                  Favorite This Order
            </button>

Billing Address

{{expressOrderReview.submittedOrder.BillingAddress | address: 'full'}}

Shipping Address

{{expressOrderReview.LineItems.Items[0].ShippingAddress | address: 'full'}}

Payment Information

Cardholder Name: {{expressOrderReview.orderPayments[$index].creditCardDetails.CardholderName}}

<i class="fa fa-2x"
                              ng-class="{'fa-cc-visa': expressOrderReview.orderPayments[$index].creditCardDetails.CardType == 'Visa',
                          'fa-cc-mastercard': expressOrderReview.orderPayments[$index].creditCardDetails.CardType == 'Master Card',
                          'fa-cc-amex': expressOrderReview.orderPayments[$index].creditCardDetails.CardType == 'American Expresss',
                          'fa-cc-discover': expressOrderReview.orderPayments[$index].creditCardDetails.CardType == 'Discover'}">

                            ending in {{expressOrderReview.orderPayments[$index].creditCardDetails.PartialAccountNumber}}

                        Spending Account ID: {{expressOrderReview.orderPayments[$index].spendingAccountDetails.Name}}

                        Purchase Order

                            : {{expressOrderReview.orderPayments[$index].xp.PONumber}}

                    Amount: {{payment.Amount | currency}}

                    Total: {{expressOrderReview.submittedOrder.Total | currency}}

Line Items

                        <colgroup>
                            <col style="width:100px;">
                            <col>
                            <col style="width:75px;">
                        </colgroup>

                                {{lineItem.Quantity}}

                                {{lineItem.Product.Name}}

                                {{lineItem.ProductID}}

                                    Shipping To:

{{lineItem.ShippingAddress | address}}


text:
<link rel="stylesheet" href="style.css" type="text/css">
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
<link rel="Start" href="index.html">
<link title="Index of values" rel=Appendix href="index_values.html">
<link title="Index of modules" rel=Appendix href="index_modules.html">
<link title="Lyrica" rel="Chapter" href="Lyrica.html"><title>Lyrica : Lyrica.install_handler</title>

let install_handler signal fn =

  let handler = Sys.Signal_handle (fun _ -> fn ()) in

    Sys.set_signal signal handler


text:
NETDATA_VER="1.6.0"
NET_MOD_HOCVPS="/etc/hocvps/cq_modules"
NET_DIR_PACK="${NET_MOD_HOCVPS}/netdata"
NET_DIR_NGX="${NET_DIR_PACK}/nginx"
NET_DIR_SCRIPTS="${NET_DIR_PACK}/scripts"

# Netdata port
NET_PORT_WEB="2244"
NET_PORT_STAT="2245"

NET_INSTALLER="${PWD}"
NET_INSTALLER_CONF="${PWD}/conf/"

NETDATA_DOWN_URL="https://cuongquach.com/download/packages/netdata/${NETDATA_VER}/netdata-${NETDATA_VER}.tar.gz"
NETDATA_DOWN_CHECKSUM="https://cuongquach.com/download/packages/netdata/${NETDATA_VER}/md5-netdata-${NETDATA_VER}.txt"


text:
<?php
namespace Cannoli\Framework\Core\Context;

use Cannoli\Framework\Core\Utility;

class InputManager extends Utility\Singleton implements IInputManager
{
	protected $data = array();

	public function has($key) {
		return isset($this->data[$key]);
	}

	public function data($key, $defaultValue = null) {
		if ( !$this->has($key) ) return $defaultValue;

		return $this->data[$key];
	}

	/*///////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
						ARRAYACCESS IMPLEMENTATION
	\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\//////////////////////////////*/

	/**
	 * @access public
	 * @param $offset
	 * @return boolean
	 */
	public function offsetExists($offset) {
		return isset($this->data[$offset]);
	}

	/**
	 * @access public
	 * @param $offset
	 * @return mixed
	 */
	public function offsetGet($offset) {
		return (isset($this->data[$offset]) ? $this->data[$offset] : null);
	}

	/**
	 * @access public
	 * @param $offset
	 * @param $value
	 * @return void
	 */
	public function offsetSet($offset, $value) {
		if ( !is_null($offset) ) {
            $this->data[$offset] = $value;
        }
	}

	/**
	 * @access public
	 * @param $offset
	 * @return void
	 */
	public function offsetUnset($offset) {
		unset($this->data[$offset]);
	}

	/**
	 * @access public
	 * @return void
	 */
	public function rewind() {
    	reset($this->data);
    }

    /**
     * @access public
     * @return mixed
     */
    public function current() {
		return current($this->data);
    }

    /**
     * @access public
     * @return mixed
     */
    public function key() {
		return key($this->data);
    }

    /**
     * @access public
     * @return mixed
     */
    public function next() {
		return next($this->data);
    }

    /**
     * @access public
     * @return boolean
     */
    public function valid() {
		return $this->current() !== false;
    }
}
?>


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/et_bg_black_shape" android:state_enabled="true"></item>
    <item android:drawable="@drawable/et_bg_black_shape_unenable"></item>

</selector>


text:
using System;
using Foundatio.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

namespace Foundatio.Azure.Extensions {
    public static class StorageExtensions {
        public static FileSpec ToFileInfo(this CloudBlockBlob blob) {
            if (blob.Properties.Length == -1)
                return null;

            return new FileSpec {
                Path = blob.Name,
                Size = blob.Properties.Length,
                Modified = blob.Properties.LastModified.HasValue ? blob.Properties.LastModified.Value.UtcDateTime : DateTime.MinValue,
                Created = blob.Properties.LastModified.HasValue ? blob.Properties.LastModified.Value.UtcDateTime : DateTime.MinValue
            };
        }
    }
}


text:
require "spec_helper"
require 'data_imp/parser/xls'

RSpec.describe DataImp::Parser::Xls do
  it_behaves_like "parser", "data/heros.xls", 9991212
end


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
    />
    <meta
      name="description"
      content="Multiple views synced across time and space."
    />
    <meta name="cesium-sandcastle-labels" content="Beginner, Showcases" />
    <title>Cesium Demo</title>

Loading...


text:
/**
 * Search component for bv-ui
 */
(function() {
    'use strict';

    angular
        .module('bv-ui.search-component', [
        ]);
})();


text:
<stix:STIX_Package
	xmlns:cyboxCommon="http://cybox.mitre.org/common-2"
	xmlns:cybox="http://cybox.mitre.org/cybox-2"
	xmlns:cyboxVocabs="http://cybox.mitre.org/default_vocabularies-2"
	xmlns:example="http://example.com"
	xmlns:incident="http://stix.mitre.org/Incident-1"
	xmlns:ta="http://stix.mitre.org/ThreatActor-1"
	xmlns:stixCommon="http://stix.mitre.org/common-1"
	xmlns:stixVocabs="http://stix.mitre.org/default_vocabularies-1"
	xmlns:stix-ciqidentity="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1"
	xmlns:stix="http://stix.mitre.org/stix-1"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:xal="urn:oasis:names:tc:ciq:xal:3"
	xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3"
	xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3"
	xsi:schemaLocation="
	http://cybox.mitre.org/common-2 http://cybox.mitre.org/XMLSchema/common/2.1/cybox_common.xsd
	http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.1/cybox_core.xsd
	http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.1/cybox_default_vocabularies.xsd
	http://stix.mitre.org/Incident-1 http://stix.mitre.org/XMLSchema/incident/1.1.1/incident.xsd
	http://stix.mitre.org/ThreatActor-1 http://stix.mitre.org/XMLSchema/threat_actor/1.1.1/threat_actor.xsd
	http://stix.mitre.org/common-1 http://stix.mitre.org/XMLSchema/common/1.1.1/stix_common.xsd
	http://stix.mitre.org/default_vocabularies-1 http://stix.mitre.org/XMLSchema/default_vocabularies/1.1.1/stix_default_vocabularies.xsd
	http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1 http://stix.mitre.org/XMLSchema/extensions/identity/ciq_3.0/1.1.1/ciq_3.0_identity.xsd
	http://stix.mitre.org/stix-1 http://stix.mitre.org/XMLSchema/core/1.1.1/stix_core.xsd
	urn:oasis:names:tc:ciq:xal:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xAL.xsd
	urn:oasis:names:tc:ciq:xnl:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xNL.xsd
	urn:oasis:names:tc:ciq:xpil:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xPIL.xsd" id="example:Package-4f6248f6-08cc-4e9a-a6b9-5fcff20f5783" version="1.1.1" timestamp="2013-02-21T00:11:43+00:00">
    <stix:Incidents>
        <stix:Incident id="example:incident-e804ec76-fd6b-4d64-8f23-18b35aa7f94a" timestamp="2014-05-10T00:58:19+00:00" xsi:type='incident:IncidentType'>
            <incident:Title>EmblemHealth is notifying approximately 1,800 GHI PPO members about a privacy breach that occurred in November 2012 and offering those affected free credit monitoring for the next 12 months.  On November 26, 2012, EmblemHealth discovered it had inadvertently included individual personal information on postcards that were sent to remind members about immunizations recommended for their children. The postcards were mailed on November 13, 2012, and addressed "To the Parent(s)/Guardian(s) of," and contained the child's name and address along with the subscriber's Social Security number embedded within a series of other mailing-related numbers.</incident:Title>
            <incident:External_ID source="VERIS">83C7C7AB-9B4E-4ECE-B02A-5C6004755D92</incident:External_ID>
            <incident:Time>
                <incident:Initial_Compromise precision="year">2012-01-01T00:00:00</incident:Initial_Compromise>
            </incident:Time>
            <incident:Reporter>
                <stixCommon:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                    <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">swidup</xnl:NameLine>
  </xpil:PartyName>
</ExtSch:Specification>
                </stixCommon:Identity>
            </incident:Reporter>
            <incident:Victim xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">EmblemHealth</xnl:NameLine>
  </xpil:PartyName>
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>US</xal:NameElement>
      </xal:Country>
      <xal:AdministrativeArea xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>NY</xal:NameElement>
      </xal:AdministrativeArea>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </incident:Victim>
            <incident:Affected_Assets>
                <incident:Affected_Asset>
                    <incident:Type>Documents</incident:Type>
                    <incident:Nature_Of_Security_Effect>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Confidentiality</incident:Property>
                            <incident:Description_Of_Effect>Personal: 1800</incident:Description_Of_Effect>
                        </incident:Property_Affected>
                    </incident:Nature_Of_Security_Effect>
                </incident:Affected_Asset>
            </incident:Affected_Assets>
            <incident:Impact_Assessment>
                <incident:Impact_Qualification xsi:type="stixVocabs:ImpactQualificationVocab-1.0">Unknown</incident:Impact_Qualification>
            </incident:Impact_Assessment>
            <incident:Attributed_Threat_Actors>
                <incident:Threat_Actor>
                    <stixCommon:Threat_Actor idref="example:threatactor-de165ee6-abb1-4b50-bb91-c019f300ebdb" xsi:type='ta:ThreatActorType'/>
                </incident:Threat_Actor>
            </incident:Attributed_Threat_Actors>
            <incident:Security_Compromise xsi:type="stixVocabs:SecurityCompromiseVocab-1.0">Yes</incident:Security_Compromise>
            <incident:Discovery_Method xsi:type="stixVocabs:DiscoveryMethodVocab-1.0">Unknown</incident:Discovery_Method>
            <incident:Information_Source>
                <stixCommon:Identity>
                    <stixCommon:Name>vcdb</stixCommon:Name>
                </stixCommon:Identity>
                <stixCommon:Tools>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>veris2stix</cyboxCommon:Name>
                        <cyboxCommon:Vendor>MITRE</cyboxCommon:Vendor>
                        <cyboxCommon:Version>0.1</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>VERIS schema</cyboxCommon:Name>
                        <cyboxCommon:Vendor>Verizon</cyboxCommon:Vendor>
                        <cyboxCommon:Version>1.3.0</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                </stixCommon:Tools>
                <stixCommon:References>
                    <stixCommon:Reference>http://www.emblemhealth.com/default.aspx?Page=about_news_20121219_privacy</stixCommon:Reference>
                </stixCommon:References>
            </incident:Information_Source>
        </stix:Incident>
    </stix:Incidents>
    <stix:Threat_Actors>
        <stix:Threat_Actor id="example:threatactor-de165ee6-abb1-4b50-bb91-c019f300ebdb" timestamp="2014-12-22T16:30:40.919000+00:00" xsi:type='ta:ThreatActorType'>
            <ta:Type timestamp="2014-12-22T16:30:40.919000+00:00">
                <stixCommon:Value xsi:type="stixVocabs:ThreatActorTypeVocab-1.0">Insider Threat</stixCommon:Value>
                <stixCommon:Description>End-user</stixCommon:Description>
            </ta:Type>
            <ta:Motivation timestamp="2014-12-22T16:30:40.919000+00:00">
                <stixCommon:Value>NA</stixCommon:Value>
            </ta:Motivation>
        </stix:Threat_Actor>
    </stix:Threat_Actors>
</stix:STIX_Package>


text:
<?php

require APPPATH.'third_party/phpmailer/PHPMailerAutoload.php';
require APPPATH.'third_party/htmlpurifier/library/HTMLPurifier/Bootstrap.php';

spl_autoload_register('_common_autoloader');

/**
 * Automatically loads classes in PHP5 way, using SPL.
 * @param   string      $class              The class name, no namespaces are supported.
 * @return  bool                            TRUE if a class have been found and loaded, FALSE otherwise.
 * @author  Ivan Tcholakov, 2013
 * @license The MIT License
 */
function _common_autoloader($class) {

    static $locations = null;

    if (!isset($locations)) {

        $locations = array();
        $autoload = null;

        _autoload_classes_read_config($autoload, APPPATH.'config/autoload_classes.php');
        _autoload_classes_read_config($autoload, APPPATH.'config/'.ENVIRONMENT.'/autoload_classes.php');

        if (isset($autoload) && is_array($autoload) && isset($autoload['classes']) && is_array($autoload['classes'])) {
            $locations = $autoload['classes'];
        }
    }

    $class = (string) $class;

    // No class name? Abort.
    if ($class == '') {
        return false;
    }

    // Scanning for classes in specific directories (see the array above).
    if (isset($locations[$class])) {
        require $locations[$class];
        return true;
    }

    // Autoload CodeIgniter classes.

    if (strpos($class, 'CI_') === 0) {

        if (is_file($location = BASEPATH.'core/'.substr($class, 3).'.php')) {
            require $location;
            return true;
        }

        if (is_file($location = BASEPATH.'libraries/'.substr($class, 3).'.php')) {
            require $location;
            return true;
        }

        if (is_file($location = BASEPATH.'libraries/'.substr($class, 3).'/'.substr($class, 3).'.php')) {
            require $location;
            return true;
        }
    }

    // Autoload core classes.

    if (is_file($location = APPPATH."core/$class.php")) {
        require $location;
        return true;
    }

    // Autoload Modular Extensions MX core classes.
    if (strpos($class, 'MX_') === 0 && is_file($location = APPPATH.'third_party/MX/'.substr($class, 3).'.php')) {
        require $location;
        return true;
    }

    // Autoload library classes.

    if (is_file($location = APPPATH."libraries/$class.php")) {
        require $location;
        return true;
    }

    // Autoload models (that are extended by other models).

    if (is_file($location = APPPATH."models/$class.php")) {
        require $location;
        return true;
    }

    // Autoload custom classes, non-standard way.

    if (is_file($location = APPPATH."classes/$class.php")) {
        require $location;
        return true;
    }

    // PSR-0 autoloading.

    if (is_file($location = APPPATH.'classes/'.str_replace('_', DIRECTORY_SEPARATOR, $class).'.php')) {
        require $location;
        return true;
    }

    // Autoload HTMLPurifier classes.
    if (HTMLPurifier_Bootstrap::autoload($class)) {
        return true;
    }

    // Autoload PEAR packages that are integrated in this platform.
    if (is_file($location = APPPATH.'third_party/pear/'.str_replace('_', DIRECTORY_SEPARATOR, $class).'.php')) {
        require $location;
        return true;
    }

    return false;
}

/**
 * Merges information from autoload_classes.php configuration files in different locations.
 * @param   null|array  $config_output      The result array (output parameter).
 * @param   string      $config_file        The current configuration file autoload_classes.php (a full path).
 * @return  void
 * @author  Ivan Tcholakov, 2013
 * @license The MIT License
 */
function _autoload_classes_read_config(& $config_output, $config_file) {

    if (file_exists($config_file)) {

        include($config_file);

        if (isset($autoload) && is_array($autoload)) {

            if (!isset($config_output) || !is_array($config_output)) {
                $config_output = array();
            }

            $config_output = array_merge_recursive($config_output, $autoload);
        }
    }
}


text:
<?php

namespace Test\TaskBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Show\ShowMapper;

class CategoryAdmin extends Admin
{

    protected function configureFormFields(FormMapper $formMapper)
    {

        $formMapper
             ->add('title')
            ->add('description')
        ;

    }

    // Fields to be shown on filter forms
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('title')
            ->add('description')
        ;
    }

//    // Fields to be shown on lists
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->add('title')
            ->add('_action', 'actions', array(
                    'actions' => array(
                        'show' => array(),
                        'edit' => array(),
                        'delete' => array(),
                    )
                ))
        ;
    }

    protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('title')
            ->add('description')
            ->end();
    }

}


text:
"""
    flask.ctx
    ~~~~~~~~~

    Implements the objects required to keep the context.

    :copyright: (c) 2010 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""

from werkzeug.exceptions import HTTPException

from .globals import _request_ctx_stack
from .session import _NullSession

class _RequestGlobals(object):
    pass

class _RequestContext(object):
    """The request context contains all request relevant information.  It is
    created at the beginning of the request and pushed to the
    `_request_ctx_stack` and removed at the end of it.  It will create the
    URL adapter and request object for the WSGI environment provided.
    """

    def __init__(self, app, environ):
        self.app = app
        self.request = app.request_class(environ)
        self.url_adapter = app.create_url_adapter(self.request)
        self.session = app.open_session(self.request)
        if self.session is None:
            self.session = _NullSession()
        self.g = _RequestGlobals()
        self.flashes = None

        try:
            url_rule, self.request.view_args = \
                self.url_adapter.match(return_rule=True)
            self.request.url_rule = url_rule
        except HTTPException, e:
            self.request.routing_exception = e

    def push(self):
        """Binds the request context."""
        _request_ctx_stack.push(self)

    def pop(self):
        """Pops the request context."""
        _request_ctx_stack.pop()

    def __enter__(self):
        self.push()
        return self

    def __exit__(self, exc_type, exc_value, tb):
        # do not pop the request stack if we are in debug mode and an
        # exception happened.  This will allow the debugger to still
        # access the request object in the interactive shell.  Furthermore
        # the context can be force kept alive for the test client.
        # See flask.testing for how this works.
        if not self.request.environ.get('flask._preserve_context') and \
           (tb is None or not self.app.debug):
            self.pop()


text:
use crate::xyy::XyY;
use crate::xyz::Xyz;

/// A named standard illuminant, expressed as XYZ coordinates
pub trait WhitePoint<T>: Clone + PartialEq {
    /// Return the white point's XYZ coordinates
    fn get_xyz(&self) -> Xyz<T>;
    /// Return the white point's coordinates expressed in xyY chromaticity space
    fn get_xy_chromaticity(&self) -> XyY<T>;
}

/// A `WhitePoint` which carries no data
pub trait UnitWhitePoint<T>: WhitePoint<T> + Default + Copy {}

impl<'a, T, U> WhitePoint<T> for &'a U
where
    U: WhitePoint<T>,
{
    fn get_xyz(&self) -> Xyz<T> {
        <U as WhitePoint<T>>::get_xyz(&self)
    }
    fn get_xy_chromaticity(&self) -> XyY<T> {
        <U as WhitePoint<T>>::get_xy_chromaticity(&self)
    }
}

pub mod deg_10;
pub mod deg_2;

pub use self::deg_2::*;