text:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals

from collections import namedtuple
import string
import re

from schematics.exceptions import StopValidation
from schematics.exceptions import ValidationError

from schematics.models import Model

from schematics.types import fill_template
from schematics.types import random_string

from schematics.types import BaseType
from schematics.types import BooleanType
from schematics.types import DateTimeType
from schematics.types import EmailType
from schematics.types import HashType
from schematics.types import LongType
from schematics.types import MD5Type
from schematics.types import SHA1Type
from schematics.types import StringType
from schematics.types import URLType

from schematics.types.compound import DictType
from schematics.types.compound import ListType
from schematics.types.compound import ModelType
from schematics.transforms import blacklist

"""
Common data model for package information and dependencies, abstracting the
many small differences existing between package management formats and tools.

At a high level a package is some piece of code that can be consumed as a unit
and provisioned by some package manager or can be installed as such.

In the simplest case, it can be a single file such as script; more commonly a
package is a complex set of archives, directories structures, file systems
images or self-executable installers.

A package typically contains:
 - some metadata,
 - some payload of code, doc, data.

Package metadata are found in multiple places:
- inside code text  (JavaDoc tags or Python __copyright__ magic)
- inside binaries (such as a Linux Elf or LKM or a Windows PE or an RPM header).
- in dedicated metafiles (such as a Maven POM, NPM package.json and many others)

These metadata provide details for:
 - information on the version of the file format of the current metadata file or header.
 - the package id or name and version.
 - a package namespace such as a central registry ensuing uniqueness of names.
 - some pre-requisite such as a specific OS (Linux), runtime (Java) or
   processor or architecture, some API level (such as an ABI or else),
 - info on the programming language used or needed or technical domain, either
   implicitly or explicitly.
 - documentation such as descriptions, notes, categories, tags,
   classifications or groups of sorts. This can include urls to external
   documentation, either explicitly or implicitly.
 - origin information: author, provider, distributor, vendor, owner, home
   urls, etc.
 - some contact or support information such as emails, mailing lists, forums,
 - some checksum or crypto signature of sorts to verify the integrity of the
   package, often stored outside the package itself,
 - version control info such as a Git or SVN repo where the source came from.
 - license and copyright info, either structured or not, eventually per-file
   or directory.
 - dependent packages, possibly grouped by purpose (dev, build, test, prod)
   The dependencies are either a complete tree or only the first level direct
   dependencies as a flat list. They can point to a name or some remote of local
   files. Dependencies are expressed usually as a package name and a version
   constraint or in some cases as lower level programming language-specific
   dependencies (such as OSGi Java package imports).
 - build and packaging instructions. Several package metadata formats mix
   build/packaging directives or instructions with the package metadata (such
   as RPM spec files).
 - installation directives and installation scripts to actually install the
   payload. These can be implicit such as with RPM directory structures.
 - where to fetch corresponding sources when compiled, either explicitly or
   implicitly, such as a VCS or some other package.
 - modification or patches applied and the patches themselves, with possibly
   changelog docs.
 - pointers to package registries where to fetch this or dependent packages,
   either explicitly or implicitly, including local files, VCS pointers or
   some central registry/repository URL.
 - description of the specific things provided by the payload, such as a
   binary, some API/ABI level, some library, some language namespace or some
   capability of sorts.

The payload of files and directories possibly contains:
  -- documentation,
  -- data files,
  -- code in source or compiled form or both.
"""

class ListType(ListType):
    """
    ListType with a default of an empty list.
    """
    def __init__(self, field, **kwargs):
        super(ListType, self).__init__(field=field, default=[], **kwargs)

PackageId = namedtuple('PackageId', 'type name version')

class PackageIndentifierType(BaseType):
    """
    Global identifier for a package
    """
    def __init__(self, **kwargs):
        super(PackageIndentifierType, self).__init__(**kwargs)

    def to_primitive(self, value, context=None):
        """
        Return a package id string, joining segments with a pipe separator.
        """
        if not value:
            return value

        if isinstance(value, PackageId):
            return u'|'.join(v or u'' for v in value)
        else:
            raise TypeError('Invalid package identifier')

    def to_native(self, value):
        return value

    def validate_id(self, value):
        if not isinstance(value, PackageId):
            raise StopValidation(self.messages['Invalid Package ID: must be PackageId named tuple'])

class SHA256Type(HashType):
    LENGTH = 64

class SHA512Type(HashType):
    LENGTH = 128

class URIType(StringType):
    """
    A field that validates input as a URI with several supported schemes beyond
    HTTP.
    """
    # Regex is derived from the code of schematics.URLType. BSD-licensed, see corresponding ABOUT file
    URI_REGEX = re.compile(
        r'^'
        r'(?:'
            r'(?:https?'
            r'|ftp|sftp|ftps'
            r'|rsync'
            r'|ssh'
            r'|git|git\+https?|git\+ssh|git\+git|git\+file'
            r'|hg|hg\+https?|hg\+ssh|hg\+static-https?'

            r'|bzr|bzr\+https?|bzr\+ssh|bzr\+sftp|bzr\+ftp|bzr+lp'
            r'|svn|svn\+http?|svn\+ssh|svn\+svn'
            r')'
            r'://'

        r'|'
            r'git\@'
        r')'

        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,2000}[A-Z0-9])?\.)+[A-Z]{2,63}\.?|'
        r'localhost|'
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
        r'(?::\d+)?'
        r'(?:/?|[/?]\S+)$', re.IGNORECASE
    )

    def __init__(self, **kwargs):
        super(URIType, self).__init__(**kwargs)

    def _mock(self, context=None):
        return fill_template('https://a%s.ZZ', self.min_length, self.max_length)

    def validate_url(self, value):
        if not self.__class__.URI_REGEX.match(value):
            raise StopValidation(self.messages['Invalid URI'])

    def canonical(self):
        """
        Return a canonical representation of this URI.
        """
        raise NotImplementedError()

class VersionType(BaseType):
    """
    A Package version is a string or a sequence of strings (list or tuple).

    'separator' is the separator string used to join a version sequence made of
    parts such as major, minor and patch.

    Packages with alternative versioning can subclass to define their own
    versioning scheme with add extra methods, a refined compare method for
    instance when storing a tuple, namedtuple or list for each each version
    parts or parsing the version in parts or exposiing parts.
    """
    metadata = dict(
        label='version',
        description='The version of the package as a string. '
        'Package types may implement specialized handling for versions, but this seralizes as a string')

    def __init__(self, separator=None, **kwargs):
        if not separator:
            separator = ''
        self.separator = separator
        super(VersionType, self).__init__(**kwargs)

    def validate_version(self, value):
        """
        Accept strings and empty strings or None as values in a value list
        """
        if value is None or isinstance(value, basestring):
            return

        if isinstance(value, (list, tuple,)) and all(isinstance(v, basestring) or v in (None, '') for v in value):
            return

        msg = 'Version must be a string or sequence of strings, not %r'
        raise ValidationError(msg % value)

    def to_primitive(self, value, context=None):
        """
        Return a version string. If the version is a sequence, join segments with separators.
        Subclasses can override.
        """
        if not value:
            return value
        if isinstance(value, (list, tuple,)):
            return unicode(self.separator).join(v for v in value if v)
        return unicode(value)

    def to_native(self, value):
        return value

    def sortable(self, value):
        """
        Return an opaque tuple to sort or compare versions. When not defined, a
        version sorts first.

        Each segment of a version is split on spaces, underscore, period and
        dash and returned separately in a sequence. Number are converted to int. This allows
        for a more natural sort.
        """
        if not value:
            return (-1,)
        srt = []
        if isinstance(value, (list, tuple,)):
            return tuple(value)

        # isinstance(value, basestring):
        for v in re.split('[\.\s\-_]', value):
            srt.append(v.isdigit() and int(v) or v)
        return tuple(srt)

    def _mock(self, context=None):
        a = random_string(1, string.digits)
        b = random_string(1, string.digits)
        return self.separator.join([a, b])

class BaseModel(Model):
    """
    Base class for all schematics models.
    """
    def __init__(self, **kwargs):
        super(BaseModel, self).__init__(raw_data=kwargs)

    def to_dict(self, **kwargs):
        """
        Return a dict of primitive Python types for this model instance.
        This is an OrderedDict because each model has a 'field_order' option.
        """
        return self.to_primitive(**kwargs)

# Package repo types
###############################
repo_bower = 'Bower'
repo_cpan = 'CPAN'
repo_debian = 'Debian'
repo_gems = 'Rubygems'
repo_godoc = 'Godoc'
repo_ivy = 'IVY'
repo_maven = 'Maven'
repo_npm = 'NPM'
repo_phpcomposer = 'Packagist'
repo_nuget = 'Nuget'
repo_python = 'Pypi'
repo_yum = 'YUM'

REPO_TYPES = (
    repo_bower,
    repo_cpan,
    repo_debian,
    repo_gems,
    repo_godoc,
    repo_ivy,
    repo_maven,
    repo_npm,
    repo_phpcomposer,
    repo_nuget,
    repo_python,
    repo_yum,
)

class Repository(BaseModel):
    metadata = dict(
        label='package repository',
        description='Represents a package repository.')

    type = StringType(choices=REPO_TYPES)
    type.metadata = dict(
        label='package repository type',
        description='The type of package repository for this repository. '
        'One of: ' + ', '.join(REPO_TYPES))

    url = URIType()
    url.metadata = dict(
        label='url',
        description='URL to this repository.')

    public = BooleanType(default=False)
    public.metadata = dict(
        label='public repository',
        description='A flag set to true if this is a public repository.')

    mirror_urls = ListType(URIType)
    mirror_urls.metadata = dict(
        label='repository mirror urls',
        description='A list of URLs for mirrors of this repository.')

    nickname = StringType()
    nickname.metadata = dict(
        label='repository nickname',
        description='nickname used for well known "named" public repos such as: '
        'Maven Central, Pypi, RubyGems, npmjs.org or their mirrors')

    class Options:
        fields_order = 'type', 'url', 'public', 'mirror_urls', 'name'

    def download_url(self, package):
        """
        Return a download URL for this package in this repository.
        """
        return NotImplementedError()

    def packages(self):
        """
        Return an iterable of Package objects available in this repository.
        """
        return NotImplementedError()

class AssertedLicense(BaseModel):
    metadata = dict(
        label='asserted license',
        description='Represents the licensing as asserted in a package metadata.')

    license = StringType()
    license.metadata = dict(
        label='license',
        description='license as asserted. This can be a text, a name or anything.')

    url = URIType()
    url.metadata = dict(
        label='url',
        description='URL to a web page for this license.')

    text = StringType()
    text.metadata = dict(
        label='license text',
        description='license text as asserted.')

    notice = StringType()
    notice.metadata = dict(
        label='notice',
        description='a license notice for this package')

    class Options:
        fields_order = 'license', 'url', 'text', 'notice'

# Party types
#################################
party_person = 'person'
party_project = 'project'  # often loosely defined
party_org = 'organization'  # more formally defined
PARTY_TYPES = (party_person, party_project, party_org,)

