text:
import collections
import httplib2
import math
import json
import time
import urllib
import sys

# This imports all the public packages (the ones that don't start with an underscore) and the content of __all__
from . import *
# So we need to add _pyrest_core
from . import _pyrest_core

class RestServerException(Exception):
    """Used when the server returned a non-OK code"""
    pass

class UnknownResponseCodeException(RestServerException):
    """Used when the RestServer does not know the meaning of the HTTP response code returned by the server"""
    pass
class NotOKResponseCodeException(RestServerException):
    """Used when the server returned the response code of an error"""
    pass

class UnavailableFormatException(RestServerException):
    """Used when the required output format is not available for this endpoint"""
    pass

class RestServer:
    """
    RestServer is a class that knows how to communicate with the Ensembl REST servers.
    """

    __content_types = {
    "bed": "text/x-bed",
"fasta": "text/x-fasta",
"gff3": "text/x-gff3",
"json": "application/json",
"nh": "text/x-nh",
"phyloxml": "text/x-phyloxml+xml",
"xml": "text/xml",
"yaml": "text/x-yaml",
"text": "text/plain"
    }

    __return_codes = {
    200: ("OK", "Request was a success"),
400: ("Bad Request", "Occurs during exceptional circumstances such as the service is unable to find an ID"),
404: ("Not Found", "Indicates a badly formatted request. Check your URL"),
429: ("Too Many Requests", "You have been rate-limited; wait and retry"),
503: ("Service Unavailable", "The service is temporarily down; retry after a pause")
    }

    def __init__(self, server_url):
        """
        Constructor for the RestServer class.
        server_url is the URL of the server.
        """
        self.server_url = server_url
        self.http = httplib2.Http()
        self.last_headers = None

    def __get_json_answer(self, url, content_type=None):

        # Rate limiter
        # FIXME: check whether it is ever used and delete otherwise
        if self.last_headers is not None:
            time_remaining = int(self.last_headers['x-ratelimit-reset'])
            requests_remaining = int(self.last_headers['x-ratelimit-remaining'])
            t = time_remaining * math.exp( -requests_remaining / time_remaining )
            if t > .001:
                print("sleeping", t, "seconds before calling", self.server_url)
                time.sleep(t)

        #print("getting "+self.server_url+"/"+url+" with the content_type:"+content_type)
        while True:
            resp, content = self.http.request(self.server_url+"/"+url, method="GET", headers={"Content-Type":content_type})
            if resp.status == 429:
                print(self.server_url, "asked to wait", resp['retry-after'], "seconds", file=sys.stderr)
                time.sleep(float(resp['retry-after']))
            else:
                break

        if resp.status not in self.__return_codes:
            raise UnknownResponseCodeException(resp.status, resp, content)
        if self.__return_codes[resp.status][0] != "OK":
            raise NotOKResponseCodeException(self.__return_codes[resp.status], resp.status, resp, content )
        self.last_headers = resp

        return content.decode('utf-8')

    def __build_rest_answer(self, new_object, allowed_formats, optional_params, accessor, url, kwargs={}):

        format = kwargs.pop('output_format', None)
        if format is not None:
            format = format.lower()
            if format not in allowed_formats:
                raise UnavailableFormatException(format)
                format = None

        if len(kwargs):
            ps = set(kwargs).intersection(optional_params)
            pairs = []
            for p in ps:
                vv = kwargs[p]
                if isinstance(vv, list):
                    pairs.extend( (p,_) for _ in vv)
                else:
                    pairs.append( (p,vv) )
            url = url + "?" + "&".join("%s=%s" % (p,urllib.parse.quote(str(v))) for (p,v) in pairs)

        content = self.__get_json_answer(url, self.__content_types.get(format, self.__content_types['json']))

        #print "Format", format
        if format is not None:
            return content

        j = json.loads(content)
        if accessor is not None:
            j = j[accessor]
        return _pyrest_core.construct_object_from_json(j, new_object, self)

    def getArchiveEntry(self, id, **kwargs):
        """Uses the given identifier to return the archived sequence

Return type: ensembl.info.ArchiveEntry
Valid formats: json, xml
HTTP endpoint: archive/id/:id

Required parameters:
- id (String)
    An Ensembl stable ID

"""
        return self.__build_rest_answer(info.ArchiveEntry, ['json', 'xml'], [], None, 'archive/id/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def getAssemblyInfo(self, species, **kwargs):
        """List the currently available assemblies for a species.

Return type: ensembl.info.Assembly
Valid formats: json, xml
HTTP endpoint: info/assembly/:species

Required parameters:
- species (String)
    Species name/alias

Optional parameters:
- bands (Boolean(0,1))
    If set to 1, include karyotype band information. Only display if band information is available
"""
        return self.__build_rest_answer(info.Assembly, ['json', 'xml'], ['bands'], None, 'info/assembly/{0}'.format(urllib.parse.quote(str(species))), kwargs)

    def getAssemblyInfoRegion(self, species, region_name, **kwargs):
        """Returns information about the specified toplevel sequence region for the given species.

Return type: ensembl.info.SeqRegion
Valid formats: json, xml
HTTP endpoint: info/assembly/:species/:region_name

Required parameters:
- species (String)
    Species name/alias
- region_name (String)
    The (top level) sequence region name.

Optional parameters:
- bands (Boolean(0,1))
    If set to 1, include karyotype band information. Only display if band information is available
"""
        return self.__build_rest_answer(info.SeqRegion, ['json', 'xml'], ['bands'], None, 'info/assembly/{0}/{1}'.format(urllib.parse.quote(str(species)), urllib.parse.quote(str(region_name))), kwargs)

    def getGeneTreeById(self, id, **kwargs):
        """Retrieves a gene tree dump for a gene tree stable identifier

Return type: ensembl.compara.GeneTree
Valid formats: phyloxml, nh, json
HTTP endpoint: genetree/id/:id

Required parameters:
- id (String)
    An Ensembl genetree ID

Optional parameters:
- compara (String)
    Name of the compara database to use. Multiple comparas can exist on a server if you are accessing Ensembl Genomes data
- aligned (Boolean)
    Return the aligned string if true. Otherwise, return the original sequence (no insertions)
- sequence (Enum(none, cdna, protein))
    The type of sequence to bring back. Setting it to none results in no sequence being returned
- nh_format (Enum(full, display_label_composite, simple, species, species_short_name, ncbi_taxon, ncbi_name, njtree, phylip))
    The format of a NH (New Hampshire) request.
"""
        return self.__build_rest_answer(compara.GeneTree, ['phyloxml', 'nh', 'json'], ['compara', 'aligned', 'sequence', 'nh_format'], None, 'genetree/id/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def getGeneTreeByMemberId(self, id, **kwargs):
        """Retrieves a gene tree that contains the stable identifier

Return type: ensembl.compara.GeneTree
Valid formats: phyloxml, nh, json
HTTP endpoint: genetree/member/id/:id

Required parameters:
- id (String)
    An Ensembl stable ID

Optional parameters:
- species (String)
    Species name/alias
- db_type (String)
    Restrict the search to a database other than the default. Useful if you need to use a DB other than core
- object_type (String)
    Filter by feature type
- compara (String)
    Name of the compara database to use. Multiple comparas can exist on a server if you are accessing Ensembl Genomes data
- aligned (Boolean)
    Return the aligned string if true. Otherwise, return the original sequence (no insertions)
- sequence (Enum(none, cdna, protein))
    The type of sequence to bring back. Setting it to none results in no sequence being returned
- nh_format (Enum(full, display_label_composite, simple, species, species_short_name, ncbi_taxon, ncbi_name, njtree, phylip))
    The format of a NH (New Hampshire) request.
"""
        return self.__build_rest_answer(compara.GeneTree, ['phyloxml', 'nh', 'json'], ['species', 'db_type', 'object_type', 'compara', 'aligned', 'sequence', 'nh_format'], None, 'genetree/member/id/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def getGeneTreeByMemberSymbol(self, species, symbol, **kwargs):
        """Retrieves a gene tree containing the gene identified by a symbol

Return type: ensembl.compara.GeneTree
Valid formats: phyloxml, nh, json
HTTP endpoint: genetree/member/symbol/:species/:symbol

Required parameters:
- species (String)
    Species name/alias
- symbol (String)
    Symbol or display name of a gene

Optional parameters:
- db_type (String)
    Restrict the search to a database other than the default. Useful if you need to use a DB other than core
- external_db (String)
    Filter by external database
- object_type (String)
    Filter by feature type
- compara (String)
    Name of the compara database to use. Multiple comparas can exist on a server if you are accessing Ensembl Genomes data
- aligned (Boolean)
    Return the aligned string if true. Otherwise, return the original sequence (no insertions)
- sequence (Enum(none, cdna, protein))
    The type of sequence to bring back. Setting it to none results in no sequence being returned
- nh_format (Enum(full, display_label_composite, simple, species, species_short_name, ncbi_taxon, ncbi_name, njtree, phylip))
    The format of a NH (New Hampshire) request.
"""
        return self.__build_rest_answer(compara.GeneTree, ['phyloxml', 'nh', 'json'], ['db_type', 'external_db', 'object_type', 'compara', 'aligned', 'sequence', 'nh_format'], None, 'genetree/member/symbol/{0}/{1}'.format(urllib.parse.quote(str(species)), urllib.parse.quote(str(symbol))), kwargs)

    def getHomologyByGeneSymbol(self, species, symbol, **kwargs):
        """Retrieves homology information (orthologs) by symbol

Return type: ensembl.compara.HomologyGroup
Valid formats: json, xml, orthoxml
HTTP endpoint: homology/symbol/:species/:symbol

Required parameters:
- species (String)
    Species name/alias
- symbol (String)
    Symbol or display name of a gene

Optional parameters:
- compara (String)
    Name of the compara database to use. Multiple comparas can exist on a server if you are accessing Ensembl Genomes data
- external_db (String)
    Filter by external database
- format (Enum(full,condensed))
    Layout of the response
- type (Enum(orthologues, paralogues, projections, all))
    The type of homology to return from this call. Projections are orthology calls defined between alternative assemblies and the genes shared between them. Useful if you need only one type of homology back from the service
- target_species (String)
    Filter by species. Supports all species aliases
- target_taxon (Integer)
    Filter by taxon
- aligned (Boolean)
    Return the aligned string if true. Otherwise, return the original sequence (no insertions)
- sequence (Enum(none, cdna, protein))
    The type of sequence to bring back. Setting it to none results in no sequence being returned
"""
        return self.__build_rest_answer(compara.HomologyGroup, ['json', 'xml', 'orthoxml'], ['compara', 'external_db', 'format', 'type', 'target_species', 'target_taxon', 'aligned', 'sequence'], "data", 'homology/symbol/{0}/{1}'.format(urllib.parse.quote(str(species)), urllib.parse.quote(str(symbol))), kwargs)

    def getHomologyByGeneStableID(self, id, **kwargs):
        """Retrieves homology information (orthologs) by Ensembl gene id

Return type: ensembl.compara.HomologyGroup
Valid formats: json, xml, orthoxml
HTTP endpoint: homology/id/:id

Required parameters:
- id (String)
    An Ensembl stable ID

Optional parameters:
- species (String)
    Species name/alias
- compara (String)
    Name of the compara database to use. Multiple comparas can exist on a server if you are accessing Ensembl Genomes data
- format (Enum(full, condensed))
    Layout of the response
- type (Enum(orthologues, paralogues, projections, all))
    The type of homology to return from this call. Projections are orthology calls defined between alternative assemblies and the genes shared between them. Useful if you need only one type of homology back from the service
- target_species (String)
    Filter by species. Supports all species aliases
- target_taxon (Integer)
    Filter by taxon
- aligned (Boolean)
    Return the aligned string if true. Otherwise, return the original sequence (no insertions)
- sequence (Enum(none, cdna, protein))
    The type of sequence to bring back. Setting it to none results in no sequence being returned
"""
        return self.__build_rest_answer(compara.HomologyGroup, ['json', 'xml', 'orthoxml'], ['species', 'compara', 'format', 'type', 'target_species', 'target_taxon', 'aligned', 'sequence'], "data", 'homology/id/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def getGenomicAlignmentByRegion(self, species, region, **kwargs):
        """Retrieves genomic alignments as separate blocks based on a region and species

Return type: ensembl.compara.GenomicAlignment
Valid formats: json, xml, phyloxml
HTTP endpoint: alignment/region/:species/:region

Required parameters:
- species (String)
    Species name/alias
- region (String)
    Query region. A maximum of 10Mb is allowed to be requested at any one time

Optional parameters:
- compara (String)
    Name of the compara database to use. Multiple comparas can exist on a server if you are accessing Ensembl Genomes data
- aligned (Boolean)
    Return the aligned string if true. Otherwise, return the original sequence (no insertions)
- mask (Enum(hard,soft))
    Request the sequence masked for repeat sequences. Hard will mask all repeats as N's and soft will mask repeats as lowercased characters.
- species_set_group (String)
    The species set group name of the multiple alignment. Should not be used with the species_set parameter. Use /info/compara/species_sets/:method with one of the methods listed above to obtain a valid list of group names.
- species_set (String)
    The set of species used to define the pairwise alignment (multiple values). Should not be used with the species_set_group parameter. Use /info/compara/species_sets/:method with one of the methods listed above to obtain a valid list of species sets. Any valid alias may be used.
- method (Enum(EPO, EPO_LOW_COVERAGE, PECAN, LASTZ_NET, BLASTZ_NET, TRANSLATED_BLAT_NET))
    The alignment method
- display_species_set (String)
    Subset of species in the alignment to be displayed (multiple values). All the species in the alignment will be displayed if this is not set. Any valid alias may be used.
- compact (Boolean)
    Applicable to EPO_LOW_COVERAGE alignments. If true, concatenate the low coverage species sequences together to create a single sequence. Otherwise, separates out all sequences.
"""
        return self.__build_rest_answer(compara.GenomicAlignment, ['json', 'xml', 'phyloxml'], ['compara', 'aligned', 'mask', 'species_set_group', 'species_set', 'method', 'display_species_set', 'compact'], None, 'alignment/region/{0}/{1}'.format(urllib.parse.quote(str(species)), urllib.parse.quote(str(region))), kwargs)

    def ping(self, **kwargs):
        """Checks if the service is alive.

Return type: None
Valid formats: json, xml
HTTP endpoint: info/ping

"""
        return self.__build_rest_answer(None, ['json', 'xml'], [], "ping", 'info/ping', kwargs)

    def listSpecies(self, **kwargs):
        """Lists all available species, their aliases, available adaptor groups and data release.

Return type: ensembl.info.Species
Valid formats: json, xml
HTTP endpoint: info/species

Optional parameters:
- division (String)
    Filter by Ensembl or Ensembl Genomes division.
"""
        return self.__build_rest_answer(info.Species, ['json', 'xml'], ['division'], "species", 'info/species', kwargs)

    def listComparaDatabases(self, **kwargs):
        """Lists all available comparative genomics databases and their data release.

Return type: None
Valid formats: json, xml
HTTP endpoint: info/comparas

"""
        return self.__build_rest_answer(None, ['json', 'xml'], [], "comparas", 'info/comparas', kwargs)

    def ensembl_version(self, **kwargs):
        """Shows the current version of the Ensembl API used by the REST server.

Return type: None
Valid formats: json, xml
HTTP endpoint: info/software

"""
        return self.__build_rest_answer(None, ['json', 'xml'], [], "release", 'info/software', kwargs)

    def rest_version(self, **kwargs):
        """Shows the current version of the Ensembl REST API.

Return type: None
Valid formats: json, xml
HTTP endpoint: info/rest

"""
        return self.__build_rest_answer(None, ['json', 'xml'], [], "release", 'info/rest', kwargs)

    def listAvailableReleases(self, **kwargs):
        """Shows the data releases available on this REST server. May return more than one release (unfrequent non-standard Ensembl configuration).

Return type: None
Valid formats: json, xml
HTTP endpoint: info/data

"""
        return self.__build_rest_answer(None, ['json', 'xml'], [], "releases", 'info/data', kwargs)

    def getAnalysisList(self, species, **kwargs):
        """List the names of analyses involved in generating Ensembl data.

Return type: None
Valid formats: json, xml
HTTP endpoint: info/analysis/:species

Required parameters:
- species (String)
    Species name/alias

"""
        return self.__build_rest_answer(None, ['json', 'xml'], [], None, 'info/analysis/{0}'.format(urllib.parse.quote(str(species))), kwargs)

    def getBiotypesBySpecies(self, species, **kwargs):
        """List the functional classifications of gene models that Ensembl associates with a particular species. Useful for restricting the type of genes/transcripts retrieved by other endpoints.

Return type: ensembl.info.Biotype
Valid formats: json, xml
HTTP endpoint: info/biotypes/:species

Required parameters:
- species (String)
    Species name/alias

"""
        return self.__build_rest_answer(info.Biotype, ['json', 'xml'], [], None, 'info/biotypes/{0}'.format(urllib.parse.quote(str(species))), kwargs)

    def getExternalDatabasesBySpecies(self, species, **kwargs):
        """Lists all available external sources for a species.

Return type: ensembl.info.ExternalDatabase
Valid formats: json, xml
HTTP endpoint: info/external_dbs/:species

Required parameters:
- species (String)
    Species name/alias

Optional parameters:
- filter (String)
    Restrict external DB searches to a single source or pattern. SQL-LIKE patterns are supported.
"""
        return self.__build_rest_answer(info.ExternalDatabase, ['json', 'xml'], ['filter'], None, 'info/external_dbs/{0}'.format(urllib.parse.quote(str(species))), kwargs)

    def getAllComparaMethods(self, **kwargs):
        """List all compara analyses available (an analysis defines the type of comparative data).

Return type: None
Valid formats: json, json, yaml, xml
HTTP endpoint: info/compara/methods

Optional parameters:
- compara (String)
    Name of the compara database to use. Multiple comparas may exist on a server when accessing Ensembl Genomes data.
- class (String)
    The class of the method to query for. Regular expression patterns are supported.
"""
        return self.__build_rest_answer(None, ['json', 'json', 'yaml', 'xml'], ['compara', 'class'], None, 'info/compara/methods', kwargs)

    def getSpeciesSetByComparaMethod(self, method, **kwargs):
        """List all collections of species analysed with the specified compara method.

Return type: ensembl.compara.MethodLinkSpeciesSet
Valid formats: json, yaml, xml
HTTP endpoint: info/compara/species_sets/:method

Required parameters:
- method (String)
    Filter by compara method. Use one the methods returned by /info/compara/methods endpoint.

Optional parameters:
- compara (String)
    Name of the compara database to use. Multiple comparas may exist on a server when accessing Ensembl Genomes data.
"""
        return self.__build_rest_answer(compara.MethodLinkSpeciesSet, ['json', 'yaml', 'xml'], ['compara'], None, 'info/compara/species_sets/{0}'.format(urllib.parse.quote(str(method))), kwargs)

    def lookupIdentifier(self, id, **kwargs):
        """Find the species and database for a single identifier

Return type: ensembl.genome.feature_wrapper
Valid formats: json, xml
HTTP endpoint: lookup/id/:id

Required parameters:
- id (String)
    An Ensembl stable ID

Optional parameters:
- species (String)
    Species name/alias
- db_type (String)
    Restrict the search to a database other than the default. Useful if you need to use a DB other than core
- format (Enum(full,condensed))
    Specify the formats to emit from this endpoint
- expand (Boolean(0,1))
    Expands the search to include any connected features. e.g. If the object is a gene, its transcripts, translations and exons will be returned as well.
"""
        return self.__build_rest_answer(genome.feature_wrapper, ['json', 'xml'], ['species', 'db_type', 'format', 'expand'], None, 'lookup/id/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def lookupGeneSymbol(self, species, symbol, **kwargs):
        """Find the species and database for a symbol in a linked external database

Return type: ensembl.genome.feature_wrapper
Valid formats: json, xml
HTTP endpoint: lookup/symbol/:species/:symbol

Required parameters:
- species (String)
    Species name/alias
- symbol (String)
    A name or symbol from an annotation source has been linked to a genetic feature

Optional parameters:
- format (Enum(full,condensed))
    Specify the layout of the response
- expand (Boolean(0,1))
    Expands the search to include any connected features. e.g. If the object is a gene, its transcripts, translations and exons will be returned as well.
"""
        return self.__build_rest_answer(genome.feature_wrapper, ['json', 'xml'], ['format', 'expand'], None, 'lookup/symbol/{0}/{1}'.format(urllib.parse.quote(str(species)), urllib.parse.quote(str(symbol))), kwargs)

    def mapCoordinatesBetweenAssemblies(self, species, asm_one, region, asm_two, **kwargs):
        """Convert the co-ordinates of one assembly to another

Return type: ensembl.genome.CoordMapping
Valid formats: json, xml
HTTP endpoint: map/:species/:asm_one/:region/:asm_two

Required parameters:
- species (String)
    Species name/alias
- asm_one (String)
    Version of the input assembly
- region (String)
    Query region
- asm_two (String)
    Version of the output assembly

Optional parameters:
- coord_system (String)
    Name of the output coordinate system
"""
        return self.__build_rest_answer(genome.CoordMapping, ['json', 'xml'], ['coord_system'], "mappings", 'map/{0}/{1}/{2}/{3}'.format(urllib.parse.quote(str(species)), urllib.parse.quote(str(asm_one)), urllib.parse.quote(str(region)), urllib.parse.quote(str(asm_two))), kwargs)

    def mapCDNACoordinatesToGenome(self, id, region, **kwargs):
        """Convert from cDNA coordinates to genomic coordinates. Output reflects forward orientation coordinates as returned from the Ensembl API.

Return type: ensembl.genome.Location
Valid formats: json, xml
HTTP endpoint: map/cdna/:id/:region

Required parameters:
- id (String)
    An Ensembl stable ID
- region (String)
    Query region

Optional parameters:
- species (String)
    Species name/alias
"""
        return self.__build_rest_answer(genome.Location, ['json', 'xml'], ['species'], "mappings", 'map/cdna/{0}/{1}'.format(urllib.parse.quote(str(id)), urllib.parse.quote(str(region))), kwargs)

    def mapCDSCoordinatesToGenome(self, id, region, **kwargs):
        """Convert from CDS coordinates to genomic coordinates. Output reflects forward orientation coordinates as returned from the Ensembl API.

Return type: ensembl.genome.Location
Valid formats: json, xml
HTTP endpoint: map/cds/:id/:region

Required parameters:
- id (String)
    An Ensembl stable ID
- region (String)
    Query region

Optional parameters:
- species (String)
    Species name/alias
"""
        return self.__build_rest_answer(genome.Location, ['json', 'xml'], ['species'], "mappings", 'map/cds/{0}/{1}'.format(urllib.parse.quote(str(id)), urllib.parse.quote(str(region))), kwargs)

    def mapProteinCoordinatesToGenome(self, id, region, **kwargs):
        """Convert from protein (translation) coordinates to genomic coordinates. Output reflects forward orientation coordinates as returned from the Ensembl API.

Return type: ensembl.genome.Location
Valid formats: json, xml
HTTP endpoint: map/translation/:id/:region

Required parameters:
- id (String)
    An Ensembl stable ID
- region (String)
    Query region

Optional parameters:
- species (String)
    Species name/alias
"""
        return self.__build_rest_answer(genome.Location, ['json', 'xml'], ['species'], "mappings", 'map/translation/{0}/{1}'.format(urllib.parse.quote(str(id)), urllib.parse.quote(str(region))), kwargs)

    def getOntologyByID(self, id, **kwargs):
        """Search for an ontological term by its namespaced identifier

Return type: ensembl.info.OntologyTerm
Valid formats: json, xml, yaml
HTTP endpoint: ontology/id/:id

Required parameters:
- id (String)
    An ontology term identifier

Optional parameters:
- relation (String)
    The types of relationships to include in the output. Fetches all relations by default
- simple (Boolean)
    If set the API will avoid the fetching of parent and child terms
"""
        return self.__build_rest_answer(info.OntologyTerm, ['json', 'xml', 'yaml'], ['relation', 'simple'], None, 'ontology/id/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def getOntologyByName(self, name, **kwargs):
        """Search for a list of ontological terms by their name

Return type: ensembl.info.OntologyTerm
Valid formats: json, xml, yaml
HTTP endpoint: ontology/name/:name

Required parameters:
- name (String)
    An ontology name. SQL wildcards are supported

Optional parameters:
- ontology (String)
    Filter by ontology. Used to disambiguate terms which are shared between ontologies such as GO and EFO
- relation (String)
    The types of relationships to include in the output. Fetches all relations by default
- simple (Boolean)
    If set the API will avoid the fetching of parent and child terms
"""
        return self.__build_rest_answer(info.OntologyTerm, ['json', 'xml', 'yaml'], ['ontology', 'relation', 'simple'], None, 'ontology/name/{0}'.format(urllib.parse.quote(str(name))), kwargs)

    def getAllAncestorsOfOntologyID(self, id, **kwargs):
        """Reconstruct the entire ancestry of a term from is_a and part_of relationships

Return type: ensembl.info.OntologyTerm
Valid formats: json, xml, yaml
HTTP endpoint: ontology/ancestors/:id

Required parameters:
- id (String)
    An ontology term identifier

Optional parameters:
- ontology (String)
    Filter by ontology. Used to disambiguate terms which are shared between ontologies such as GO and EFO
"""
        return self.__build_rest_answer(info.OntologyTerm, ['json', 'xml', 'yaml'], ['ontology'], None, 'ontology/ancestors/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def getAllDescendantsOfOntologyID(self, id, **kwargs):
        """Find all the terms descended from a given term. By default searches are conducted within the namespace of the given identifier

Return type: ensembl.info.OntologyTerm
Valid formats: json, xml
HTTP endpoint: ontology/descendants/:id

Required parameters:
- id (String)
    An ontology term identifier

Optional parameters:
- ontology (String)
    Filter by ontology. Used to disambiguate terms which are shared between ontologies such as GO and EFO
- subset (String)
    Filter terms by the specified subset
- closest_term (Boolean)
    If true return only the closest terms to the specified term
- zero_distance (Boolean)
    Return terms with a distance of 0
"""
        return self.__build_rest_answer(info.OntologyTerm, ['json', 'xml'], ['ontology', 'subset', 'closest_term', 'zero_distance'], None, 'ontology/descendants/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def getOntologyAncestorChart(self, id, **kwargs):
        """Reconstruct the entire ancestry of a term from is_a and part_of relationships.

Return type: Dictionary of String -> ensembl.info.OntologyEntry
Valid formats: json, xml
HTTP endpoint: ontology/ancestors/chart/:id

Required parameters:
- id (String)
    An ontology term identifier

Optional parameters:
- ontology (String)
    Filter by ontology. Used to disambiguate terms which are shared between ontologies such as GO and EFO
"""
        return self.__build_rest_answer(_pyrest_core.dict_wrapper(info.OntologyEntry), ['json', 'xml'], ['ontology'], None, 'ontology/ancestors/chart/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def getAllFeaturesOnFeatureID(self, id, **kwargs):
        """Retrieves features (e.g. genes, transcripts, variations etc.) that overlap a region defined by the given identifier.

Return type: ensembl.genome.feature_wrapper
Valid formats: json, xml, gff3, bed
HTTP endpoint: overlap/id/:id

Required parameters:
- id (String)
    An Ensembl stable ID

Optional parameters:
- species (String)
    Species name/alias.
- object_type (String)
    Filter by feature type
- db_type (String)
    Restrict the search to a database other than the default. Useful if you need to use a DB other than core
- feature (Enum(gene, transcript, cds, exon, repeat, simple, misc, variation, somatic_variation, structural_variation, somatic_structural_variation, constrained, regulatory, segmentation, motif, chipseq, array_probe))
    The type of feature to retrieve. Multiple values are accepted.
- species_set (String)
    Filter by species set for retrieving constrained elements.
- logic_name (String)
    Limit retrieval of genes, transcripts and exons by a given name of an analysis.
- so_term (String)
    Sequence Ontology term to narrow down the possible variations returned.
- misc_set (String)
    Miscellaneous set which groups together feature entries. Consult the DB or returned data sets to discover what is available.
- biotype (String)
    The functional classification of the gene or transcript to fetch. Cannot be used in conjunction with logic_name when querying transcripts.
"""
        return self.__build_rest_answer(genome.feature_wrapper, ['json', 'xml', 'gff3', 'bed'], ['species', 'object_type', 'db_type', 'feature', 'species_set', 'logic_name', 'so_term', 'misc_set', 'biotype'], None, 'overlap/id/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def getAllFeaturesOnRegion(self, species, region, **kwargs):
        """Retrieves multiple types of features for a given region.

Return type: ensembl.genome.feature_wrapper
Valid formats: json, xml, gff3, bed
HTTP endpoint: overlap/region/:species/:region

Required parameters:
- species (String)
    Species name/alias.
- region (String)
    Query region. A maximum of 5Mb is allowed to be requested at any one time

Optional parameters:
- db_type (String)
    Specify the database type to retrieve features from if not using the core database. We automatically choose the correct type of DB for variation, comparative and regulation features.
- feature (Enum(gene, transcript, cds, exon, repeat, simple, misc, variation, somatic_variation, structural_variation, somatic_structural_variation, constrained, regulatory, segmentation, motif, chipseq, array_probe))
    The type of feature to retrieve. Multiple values are accepted.
- species_set (String)
    The species set name for retrieving constrained elements.
- logic_name (String)
    Limit retrieval of genes, transcripts and exons by the name of analysis.
- so_term (String)
    Sequence Ontology term to restrict the variations found. Its descendants are also included in the search.
- cell_type (String)
    Cell type name in Ensembl's Regulatory Build, required for segmentation feature, optional for regulatory elements.
- misc_set (String)
    Miscellaneous set which groups together feature entries. Consult the DB or returned data sets to discover what is available.
- biotype (String)
    Functional classification of the gene or transcript to fetch. Cannot be used in conjunction with logic_name when querying transcripts.
- trim_upstream (Boolean)
    Do not return features which overlap upstream end of the region.
- trim_downstream (Boolean)
    Do not return features which overlap the downstream end of the region.
"""
        return self.__build_rest_answer(genome.feature_wrapper, ['json', 'xml', 'gff3', 'bed'], ['db_type', 'feature', 'species_set', 'logic_name', 'so_term', 'cell_type', 'misc_set', 'biotype', 'trim_upstream', 'trim_downstream'], None, 'overlap/region/{0}/{1}'.format(urllib.parse.quote(str(species)), urllib.parse.quote(str(region))), kwargs)

    def getAllFeaturesOnTranslation(self, id, **kwargs):
        """Retrieve features related to a specific Translation as described by its stable ID (e.g. domains, variations).

Return type: ensembl.genome.feature_wrapper
Valid formats: json, xml
HTTP endpoint: overlap/translation/:id

Required parameters:
- id (String)
    An Ensembl stable ID

Optional parameters:
- species (String)
    Species name/alias.
- db_type (String)
    Restrict the search to a database other than the default. Useful if you need to use a DB other than core
- feature (Enum(transcript_variation, protein_feature, residue_overlap, translation_exon, somatic_transcript_variation))
    Specify the type of features requested for the translation.
- type (String)
    Type of data to filter by. By default, all features are returned. Can specify a domain or consequence type.
- so_term (String)
    Sequence Ontology term to restrict the variations found. Its descendants are also included in the search.
"""
        return self.__build_rest_answer(genome.feature_wrapper, ['json', 'xml'], ['species', 'db_type', 'feature', 'type', 'so_term'], None, 'overlap/translation/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def getRegulatoryFeatureByID(self, species, id, **kwargs):
        """Returns a RegulatoryFeature given its stable ID (e.g. ENSR00001348195)

Return type: ensembl.funcgen.RegulatoryFeature
Valid formats: json, xml
HTTP endpoint: regulatory/:species/:id

Required parameters:
- species (String)
    Species name/alias
- id (String)
    RegulatoryFeature stable ID

"""
        return self.__build_rest_answer(funcgen.RegulatoryFeature, ['json', 'xml'], [], None, 'regulatory/{0}/{1}'.format(urllib.parse.quote(str(species)), urllib.parse.quote(str(id))), kwargs)

    def getFeatureSequenceByID(self, id, **kwargs):
        """Request multiple types of sequence by stable identifier.

Return type: ensembl.genome.Sequence
Valid formats: fasta, json, text, yaml
HTTP endpoint: sequence/id/:id

Required parameters:
- id (String)
    An Ensembl stable ID

Optional parameters:
- type (Enum(genomic,cds,cdna,protein))
    Type of sequence. Defaults to genomic where applicable, i.e. not translations. cdna refers to the spliced transcript sequence with UTR; cds refers to the spliced transcript sequence without UTR.
- species (String)
    Species name/alias
- object_type (String)
    Filter by feature type
- db_type (String)
    Restrict the search to a database other than the default. Useful if you need to use a DB other than core
- format (Enum(fasta))
    Format of the data
- mask (Enum(hard,soft))
    Request the sequence masked for repeat sequences. Hard will mask all repeats as N's and soft will mask repeats as lowercased characters. Only available when using genomic sequence type.
- mask_feature (Boolean)
    Mask features on the sequence. If sequence is genomic, mask introns. If sequence is cDNA, mask UTRs. Incompatible with the 'mask' option
- expand_5prime (Int)
    Expand the sequence upstream of the sequence by this many basepairs. Only available when using genomic sequence type.
- expand_3prime (Int)
    Expand the sequence downstream of the sequence by this many basepairs. Only available when using genomic sequence type.
- multiple_sequences (Boolean)
    Allow the service to return more than 1 sequence per identifier. This is useful when querying for a gene but using a type such as protein.
"""
        return self.__build_rest_answer(genome.Sequence, ['fasta', 'json', 'text', 'yaml'], ['type', 'species', 'object_type', 'db_type', 'format', 'mask', 'mask_feature', 'expand_5prime', 'expand_3prime', 'multiple_sequences'], None, 'sequence/id/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def getSequenceOfRegion(self, species, region, **kwargs):
        """Returns the genomic sequence of the specified region of the given species.

Return type: ensembl.genome.Sequence
Valid formats: fasta, json, text, yaml
HTTP endpoint: sequence/region/:species/:region

Required parameters:
- species (String)
    Species name/alias
- region (String)
    Query region. A maximum of 10Mb is allowed to be requested at any one time

Optional parameters:
- format (Enum(fasta))
    Format of the data.
- mask (Enum(hard,soft))
    Request the sequence masked for repeat sequences. Hard will mask all repeats as N's and soft will mask repeats as lower cased characters. Only available when using genomic sequence type.
- mask_feature (Boolean)
    Mask features on the sequence. If sequence is genomic, mask introns. If sequence is cDNA, mask UTRs. Incompatible with the 'mask' option
- expand_5prime (Int)
    Expand the sequence upstream of the sequence by this many basepairs. Only available when using genomic sequence type.
- expand_3prime (Int)
    Expand the sequence downstream of the sequence by this many basepairs. Only available when using genomic sequence type.
- coord_system (String)
    Filter by coordinate system name
- coord_system_version (String)
    Filter by coordinate system version
"""
        return self.__build_rest_answer(genome.Sequence, ['fasta', 'json', 'text', 'yaml'], ['format', 'mask', 'mask_feature', 'expand_5prime', 'expand_3prime', 'coord_system', 'coord_system_version'], None, 'sequence/region/{0}/{1}'.format(urllib.parse.quote(str(species)), urllib.parse.quote(str(region))), kwargs)

    def getTaxonomyEntryByID(self, id, **kwargs):
        """Search for a taxonomic term by its identifier or name

Return type: ensembl.compara.NCBITaxon
Valid formats: json, xml, yaml
HTTP endpoint: taxonomy/id/:id

Required parameters:
- id (String)
    A taxon identifier. Can be a NCBI taxon id or a name

Optional parameters:
- simple (Boolean)
    If set the API will avoid the fetching of parent and child terms
"""
        return self.__build_rest_answer(compara.NCBITaxon, ['json', 'xml', 'yaml'], ['simple'], None, 'taxonomy/id/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def getTaxonomyClassificationByID(self, id, **kwargs):
        """Return the taxonomic classification of a taxon node

Return type: ensembl.compara.NCBITaxon
Valid formats: json, xml, yaml
HTTP endpoint: taxonomy/classification/:id

Required parameters:
- id (String)
    A taxon identifier. Can be a NCBI taxon id or a name

"""
        return self.__build_rest_answer(compara.NCBITaxon, ['json', 'xml', 'yaml'], [], None, 'taxonomy/classification/{0}'.format(urllib.parse.quote(str(id))), kwargs)

    def getTaxonomyEntryByName(self, name, **kwargs):
        """Search for a taxonomic id by a non-scientific name

Return type: ensembl.compara.NCBITaxon
Valid formats: json, xml, yaml
HTTP endpoint: taxonomy/name/:name

Required parameters:
- name (String)
    A non-scientific species name. Can include SQL wildcards

"""
        return self.__build_rest_answer(compara.NCBITaxon, ['json', 'xml', 'yaml'], [], None, 'taxonomy/name/{0}'.format(urllib.parse.quote(str(name))), kwargs)

    def getVariationByID(self, species, id, **kwargs):
        """Uses a variation identifier (e.g. rsID) to return the variation features

Return type: ensembl.variation.Variation
Valid formats: json, xml
HTTP endpoint: variation/:species/:id

Required parameters:
- species (String)
    Species name/alias
- id (String)
    Variation id

Optional parameters:
- genotypes (Boolean(0,1))
    Include individual genotypes
- phenotypes (Boolean(0,1))
    Include phenotypes
- pops (Boolean(0,1))
    Include population allele frequencies
- population_genotypes (Boolean(0,1))
    Include population genotype frequencies
"""
        return self.__build_rest_answer(variation.Variation, ['json', 'xml'], ['genotypes', 'phenotypes', 'pops', 'population_genotypes'], None, 'variation/{0}/{1}'.format(urllib.parse.quote(str(species)), urllib.parse.quote(str(id))), kwargs)

    def getVariantConsequencesByRegionAllele(self, species, region, allele, **kwargs):
        """Fetch variant consequences

Return type: ensembl.variation.VEPResult
Valid formats: json, xml
HTTP endpoint: vep/:species/region/:region/:allele/

Required parameters:
- species (String)
    Species name/alias
- region (String)
    Query region. We only support the current assembly
- allele (String)
    Variation allele

Optional parameters:
- hgvs (Boolean)
    Include HGVS nomenclature based on Ensembl stable identifiers
- ccds (Boolean)
    Include CCDS transcript identifiers
- numbers (Boolean)
    Include affected exon and intron positions within the transcript
- domains (Boolean)
    Include names of overlapping protein domains
- canonical (Boolean)
    Include a flag indicating the canonical transcript for a gene
- protein (Boolean)
    Include Ensembl protein identifiers
- xref_refseq (Boolean)
    Include aligned RefSeq mRNA identifiers for transcript. NB: theRefSeq and Ensembl transcripts aligned in this way MAY NOT, AND FREQUENTLY WILL NOT, match exactly in sequence, exon structure and protein product
"""
        return self.__build_rest_answer(variation.VEPResult, ['json', 'xml'], ['hgvs', 'ccds', 'numbers', 'domains', 'canonical', 'protein', 'xref_refseq'], None, 'vep/{0}/region/{1}/{2}/'.format(urllib.parse.quote(str(species)), urllib.parse.quote(str(region)), urllib.parse.quote(str(allele))), kwargs)

    def getVariantConsequencesByVariationID(self, species, id, **kwargs):
        """Fetch variant consequences based on a variation identifier

Return type: ensembl.variation.VEPResult
Valid formats: json, xml
HTTP endpoint: vep/:species/id/:id

Required parameters:
- species (String)
    Species name/alias
- id (String)
    Query ID. Supports dbSNP, COSMIC and HGMD identifiers

Optional parameters:
- hgvs (Boolean)
    Include HGVS nomenclature based on Ensembl stable identifiers
- ccds (Boolean)
    Include CCDS transcript identifiers
- numbers (Boolean)
    Include affected exon and intron positions within the transcript
- domains (Boolean)
    Include names of overlapping protein domains
- canonical (Boolean)
    Include a flag indicating the canonical transcript for a gene
- protein (Boolean)
    Include Ensembl protein identifiers
- xref_refseq (Boolean)
    Include aligned RefSeq mRNA identifiers for transcript. NB: theRefSeq and Ensembl transcripts aligned in this way MAY NOT, AND FREQUENTLY WILL NOT, match exactly in sequence, exon structure and protein product
"""
        return self.__build_rest_answer(variation.VEPResult, ['json', 'xml'], ['hgvs', 'ccds', 'numbers', 'domains', 'canonical', 'protein', 'xref_refseq'], None, 'vep/{0}/id/{1}'.format(urllib.parse.quote(str(species)), urllib.parse.quote(str(id))), kwargs)

    def getVariantConsequencesByHGVS(self, species, hgvs_notation, **kwargs):
        """Fetch variant consequences based on a HGVS notation

Return type: ensembl.variation.VEPResult
Valid formats: json, xml
HTTP endpoint: vep/:species/hgvs/:hgvs_notation

Required parameters:
- species (String)
    Species name/alias
- hgvs_notation (String)
    HGVS notation. May be genomic (g), coding (c) or protein (p), with reference to chromosome name, gene name, transcript ID or protein ID.

Optional parameters:
- hgvs (Boolean)
    Include HGVS nomenclature based on Ensembl stable identifiers
- ccds (Boolean)
    Include CCDS transcript identifiers
- numbers (Boolean)
    Include affected exon and intron positions within the transcript
- domains (Boolean)
    Include names of overlapping protein domains
- canonical (Boolean)
    Include a flag indicating the canonical transcript for a gene
- protein (Boolean)
    Include Ensembl protein identifiers
- xref_refseq (Boolean)
    Include aligned RefSeq mRNA identifiers for transcript. NB: theRefSeq and Ensembl transcripts aligned in this way MAY NOT, AND FREQUENTLY WILL NOT, match exactly in sequence, exon structure and protein product
"""
        return self.__build_rest_answer(variation.VEPResult, ['json', 'xml'], ['hgvs', 'ccds', 'numbers', 'domains', 'canonical', 'protein', 'xref_refseq'], None, 'vep/{0}/hgvs/{1}'.format(urllib.parse.quote(str(species)), urllib.parse.quote(str(hgvs_notation))), kwargs)


text:
import { Factory, faker } from 'ember-cli-mirage';

export default Factory.extend({
    id: i => i,

    // crate: '...',

    num: () => faker.system.semver(),

    created_at: () => faker.date.past(),
    updated_at() {
        return faker.date.between(this.created_at, new Date());
    },

    yanked: false,
    license: () => faker.hacker.abbreviation(),

    dl_path() {
        return `/api/v1/crates/${this.crate}/${this.num}/download`;
    },

    downloads: () => faker.random.number({ max: 10000 }),
    features: () => {},
    _authors: () => [],

    afterCreate(version, server) {
        let crate = server.schema.crates.find(version.crate);
        crate.update({ versions: crate.versions.concat(parseInt(version.id, 10)) });
    }
});

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flex.forks.batik.dom.util;

/**
 * JRE specific helper functions for {@link DOMUtilities}.
 *
 * @author Cameron McCormack
 * @version $Id$
 */
public abstract class DOMUtilitiesSupport {

    /**
     * Gets a DOM 3 modifiers string from the given lock and
     * shift bitmasks.
     */
    protected static String getModifiersList(int lockState, int modifiers) {
        if ((modifiers & 0x20) != 0) {
            modifiers = 0x10 | (modifiers & 0x0f);
        } else {
            modifiers = modifiers & 0x0f;
        }
        String s = DOMUtilities.LOCK_STRINGS[lockState & 0x0f];
        if (s.length() != 0) {
            return s + ' ' + DOMUtilities.MODIFIER_STRINGS[modifiers];
        }
        return DOMUtilities.MODIFIER_STRINGS[modifiers];
    }
}


text:
#include "wsman_config.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>

#include "u/libu.h"
#include "wsman-client-api.h"
#include "wsman-client-transport.h"

int facility = LOG_DAEMON;
int errors = 0;

typedef struct {
	const char *server;
	int port;
	const char *path;
	const char *scheme;
	const char *username;
	const char *password;
} ServerData;

typedef struct {
	/* Explanation of what you should see */
	const char *explanation;

	/* Namespace containing the class */
	const char *namespace;

	/* Resource UR to test against */
	const char *resource_uri;

	/* Selectors in the form of a URI query   key=value&key2=value2 */
	char *selectors;

	const char* xpath_expression;
	char* expected_value;

	/* What the final status code should be. */
	unsigned int final_status;

	unsigned int auth_data;

} TestData;

TestData test = {
	"Test SelectorSet filter.",
	NULL,
	"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ComputerSystem",
	"Name=vamt-build.sh.intel.com&CreationClassName=Linux_ComputerSystem",
	"/s:Envelope/s:Body/s:Fault/s:Code/s:Subcode/s:Value",
	NULL,
	500,
	0
};

ServerData sd[] = {
	{"localhost", 5985, "/wsman", "http", "wsman", "secret"}
};

static void wsman_output(WsXmlDocH doc)
{
	ws_xml_dump_node_tree(stdout, ws_xml_get_doc_root(doc));
	return;
}

int main(int argc, char** argv)
{
	WsManClient *cl;
	WsXmlDocH selector_resp = NULL, doc = NULL;
	client_opt_t *options;
	char *enumContext = NULL;

	cl = wsmc_create(sd[0].server, sd[0].port, sd[0].path, sd[0].scheme, sd[0].username, sd[0].password);
	wsmc_transport_init(cl, NULL);

	options = wsmc_options_init();
	if(test.namespace)
		options->cim_ns = u_strdup(test.namespace);
	hash_t *selectors = u_parse_query(test.selectors);
	hash_t *selectors_new = hash_create2(HASHCOUNT_T_MAX, 0, 0);
	hnode_t        *hn;
	hscan_t         hs;
	key_value_t     *entry;
	hash_scan_begin(&hs, selectors);
	while ((hn = hash_scan_next(&hs))) {
          entry = key_value_create(NULL, (char *)hnode_get(hn), NULL, NULL);
		hash_alloc_insert(selectors_new, hnode_getkey(hn), entry);
	}
	filter_t *filter = filter_create_selector(selectors_new);
	wsmc_set_action_option(options, FLAG_DUMP_REQUEST);
	selector_resp = wsmc_action_enumerate(cl, (char *)test.resource_uri, options, filter);

	if(!selector_resp) {
		printf("\t\t\033[22;31mUNRESOLVED\033[m\n");
		exit(0);
	}
	wsman_output(selector_resp);

	/* Pull for the response */
	enumContext = wsmc_get_enum_context(selector_resp);
	ws_xml_destroy_doc(selector_resp);

	while(enumContext != NULL) {
		doc = wsmc_action_pull(cl, (char *)test.resource_uri, options, NULL, enumContext);
		if (!doc) {
			printf("\t\t\033[22;31mUNRESOLVED\033[m\n");
			wsmc_options_destroy(options);
			wsmc_free_enum_context(enumContext);
			wsmc_release(cl);
			return -1;
		}
		wsman_output(doc);
		wsmc_free_enum_context(enumContext);
		enumContext = wsmc_get_enum_context(doc);
	}
	if (doc)
		ws_xml_destroy_doc(doc);
	wsmc_options_destroy(options);
	wsmc_release(cl);
	return 0;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Movies by the Masses</title>

    <link href="css/reset.css" rel="stylesheet">

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/freelancer.css" rel="stylesheet">

    <link href="css/jquery-ui.css" rel="stylesheet">

    <link href="css/style.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Movies by the Masses

                        Search Movies

                        Popular Movies

                        About Us

                        Tired of listening to the critics? Find out what real people think of the movies currently showing in theaters! Just enter a movie title in the search bar below, and we'll comb Twitter for all the latest discussion to create a realistic rating.

Search for a Movie

                      <input type="text" class="form-control" id="movieSearch" placeholder="Search for a movie...">

                        <button class="btn btn-default" id="searchRequest" type="button">Go!</button>

Plot

Starring

MPAA Rating

IMDB Score

Twitter Mood Score

Loading...

                            Tweet #MoviesForMasses

Most Popular Movie Searches

About Us

Kristin Faner

Kristin resides in Austin, Texas. She enjoys wandering around on walks, playing video games, and trying new restaurants with friends.

Rebecca Leach

Rebecca lives in Austin, Texas, and she likes cats, ice cream, and the color purple.

Eric Steinberg

Eric is from El Paso, Texas.  His favorite things are hockey, homebrewing, and arduino.

                        Copyright © 2016 by Kristin Faner, Rebecca Leach, and Eric Steinberg


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.synapse.models;

import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;

/** Defines values for IntegrationRuntimeAutoUpdate. */
public final class IntegrationRuntimeAutoUpdate extends ExpandableStringEnum<IntegrationRuntimeAutoUpdate> {
    /** Static value On for IntegrationRuntimeAutoUpdate. */
    public static final IntegrationRuntimeAutoUpdate ON = fromString("On");

    /** Static value Off for IntegrationRuntimeAutoUpdate. */
    public static final IntegrationRuntimeAutoUpdate OFF = fromString("Off");

    /**
     * Creates or finds a IntegrationRuntimeAutoUpdate from its string representation.
     *
     * @param name a name to look for.
     * @return the corresponding IntegrationRuntimeAutoUpdate.
     */
    @JsonCreator
    public static IntegrationRuntimeAutoUpdate fromString(String name) {
        return fromString(name, IntegrationRuntimeAutoUpdate.class);
    }

    /** @return known IntegrationRuntimeAutoUpdate values. */
    public static Collection<IntegrationRuntimeAutoUpdate> values() {
        return values(IntegrationRuntimeAutoUpdate.class);
    }
}


text:
<?php

namespace Horus\SiteBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * Class TransportType
 * @package Horus\SiteBundle\Form
 */
class TransportType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', 'text', array('attr' => array('placeholder' => "Nom du transporteur")))
            ->add('delay', 'text', array('required' => false, 'attr' => array('placeholder' => "Délai")))
            ->add('url', 'url', array('required' => false, 'attr' => array('placeholder' => "http://www.google.fr")))
            ->add('from', 'text', array('attr' => array('placeholder' => "De")))
            ->add('to', 'text', array('attr' => array('placeholder' => "A")))
            ->add('file', null, array('required' => false))
            ->add('service', 'textarea', array('required' => false, 'attr' => array('class' => 'form-control', 'cols' => 50, 'rows' => 5, 'placeholder' => 'Ex: Garantie, Installation etc... ')))
            ->add('isVisible')
            ->add('tva', 'choice', array(
                'attr' => array('class' => 'rad'),
                'choices' => array("0" => 'Aucune taxe', "19.6" => '19.6%', "20" => '20%', "7" => '7%', "10" => '10%', "5.5" => '5.5%', "2.1" => '2.1%'),
                'required' => true,
                'preferred_choices' => array('19.6')
            ))
            ->add('nature', 'choice', array(
                'attr' => array('class' => 'rad'),
                'choices' => array(1 => 'Sur le poid', 2 => 'Sur la quantité', 3 => 'Sur le prix'),
                'required' => true
            ))
            ->add('etat', 'choice', array(
                'label' => 'Est-il actif?',
                'choices' => array(0 => 'Inactif', 1 => 'Actif'),
                'required' => true,
                'expanded' => true
            ))
            ->add('manutention', 'choice', array(
                'label' => 'Frais de manutention?',
                'choices' => array(0 => 'Non', 1 => 'Oui'),
                'required' => true,
                'expanded' => true
            ))
            ->add('extras', 'textarea', array('required' => false,'attr' => array('rows' => 5, 'cols' => 35, 'placeholder' => "Votre commentaire")))
            ->add('longueur', 'text', array('required' => false, 'attr' => array('placeholder' => "Ex: 14"), 'label' => "Longueur maximum "))
            ->add('largeur', 'text', array('required' => false, 'attr' => array('placeholder' => "Ex: 10"), 'label' => "Largeur maximum "))
            ->add('hauteur', 'text', array('required' => false, 'attr' => array('placeholder' => "Ex: 16"), 'label' => "Hauteur maximum "))
            ->add('profondeur', 'text', array('required' => false, 'attr' => array('placeholder' => "Ex: 18"), 'label' => "Profondeur maximum "))
            ->add('departement', null, array(
                'empty_value' => 'Tous les départements',
            ))
            ->add('video', 'text', array('required' => false, 'attr' => array('placeholder' => "http://www.youtube.com/watch?v=Ry0aHEAH_ug")))
            ->add('delay', 'text', array('required' => false, 'attr' => array('placeholder' => "Délai en jours")))
            ->add('content', 'textarea', array('required' => false, 'attr' => array("class" => "ckeditor", 'placeholder' => 'Description complète')));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return '';
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {

        $resolver->setDefaults(array(
            'data_class' => 'Horus\SiteBundle\Entity\Transports',
            'csrf_protection' => false
        ));
    }
}


text:
<?php

namespace Cake\Database;

/**
 * Implements default and single-use mappings for columns to their associated types
 */
class TypeMap
{

    /**
     * Associative array with the default fields and the related types this query might contain.
     *
     * Used to avoid repetition when calling multiple functions inside this class that
     * may require a custom type for a specific field.
     *
     * @var array
     */
    protected $_defaults;

    /**
     * Associative array with the fields and the related types that override defaults this query might contain
     *
     * Used to avoid repetition when calling multiple functions inside this class that
     * may require a custom type for a specific field.
     *
     * @var array
     */
    protected $_types = [];

    /**
     * Creates an instance with the given defaults
     *
     * @param array $defaults The defaults to use.
     */
    public function __construct(array $defaults = [])
    {
        $this->setDefaults($defaults);
    }

    /**
     * Configures a map of fields and associated type.
     *
     * These values will be used as the default mapping of types for every function
     * in this instance that supports a `$types` param.
     *
     * This method is useful when you want to avoid repeating type definitions
     * as setting types overwrites the last set of types.
     *
     * ### Example
     *
     * ```
     * $query->setDefaults(['created' => 'datetime', 'is_visible' => 'boolean']);
     * ```
     *
     * This method will replace all the existing default mappings with the ones provided.
     * To add into the mappings use `addDefaults()`.
     *
     * @param array $defaults Associative array where keys are field names and values
     * are the correspondent type.
     * @return $this
     */
    public function setDefaults(array $defaults)
    {
        $this->_defaults = $defaults;

        return $this;
    }

    /**
     * Returns the currently configured types.
     *
     * @return array
     */
    public function getDefaults()
    {
        return $this->_defaults;
    }

    /**
     * Configures a map of default fields and their associated types to be
     * used as the default list of types for every function in this class
     * with a $types param. Useful to avoid repetition when calling the same
     * functions using the same fields and types.
     *
     * If called with no arguments it will return the currently configured types.
     *
     * ### Example
     *
     * ```
     * $query->defaults(['created' => 'datetime', 'is_visible' => 'boolean']);
     * ```
     *
     * This method will replace all the existing default mappings with the ones provided.
     * To add into the mappings use addDefaults()
     *
     * @deprecated 3.4.0 Use setDefaults()/getDefaults() instead.
     * @param array|null $defaults associative array where keys are field names and values
     * are the correspondent type.
     * @return $this|array
     */
    public function defaults(array $defaults = null)
    {
        deprecationWarning(
            'TypeMap::defaults() is deprecated. ' .
            'Use TypeMap::setDefaults()/getDefaults() instead.'
        );
        if ($defaults !== null) {
            return $this->setDefaults($defaults);
        }

        return $this->getDefaults();
    }

    /**
     * Add additional default types into the type map.
     *
     * If a key already exists it will not be overwritten.
     *
     * @param array $types The additional types to add.
     * @return void
     */
    public function addDefaults(array $types)
    {
        $this->_defaults += $types;
    }

    /**
     * Sets a map of fields and their associated types for single-use.
     *
     * ### Example
     *
     * ```
     * $query->setTypes(['created' => 'time']);
     * ```
     *
     * This method will replace all the existing type maps with the ones provided.
     *
     * @param array $types Associative array where keys are field names and values
     * are the correspondent type.
     * @return $this
     */
    public function setTypes(array $types)
    {
        $this->_types = $types;

        return $this;
    }

    /**
     * Gets a map of fields and their associated types for single-use.
     *
     * @return array
     */
    public function getTypes()
    {
        return $this->_types;
    }

    /**
     * Sets a map of fields and their associated types for single-use.
     *
     * If called with no arguments it will return the currently configured types.
     *
     * ### Example
     *
     * ```
     * $query->types(['created' => 'time']);
     * ```
     *
     * This method will replace all the existing type maps with the ones provided.
     *
     * @deprecated 3.4.0 Use setTypes()/getTypes() instead.
     * @param array|null $types associative array where keys are field names and values
     * are the correspondent type.
     * @return $this|array
     */
    public function types(array $types = null)
    {
        deprecationWarning(
            'TypeMap::types() is deprecated. ' .
            'Use TypeMap::setTypes()/getTypes() instead.'
        );
        if ($types !== null) {
            return $this->setTypes($types);
        }

        return $this->getTypes();
    }

    /**
     * Returns the type of the given column. If there is no single use type is configured,
     * the column type will be looked for inside the default mapping. If neither exist,
     * null will be returned.
     *
     * @param string $column The type for a given column
     * @return null|string
     */
    public function type($column)
    {
        if (isset($this->_types[$column])) {
            return $this->_types[$column];
        }
        if (isset($this->_defaults[$column])) {
            return $this->_defaults[$column];
        }

        return null;
    }

    /**
     * Returns an array of all types mapped types
     *
     * @return array
     */
    public function toArray()
    {
        return $this->_types + $this->_defaults;
    }
}


text:
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <limits.h>

#include <misc/offset.h>
#include <misc/debug.h>
#include <misc/parse_number.h>
#include <structure/LinkedList0.h>
#include <structure/IndexedList.h>
#include <structure/BCountAVL.h>
#include <ncd/NCDModule.h>

#include <generated/blog_channel_ncd_value.h>

#define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)

struct value;

struct instance {
    NCDModuleInst *i;
    struct value *v;
    LinkedList0Node refs_list_node;
};

struct value {
    LinkedList0 refs_list;

    struct value *parent;
    union {
        struct {
            IndexedListNode list_contents_il_node;
        } list_parent;
        struct {
            NCDValue key;
            BCountAVLNode map_contents_tree_node;
        } map_parent;
    };

    int type;
    union {
        struct {
            char *string;
        } string;
        struct {
            IndexedList list_contents_il;
        } list;
        struct {
            BCountAVL map_contents_tree;
        } map;
    };
};

static int ncdvalue_comparator (void *unused, void *vv1, void *vv2);
static const char * get_type_str (int type);
static void value_cleanup (struct value *v);
static void value_delete (struct value *v);
static struct value * value_init_string (NCDModuleInst *i, const char *str);
static struct value * value_init_list (NCDModuleInst *i);
static size_t value_list_len (struct value *v);
static struct value * value_list_at (struct value *v, size_t index);
static int value_list_insert (NCDModuleInst *i, struct value *list, struct value *v, size_t index);
static void value_list_remove (struct value *list, struct value *v);
static struct value * value_init_map (NCDModuleInst *i);
static size_t value_map_len (struct value *map);
static struct value * value_map_at (struct value *map, size_t index);
static struct value * value_map_find (struct value *map, NCDValue *key);
static int value_map_insert (struct value *map, struct value *v, NCDValue key, NCDModuleInst *i);
static void value_map_remove (struct value *map, struct value *v);
static struct value * value_init_fromvalue (NCDModuleInst *i, NCDValue *value);
static int value_to_value (NCDModuleInst *i, struct value *v, NCDValue *out_value);
static struct value * value_get (NCDModuleInst *i, struct value *v, NCDValue *what);
static struct value * value_get_path (NCDModuleInst *i, struct value *v, NCDValue *path);

static int ncdvalue_comparator (void *unused, void *vv1, void *vv2)
{
    NCDValue *v1 = vv1;
    NCDValue *v2 = vv2;

    return NCDValue_Compare(v1, v2);
}

static const char * get_type_str (int type)
{
    switch (type) {
        case NCDVALUE_STRING: return "string";
        case NCDVALUE_LIST: return "list";
        case NCDVALUE_MAP: return "map";
    }
    ASSERT(0)
    return NULL;
}

static void value_cleanup (struct value *v)
{
    if (v->parent || !LinkedList0_IsEmpty(&v->refs_list)) {
        return;
    }

    switch (v->type) {
        case NCDVALUE_STRING: {
            free(v->string.string);
        } break;

        case NCDVALUE_LIST: {
            while (value_list_len(v) > 0) {
                struct value *ev = value_list_at(v, 0);
                value_list_remove(v, ev);
                value_cleanup(ev);
            }
        } break;

        case NCDVALUE_MAP: {
            while (value_map_len(v) > 0) {
                struct value *ev = value_map_at(v, 0);
                value_map_remove(v, ev);
                value_cleanup(ev);
            }
        } break;

        default: ASSERT(0);
    }

    free(v);
}

static void value_delete (struct value *v)
{
    if (v->parent) {
        switch (v->parent->type) {
            case NCDVALUE_LIST: {
                value_list_remove(v->parent, v);
            } break;
            case NCDVALUE_MAP: {
                value_map_remove(v->parent, v);
            } break;
            default: ASSERT(0);
        }
    }

    LinkedList0Node *ln;
    while (ln = LinkedList0_GetFirst(&v->refs_list)) {
        struct instance *inst = UPPER_OBJECT(ln, struct instance, refs_list_node);
        ASSERT(inst->v == v)
        LinkedList0_Remove(&v->refs_list, &inst->refs_list_node);
        inst->v = NULL;
    }

    switch (v->type) {
        case NCDVALUE_STRING: {
            free(v->string.string);
        } break;

        case NCDVALUE_LIST: {
            while (value_list_len(v) > 0) {
                struct value *ev = value_list_at(v, 0);
                value_delete(ev);
            }
        } break;

        case NCDVALUE_MAP: {
            while (value_map_len(v) > 0) {
                struct value *ev = value_map_at(v, 0);
                value_delete(ev);
            }
        } break;

        default: ASSERT(0);
    }

    free(v);
}

static struct value * value_init_string (NCDModuleInst *i, const char *str)
{
    struct value *v = malloc(sizeof(*v));
    if (!v) {
        ModuleLog(i, BLOG_ERROR, "malloc failed");
        goto fail0;
    }

    LinkedList0_Init(&v->refs_list);
    v->parent = NULL;
    v->type = NCDVALUE_STRING;

    if (!(v->string.string = strdup(str))) {
        ModuleLog(i, BLOG_ERROR, "strdup failed");
        goto fail1;
    }

    return v;

fail1:
    free(v);
fail0:
    return NULL;
}

static struct value * value_init_list (NCDModuleInst *i)
{
    struct value *v = malloc(sizeof(*v));
    if (!v) {
        ModuleLog(i, BLOG_ERROR, "malloc failed");
        return NULL;
    }

    LinkedList0_Init(&v->refs_list);
    v->parent = NULL;
    v->type = NCDVALUE_LIST;

    IndexedList_Init(&v->list.list_contents_il);

    return v;
}

static size_t value_list_len (struct value *v)
{
    ASSERT(v->type == NCDVALUE_LIST)

    return IndexedList_Count(&v->list.list_contents_il);
}

static struct value * value_list_at (struct value *v, size_t index)
{
    ASSERT(v->type == NCDVALUE_LIST)
    ASSERT(index < value_list_len(v))

    IndexedListNode *iln = IndexedList_GetAt(&v->list.list_contents_il, index);
    ASSERT(iln)

    struct value *e = UPPER_OBJECT(iln, struct value, list_parent.list_contents_il_node);
    ASSERT(e->parent == v)

    return e;
}

static int value_list_insert (NCDModuleInst *i, struct value *list, struct value *v, size_t index)
{
    ASSERT(list->type == NCDVALUE_LIST)
    ASSERT(!v->parent)
    ASSERT(index <= value_list_len(list))

    if (value_list_len(list) == SIZE_MAX) {
        ModuleLog(i, BLOG_ERROR, "list has too many elements");
        return 0;
    }

    IndexedList_InsertAt(&list->list.list_contents_il, &v->list_parent.list_contents_il_node, index);
    v->parent = list;

    return 1;
}

static void value_list_remove (struct value *list, struct value *v)
{
    ASSERT(list->type == NCDVALUE_LIST)
    ASSERT(v->parent == list)

    IndexedList_Remove(&list->list.list_contents_il, &v->list_parent.list_contents_il_node);
    v->parent = NULL;
}

static struct value * value_init_map (NCDModuleInst *i)
{
    struct value *v = malloc(sizeof(*v));
    if (!v) {
        ModuleLog(i, BLOG_ERROR, "malloc failed");
        return NULL;
    }

    LinkedList0_Init(&v->refs_list);
    v->parent = NULL;
    v->type = NCDVALUE_MAP;

    BCountAVL_Init(&v->map.map_contents_tree, OFFSET_DIFF(struct value, map_parent.key, map_parent.map_contents_tree_node), ncdvalue_comparator, NULL);

    return v;
}

static size_t value_map_len (struct value *map)
{
    ASSERT(map->type == NCDVALUE_MAP)

    return BCountAVL_Count(&map->map.map_contents_tree);
}

static struct value * value_map_at (struct value *map, size_t index)
{
    ASSERT(map->type == NCDVALUE_MAP)
    ASSERT(index < value_map_len(map))

    BCountAVLNode *tn = BCountAVL_GetAt(&map->map.map_contents_tree, index);
    ASSERT(tn)

    struct value *e = UPPER_OBJECT(tn, struct value, map_parent.map_contents_tree_node);
    ASSERT(e->parent == map)

    return e;
}

static struct value * value_map_find (struct value *map, NCDValue *key)
{
    ASSERT(map->type == NCDVALUE_MAP)
    ASSERT(key)

    BCountAVLNode *tn = BCountAVL_LookupExact(&map->map.map_contents_tree, key);
    if (!tn) {
        return NULL;
    }

    struct value *e = UPPER_OBJECT(tn, struct value, map_parent.map_contents_tree_node);
    ASSERT(e->parent == map)

    return e;
}

static int value_map_insert (struct value *map, struct value *v, NCDValue key, NCDModuleInst *i)
{
    ASSERT(map->type == NCDVALUE_MAP)
    ASSERT(!v->parent)
    ASSERT(!value_map_find(map, &key))

    if (value_map_len(map) == SIZE_MAX) {
        ModuleLog(i, BLOG_ERROR, "map has too many elements");
        return 0;
    }

    v->map_parent.key = key;
    int res = BCountAVL_Insert(&map->map.map_contents_tree, &v->map_parent.map_contents_tree_node, NULL);
    ASSERT(res)
    v->parent = map;

    return 1;
}

static void value_map_remove (struct value *map, struct value *v)
{
    ASSERT(map->type == NCDVALUE_MAP)
    ASSERT(v->parent == map)

    BCountAVL_Remove(&map->map.map_contents_tree, &v->map_parent.map_contents_tree_node);
    NCDValue_Free(&v->map_parent.key);
    v->parent = NULL;
}

static struct value * value_init_fromvalue (NCDModuleInst *i, NCDValue *value)
{
    struct value *v;

    switch (NCDValue_Type(value)) {
        case NCDVALUE_STRING: {
            if (!(v = value_init_string(i, NCDValue_StringValue(value)))) {
                goto fail0;
            }
        } break;

        case NCDVALUE_LIST: {
            if (!(v = value_init_list(i))) {
                goto fail0;
            }

            for (NCDValue *eval = NCDValue_ListFirst(value); eval; eval = NCDValue_ListNext(value, eval)) {
                struct value *ev = value_init_fromvalue(i, eval);
                if (!ev) {
                    goto fail1;
                }

                if (!value_list_insert(i, v, ev, value_list_len(v))) {
                    value_cleanup(ev);
                    goto fail1;
                }
            }
        } break;

        case NCDVALUE_MAP: {
            if (!(v = value_init_map(i))) {
                goto fail0;
            }

            for (NCDValue *ekey = NCDValue_MapFirstKey(value); ekey; ekey = NCDValue_MapNextKey(value, ekey)) {
                NCDValue *eval = NCDValue_MapKeyValue(value, ekey);

                NCDValue key;
                if (!NCDValue_InitCopy(&key, ekey)) {
                    BLog(BLOG_ERROR, "NCDValue_InitCopy failed");
                    goto fail1;
                }

                struct value *ev = value_init_fromvalue(i, eval);
                if (!ev) {
                    NCDValue_Free(&key);
                    goto fail1;
                }

                if (!value_map_insert(v, ev, key, i)) {
                    NCDValue_Free(&key);
                    value_cleanup(ev);
                    goto fail1;
                }
            }
        } break;

        default: ASSERT(0);
    }

    return v;

fail1:
    value_cleanup(v);
fail0:
    return NULL;
}

static int value_to_value (NCDModuleInst *i, struct value *v, NCDValue *out_value)
{
    switch (v->type) {
        case NCDVALUE_STRING: {
            if (!(NCDValue_InitString(out_value, v->string.string))) {
                ModuleLog(i, BLOG_ERROR, "NCDValue_InitString failed");
                goto fail0;
            }
        } break;

        case NCDVALUE_LIST: {
            NCDValue_InitList(out_value);

            for (size_t index = 0; index < value_list_len(v); index++) {
                NCDValue eval;
                if (!value_to_value(i, value_list_at(v, index), &eval)) {
                    goto fail1;
                }

                if (!NCDValue_ListAppend(out_value, eval)) {
                    ModuleLog(i, BLOG_ERROR, "NCDValue_ListAppend failed");
                    NCDValue_Free(&eval);
                    goto fail1;
                }
            }
        } break;

        case NCDVALUE_MAP: {
            NCDValue_InitMap(out_value);

            for (size_t index = 0; index < value_map_len(v); index++) {
                struct value *ev = value_map_at(v, index);

                NCDValue key;
                NCDValue val;

                if (!NCDValue_InitCopy(&key, &ev->map_parent.key)) {
                    ModuleLog(i, BLOG_ERROR, "NCDValue_InitCopy failed");
                    goto fail1;
                }

                if (!value_to_value(i, ev, &val)) {
                    NCDValue_Free(&key);
                    goto fail1;
                }

                if (!NCDValue_MapInsert(out_value, key, val)) {
                    ModuleLog(i, BLOG_ERROR, "NCDValue_MapInsert failed");
                    NCDValue_Free(&key);
                    NCDValue_Free(&val);
                    goto fail1;
                }
            }
        } break;

        default: ASSERT(0);
    }

    return 1;

fail1:
    NCDValue_Free(out_value);
fail0:
    return 0;
}

static struct value * value_get (NCDModuleInst *i, struct value *v, NCDValue *what)
{
    switch (v->type) {
        case NCDVALUE_STRING: {
            ModuleLog(i, BLOG_ERROR, "cannot resolve into a string");
            goto fail;
        } break;

        case NCDVALUE_LIST: {
            if (NCDValue_Type(what) != NCDVALUE_STRING) {
                ModuleLog(i, BLOG_ERROR, "index is not a string (resolving into list)");
                goto fail;
            }

            uintmax_t index;
            if (!parse_unsigned_integer(NCDValue_StringValue(what), &index)) {
                ModuleLog(i, BLOG_ERROR, "index is not a valid number (resolving into list)");
                goto fail;
            }

            if (index >= value_list_len(v)) {
                ModuleLog(i, BLOG_ERROR, "index is out of bounds (resolving into list)");
                goto fail;
            }

            v = value_list_at(v, index);
        } break;

        case NCDVALUE_MAP: {
            v = value_map_find(v, what);
            if (!v) {
                ModuleLog(i, BLOG_ERROR, "key does not exist (resolving into map)");
                goto fail;
            }
        } break;

        default: ASSERT(0);
    }

    return v;

fail:
    return NULL;
}

static struct value * value_get_path (NCDModuleInst *i, struct value *v, NCDValue *path)
{
    ASSERT(NCDValue_Type(path) == NCDVALUE_LIST)

    for (NCDValue *ev = NCDValue_ListFirst(path); ev; ev = NCDValue_ListNext(path, ev)) {
        if (!(v = value_get(i, v, ev))) {
            goto fail;
        }
    }

    return v;

fail:
    return NULL;
}

static void func_new_common (NCDModuleInst *i, struct value *v)
{
    ASSERT(v)

    // allocate instance
    struct instance *o = malloc(sizeof(*o));
    if (!o) {
        ModuleLog(i, BLOG_ERROR, "failed to allocate instance");
        goto fail0;
    }
    o->i = i;
    NCDModuleInst_Backend_SetUser(i, o);

    // set value
    o->v = v;

    // add reference
    LinkedList0_Prepend(&o->v->refs_list, &o->refs_list_node);

    NCDModuleInst_Backend_Up(i);
    return;

fail1:
    free(o);
fail0:
    value_cleanup(v);
    NCDModuleInst_Backend_SetError(i);
    NCDModuleInst_Backend_Dead(i);
}

static void func_die (void *vo)
{
    struct instance *o = vo;
    NCDModuleInst *i = o->i;

    if (o->v) {
        // remove reference
        LinkedList0_Remove(&o->v->refs_list, &o->refs_list_node);

        // cleanup after removing reference
        value_cleanup(o->v);
    }

    // free instance
    free(o);

    NCDModuleInst_Backend_Dead(i);
}

static int func_getvar (void *vo, const char *name, NCDValue *out_value)
{
    struct instance *o = vo;

    if (strcmp(name, "type") && strcmp(name, "length") && strcmp(name, "keys") && strcmp(name, "")) {
        return 0;
    }

    if (!o->v) {
        ModuleLog(o->i, BLOG_ERROR, "value was deleted");
        return 0;
    }

    if (!strcmp(name, "type")) {
        if (!NCDValue_InitString(out_value, get_type_str(o->v->type))) {
            ModuleLog(o->i, BLOG_ERROR, "NCDValue_InitString failed");
            return 0;
        }
    }
    else if (!strcmp(name, "length")) {
        size_t len;
        switch (o->v->type) {
            case NCDVALUE_LIST:
                len = value_list_len(o->v);
                break;
            case NCDVALUE_MAP:
                len = value_map_len(o->v);
                break;
            default:
                ModuleLog(o->i, BLOG_ERROR, "value is not a list or map");
                return 0;
        }

        char str[64];
        snprintf(str, sizeof(str), "%zu", len);
        if (!NCDValue_InitString(out_value, str)) {
            ModuleLog(o->i, BLOG_ERROR, "NCDValue_InitString failed");
            return 0;
        }
    }
    else if (!strcmp(name, "keys")) {
        if (o->v->type != NCDVALUE_MAP) {
            ModuleLog(o->i, BLOG_ERROR, "value is not a map (reading keys variable)");
            return 0;
        }

        NCDValue_InitList(out_value);

        for (size_t i = 0; i < value_map_len(o->v); i++) {
            struct value *ev = value_map_at(o->v, i);

            NCDValue key;
            if (!NCDValue_InitCopy(&key, &ev->map_parent.key)) {
                ModuleLog(o->i, BLOG_ERROR, "NCDValue_InitCopy failed");
                goto map_fail1;
            }

            if (!NCDValue_ListAppend(out_value, key)) {
                ModuleLog(o->i, BLOG_ERROR, "NCDValue_ListAppend failed");
                NCDValue_Free(&key);
                goto map_fail1;
            }
        }

        return 1;

    map_fail1:
        NCDValue_Free(out_value);
        return 0;
    }
    else if (!strcmp(name, "")) {
        if (!value_to_value(o->i, o->v, out_value)) {
            return 0;
        }
    }
    else {
        ASSERT(0);
    }

    return 1;
}

static void func_new_value (NCDModuleInst *i)
{
    NCDValue *value_arg;
    if (!NCDValue_ListRead(i->args, 1, &value_arg)) {
        ModuleLog(i, BLOG_ERROR, "wrong arity");
        goto fail0;
    }

    struct value *v = value_init_fromvalue(i, value_arg);
    if (!v) {
        goto fail0;
    }

    func_new_common(i, v);
    return;

fail0:
    NCDModuleInst_Backend_SetError(i);
    NCDModuleInst_Backend_Dead(i);
}

static void func_new_get (NCDModuleInst *i)
{
    NCDValue *what_arg;
    if (!NCDValue_ListRead(i->args, 1, &what_arg)) {
        ModuleLog(i, BLOG_ERROR, "wrong arity");
        goto fail0;
    }

    struct instance *mo = ((NCDModuleInst *)i->method_user)->inst_user;

    if (!mo->v) {
        ModuleLog(i, BLOG_ERROR, "value was deleted");
        goto fail0;
    }

    struct value *v = value_get(i, mo->v, what_arg);
    if (!v) {
        goto fail0;
    }

    func_new_common(i, v);
    return;

fail0:
    NCDModuleInst_Backend_SetError(i);
    NCDModuleInst_Backend_Dead(i);
}

static void func_new_getpath (NCDModuleInst *i)
{
    NCDValue *path_arg;
    if (!NCDValue_ListRead(i->args, 1, &path_arg)) {
        ModuleLog(i, BLOG_ERROR, "wrong arity");
        goto fail0;
    }
    if (NCDValue_Type(path_arg) != NCDVALUE_LIST) {
        ModuleLog(i, BLOG_ERROR, "wrong type");
        goto fail0;
    }

    struct instance *mo = ((NCDModuleInst *)i->method_user)->inst_user;

    if (!mo->v) {
        ModuleLog(i, BLOG_ERROR, "value was deleted");
        goto fail0;
    }

    struct value *v = value_get_path(i, mo->v, path_arg);
    if (!v) {
        goto fail0;
    }

    func_new_common(i, v);
    return;

fail0:
    NCDModuleInst_Backend_SetError(i);
    NCDModuleInst_Backend_Dead(i);
}

static void delete_func_new (NCDModuleInst *i)
{
    if (!NCDValue_ListRead(i->args, 0)) {
        ModuleLog(i, BLOG_ERROR, "wrong arity");
        goto fail0;
    }

    struct instance *mo = ((NCDModuleInst *)i->method_user)->inst_user;

    if (!mo->v) {
        ModuleLog(i, BLOG_ERROR, "value was deleted");
        goto fail0;
    }

    value_delete(mo->v);

    NCDModuleInst_Backend_Up(i);
    return;

fail0:
    NCDModuleInst_Backend_SetError(i);
    NCDModuleInst_Backend_Dead(i);
}

static const struct NCDModule modules[] = {
    {
        .type = "value",
        .func_new = func_new_value,
        .func_die = func_die,
        .func_getvar = func_getvar
    }, {
        .type = "value::get",
        .base_type = "value",
        .func_new = func_new_get,
        .func_die = func_die,
        .func_getvar = func_getvar
    }, {
        .type = "value::getpath",
        .base_type = "value",
        .func_new = func_new_getpath,
        .func_die = func_die,
        .func_getvar = func_getvar
    }, {
        .type = "value::delete",
        .func_new = delete_func_new
    }, {
        .type = NULL
    }
};

const struct NCDModuleGroup ncdmodule_value = {
    .modules = modules
};


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

import os

from pants.backend.jvm.targets.jar_library import JarLibrary
from pants.backend.jvm.targets.java_library import JavaLibrary
from pants.backend.jvm.targets.jvm_binary import JarRules, JvmBinary, Skip
from pants.backend.jvm.tasks.detect_duplicates import DuplicateDetector
from pants.base.exceptions import TaskError
from pants.java.jar.jar_dependency import JarDependency
from pants.java.jar.jar_dependency_utils import M2Coordinate, ResolvedJar
from pants.util.contextutil import open_zip
from pants.util.dirutil import safe_mkdir, safe_mkdir_for, touch
from pants_test.jvm.jvm_task_test_base import JvmTaskTestBase

class DuplicateDetectorTest(JvmTaskTestBase):

  @classmethod
  def task_type(cls):
    return DuplicateDetector

  def setUp(self):
    super(DuplicateDetectorTest, self).setUp()

    self.classes_dir = os.path.join(self.test_workdir, 'classes')
    safe_mkdir(self.classes_dir)

    def generate_class(name):
      path = os.path.join(self.classes_dir, name)
      touch(path)
      return path

    test_class_path = generate_class('com/twitter/Test.class')
    duplicate_class_path = generate_class('com/twitter/commons/Duplicate.class')
    unique_class_path = generate_class('org/apache/Unique.class')
    unicode_class_path = generate_class('cucumber/api/java/zh_cn/假如.class')

    def generate_jar(path, *class_name):
      jar_path = os.path.join(self.test_workdir, 'jars', path)
      safe_mkdir_for(jar_path)
      with open_zip(jar_path, 'w') as zipfile:
        for clazz in class_name:
          zipfile.write(clazz, os.path.relpath(clazz, self.classes_dir))
        return jar_path

    self.test_jar = generate_jar('test.jar', test_class_path, duplicate_class_path)
    self.dups_jar = generate_jar('dups.jar', duplicate_class_path, unique_class_path)
    self.no_dups_jar = generate_jar('no_dups.jar', unique_class_path)
    self.unicode_jar = generate_jar('unicode_class.jar', unicode_class_path)

    def resolved_jarlib(name, jar_path):
      resolved_jar = ResolvedJar(M2Coordinate(org='org.example', name=name, rev='0.0.1'),
                                 cache_path=jar_path,
                                 pants_path=jar_path)
      jar_dep = JarDependency(org='org.example', name=name, rev='0.0.1')
      jar_library = self.make_target(spec='3rdparty:{}'.format(name),
                                     target_type=JarLibrary,
                                     jars=[jar_dep])
      return jar_library, resolved_jar

    self.test_jarlib, self.test_resolved_jar = resolved_jarlib('test', self.test_jar)
    self.dups_jarlib, self.dups_resolved_jar = resolved_jarlib('dups', self.dups_jar)
    self.no_dups_jarlib, self.no_dups_resolved_jar = resolved_jarlib('no_dups', self.no_dups_jar)
    self.unicode_jarlib, self.unicode_resolved_jar = resolved_jarlib('unicode', self.unicode_jar)

  def _setup_external_duplicate(self):
    jvm_binary = self.make_target(spec='src/java/com/twitter:thing',
                                  target_type=JvmBinary,
                                  dependencies=[self.test_jarlib, self.dups_jarlib])
    context = self.context(target_roots=[jvm_binary])
    task = self.create_task(context)

    classpath = self.get_runtime_classpath(context)
    classpath.add_jars_for_targets([self.test_jarlib], 'default', [self.test_resolved_jar])
    classpath.add_jars_for_targets([self.dups_jarlib], 'default', [self.dups_resolved_jar])
    return task, jvm_binary

  def test_duplicate_found_external(self):
    self.set_options(fail_fast=False)
    task, jvm_binary = self._setup_external_duplicate()
    conflicts_by_binary = task.execute()
    expected = {
      jvm_binary: {
        ('org.example-dups-0.0.1.jar', 'org.example-test-0.0.1.jar'):
          {'com/twitter/commons/Duplicate.class'}
      }
    }
    self.assertEqual(expected, conflicts_by_binary)

  def test_duplicate_skip(self):
    self.set_options(fail_fast=False, skip=True)
    task, _ = self._setup_external_duplicate()
    conflicts_by_binary = task.execute()
    self.assertEqual(None, conflicts_by_binary)

  def test_duplicate_excluded_file(self):
    self.set_options(fail_fast=False, excludes=[], exclude_files=['Duplicate.class'])
    task, jvm_binary = self._setup_external_duplicate()
    conflicts_by_binary = task.execute()
    self.assertEqual({}, conflicts_by_binary)

  def _setup_internal_duplicate(self):
    java_library = self.make_target(spec='src/java/com/twitter:lib',
                                    target_type=JavaLibrary,
                                    sources=[])
    jvm_binary = self.make_target(spec='src/java/com/twitter:thing',
                                  target_type=JvmBinary,
                                  dependencies=[java_library])
    context = self.context(target_roots=[jvm_binary])
    task = self.create_task(context)

    classpath = self.get_runtime_classpath(context)
    classpath.add_for_target(java_library, [('default', self.classes_dir)])
    classpath.add_for_target(jvm_binary, [('default', self.classes_dir)])
    return task, jvm_binary

  def test_duplicate_found_internal(self):
    self.set_options(fail_fast=False)
    task, jvm_binary = self._setup_internal_duplicate()
    conflicts_by_binary = task.execute()

    expected = {
      jvm_binary: {
        ('src/java/com/twitter:lib', 'src/java/com/twitter:thing'):
          {'com/twitter/Test.class',
           'com/twitter/commons/Duplicate.class',
           'org/apache/Unique.class',
           'cucumber/api/java/zh_cn/假如.class'}
      }
    }
    self.assertEqual(expected, conflicts_by_binary)

  def test_duplicate_excluded_internal(self):
    self.set_options(fail_fast=False, excludes=[], exclude_files=['Duplicate.class', '假如.class'])
    task, jvm_binary = self._setup_internal_duplicate()
    conflicts_by_binary = task.execute()

    expected = {
      jvm_binary: {
        ('src/java/com/twitter:lib', 'src/java/com/twitter:thing'):
          {'com/twitter/Test.class',
           'org/apache/Unique.class'}
      }
    }
    self.assertEqual(expected, conflicts_by_binary)

  def test_duplicate_found_mixed(self):
    self.set_options(fail_fast=False)

    jvm_binary = self.make_target(spec='src/java/com/twitter:thing',
                                  target_type=JvmBinary,
                                  dependencies=[self.test_jarlib])
    context = self.context(target_roots=[jvm_binary])
    task = self.create_task(context)

    classpath = self.get_runtime_classpath(context)
    classpath.add_for_target(jvm_binary, [('default', self.classes_dir)])
    classpath.add_jars_for_targets([self.test_jarlib], 'default', [self.test_resolved_jar])

    conflicts_by_binary = task.execute()

    expected = {
      jvm_binary: {
        ('org.example-test-0.0.1.jar', 'src/java/com/twitter:thing'):
          {'com/twitter/Test.class', 'com/twitter/commons/Duplicate.class'}
      }
    }
    self.assertEqual(expected, conflicts_by_binary)

  def test_duplicate_not_found(self):
    self.set_options(fail_fast=True)

    jvm_binary = self.make_target(spec='src/java/com/twitter:thing',
                                  target_type=JvmBinary,
                                  dependencies=[self.no_dups_jarlib,
                                                self.unicode_jarlib])
    context = self.context(target_roots=[jvm_binary])
    task = self.create_task(context)

    classpath = self.get_runtime_classpath(context)
    classpath.add_jars_for_targets([self.no_dups_jarlib], 'default', [self.no_dups_resolved_jar])
    classpath.add_jars_for_targets([self.unicode_jarlib], 'default', [self.unicode_resolved_jar])

    conflicts_by_binary = task.execute()
    self.assertEqual({}, conflicts_by_binary)

  def test_fail_fast_error_raised(self):
    self.set_options(fail_fast=True)

    jvm_binary = self.make_target(spec='src/java/com/twitter:thing',
                                  target_type=JvmBinary,
                                  dependencies=[self.test_jarlib])
    context = self.context(target_roots=[jvm_binary])
    task = self.create_task(context)

    classpath = self.get_runtime_classpath(context)
    classpath.add_for_target(jvm_binary, [('default', self.classes_dir)])
    classpath.add_jars_for_targets([self.test_jarlib], 'default', [self.test_resolved_jar])

    with self.assertRaises(TaskError):
      task.execute()

  def test_is_excluded_default(self):
    task = self.create_task(self.context())
    self.assertFalse(task._is_excluded('foo'))
    self.assertFalse(task._is_excluded('foo/BCKEY.DSA'))
    # excluded_files: No directroy
    self.assertTrue(task._is_excluded('.DS_Store'))
    # excluded_files: Mixed case
    self.assertTrue(task._is_excluded('NOTICE.txt'))
    # excluded_files: Leading directory
    self.assertTrue(task._is_excluded('/foo/bar/dependencies'))
    # excluded_dirs:
    self.assertTrue(task._is_excluded('META-INF/services/foo'))
    # excluded_patterns:
    self.assertTrue(task._is_excluded('META-INF/BCKEY.RSA'))

  def test_is_excluded_pattern(self):
    self.set_options(exclude_patterns=[r'.*/garbage\.'])
    task = self.create_task(self.context())
    self.assertTrue(task._is_excluded('foo/garbage.txt'))

  def test_is_excluded_files(self):
    self.set_options(excludes=None, exclude_files=['bckey.dsa'])
    task = self.create_task(self.context())
    self.assertTrue(task._is_excluded('foo/BCKEY.DSA'))

    # Defaults are now overridden
    self.assertFalse(task._is_excluded('NOTICE.txt'))

  def test_is_excluded_files_again(self):
    self.set_options(exclude_dirs=['org/duplicated'])
    task = self.create_task(self.context())
    self.assertTrue(task._is_excluded('org/duplicated/FOO'))

    # Defaults are now overridden
    self.assertFalse(task._is_excluded('META-INF/services/foo'))

  def _setup_external_duplicate_with_rules(self, rules):
    jvm_binary = self.make_target(spec='src/java/com/twitter:thing',
                                  target_type=JvmBinary,
                                  dependencies=[self.test_jarlib, self.dups_jarlib],
                                  deploy_jar_rules=rules)
    context = self.context(target_roots=[jvm_binary])
    task = self.create_task(context)

    classpath = self.get_runtime_classpath(context)
    classpath.add_jars_for_targets([self.test_jarlib], 'default', [self.test_resolved_jar])
    classpath.add_jars_for_targets([self.dups_jarlib], 'default', [self.dups_resolved_jar])
    return task, jvm_binary

  def test_duplicate_rule_skip(self):
    self.set_options(fail_fast=False)
    task, _ = self._setup_external_duplicate_with_rules(
      rules=JarRules([Skip('^com/twitter/commons/Duplicate.class$')]))
    conflicts_by_binary = task.execute()
    self.assertEqual({}, conflicts_by_binary)

  def test_duplicate_rule_no_match(self):
    self.set_options(fail_fast=False)
    task, jvm_binary = self._setup_external_duplicate_with_rules(
      rules=JarRules([Skip('^com/twitter/commons/DoesNotExist.class$')]))
    conflicts_by_binary = task.execute()
    expected = {
      jvm_binary: {
        ('org.example-dups-0.0.1.jar', 'org.example-test-0.0.1.jar'):
          {'com/twitter/commons/Duplicate.class'}
      }
    }
    self.assertEqual(expected, conflicts_by_binary)


text:
function xy = uvToxy(uv,compute1960)
% xy = uvToxy(uv,[compute1960])
%
% Convert CIE u'v' chromaticity to CIE xy chromaticity.
%
% These are u',v' chromaticity coordinates in notation
% used by CIE.  See CIE Colorimetry 2004 publication, or Wyszecki
% and Stiles, 2cd, page 165.
%
% Note that there is an obsolete u,v chromaticity diagram that is similar
% but uses 6 in the numerator for u rather than the 9 that is used for u'.
% See CIE Coloimetry 2004, Appendix A, or Judd and Wyszecki, p. 296. If
% you want this (maybe to compute correlated color temperatures), you can
% pass this as 1.  It is 0 by default.
%
% See also uvYToXYZ, XYZTouvY, xyTouv
%
% 7/15/03  dhb, bx  Wrote it.
% 3/17/04  dhb      Fixed typos.  This must not have been tested previously.
% 5/06/11  dhb      Improve comment, optional 1960 computations

%% Handle optional arg
if (nargin < 2 || isempty(compute1960))
    compute1960 = 0;
end

%% Do it, using uvYToXYZ as engine
uvY = [uv ; ones(1,size(uv,2))];
XYZ = uvYToXYZ(uvY,compute1960);
xyY = XYZToxyY(XYZ);
xy = xyY(1:2,:);


text:
title: Create Visual Balance Using the text-align Property
localeTitle: Crear balance visual usando la propiedad text-align
---
## Crear balance visual usando la propiedad text-align

Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/responsive-web-design/applied-visual-design/create-visual-balance-using-the-text-align-property/index.md) .

[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
/**
 * @fileoverview Ensure that contract, library, modifier and struct names follow CamelCase notation
 * @author Raghav Dua <duaraghav8@gmail.com>
 */

"use strict";

module.exports = {

    meta: {

        docs: {
            recommended: true,
            type: "warning",
            description: "Ensure that contract, library, modifier and struct names follow CamelCase notation"
        },

        schema: []

    },

    create: function(context) {

        let camelCaseRegEx = /^([A-Z][A-Za-z0-9]+)+$/;
        let nodesToWatch = {
            "ContractStatement": "Contract",
            "LibraryStatement": "Library",
            "StructDeclaration": "Struct",
            "EventDeclaration": "Event"
        };

        function createInspector(nodeDesc) {
            return (function inspect(emitted) {
                let node = emitted.node;

                if (emitted.exit) {
                    return;
                }

                if (!camelCaseRegEx.test(node.name)) {
                    context.report({
                        node: node,
                        message: nodeDesc + " name '" + node.name + "' doesn't follow the CamelCase notation."
                    });
                }
            });
        }

        return Object.keys(nodesToWatch).reduce(function(listeners, nodeName) {

            listeners [nodeName] = createInspector(nodesToWatch [nodeName]);
            return listeners;

        }, {});

    }

};