class Party(BaseModel):
    metadata = dict(
        label='party',
        description='A party is a person, project or organization related to a package.')

    type = StringType(choices=PARTY_TYPES)
    type.metadata = dict(
        label='party type',
        description='the type of this party: One of: ' + ', '.join(PARTY_TYPES))

    name = StringType()
    name.metadata = dict(
        label='name',
        description='Name of this party.')

    url = URLType()
    name.metadata = dict(
        label='url',
        description='URL to a primary web page for this party.')

    email = EmailType()
    email.metadata = dict(
        label='email',
        description='Email for this party.')

    class Options:
        fields_order = 'type', 'name', 'email', 'url'

# Groupings of package dependencies
###################################
dep_runtime = 'runtime'
dep_dev = 'development'
dep_test = 'test'
dep_build = 'build'
dep_optional = 'optional'
dep_bundled = 'bundled'
dep_ci = 'continuous integration'
DEPENDENCY_GROUPS = (dep_runtime, dep_dev, dep_optional, dep_test, dep_build, dep_ci, dep_bundled,)

# FIXME: this is broken ... OSGi uses "Java packages" deps as an indirection and not directly package deps.
class Dependency(BaseModel):
    metadata = dict(
        label='dependency',
        description='A dependency points to a Package via a package name and a version constraint '
        '(such as ">= 3.4"). The version is the effective version that has been '
        'picked and resolved.')

    name = StringType(required=True)
    name.metadata = dict(
        label='name',
        description='Name of the package for this dependency.')

    version = VersionType()
    version.metadata = dict(
        label='version',
        description='Version of this dependent package: '
        'The effective or concrete resolved and used version.')

    version_constraint = StringType()
    version_constraint.metadata = dict(
        label='version',
        description='The version constraints (aka. possible versions) '
        'for this dependent package: The meaning of this constraings is '
        'package type-specific. ')

    class Options:
        fields_order = 'type', 'name', 'version', 'version_constraint'

    def resolve(self):
        """
        Compute a concrete version.
        """
        # A normalized list of version constraints for this dep. This is package-
        # independent and should be a normalized data structure describing all the
        # different version range constraints
        # normalized_version_constraints = ListType(StringType())
        raise NotImplementedError()

# Types of the payload of a Package
###################################
payload_src = 'source'
# binaries include minified JavaScripts and similar obfuscated texts formats
payload_bin = 'binary'
payload_doc = 'doc'
PAYLOADS = (payload_src, payload_bin, payload_doc)

# Packaging types
#################################
as_archive = 'archive'
as_dir = 'directory'
as_file = 'file'
PACKAGINGS = (as_archive, as_dir, as_file)

# TODO: define relations. See SPDX specs

class RelatedPackage(BaseModel):
    metadata = dict(
        label='related package',
        description='A generic related package.')

    type = StringType(required=True)
    type.metadata = dict(
        label='type',
        description='Descriptive name of the type of package: '
        'RubyGem, Python Wheel, Java Jar, Debian package, etc.')

    name = StringType(required=True)
    name.metadata = dict(
        label='name',
        description='Name of the package.')

    version = VersionType()
    version.metadata = dict(
        label='version',
        description='Version of the package')

    payload_type = StringType(choices=PAYLOADS)
    payload_type.metadata = dict(
        label='Payload type',
        description='The type of payload for this package. One of: ' + ', '.join(PAYLOADS))

    class Options:
        fields_order = 'type', 'name', 'version', 'payload_type'

class Package(BaseModel):
    """
    A package object.
    Override for specific package behaviour. The way a
    package is created and serialized should be uniform across all Package
    types.
    """
    metadata = dict(
        label='package',
        description='A package object.')

    ###############################
    # real class-level attributes
    ###############################
    # content types data to recognize a package
    filetypes = tuple()
    mimetypes = tuple()
    extensions = tuple()
    # list of known metafiles for a package type, to recognize a package
    metafiles = []

    # list of supported repository types a package type, for reference
    repo_types = []

    ###############################
    # Field descriptors
    ###############################
    # from here on, these are actual instance attributes, using descriptors

    type = StringType(required=True)
    type.metadata = dict(
        label='package type',
        description='Descriptive name of the type of package: '
        'RubyGem, Python Wheel, Java Jar, Debian package, etc.')

    name = StringType(required=True)
    name.metadata = dict(
        label='package name',
        description='Name of the package.')

    version = VersionType()
    version.metadata = dict(
        label='package version',
        description='Version of the package. '
        'Package types may implement specific handling for versions but this is always serialized as a string.')

    primary_language = StringType()
    primary_language.metadata = dict(
        label='Primary programming language',
        description='Primary programming language of the package, such as Java, C, C++. '
        'Derived from the package type: i.e. RubyGems are primarily ruby, etc.')

    packaging = StringType(choices=PACKAGINGS)
    packaging.metadata = dict(
        label='Packaging',
        description='How a package is packaged. One of: ' + ', '.join(PACKAGINGS))

    # TODO: add os and arches!!

    summary = StringType()
    summary.metadata = dict(
        label='Summary',
        description='Summary for this package i.e. a short description')

    description = StringType()
    description.metadata = dict(
        label='Description',
        description='Description for this package '
        'i.e. a long description, often several pages of text')

    payload_type = StringType(choices=PAYLOADS)
    payload_type.metadata = dict(
        label='Payload type',
        description='The type of payload for this package. One of: ' + ', '.join(PAYLOADS))

    # we useLongType instead of IntType is because
    # IntType 2147483647 is the max size which means we cannot store
    # more than 2GB files
    size = LongType()
    size.metadata = dict(
        label='size',
        description='size of the package download in bytes')

    release_date = DateTimeType()
    release_date.metadata = dict(
        label='release date',
        description='Release date of the package')

    # FIXME: this would be simpler as a list where each Party has also a type
    authors = ListType(ModelType(Party))
    authors.metadata = dict(
        label='authors',
        description='A list of party objects. Note: this model schema will change soon.')

    maintainers = ListType(ModelType(Party))
    maintainers.metadata = dict(
        label='maintainers',
        description='A list of party objects. Note: this model schema will change soon.')

    contributors = ListType(ModelType(Party))
    contributors.metadata = dict(
        label='contributors',
        description='A list of party objects. Note: this model schema will change soon.')

    owners = ListType(ModelType(Party))
    owners.metadata = dict(
        label='owners',
        description='A list of party objects. Note: this model schema will change soon.')

    packagers = ListType(ModelType(Party))
    packagers.metadata = dict(
        label='owners',
        description='A list of party objects. Note: this model schema will change soon.')

    distributors = ListType(ModelType(Party))
    distributors.metadata = dict(
        label='distributors',
        description='A list of party objects. Note: this model schema will change soon.')

    vendors = ListType(ModelType(Party))
    vendors.metadata = dict(
        label='vendors',
        description='A list of party objects. Note: this model schema will change soon.')

    keywords = ListType(StringType())
    keywords.metadata = dict(
        label='keywords',
        description='A list of keywords or tags.')

    # FIXME: this is a Package-class attribute
    keywords_doc_url = URLType()
    keywords_doc_url.metadata = dict(
        label='keywords documentation URL',
        description='URL to a reference documentation for keywords or '
        'tags (such as a Pypi or SF.net Trove map)')

    metafile_locations = ListType(StringType())
    metafile_locations.metadata = dict(
        label='metafile locations',
        description='A list of metafile locations for this package '
        '(such as a package.json, a setup.py). '
        'Relative to the package root directory or archive root')

    metafile_urls = ListType(URIType())
    metafile_urls.metadata = dict(
        label='metafile URLs',
        description='A list of metafile remote URLs for this package '
        '(such as a package.json, a setup.py)')

    homepage_url = URIType()
    homepage_url.metadata = dict(
        label='homepage URL',
        description='URL to the homepage for this package')

    notes = StringType()
    notes.metadata = dict(
        label='Notes',
        description='Notes, free text about this package')

    download_urls = ListType(URIType())
    download_urls.metadata = dict(
        label='Download URLs',
        description='A list of direct download URLs, possibly in SPDX VCS url form. '
        'The first item is considered to be the primary download URL')

    download_sha1 = SHA1Type()
    download_sha1.metadata = dict(label='Download SHA1', description='Shecksum for the download')
    download_sha256 = SHA256Type()
    download_sha256.metadata = dict(label='Download SHA256', description='Shecksum for the download')
    download_md5 = MD5Type()
    download_md5.metadata = dict(label='Download MD5', description='Shecksum for the download')

    bug_tracking_url = URLType()
    bug_tracking_url.metadata = dict(
        label='bug tracking URL',
        description='URL to the issue or bug tracker for this package')

    support_contacts = ListType(StringType())
    support_contacts.metadata = dict(
        label='Support contacts',
        description='A list of strings (such as email, urls, etc) for support contacts')

    code_view_url = URIType()
    code_view_url.metadata = dict(
        label='code view URL',
        description='a URL where the code can be browsed online')

    VCS_CHOICES = ['git', 'svn', 'hg', 'bzr', 'cvs']
    vcs_tool = StringType(choices=VCS_CHOICES)
    vcs_tool.metadata = dict(
        label='Version control system tool',
        description='The type of VCS tool for this package. One of: ' + ', '.join(VCS_CHOICES))

    vcs_repository = URIType()
    vcs_repository.metadata = dict(
        label='VCS Repository URL',
        description='a URL to the VCS repository in the SPDX form of:'
        'git+https://github.com/nexb/scancode-toolkit.git')

    vcs_revision = StringType()
    vcs_revision.metadata = dict(
        label='VCS revision',
        description='a revision, commit, branch or tag reference, etc. '
        '(can also be included in the URL)')

    copyright_top_level = StringType()
    copyright_top_level.metadata = dict(
        label='Top level Copyright',
        description='a top level copyright often asserted in package metadata')

    copyrights = ListType(StringType())
    copyrights.metadata = dict(
        label='Copyrights',
        description='A list of effective copyrights as detected and eventually summarized')

    asserted_licenses = ListType(ModelType(AssertedLicense))
    asserted_licenses.metadata = dict(
        label='asserted licenses',
        description='A list of asserted license objects representing '
        'the asserted licensing information for this package')

    legal_file_locations = ListType(StringType())
    legal_file_locations.metadata = dict(
        label='legal file locations',
        description='A list of paths to legal files '
        '(such as COPYING, NOTICE, LICENSE, README, etc.). '
        'Paths are relative to the root of the package')

    license_expression = StringType()
    license_expression.metadata = dict(
        label='license expression',
        description='license expression: either resolved or detected license expression')

    license_texts = ListType(StringType())
    license_texts.metadata = dict(
        label='license texts',
        description='A list of license texts for this package.')

    notice_texts = ListType(StringType())
    license_texts.metadata = dict(
        label='notice texts',
        description='A list of notice texts for this package.')

    # Map a DEPENDENCY_GROUPS group name to a list of Dependency
    # FIXME: we should instead just have a plain list where each dep contain a group.
    dependencies = DictType(ListType(ModelType(Dependency)), default={})
    dependencies.metadata = dict(
        label='dependencies',
        description='An object mapping a dependency group to a '
        'list of dependency objects for this package. '
        'Note: the schema for this will change soon.'
        'The possible values for dependency grousp are:' + ', '.join(DEPENDENCY_GROUPS)
        )

    related_packages = ListType(ModelType(RelatedPackage))
    related_packages.metadata = dict(
        label='related packages',
        description='A list of related_package objects for this package. '
        'For instance the SRPM source of a binary RPM.')

    class Options:
        # this defines the important serialization order
        fields_order = [
            'type',
            'name',
            'version',
            'primary_language',
            'packaging',
            'summary',
            'description',
            'payload_type',
            'size',
            'release_date',

            'authors',
            'maintainers',
            'contributors',
            'owners',
            'packagers',
            'distributors',
            'vendors',

            'keywords',
            'keywords_doc_url',

            'metafile_locations',
            'metafile_urls',

            'homepage_url',
            'notes',
            'download_urls',
            'download_sha1',
            'download_sha256',
            'download_md5',

            'bug_tracking_url',
            'support_contacts',
            'code_view_url',

            'vcs_tool',
            'vcs_repository',
            'vcs_revision',

            'copyright_top_level',
            'copyrights',

            'asserted_licenses',
            'legal_file_locations',
            'license_expression',
            'license_texts',
            'notice_texts',

            'dependencies',
            'related_packages'
        ]

        # we use for now a "role" that excludes deps and relationships from the
        # serailization
        roles = {'no_deps': blacklist('dependencies', 'related_packages')}

    def __init__(self, location=None, **kwargs):
        """
        Initialize a new Package.
        Subclass can override but should override the recognize method to populate a package accordingly.
        """
        # path to a file or directory where this Package is found in a scan
        self.location = location
        super(Package, self).__init__(**kwargs)

    @classmethod
    def recognize(cls, location):
        """
        Return a Package object or None given a location to a file or directory
        pointing to a package archive, metafile or similar.

        Sub-classes should override to implement their own package recognition.
        """
        return

    @property
    def component_version(self):
        """
        Return the component-level version representation for this package.
        Subclasses can override.
        """
        return self.version

    def compare_version(self, other, component_level=False):
        """
        Compare the version of this package with another package version.

        Use the same semantics as the builtin cmp function. It returns:
        - a negaitive integer if this version < other version,
        - zero if this version== other.version
        - a positive interger if this version > other version.

        Use the component-level version if `component_level` is True.

        Subclasses can override for package-type specific comparisons.

        For example:
        # >>> q=Package(version='2')
        # >>> p=Package(version='1')
        # >>> p.compare_version(q)
        # -1
        # >>> p.compare_version(p)
        # 0
        # >>> r=Package(version='0')
        # >>> p.compare_version(r)
        # 1
        # >>> s=Package(version='1')
        # >>> p.compare_version(s)
        # 0
        """
        x = component_level and self.component_version() or self.version
        y = component_level and other.component_version() or self.version
        return cmp(x, y)

    def sort_key(self):
        """
        Return some data suiatble to use as a key function when sorting.
        """
        return (self.type, self.name, self.version.sortable(self.version),)

    @property
    def identifier(self):
        """
        Return a PackageId object for this package.
        """
        return PackageId(self.type, self.name, self.version)

#
# Package sub types
# NOTE: this is somewhat redundant with extractcode archive handlers
# yet the purpose and semantics are rather different here

class DebianPackage(Package):
    metafiles = ('*.control',)
    extensions = ('.deb',)
    filetypes = ('debian binary package',)
    mimetypes = ('application/x-archive', 'application/vnd.debian.binary-package',)
    repo_types = (repo_debian,)

    type = StringType(default='Debian package')
    packaging = StringType(default=as_archive)

class JavaJar(Package):
    metafiles = ('META-INF/MANIFEST.MF',)
    extensions = ('.jar',)
    filetypes = ('java archive ', 'zip archive',)
    mimetypes = ('application/java-archive', 'application/zip',)
    repo_types = (repo_maven, repo_ivy,)

    type = StringType(default='Java Jar')
    packaging = StringType(default=as_archive)
    primary_language = StringType(default='Java')

class JavaWar(Package):
    metafiles = ('WEB-INF/web.xml',)
    extensions = ('.war',)
    filetypes = ('java archive ', 'zip archive',)
    mimetypes = ('application/java-archive', 'application/zip')
    repo_types = (repo_maven, repo_ivy,)

    type = StringType(default='Java Web application')
    packaging = StringType(default=as_archive)
    primary_language = StringType(default='Java')

class JavaEar(Package):
    metafiles = ('META-INF/application.xml', 'META-INF/ejb-jar.xml')
    extensions = ('.ear',)
    filetypes = ('java archive ', 'zip archive',)
    mimetypes = ('application/java-archive', 'application/zip')
    repo_types = (repo_maven, repo_ivy,)

    type = StringType(default='Enterprise Java application')
    packaging = StringType(default=as_archive)
    primary_language = StringType(default='Java')

class Axis2Mar(Package):
    metafiles = ('META-INF/module.xml',)
    extensions = ('.mar',)
    filetypes = ('java archive ', 'zip archive',)
    mimetypes = ('application/java-archive', 'application/zip')
    repo_types = (repo_maven, repo_ivy,)

    type = StringType(default='Apache Axis2 module')
    packaging = StringType(default=as_archive)
    primary_language = StringType(default='Java')

class JBossSar(Package):
    metafiles = ('META-INF/jboss-service.xml',)
    extensions = ('.sar',)
    filetypes = ('java archive ', 'zip archive',)
    mimetypes = ('application/java-archive', 'application/zip')
    repo_types = (repo_maven, repo_ivy,)

    type = StringType(default='JBoss service archive')
    packaging = StringType(default=as_archive)
    primary_language = StringType(default='Java')

class IvyJar(JavaJar):
    metafiles = ('ivy.xml',)
    repo_types = (repo_ivy,)

    type = StringType(default='Apache IVY package')

class BowerPackage(Package):
    metafiles = ('bower.json',)
    repo_types = (repo_bower, repo_npm,)

    type = StringType(default='Bower package')
    primary_language = StringType(default='JavaScript')

class MeteorPackage(Package):
    metafiles = ('package.js',)

    type = StringType(default='Meteor package')
    primary_language = 'JavaScript'

class CpanModule(Package):
    metafiles = ('*.pod', '*.pm', 'MANIFEST', 'Makefile.PL', 'META.yml', 'META.json', '*.meta', 'dist.ini')
    # TODO: refine me
    extensions = (
        '.tar.gz',
    )
    repo_types = (repo_cpan,)

    type = StringType(default='CPAN Perl module')
    primary_language = 'Perl'

# TODO: refine me
class Godep(Package):
    metafiles = ('Godeps',)
    repo_types = (repo_godoc,)

    type = StringType(default='Go package')
    primary_language = 'Go'

class RubyGem(Package):
    metafiles = ('*.control', '*.gemspec', 'Gemfile', 'Gemfile.lock',)
    filetypes = ('.tar', 'tar archive',)
    mimetypes = ('application/x-tar',)
    extensions = ('.gem',)
    repo_types = (repo_gems,)

    type = StringType(default='RubyGem')
    primary_language = 'Ruby'
    packaging = StringType(default=as_archive)

class AndroidApp(Package):
    filetypes = ('zip archive',)
    mimetypes = ('application/zip',)
    extensions = ('.apk',)

    type = StringType(default='Android app')
    primary_language = StringType(default='Java')
    packaging = StringType(default=as_archive)

# see http://tools.android.com/tech-docs/new-build-system/aar-formats
class AndroidLibrary(Package):
    filetypes = ('zip archive',)
    mimetypes = ('application/zip',)
    # note: Apache Axis also uses AAR extensions for plain Jars.
    # this could be decided based on internal structure
    extensions = ('.aar',)

    type = StringType(default='Android library')
    primary_language = StringType(default='Java')
    packaging = StringType(default=as_archive)

class MozillaExtension(Package):
    filetypes = ('zip archive',)
    mimetypes = ('application/zip',)
    extensions = ('.xpi',)

    type = StringType(default='Mozilla extension')
    primary_language = StringType(default='JavaScript')
    packaging = StringType(default=as_archive)

class ChromeExtension(Package):
    filetypes = ('data',)
    mimetypes = ('application/octet-stream',)
    extensions = ('.crx',)

    type = StringType(default='Chrome extension')
    primary_language = StringType(default='JavaScript')
    packaging = StringType(default=as_archive)

class IOSApp(Package):
    filetypes = ('zip archive',)
    mimetypes = ('application/zip',)
    extensions = ('.ipa',)

    type = StringType(default='iOS app')
    primary_language = StringType(default='Objective-C')
    packaging = StringType(default=as_archive)

class PythonPackage(Package):
    filetypes = ('zip archive',)
    mimetypes = ('application/zip',)
    extensions = ('.egg', '.whl', '.pyz', '.pex',)
    repo_types = (repo_python,)

    type = StringType(default='Python package')
    primary_language = StringType(default='Python')
    packaging = StringType(default=as_archive)

class CabPackage(Package):
    filetypes = ('microsoft cabinet',)
    mimetypes = ('application/vnd.ms-cab-compressed',)
    extensions = ('.cab',)

    type = StringType(default='Microsoft cab')
    packaging = StringType(default=as_archive)

class MsiInstallerPackage(Package):
    filetypes = ('msi installer',)
    mimetypes = ('application/x-msi',)
    extensions = ('.msi',)

    type = StringType(default='Microsoft MSI Installer')
    packaging = StringType(default=as_archive)

class InstallShieldPackage(Package):
    filetypes = ('installshield',)
    mimetypes = ('application/x-dosexec',)
    extensions = ('.exe',)

    type = StringType(default='InstallShield Installer')
    packaging = StringType(default=as_archive)

class NSISInstallerPackage(Package):
    filetypes = ('nullsoft installer',)
    mimetypes = ('application/x-dosexec',)
    extensions = ('.exe',)

    type = StringType(default='Nullsoft Installer')
    packaging = StringType(default=as_archive)

class SharPackage(Package):
    filetypes = ('posix shell script',)
    mimetypes = ('text/x-shellscript',)
    extensions = ('.sha', '.shar', '.bin',)

    type = StringType(default='shar shell archive')
    packaging = StringType(default=as_archive)

class AppleDmgPackage(Package):
    filetypes = ('zlib compressed',)
    mimetypes = ('application/zlib',)
    extensions = ('.dmg', '.sparseimage',)

    type = StringType(default='Apple dmg')
    packaging = StringType(default=as_archive)

class IsoImagePackage(Package):
    filetypes = ('iso 9660 cd-rom', 'high sierra cd-rom',)
    mimetypes = ('application/x-iso9660-image',)
    extensions = ('.iso', '.udf', '.img',)

    type = StringType(default='ISO CD image')
    packaging = StringType(default=as_archive)

class SquashfsPackage(Package):
    filetypes = ('squashfs',)

    type = StringType(default='squashfs image')
    packaging = StringType(default=as_archive)

#
# these very generic archive packages must come last in recogniztion order
#

class RarPackage(Package):
    filetypes = ('rar archive',)
    mimetypes = ('application/x-rar',)
    extensions = ('.rar',)

    type = StringType(default='RAR archive')
    packaging = StringType(default=as_archive)

class TarPackage(Package):
    filetypes = (
        '.tar', 'tar archive',
        'xz compressed', 'lzma compressed',
        'gzip compressed',
        'bzip2 compressed',
        '7-zip archive',
        "compress'd data",
    )
    mimetypes = (
        'application/x-xz',
        'application/x-tar',
        'application/x-lzma',
        'application/x-gzip',
        'application/x-bzip2',
        'application/x-7z-compressed',
        'application/x-compress',
    )
    extensions = (
        '.tar', '.tar.xz', '.txz', '.tarxz',
        'tar.lzma', '.tlz', '.tarlz', '.tarlzma',
        '.tgz', '.tar.gz', '.tar.gzip', '.targz', '.targzip', '.tgzip',
        '.tar.bz2', '.tar.bz', '.tar.bzip', '.tar.bzip2', '.tbz',
        '.tbz2', '.tb2', '.tarbz2',
        '.tar.7z', '.tar.7zip', '.t7z',
        '.tz', '.tar.z', '.tarz',
    )

    type = StringType(default='plain tarball')
    packaging = StringType(default=as_archive)

class PlainZipPackage(Package):
    filetypes = ('zip archive', '7-zip archive',)
    mimetypes = ('application/zip', 'application/x-7z-compressed',)
    extensions = ('.zip', '.zipx', '.7z',)

    packaging = StringType(default=as_archive)
    type = StringType(default='plain zip')

# TODO: Add VM images formats(VMDK, OVA, OVF, VDI, etc) and Docker/other containers


text:
package org.python.modules._jythonlib;

import org.python.core.ClassDictInit;
import org.python.core.PyObject;
import org.python.core.PyString;

public class _jythonlib implements ClassDictInit {

    public static final PyString __doc__ = new PyString("jythonlib module");

    public static void classDictInit(PyObject dict) {
        dict.__setitem__("__name__", new PyString("_jythonlib"));
        dict.__setitem__("__doc__", __doc__);
        dict.__setitem__("__module__", new PyString("_jythonlib"));
        dict.__setitem__("dict_builder", dict_builder.TYPE);
        dict.__setitem__("set_builder", set_builder.TYPE);

        // Hide from Python
        dict.__setitem__("classDictInit", null);
    }

}

redpajama_set_name: RedPajamaGithub


text:
function showElem(elem: HTMLElement): void {
  elem.className = 'shown';
  elem.innerHTML = ansiToHTML(elem.innerHTML);
}

// given a string containing ansi formatting directives, return a new one
// with designated regions of text marked with the appropriate color directives,
// and with all unknown directives stripped
function ansiToHTML(orig: string): string {
  // Given a cmd (like "32" or "0;97"), some enclosed body text, and the original string,
  // either return the body wrapped in an element to achieve the desired result, or the
  // original string if nothing works.
  function annotate(cmd: string, body: string): string {
    const code = +(cmd.replace('0;', ''));
    if (code === 0) {
      // reset
      return body;
    } else if (code === 1) {
      // bold
      return `<strong>${body}</strong>`;
    } else if (code === 3) {
      // italic
      return `<em>${body}</em>`;
    } else if (30 <= code && code <= 37) {
      // foreground color
      return `<span class="ansi-${(code - 30)}">${body}</span>`;
    } else if (90 <= code && code <= 97) {
      // foreground color, bright
      return `<span class="ansi-${(code - 90 + 8)}">${body}</span>`;
    }
    return body;  // fallback: don't change anything
  }
  // Find commands, optionally followed by a bold command, with some content, then a reset command.
  // Unpaired commands are *not* handled here, but they're very uncommon.
  const filtered = orig.replace(/\033\[([0-9;]*)\w(\033\[1m)?([^\033]*?)\033\[0m/g, (match: string, cmd: string, bold: string, body: string, offset: number, str: string) => {
    if (bold !== undefined) {
      // normal code + bold
      return `<strong>${annotate(cmd, body)}</strong>`;
    }
    return annotate(cmd, body);
  });
  // Strip out anything left over.
  return filtered.replace(/\033\[([0-9;]*\w)/g, (match: string, cmd: string, offset: number, str: string) => {
    console.log('unhandled ansi code: ', cmd, "context:", filtered);
    return '';
  });
}

interface ArtifactRequest {
  artifact: string;
  bottom?: number;
  length?: number;
  offset?: number;
  startLine: number;
  top?: number;
  saveEnd?: number;
}

async function replaceElementWithContent(element: HTMLDivElement, top: number, bottom: number) {

  //
 will show up as element.dataset = {"foo": "1", "bar": "this"}
  const {artifact, offset, length, startLine} = element.dataset;

  // length! => we know these values are non-null:
  // - we know this because its tightly coupled with template.html
  // TODO(fejta): consider more robust code, looser coupling.
  const r: ArtifactRequest = {
    artifact: artifact!,
    bottom,
    length: Number(length!),
    offset: Number(offset!),
    startLine: Number(startLine!),
    top,
  };
  const content = await spyglass.request(JSON.stringify(r));
  showElem(element);
  element.outerHTML = ansiToHTML(content);
  fixLinks(document.documentElement);
  for (const button of Array.from(document.querySelectorAll<HTMLDivElement>(".show-skipped"))) {
    if (button.classList.contains("showable")) {
      continue;
    }
    button.addEventListener('click', handleShowSkipped);
    button.classList.add("showable");
  }

  for (const button of Array.from(document.querySelectorAll<HTMLDivElement>(".show-skipped"))) {
    button.addEventListener('click', handleShowSkipped);
  }

  // Remove the "show all" button if we no longer need it.
  // TODO(fejta): avoid id selectors: https://google.github.io/styleguide/htmlcssguide.html#ID_Selectors
  const log = document.getElementById(`${r.artifact}-content`)!;
  const skipped = log.querySelectorAll<HTMLElement>(".show-skipped");
  if (skipped.length === 0) {
    const button = document.querySelector('button.show-all-button')!;
    button.parentNode!.removeChild(button);
  }
  spyglass.contentUpdated();
}

async function handleShowSkipped(this: HTMLDivElement, e: MouseEvent): Promise<void> {
  // Don't do anything unless they actually clicked the button.
  let target: HTMLButtonElement;
  if (!(e.target instanceof HTMLButtonElement)) {
    if (e.target instanceof Node && e.target.parentElement instanceof HTMLButtonElement) {
      target = e.target.parentElement;
    } else {
      return;
    }
  } else {
    target = e.target;
  }

  const classes: DOMTokenList = target.classList;
  let top = 0;
  let bottom = 0;
  if (classes.contains("top")) {
    top = 10;
  }
  if (classes.contains("bottom")) {
    bottom = 10;
  }

  for (const mod of [e.altKey, e.metaKey, e.ctrlKey, e.shiftKey]) {
    if (!mod) {
      continue;
    }
    bottom *= 10;
    top *= 10;
  }

  await replaceElementWithContent(this, top, bottom);
}

async function handleShowAll(this: HTMLButtonElement) {
  // Remove ourselves immediately.
  if (this.parentElement) {
    this.parentElement.removeChild(this);
  }

  const {artifact} = this.dataset;
  const content = await spyglass.request(JSON.stringify({artifact, offset: 0, length: -1}));
  document.getElementById(`${artifact}-content`)!.innerHTML = `<tbody class="shown">${ansiToHTML(content)}</tbody>`;
  spyglass.contentUpdated();
}

async function handlePin(e: MouseEvent) {
  const result = parseHash();
  if (!result) {
    return;
  }
  const [artifact, start, end] = result;
  const r: ArtifactRequest = {
    artifact,
    saveEnd: end,
    startLine: start,
  };
  const content = await spyglass.request(JSON.stringify(r));
  if (content !== "") {
    console.log("Failed to pin lines", content, r);
    return;
  }
  const button = document.getElementById("annotate-pin");
  if (button) {
    const firstEl = await highlightLines(artifact, start, end, 'focus-line', button.parentElement!.parentElement);
    button.remove();
    if (firstEl) {
      clipLine(firstEl);
      scrollTo(firstEl);
    }
  }
  location.hash = "";

  clearHighlightedLines('highlighted-line', document);
}

function handleLineLink(e: MouseEvent): void {
  if (!e.target) {
    return;
  }
  const el = e.target as HTMLElement;
  if (!el.dataset.lineNumber) {
    return;
  }
  const multiple = e.shiftKey;
  const goal = Number(el.dataset.lineNumber);
  if (isNaN(goal)) {
    return;
  }
  let result = parseHash();
  if (result === null || !multiple) {
    result = ["", goal, goal];
  }
  let startNum = result[1];
  let endNum = result[2];
  if (goal > startNum) {
    endNum = goal;
  } else {
    [startNum, endNum] = [goal, startNum];
  }
  if (endNum !== startNum) {
    location.hash = `#${el.dataset.artifact}:${startNum}-${endNum}`;
  } else {
    location.hash = `#${el.dataset.artifact}:${startNum}`;
  }
  e.preventDefault();
}

interface Selector {
  querySelectorAll(s: string): NodeListOf<Element>;
}

function clearHighlightedLines(highlight: string, selector: Selector): void {
  for (const oldEl of Array.from(selector.querySelectorAll(`.${highlight}`))) {
    oldEl.classList.remove(highlight);
  }
}

function fixLinks(parent: HTMLElement): void {
  const links = parent.querySelectorAll<HTMLAnchorElement>('a[data-artifact][data-line-number]');
  for (const link of Array.from(links)) {
    link.href = spyglass.makeFragmentLink(`${link.dataset.artifact}:${link.dataset.lineNumber}`);
  }
}

async function loadLine(artifact: string, line: number): Promise<boolean> {
  const showers = document.querySelectorAll<HTMLDivElement>(`.show-skipped[data-artifact="${artifact}"]`);
  for (const shower of Array.from(showers)) {
    if (line >= Number(shower.dataset.startLine) && line <= Number(shower.dataset.endLine)) {
      // TODO(fejta): could maybe do something smarter here than the whole
      // block.
      await replaceElementWithContent(shower, 0, 0);
      return true;
    }
  }
  return false;
}

// parseHash extracts an artifact and line range.
//
// Expects URL fragment to be any of the following forms:
// * <empty>
// * single line: #artifact:5
// * range of lines: #artifact:5-12.
function parseHash(): [string, number, number]|null {
  const hash = location.hash.substr(1);
  const colonPos = hash.lastIndexOf(':');
  if (colonPos === -1) {
    return null;
  }
  const artifact = hash.substring(0, colonPos);
  const lineRange = hash.substring(colonPos + 1);
  const hyphenPos = lineRange.lastIndexOf('-');

  let startNum;
  let endNum;

  if (hyphenPos > 0 ) {
    startNum = Number(lineRange.substring(0, hyphenPos));
    endNum = Number(lineRange.substring(hyphenPos + 1));
  } else {
    startNum = Number(lineRange);
    endNum = startNum;
  }
  if (isNaN(startNum) || isNaN(endNum)) {
    return null;
  }
  if (endNum < startNum) { // ensure start has the smallest value.
    [startNum, endNum] = [endNum, startNum];
  }
  return [artifact, startNum, endNum];
}

async function handleHash(): Promise<void> {
  const result = parseHash();
  if (!result) {
    return;
  }
  const [artifact, startNum, endNum] = result;

  const firstEl = await highlightLines(artifact, startNum, endNum, 'highlighted-line', document);

  if (!firstEl) {
    return;
  }

  const content = document.getElementById(`${artifact}-content`);
  if (content && content.classList.contains("savable")) {
    pinLine(firstEl);
  }
  scrollTo(firstEl);
}

function scrollTo(elem: Element) {
      const top = elem.getBoundingClientRect().top + window.pageYOffset - 50;
      spyglass.scrollTo(0, top).then();
}

async function highlightLines(artifact: string, startNum: number, endNum: number, highlight: string = 'highlighted-line', selector: Selector|null): Promise<HTMLDivElement|null> {
  let firstEl: HTMLDivElement|null = null;
  for (let lineNum = startNum; lineNum <= endNum; lineNum++) {
    const lineId = `${artifact}:${lineNum}`;
    let lineEl = document.getElementById(lineId);
    if (!lineEl) {
      if (!await loadLine(artifact, lineNum)) {
        return null;
      }
      lineEl = document.getElementById(lineId);
      if (!lineEl) {
        return null;
      }
    }
    if (firstEl === null) {
      if (lineEl instanceof HTMLDivElement) {
        firstEl = lineEl;
      } else {
        return null;
      }
      if (selector) {
        clearHighlightedLines(highlight, selector);
      }
    }
    lineEl.classList.add(highlight);
  }
  return firstEl;
}

function pinLine(lineEl: HTMLDivElement) {
  let pin = document.getElementById("annotate-pin");
  if (!pin) {
    pin = document.createElement("button");
    pin.classList.add("annotate-pin");
    pin.title = "Pin selected lines to always display on page load";
    pin.id = "annotate-pin";
    pin.innerHTML = "push_pin";
    pin.addEventListener('click', handlePin);
  }
  lineEl.insertAdjacentElement("afterbegin", pin);
}

function clipLine(lineEl: HTMLDivElement) {
  let pin = document.getElementById("focus-clip");
  if (!pin) {
    pin = document.createElement("button");
    pin.classList.add("focus-clip");
    pin.id = "focus-clip";
    pin.innerHTML = "attachment";
  }
  lineEl.insertAdjacentElement("afterbegin", pin);
}

window.addEventListener('hashchange', () => handleHash());

window.addEventListener('load', () => {
  const shown = document.getElementsByClassName("shown");
  for (const child of Array.from(shown)) {
    child.innerHTML = ansiToHTML(child.innerHTML);
  }

  for (const button of Array.from(document.querySelectorAll<HTMLDivElement>(".show-skipped"))) {
    button.addEventListener('click', handleShowSkipped);
    button.classList.add("showable");
  }

  for (const button of Array.from(document.querySelectorAll<HTMLButtonElement>("button.show-all-button"))) {
    button.addEventListener('click', handleShowAll);
  }

  for (const container of Array.from(document.querySelectorAll<HTMLElement>('.loglines'))) {
    container.addEventListener('click', handleLineLink, {capture: true});
  }
  fixLinks(document.documentElement);

  handleHash();
});


text:
package gov.va.isaac.interfaces.gui.views.commonFunctionality;

import org.jvnet.hk2.annotations.Contract;

/**
 * ListBatchViewI
 *
 * @author Joel Kniaz
 */

import gov.va.isaac.interfaces.gui.views.EmbeddableViewI;
import java.util.List;

/**
 * {@link ListBatchViewI}
 *
 * An interface that allows the creation of an ListBatchViewI implementation, which
 * will be a JavaFX component that extends {@link EmbeddableViewI}.  The resulting ISAAC panel
 * is intended to allow importation into, display and manipulation of concepts to and
 * from other ISAAC panels
 *
 * @author Joel Kniaz
 */
@Contract
public interface ListBatchViewI extends EmbeddableViewI {
	/**
	 * Update the view to show the specified concepts
	 * @param List<Integer> the list of specified concepts as int NID
	 */
	public void addConcepts(List<Integer> nids);

	/**
	 * Update the view to show the specified concept
	 * @param int the specified concept as int NID
	 */
	public void addConcept(int nid);
}


text:
Coffee
###################

Criação de um sistema para concorrer a uma bolsa na ufpa

*******************
Tecnologias utilizadas
*******************

- Codeigniter
- Bootstrap
- jquery
- Datepicker

**************************
Progamação:
**************************

Tiago França Ferreira
tiagoweb.tk


text:
require 'bundler/setup'
require 'active_record'
require 'timecop'
require 'byebug'

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'zombie_record'

class Book < ActiveRecord::Base
  include ZombieRecord::Restorable

  belongs_to :library
  belongs_to :author, dependent: :destroy
  has_one :cover, dependent: :destroy

  has_many :chapters, dependent: :destroy
  has_many :bookmarks, dependent: :destroy
  has_many :notes, dependent: :destroy
end

class Chapter < ActiveRecord::Base
  include ZombieRecord::Restorable

  belongs_to :book
end

class Bookmark < ActiveRecord::Base
  include ZombieRecord::Restorable

  belongs_to :book, counter_cache: true
end

class Note < ActiveRecord::Base
  belongs_to :book
end

class Author < ActiveRecord::Base
  include ZombieRecord::Restorable

  has_many :books
end

class Tag < ActiveRecord::Base
  include ZombieRecord::Restorable

  belongs_to :taggable, polymorphic: true, dependent: :destroy
end

class Cover < ActiveRecord::Base
  include ZombieRecord::Restorable

  belongs_to :book
end

class Library < ActiveRecord::Base
  include ZombieRecord::Restorable

  has_many :book
end

RSpec.configure do |config|
  config.disable_monkey_patching!

  config.around do |example|
    ActiveRecord::Base.transaction do
      example.run
      raise ActiveRecord::Rollback
    end
  end

  config.before :suite do
    ActiveRecord::Base.establish_connection(
      adapter: "sqlite3",
      database: ":memory:"
    )

    ActiveRecord::Schema.define do
      self.verbose = false

      create_table :books do |t|
        t.integer :author_id
        t.integer :library_id
        t.integer :bookmarks_count
        t.timestamps null: false
        t.string :title
        t.timestamp :deleted_at
      end

      create_table :chapters do |t|
        t.integer :book_id
        t.timestamps null: false
        t.timestamp :deleted_at
      end

      create_table :bookmarks do |t|
        t.integer :book_id
        t.timestamp :created_at
        t.timestamp :deleted_at
      end

      create_table :notes do |t|
        t.integer :book_id
        t.timestamps null: false
      end

      create_table :tags do |t|
        t.string :name
        t.string :taggable_type
        t.integer :taggable_id
        t.timestamp :deleted_at
      end

      create_table :covers do |t|
        t.integer :book_id
        t.timestamps null: false
        t.timestamp :deleted_at
      end

      create_table :authors do |t|
        t.timestamps null: false
        t.timestamp :deleted_at
      end

      create_table :libraries do |t|
        t.timestamps null: false
        t.timestamp :deleted_at
      end
    end
  end

  config.after :suite do
    ActiveRecord::Base.connection.drop_database("zombie_record") rescue nil
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<title>
Exemplo simples
</title>

Exemplo simples

Este é um complemento de exemplo simples, que você pode copiar e usar como base para criar um novo Add-on/complemento que faça algo realmente útil.

Ele contém:
Menu de nível superior
 Um item no menu de nível superior 'Ferramentas'.

Menu de botão direito
 Um item de Menu para o botão direito do mouse, que está habilitado para exibir mensagens.

Painel de status
 Um painel básico de status.

Arquivo de ajuda
 Este arquivo de ajuda.


text:
<!DOCTYPE html>

  <title>Your page title here</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="../stylesheets/blog-stylesheet.css">

      WELCOME TO MY BLOG!

      Links go here

Of Methods and Maps

March 21, 2015

        The map method in Ruby is an extremely useful tool when we are dealing with enumerable objects.  Methods such as #map allow well-grounded rubyists to iterate through enumerables more efficiently and with staggeringly little code.  Only by mastering the logic behind chaining large groups of methods into fewer and fewer lines of code can one advance in their knowledge and skill of Ruby.

        The method I'll talk about this time is #map.  This is a powerful tool that takes a line or even block of code, and iterates through an enumerable and runs this code for each element inside.  What does this mean?  For simpler operations, such as adding an inputted value to every integer in an array, one can simply use array.map and apply the given value in any way shape or form to every single element contained in array.  This cuts down on a multitude of code by iterating through the enumerable without having to use loops.

        For example, imagine we want to add x to every integer contained inside an array.  In other languages such as C++, one would have to use a while or for loop to iterate through the array, then use if statements to determine the values contained within, and finally act out the code they wish.  In ruby, we can solve this by simply returning "array.map!{|value| value.is_a?(Integer) ? value + x: value", which would iterate through every element in array, check to see if each value is indeed an integer, add x to it if so, and do nothing if else.  Ruby is the best!


text:
package cn.elvea.platform.sba.config;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.util.UUID;

/**
 * @author elvea
 * @since 0.0.1
 */
@Configuration
@EnableAdminServer
public class Config {

    private final AdminServerProperties adminServer;

    public Config(AdminServerProperties adminServer) {
        this.adminServer = adminServer;
    }

    /**
     * 默认安全设置
     */
    @Bean
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(this.adminServer.path("/"));

        http.authorizeHttpRequests()
                .requestMatchers(this.adminServer.path("/assets/**")).permitAll()
                .requestMatchers(this.adminServer.path("/login")).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage(this.adminServer.path("/login")).successHandler(successHandler).and()
                .logout().logoutUrl(this.adminServer.path("/logout")).and()
                .httpBasic().and()
                .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringRequestMatchers(
                        new AntPathRequestMatcher(this.adminServer.path("/instances"), HttpMethod.POST.toString()),
                        new AntPathRequestMatcher(this.adminServer.path("/instances/*"), HttpMethod.DELETE.toString()),
                        new AntPathRequestMatcher(this.adminServer.path("/actuator/**"))
                )
                .and()
                .rememberMe().key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600);

        return http.build();
    }

}


text:
#ifndef D__DURABILITY_H
#define D__DURABILITY_H

#include "d__types.h"
#include "d__thread.h"
#include "u_user.h"
#include "vortex_os.h"
#include "os_thread.h"
#include "os_time.h"
#include "os_atomics.h"

#if defined (__cplusplus)
extern "C" {
#endif

/* Vendor ids, used for client-durability */
#define D_VENDORID_UNKNOWN                          {{ 0x00, 0x00 }}
#define D_VENDORID_RTI                              {{ 0x01, 0x01 }}
#define D_VENDORID_PRISMTECH_OSPL                   {{ 0x01, 0x02 }}
#define D_VENDORID_OCI                              {{ 0x01, 0x03 }}
#define D_VENDORID_MILSOFT                          {{ 0x01, 0x04 }}
#define D_VENDORID_KONGSBERG                        {{ 0x01, 0x05 }}
#define D_VENDORID_TWINOAKS                         {{ 0x01, 0x06 }}
#define D_VENDORID_LAKOTA                           {{ 0x01, 0x07 }}
#define D_VENDORID_ICOUP                            {{ 0x01, 0x08 }}
#define D_VENDORID_ETRI                             {{ 0x01, 0x09 }}
#define D_VENDORID_RTI_MICRO                        {{ 0x01, 0x0a }}
#define D_VENDORID_PRISMTECH_JAVA                   {{ 0x01, 0x0b }}
#define D_VENDORID_PRISMTECH_GATEWAY                {{ 0x01, 0x0c }}
#define D_VENDORID_PRISMTECH_LITE                   {{ 0x01, 0x0d }}
#define D_VENDORID_TECHNICOLOR                      {{ 0x01, 0x0e }}
#define D_VENDORID_EPROSIMA                         {{ 0x01, 0x0f }}
#define D_VENDORID_PRISMTECH_CLOUD                  {{ 0x01, 0x20 }}

#define MY_VENDOR_ID                                D_VENDORID_PRISMTECH_OSPL

/* Durability version */
#define D_DURABILITY_VERSION_MAJOR                  2
#define D_DURABILITY_VERSION_MINOR                  0  /* From version 2.0 timestamps beyond 2038 are supported */
#define D_DURABILITY_VERSION_VENDOR_ID              MY_VENDOR_ID

/**
 * Macro that checks the d_durability validity.
 * Because d_durability is a concrete class typechecking is required.
 */
#define             d_durabilityIsValid(_this)   \
    d_objectIsValid(d_object(_this), D_DURABILITY)

/**
 * \brief The d_durability cast macro.
 *
 * This macro casts an object to a d_durability object.
 */
#define d_durability(_this) ((d_durability)(_this))

typedef void (*d_durabilityStatisticsCallback)(v_durabilityStatistics statistics, c_voidp userData);

C_STRUCT(d_durability){
    C_EXTENDS(d_object);
    u_service        service;
    u_serviceManager serviceManager;
    d_configuration  configuration;
    d_admin          admin;
    d_serviceState   state;
    os_threadId      statusThread;
    volatile c_bool  splicedRunning;
    os_cond          terminateCondition;
    os_mutex         terminateMutex;
    c_bool           died;                /* set to TRUE if something bad happened,
                                           * used in d_durabilityDeinit to annnounce
                                           * the service has died
                                           */
    struct _DDS_DurabilityVersion_t myVersion;
    struct _DDS_Gid_t myServerId;
    pa_uint32_t      requestId;           /* atomic id to handout to new requests */
    pa_uint32_t      conflictId;          /* monotonic conflict-id counter */
    pa_uint32_t      incarnation;         /* incarnation used to detect asymmetric disconnects */
    pa_uint32_t      forceStatusWrite;
};

typedef enum d_connectivity_s {
    D_CONNECTIVITY_UNDETERMINED,
    D_CONNECTIVITY_OK,
    D_CONNECTIVITY_INCOMPATIBLE_STATE,
    D_CONNECTIVITY_INCOMPATIBLE_DATA_MODEL
} d_connectivity;

#define D_OSPL_NODE "__NODE"
#define D_OSPL_BUILTIN_PARTITION "BUILT-IN PARTITION__"

d_durability        d_durabilityNew                     (const c_char* uri,
                                                         const c_char* serviceName,
                                                         c_long domainId);

void                d_durabilityInit                    (d_durability durability);

void                d_durabilityDeinit                  (d_durability durability);

d_connectivity      d_durabilityDetermineConnectivity   (d_durability durability);

void                d_durabilityHandlePersistentInitial (d_durability durability);

void                d_durabilityHandleInitialAlignment  (d_durability durability);

void                d_durabilityFree                    (d_durability durability);

c_bool              d_durabilityArgumentsProcessing     (int argc,
                                                         char *argv[],
                                                         c_char **uri,
                                                         c_char **serviceName);

void                d_durabilityWatchSpliceDaemon       (v_serviceStateKind spliceDaemonState,
                                                         c_voidp usrData);

void                d_durabilityLoadModule              (v_public entity,
                                                         c_voidp args);

u_service           d_durabilityGetService              (d_durability durability);

d_configuration     d_durabilityGetConfiguration        (d_durability durability);

c_bool              d_durabilityWaitForAttachToGroup    (d_durability durability,
                                                         v_group group);

d_serviceState      d_durabilityGetState                (d_durability durability);

void                d_durabilitySetState                (d_durability durability,
                                                         d_serviceState state);

void                d_durabilityHeartbeatProcessed      (_In_ d_durability durability);

c_bool              d_durabilityMustTerminate           (d_durability durability);

void                d_durabilityTerminate               (d_durability durability,
                                                         c_bool died);

void                d_durabilityUpdateStatistics        (d_durability durability,
                                                         d_durabilityStatisticsCallback callback,
                                                         c_voidp userData);

u_result            d_durabilityTakePersistentSnapshot  (d_durability durability,
                                                         c_char* partitionExpr,
                                                         c_char* topicExpr,
                                                         c_char* uri);

void                d_durabilitySetVersion              (d_durability durability,
                                                         c_ushort major,
                                                         c_ushort minor);

struct _DDS_DurabilityVersion_t d_durabilityGetMyVersion (d_durability durability);

struct _DDS_Gid_t   d_durabilityGetMyServerId           (d_durability durability);

c_bool              d_durabilityRequestIsForMe          (d_durability durability,
                                                         c_iter serverIds,
                                                         c_bool *forMe,
                                                         c_bool *forEverybody);

struct _DDS_RequestId_t  d_durabilityGetRequestId       (d_durability durability);

c_ulong             d_durabilityGenerateConflictId      (_Inout_ d_durability durability);

d_fellow            d_durabilityGetOrCreateFellowFromMessage(d_admin admin,
                                                             d_networkAddress fellowAddr,
                                                             d_message message);

c_ulong             d_durabilityGetNewIncarnation       (d_durability durability);

void                d_durabilityDetermineNameSpaceCompleteness (
                                                         d_durability durability);

void                d_durabilityDoInitialMerge          (d_durability durability);

void                d_durabilityReportKernelGroupCompleteness (_In_ d_durability durability);

#if defined (__cplusplus)
}
#endif

#endif /* D__DURABILITY_H */


text:
import { FileFormat } from './fileFormat';

export interface IDefaultExtension {
  /**
   * name of the icon.
   */
  icon: string;
  /**
   * format of the icon
   */
  format: FileFormat | string;
  /**
   * user customization: if false the extension won't be exported.
   */
  disabled?: boolean;
  /**
   * set this to true if you want to use a bundle icon.
   * This will override the `default` prefix with the one for files or folders.
   */
  useBundledIcon?: boolean;
}


text:
/**
 * @file Vector.h
 * Brief Description.
 */

#ifndef INCLUDE_VECTOR_H_
#define INCLUDE_VECTOR_H_

#include <algorithm>

class Vector {
 public:
    float x;
    float y;
    explicit Vector(float mx = 0, float my = 0);
    void rotate(Vector origin, float angle);
    /**
     * Not used method.
     */
    void transform(float module, float angle);

    Vector operator+(const Vector& rhs) const;
    Vector operator-(const Vector& rhs) const;
    Vector operator*(const float rhs) const;
};

#endif  // INCLUDE_VECTOR_H_


text:
<?php
/* File: api/z/regis.ter.php  */
 require_once('sys.registration.php');
    $secureKey  = substr(strrchr($_SERVER['QUERY_STRING'], '/'), 1);
    $uReg       =   new Registration(0); // Extended by company class, passing 0 means without login check
    if (is_numeric($secureKey)) {
        $iUe    =   $uReg->chkUsrExis($secureKey); // Check username with security key

        if (is_object($iUe)) { // If its object means user exists with Secure key
            $uEmail = $iUe->emailAddress;
        } else {
            header("Location: ../../user/login");
        }
    } else { // If url not exists
        header("Location: ../../user/login");
    }

    if (isset($_POST['submit']) && $_POST['submit']!='') {
        $nfst = $_POST['nfst'];
        $nlst = $_POST['nlst'];
        $language = $_POST['language'];
        // Save users with details and as well as add as a member of 'All' community
        $rResult = $uReg->saveUsers($iUe ->idUser, $iUe ->idClient);
    } else {
        $nfst = '';
        $nlst = '';
        $language = 'en';
        $rResult ='';
    }

    // If Error exists
    if (isset($rResult) && $rResult!='') {
        if (!is_numeric($rResult)) {
            $sClass = "form-error text-red";
        } else {
            $sClass = "success";
        }
    } else $sClass = '';
?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="description" content="Enterprise Architecture Solutions">
    <meta name="author" content="martin.owen@company.co.uk">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="shortcut icon" href="../../../imgs/system/favicon.gif"/>
    <title>company SPP Registration</title>
    <link rel="stylesheet" type="text/css" href="../../../ss/css/main.css">

Registration

        <form id="login" method="post" class="pure-form pure-form-custom border padding" action="">

                <div class="centered-text <?php echo $sClass ;?>" >
                    <?php
                        if (isset($rResult) && $rResult!='' ) {
                            if (!is_numeric($rResult)) {
                                echo $rResult;
                            } else {
                                header("Location: ../../user/login?reg=true");
                            }
                        }
                    ?>

                    <fieldset>
                        <legend>Personal Details</legend>
                        First Name
                        <input type="text" name="nfst" id="nameFirst" value="<?=$nfst;?>" class="pure-input-1 margin-bottom">

First Name Should not accepts Special Characters

                        Last Name
                        <input type="text" name="nlst" id="nameLast" class="pure-input-1 margin-bottom" value="<?=$nlst;?>">

Last Name Should not accepts Special Characters

                        Language

                            <select name="language" id="user-language" class="pure-input-1">
                                <option disabled>Choose a language</option>
                                <option disabled>-----------------</option>
                                <option value="en" <?php if($language=='en') echo 'selected'?>>English</option>
                                <option value="fr" <?php if($language=='fr') echo 'selected'?> >French</option>
                                <option value="ge" <?php if($language=='ge') echo 'selected'?>>German</option>
                                <option value="sp" <?php if($language=='sp') echo 'selected'?> >Spanish</option>
                                <option value="nl" <?php if($language=='nl') echo 'selected'?>>Dutch</option>
                                <option value="po" <?php if($language=='po') echo 'selected'?> >Portuguese</option>
                            </select>

                    </fieldset>

                    <fieldset>
                        <legend>Account Details</legend>
                        Username
                        <input type="text" name="usr" id="username" class="pure-input-1 margin-bottom">

Username Should not accepts Special Characters

                        Email address
                        <input type="text" value="<?=$uEmail;?>" name="email" id="email" class="pure-input-1 margin-bottom" readonly>
                    </fieldset>

                    <fieldset>
                        <legend>Password</legend>
                        Enter a new password
                        <input type="password" name="pas" id="password" class="pure-input-1 margin-bottom">

Enter Valid Password

                        Confirm your new password
                        <input type="password" name="repas" id="repassword" class="pure-input-1 margin-bottom">

Password do not match

                            <input type="checkbox" id="user-passwords-show" class="form-show-passwords"> Show passwords

                    </fieldset>

                <input type="submit" id="submit" name="submit" data-form-button="" class="pure-button pure-button-custom button-small" value="Register">

        </form>


text:
package at.int32.sweaty.ui.annotations;

import at.int32.sweaty.ui.Control;

public class OnToggleEvent extends OnEvent {
	private Boolean checked;

	public OnToggleEvent(Control source, boolean checked) {
		super(source);
		this.checked = checked;
	}

	public boolean checked() {
		return this.checked;
	}
}


text:
var ConsolePos, afterNewline, exports, stringLength,
  __slice = [].slice;

stringLength = require('string-length');

afterNewline = function(str) {
  var i;
  i = ('' + str).indexOf('\n');
  if (i !== -1) {
    return afterNewline(str.substr(i + 1, str.length));
  } else {
    return str;
  }
};

ConsolePos = (function() {
  var _currentLine;

  _currentLine = '';

  function ConsolePos(output) {
    if (output == null) {
      throw new Error('console-pos requires an output stream.');
    }
    this.reset();
    output._consolePosOriginalWrite = output.write;
    output.write = function() {
      var args, str;
      args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
      str = args[0];
      if (("" + str).indexOf('\n') !== -1) {
        _currentLine = '';
      }
      str = afterNewline(str);
      _currentLine += str;
      return output._consolePosOriginalWrite.apply(output, args);
    };
  }

  ConsolePos.prototype.row = function() {
    return stringLength(_currentLine);
  };

  ConsolePos.prototype.reset = function() {
    return _currentLine = '';
  };

  return ConsolePos;

})();

module.exports = exports = function(output) {
  return new ConsolePos(output);
};


text:
require 'zermelo/filter'

module Zermelo
  module Filters
    class InfluxDB

      include Zermelo::Filter

      private

      def _exists?(id)
        return if id.nil?
        @steps << Zermelo::Filters::Steps::SetStep.new({:op => :intersect}, {:id => id})
        resolve_steps(:count) > 0
      end

      def lock(when_steps_empty = true, *klasses, &block)
        # no-op
        block.call
      end

      def _ids
        resolve_steps(:ids)
      end

      def _count
        resolve_steps(:count)
      end

      def escaped_id(id)
        if id.is_a?(Numeric)
          id
        else
          "'" + id.gsub(/'/, "\\'").gsub(/\\/, "\\\\'") + "'"
        end
      end

      # TODO support the new before/after_read callbacks
      def resolve_steps(result_type)
        class_key = @associated_class.send(:class_key)

        query = case result_type
        when :ids
          "SELECT id FROM /#{class_key}\\/.*/"
        when :count
          "SELECT COUNT(id) FROM /#{class_key}\\/.*/"
        end

        unless @initial_key.id.nil?
          query += ' WHERE '

          initial_class_key = @initial_key.klass.send(:class_key)

          ii_query = "SELECT #{@initial_key.name} FROM \"#{initial_class_key}/#{@initial_key.id}\" " +
            "LIMIT 1"

          begin
            initial_id_data =
              Zermelo.influxdb.query(ii_query)["#{initial_class_key}/#{@initial_key.id}"]
          rescue ::InfluxDB::Error => ide
            raise unless
              /^Field #{@initial_key.name} doesn't exist in series #{initial_class_key}\/#{@initial_key.id}$/ === ide.message

            initial_id_data = nil
          end

          if initial_id_data.nil?
            ret = case result_type
            when :ids
              Set.new
            when :count
              0
            end
            return ret
          end

          initial_ids = initial_id_data.first[@initial_key.name]

          if initial_ids.nil? || initial_ids.empty?
            # make it impossible for the query to return anything
            query += '(1 = 0)'
          else
            query += '((' + initial_ids.collect {|id|
              "id = #{escaped_id(id)}"
            }.join(') OR (') + '))'
          end
        end

        unless @steps.empty?
          query += (@initial_key.id.nil? ? ' WHERE ' : ' AND ') +
                   ('(' * @steps.size)

          first_step = steps.first

          attr_types = @associated_class.send(:attribute_types)

          query += @steps.collect {|step|
            step.resolve(backend, @associated_class, :first => (step == first_step),
              :attr_types  => attr_types)
          }.join("")
        end

        query += " ORDER ASC LIMIT 1"

        begin
          result = Zermelo.influxdb.query(query)
        rescue ::InfluxDB::Error => ide
          raise unless /^Couldn't look up columns$/ === ide.message
          result = {}
        end

        data_keys = result.keys.select {|k| k =~ /^#{class_key}\// }

        case result_type
        when :ids
          data_keys.empty? ? Set.new : Set.new(data_keys.collect {|k| k =~ /^#{class_key}\/(.+)$/; $1 })
        when :count
          data_keys.empty? ? 0 : data_keys.size
        end
      end
    end
  end
end


text:
/**
 * Created by ivar on 15.12.15.
 */

define([
    'angularAMD'
], function (angularAMD) {

    angularAMD.controller('TreeViewCtrl', ['$scope','$state', '$stateParams', 'wnwbApi', function ($scope, $state, $stateParams, wnwbApi) {

        $scope.delete = function(data) {
            data.nodes = [];
        };

        $scope.add = function(data) {
            var post = data.nodes.length + 1;
            var newName = data.name + '-' + post;
            data.nodes.push({name: newName,nodes: []});
        };

        $scope.tree = [{name: "Node", nodes: []}];

    }]);
});


text:
using namespace std;

void testHumanAi() {
  GameSettingsWrapper gameSettings;
  gameSettings.setMaxPips(6);
  gameSettings.setStartingHandSize(9);
  gameSettings.setNumberOfPlayers(2);

  vector<unique_ptr<PlayerAI>> playerAis;
  playerAis.emplace_back(std::make_unique<HumanPlayerAI>(std::cin, &std::cout));
  playerAis.emplace_back(std::make_unique<RandomPlayerAI>(nullptr));
  Game Game(&std::cout, gameSettings, playerAis);
  Game.run();
}

void testRandomAi() {
  GameSettingsWrapper gameSettings;
  gameSettings.setMaxPips(6);
  gameSettings.setStartingHandSize(9);
  gameSettings.setNumberOfPlayers(2);

  for (int32 i = 0; i < 1000; i++) {
    vector<unique_ptr<PlayerAI>> playerAis;
    playerAis.emplace_back(std::make_unique<RandomPlayerAI>(nullptr));
    playerAis.emplace_back(std::make_unique<RandomPlayerAI>(nullptr));
    Game Game(nullptr, gameSettings, playerAis);
    Game.run();
  }
}

void testGreedyAi() {
  GameSettingsWrapper gameSettings;
  gameSettings.setMaxPips(6);
  gameSettings.setStartingHandSize(9);
  gameSettings.setNumberOfPlayers(2);

  for (int32 i = 0; i < 1000; i++) {
    vector<unique_ptr<PlayerAI>> playerAis;
    playerAis.emplace_back(std::make_unique<RandomPlayerAI>(nullptr));
    playerAis.emplace_back(std::make_unique<GreedyPlayerAI>(nullptr));
    Game Game(nullptr, gameSettings, playerAis);
    Game.run();
  }
}

void testSmartAi() {
  GameSettingsWrapper gameSettings;
  gameSettings.setMaxPips(12);
  gameSettings.setStartingHandSize(15);
  gameSettings.setNumberOfPlayers(3);

  for (int32 i = 0; i < 1000; i++) {
    vector<unique_ptr<PlayerAI>> playerAis;
    playerAis.emplace_back(std::make_unique<RandomPlayerAI>(nullptr));
    playerAis.emplace_back(std::make_unique<GreedyPlayerAI>(nullptr));
    playerAis.emplace_back(std::make_unique<SmartPlayerAI>(nullptr));
    Game Game(nullptr, gameSettings, playerAis);
    Game.run();
  }
}

int main() {
  testRandomAi();
  // testHumanAi();
  testGreedyAi();
  testSmartAi();

  std::cout << StatTracker::get();

  return 0;
}


text:
import copy

import mock
import mox

from heat.common import exception
from heat.common import template_format
from heat.engine.clients.os import ceilometer
from heat.engine.resources.openstack.ceilometer import gnocchi_alarm as gnocchi
from heat.engine import scheduler
from heat.tests import common
from heat.tests import utils

gnocchi_resources_alarm_template = '''
heat_template_version: 2013-05-23
description: Gnocchi Resources Alarm Test
resources:
  GnoResAlarm:
    type: OS::Ceilometer::GnocchiResourcesAlarm
    properties:
      description: Do stuff with gnocchi
      metric: cpu_util
      aggregation_method: mean
      granularity: 60
      evaluation_periods: 1
      threshold: 50
      alarm_actions: []
      resource_type: instance
      resource_id: 5a517ceb-b068-4aca-9eb9-3e4eb9b90d9a
      comparison_operator: gt
'''

gnocchi_aggregation_by_metrics_alarm_template = '''
heat_template_version: 2013-05-23
description: Gnocchi Aggregation by Metrics Alarm Test
resources:
  GnoAggregationByMetricsAlarm:
    type: OS::Ceilometer::GnocchiAggregationByMetricsAlarm
    properties:
      description: Do stuff with gnocchi metrics
      metrics: ["911fce07-e0d7-4210-8c8c-4a9d811fcabc",
                "2543d435-fe93-4443-9351-fb0156930f94"]
      aggregation_method: mean
      granularity: 60
      evaluation_periods: 1
      threshold: 50
      alarm_actions: []
      comparison_operator: gt
'''

gnocchi_aggregation_by_resources_alarm_template = '''
heat_template_version: 2013-05-23
description: Gnocchi Aggregation by Resources Alarm Test
resources:
  GnoAggregationByResourcesAlarm:
    type: OS::Ceilometer::GnocchiAggregationByResourcesAlarm
    properties:
      description: Do stuff with gnocchi aggregation by resource
      aggregation_method: mean
      granularity: 60
      evaluation_periods: 1
      threshold: 50
      metric: cpu_util
      alarm_actions: []
      resource_type: instance
      query: '{"=": {"server_group": "my_autoscaling_group"}}'
      comparison_operator: gt
'''

class FakeCeilometerAlarm(object):
    alarm_id = 'foo'

    def __init__(self):
        self.to_dict = lambda: {'attr': 'val'}

class GnocchiResourcesAlarmTest(common.HeatTestCase):
    def setUp(self):
        super(GnocchiResourcesAlarmTest, self).setUp()
        self.fc = mock.Mock()

    def create_alarm(self):
        self.m.StubOutWithMock(ceilometer.CeilometerClientPlugin, '_create')
        ceilometer.CeilometerClientPlugin._create().AndReturn(
            self.fc)
        self.m.StubOutWithMock(self.fc.alarms, 'create')
        self.fc.alarms.create(
            alarm_actions=[],
            description=u'Do stuff with gnocchi',
            enabled=True,
            insufficient_data_actions=None,
            ok_actions=None,
            name=mox.IgnoreArg(), type='gnocchi_resources_threshold',
            repeat_actions=True,
            gnocchi_resources_threshold_rule={
                "metric": "cpu_util",
                "aggregation_method": "mean",
                "granularity": 60,
                "evaluation_periods": 1,
                "threshold": 50,
                "resource_type": "instance",
                "resource_id": "5a517ceb-b068-4aca-9eb9-3e4eb9b90d9a",
                "comparison_operator": "gt",
            },
            time_constraints=[],
            severity='low',
        ).AndReturn(FakeCeilometerAlarm())
        snippet = template_format.parse(gnocchi_resources_alarm_template)
        self.stack = utils.parse_stack(snippet)
        resource_defns = self.stack.t.resource_definitions(self.stack)
        return gnocchi.CeilometerGnocchiResourcesAlarm(
            'GnoResAlarm', resource_defns['GnoResAlarm'], self.stack)

    def test_update(self):
        rsrc = self.create_alarm()
        self.m.StubOutWithMock(self.fc.alarms, 'update')
        self.fc.alarms.update(
            alarm_id='foo',
            gnocchi_resources_threshold_rule={
                'resource_id': 'd3d6c642-921e-4fc2-9c5f-15d9a5afb598'})

        self.m.ReplayAll()
        scheduler.TaskRunner(rsrc.create)()

        update_template = copy.deepcopy(rsrc.t)
        update_template['Properties']['resource_id'] = (
            'd3d6c642-921e-4fc2-9c5f-15d9a5afb598')
        scheduler.TaskRunner(rsrc.update, update_template)()
        self.assertEqual((rsrc.UPDATE, rsrc.COMPLETE), rsrc.state)

        self.m.VerifyAll()

    def _prepare_check_resource(self):
        snippet = template_format.parse(gnocchi_resources_alarm_template)
        self.stack = utils.parse_stack(snippet)
        res = self.stack['GnoResAlarm']
        res.client = mock.Mock()
        mock_alarm = mock.Mock(enabled=True, state='ok')
        res.client().alarms.get.return_value = mock_alarm
        return res

    def test_create(self):
        rsrc = self.create_alarm()

        self.m.ReplayAll()
        scheduler.TaskRunner(rsrc.create)()
        self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state)
        self.assertEqual('foo', rsrc.resource_id)
        self.m.VerifyAll()

    def test_suspend(self):
        rsrc = self.create_alarm()
        self.m.StubOutWithMock(self.fc.alarms, 'update')
        self.fc.alarms.update(alarm_id='foo', enabled=False)

        self.m.ReplayAll()
        scheduler.TaskRunner(rsrc.create)()

        scheduler.TaskRunner(rsrc.suspend)()
        self.assertEqual((rsrc.SUSPEND, rsrc.COMPLETE), rsrc.state)

        self.m.VerifyAll()

    def test_resume(self):
        rsrc = self.create_alarm()
        self.m.StubOutWithMock(self.fc.alarms, 'update')
        self.fc.alarms.update(alarm_id='foo', enabled=True)

        self.m.ReplayAll()
        scheduler.TaskRunner(rsrc.create)()
        rsrc.state_set(rsrc.SUSPEND, rsrc.COMPLETE)

        scheduler.TaskRunner(rsrc.resume)()
        self.assertEqual((rsrc.RESUME, rsrc.COMPLETE), rsrc.state)

        self.m.VerifyAll()

    def test_check(self):
        res = self._prepare_check_resource()
        scheduler.TaskRunner(res.check)()
        self.assertEqual((res.CHECK, res.COMPLETE), res.state)

    def test_check_failure(self):
        res = self._prepare_check_resource()
        res.client().alarms.get.side_effect = Exception('Boom')

        self.assertRaises(exception.ResourceFailure,
                          scheduler.TaskRunner(res.check))
        self.assertEqual((res.CHECK, res.FAILED), res.state)
        self.assertIn('Boom', res.status_reason)

    def test_show_resource(self):
        res = self._prepare_check_resource()
        res.client().alarms.create.return_value = mock.MagicMock(
            alarm_id='2')
        res.client().alarms.get.return_value = FakeCeilometerAlarm()
        scheduler.TaskRunner(res.create)()
        self.assertEqual({'attr': 'val'}, res.FnGetAtt('show'))

class GnocchiAggregationByMetricsAlarmTest(GnocchiResourcesAlarmTest):

    def create_alarm(self):
        self.m.StubOutWithMock(ceilometer.CeilometerClientPlugin, '_create')
        ceilometer.CeilometerClientPlugin._create().AndReturn(
            self.fc)
        self.m.StubOutWithMock(self.fc.alarms, 'create')
        self.fc.alarms.create(
            alarm_actions=[],
            description=u'Do stuff with gnocchi metrics',
            enabled=True,
            insufficient_data_actions=None,
            ok_actions=None,
            name=mox.IgnoreArg(),
            type='gnocchi_aggregation_by_metrics_threshold',
            repeat_actions=True,
            gnocchi_aggregation_by_metrics_threshold_rule={
                "aggregation_method": "mean",
                "granularity": 60,
                "evaluation_periods": 1,
                "threshold": 50,
                "comparison_operator": "gt",
                "metrics": ["911fce07-e0d7-4210-8c8c-4a9d811fcabc",
                            "2543d435-fe93-4443-9351-fb0156930f94"],
            },
            time_constraints=[],
            severity='low',
        ).AndReturn(FakeCeilometerAlarm())
        snippet = template_format.parse(
            gnocchi_aggregation_by_metrics_alarm_template)
        self.stack = utils.parse_stack(snippet)
        resource_defns = self.stack.t.resource_definitions(self.stack)
        return gnocchi.CeilometerGnocchiAggregationByMetricsAlarm(
            'GnoAggregationByMetricsAlarm',
            resource_defns['GnoAggregationByMetricsAlarm'], self.stack)

    def test_update(self):
        rsrc = self.create_alarm()
        self.m.StubOutWithMock(self.fc.alarms, 'update')
        self.fc.alarms.update(
            alarm_id='foo',
            gnocchi_aggregation_by_metrics_threshold_rule={
                'metrics': ['d3d6c642-921e-4fc2-9c5f-15d9a5afb598',
                            'bc60f822-18a0-4a0c-94e7-94c554b00901']})

        self.m.ReplayAll()
        scheduler.TaskRunner(rsrc.create)()

        update_template = copy.deepcopy(rsrc.t)
        update_template['Properties']['metrics'] = [
            'd3d6c642-921e-4fc2-9c5f-15d9a5afb598',
            'bc60f822-18a0-4a0c-94e7-94c554b00901']
        scheduler.TaskRunner(rsrc.update, update_template)()
        self.assertEqual((rsrc.UPDATE, rsrc.COMPLETE), rsrc.state)

        self.m.VerifyAll()

    def _prepare_check_resource(self):
        snippet = template_format.parse(
            gnocchi_aggregation_by_metrics_alarm_template)
        self.stack = utils.parse_stack(snippet)
        res = self.stack['GnoAggregationByMetricsAlarm']
        res.client = mock.Mock()
        mock_alarm = mock.Mock(enabled=True, state='ok')
        res.client().alarms.get.return_value = mock_alarm
        return res

    def test_show_resource(self):
        res = self._prepare_check_resource()
        res.client().alarms.create.return_value = mock.MagicMock(
            alarm_id='2')
        res.client().alarms.get.return_value = FakeCeilometerAlarm()
        scheduler.TaskRunner(res.create)()
        self.assertEqual({'attr': 'val'}, res.FnGetAtt('show'))

class GnocchiAggregationByResourcesAlarmTest(GnocchiResourcesAlarmTest):

    def create_alarm(self):
        self.m.StubOutWithMock(ceilometer.CeilometerClientPlugin, '_create')
        ceilometer.CeilometerClientPlugin._create().AndReturn(
            self.fc)
        self.m.StubOutWithMock(self.fc.alarms, 'create')
        self.fc.alarms.create(
            alarm_actions=[],
            description=u'Do stuff with gnocchi aggregation by resource',
            enabled=True,
            insufficient_data_actions=None,
            ok_actions=None,
            name=mox.IgnoreArg(),
            type='gnocchi_aggregation_by_resources_threshold',
            repeat_actions=True,
            gnocchi_aggregation_by_resources_threshold_rule={
                "aggregation_method": "mean",
                "granularity": 60,
                "evaluation_periods": 1,
                "threshold": 50,
                "comparison_operator": "gt",
                "metric": "cpu_util",
                "resource_type": "instance",
                "query": '{"=": {"server_group": "my_autoscaling_group"}}',
            },
            time_constraints=[],
            severity='low',
        ).AndReturn(FakeCeilometerAlarm())
        snippet = template_format.parse(
            gnocchi_aggregation_by_resources_alarm_template)
        self.stack = utils.parse_stack(snippet)
        resource_defns = self.stack.t.resource_definitions(self.stack)
        return gnocchi.CeilometerGnocchiAggregationByResourcesAlarm(
            'GnoAggregationByResourcesAlarm',
            resource_defns['GnoAggregationByResourcesAlarm'], self.stack)

    def test_update(self):
        rsrc = self.create_alarm()
        self.m.StubOutWithMock(self.fc.alarms, 'update')
        self.fc.alarms.update(
            alarm_id='foo',
            gnocchi_aggregation_by_resources_threshold_rule={
                'query': '{"=": {"server_group": "my_new_group"}}'})

        self.m.ReplayAll()
        scheduler.TaskRunner(rsrc.create)()

        update_template = copy.deepcopy(rsrc.t)
        update_template['Properties']['query'] = (
            '{"=": {"server_group": "my_new_group"}}')
        scheduler.TaskRunner(rsrc.update, update_template)()
        self.assertEqual((rsrc.UPDATE, rsrc.COMPLETE), rsrc.state)

        self.m.VerifyAll()

    def _prepare_check_resource(self):
        snippet = template_format.parse(
            gnocchi_aggregation_by_resources_alarm_template)
        self.stack = utils.parse_stack(snippet)
        res = self.stack['GnoAggregationByResourcesAlarm']
        res.client = mock.Mock()
        mock_alarm = mock.Mock(enabled=True, state='ok')
        res.client().alarms.get.return_value = mock_alarm
        return res

    def test_show_resource(self):
        res = self._prepare_check_resource()
        res.client().alarms.create.return_value = mock.MagicMock(
            alarm_id='2')
        res.client().alarms.get.return_value = FakeCeilometerAlarm()
        scheduler.TaskRunner(res.create)()
        self.assertEqual({'attr': 'val'}, res.FnGetAtt('show'))