Make sure any event day we send back for weekday repeating
    events is not a weekend.


Parse all data necessary for loading a case into scout

    This can be done either by providing a VCF file and other information
    on the command line. Or all the information can be specified in a config file.
    Please see Scout documentation for further instructions.

    Args:
        config(dict): A yaml formatted config file
        ped(iterable(str)): A ped formatted family file
        owner(str): The institute that owns a case
        vcf_snv(str): Path to a vcf file
        vcf_str(str): Path to a VCF file
        vcf_sv(str): Path to a vcf file
        vcf_cancer(str): Path to a vcf file
        peddy_ped(str): Path to a peddy ped
        multiqc(str): Path to dir with multiqc information

    Returns:
        config_data(dict): Holds all the necessary information for loading
                           Scout


Add information from peddy outfiles to the individuals


Parse the individual information

        Reformat sample information to proper individuals

        Args:
            samples(list(dict))

        Returns:
            individuals(list(dict))


Parse out minimal family information from a PED file.

    Args:
        ped_stream(iterable(str))
        family_type(str): Format of the pedigree information

    Returns:
        family_id(str), samples(list[dict])


Build a evaluation object ready to be inserted to database

    Args:
        variant_specific(str): md5 string for the specific variant
        variant_id(str): md5 string for the common variant
        user_id(str)
        user_name(str)
        institute_id(str)
        case_id(str)
        classification(str): The ACMG classification
        criteria(list(dict)): A list of dictionaries with ACMG criterias

    Returns:
        evaluation_obj(dict): Correctly formatted evaluation object


Export all mitochondrial variants for each sample of a case
       and write them to an excel file

        Args:
            adapter(MongoAdapter)
            case_id(str)
            test(bool): True if the function is called for testing purposes
            outpath(str): path to output file

        Returns:
            written_files(int): number of written or simulated files


Check if criterias for Likely Benign are fullfilled

    The following are descriptions of Likely Benign clasification from ACMG paper:

    Likely Benign
      (i) 1 Strong (BS1–BS4) and 1 supporting (BP1– BP7) OR
      (ii) ≥2 Supporting (BP1–BP7)

    Args:
        bs_terms(list(str)): Terms that indicate strong evidence for benign variant
        bp_terms(list(str)): Terms that indicate supporting evidence for benign variant

    Returns:
        bool: if classification indicates Benign level


Add extra information about genes from gene panels

        Args:
            variant_obj(dict): A variant from the database
            gene_panels(list(dict)): List of panels from database


Return all variants with sanger information

        Args:
            institute_id(str)
            case_id(str)

        Returns:
            res(pymongo.Cursor): A Cursor with all variants with sanger activity


Returns the specified variant.

           Arguments:
               document_id : A md5 key that represents the variant or "variant_id"
               gene_panels(List[GenePanel])
               case_id (str): case id (will search with "variant_id")

           Returns:
               variant_object(Variant): A odm variant object


Return all verified variants for a given institute

        Args:
            institute_id(str): institute id

        Returns:
            res(list): a list with validated variants


Check if there are any variants that are previously marked causative

            Loop through all variants that are marked 'causative' for an
            institute and check if any of the variants are present in the
            current case.

            Args:
                case_obj (dict): A Case object
                institute_obj (dict): check across the whole institute

            Returns:
                causatives(iterable(Variant))


Find the same variant in other cases marked causative.

        Args:
            case_obj(dict)
            variant_obj(dict)

        Yields:
            other_variant(dict)


Delete variants of one type for a case

            This is used when a case is reanalyzed

            Args:
                case_id(str): The case id
                variant_type(str): 'research' or 'clinical'
                category(str): 'snv', 'sv' or 'cancer'


Return overlapping variants.

        Look at the genes that a variant overlaps to.
        Then return all variants that overlap these genes.

        If variant_obj is sv it will return the overlapping snvs and oposite
        There is a problem when SVs are huge since there are to many overlapping variants.

        Args:
            variant_obj(dict)

        Returns:
            variants(iterable(dict))


Returns variants that has been evaluated

        Return all variants, snvs/indels and svs from case case_id
        which have a entry for 'acmg_classification', 'manual_rank', 'dismiss_variant'
        or if they are commented.

        Args:
            case_id(str)

        Returns:
            variants(iterable(Variant))


Produce a reduced vcf with variants from the specified coordinates
           This is used for the alignment viewer.

        Args:
            case_obj(dict): A case from the scout database
            variant_type(str): 'clinical' or 'research'. Default: 'clinical'
            category(str): 'snv' or 'sv'. Default: 'snv'
            rank_threshold(float): Only load variants above this score. Default: 5
            chrom(str): Load variants from a certain chromosome
            start(int): Specify the start position
            end(int): Specify the end position
            gene_obj(dict): A gene object from the database

        Returns:
            file_name(str): Path to the temporary file


Given a list of variants get variant objects found in a specific patient

        Args:
            variants(list): a list of variant ids
            sample_name(str): a sample display name
            category(str): 'snv', 'sv' ..

        Returns:
            result(iterable(Variant))


Determine which fields to include in csv header by checking a list of submission objects

        Args:
            submission_objs(list): a list of objects (variants or casedata) to include in a csv file
            csv_type(str) : 'variant_data' or 'case_data'

        Returns:
            custom_header(dict): A dictionary with the fields required in the csv header. Keys and values are specified in CLINVAR_HEADER and CASEDATA_HEADER


Load all the transcripts

    Transcript information is from ensembl.

    Args:
        adapter(MongoAdapter)
        transcripts_lines(iterable): iterable with ensembl transcript lines
        build(str)
        ensembl_genes(dict): Map from ensembl_id -> HgncGene

    Returns:
        transcript_objs(list): A list with all transcript objects


Add a gene panel to the database.


Delete a version of a gene panel or all versions of a gene panel


Delete all indexes in the database


Delete a user from the database


Delete all exons in the database


Delete a case and it's variants from the database


Show all individuals from all cases in the database


Parse a list of matchmaker matches objects and returns
       a readable list of matches to display in matchmaker matches view.

    Args:
        patient_id(str): id of a mme patient
        match_objs(list): list of match objs returned by MME server for the patient
                # match_objs looks like this:
                    [
                        {
                            'node' : { id : node_id , label: node_label},
                            'patients' : [
                                { 'patient': {patient1_data} },
                                { 'patient': {patient2_data} },
                                ..
                            ]
                        },
                        ..
                    ]

    Returns:
        parsed_matches(list): a list of parsed match objects


Display cases from the database


Returns the currently active user as an object.


Login a user if they have access.


Build a institute object

    Args:
        internal_id(str)
        display_name(str)
        sanger_recipients(list(str)): List with email addresses

    Returns:
        institute_obj(scout.models.Institute)


Delete a event

            Arguments:
                event_id (str): The database key for the event


Fetch events from the database.

          Args:
            institute (dict): A institute
            case (dict): A case
            variant_id (str, optional): global variant id
            level (str, optional): restrict comments to 'specific' or 'global'
            comments (bool, optional): restrict events to include only comments
            panel (str): A panel name

          Returns:
              pymongo.Cursor: Query result


Fetch all events by a specific user.


Remove an existing phenotype from a case

        Args:
            institute (dict): A Institute object
            case (dict): Case object
            user (dict): A User object
            link (dict): The url to be used in the event
            phenotype_id (str): A phenotype id

        Returns:
            updated_case(dict)


Add a comment to a variant or a case.

        This function will create an Event to log that a user have commented on
        a variant. If a variant id is given it will be a variant comment.
        A variant comment can be 'global' or specific. The global comments will
        be shown for this variation in all cases while the specific comments
        will only be shown for a specific case.

        Arguments:
            institute (dict): A Institute object
            case (dict): A Case object
            user (dict): A User object
            link (str): The url to be used in the event
            variant (dict): A variant object
            content (str): The content of the comment
            comment_level (str): Any one of 'specific' or 'global'.
                                 Default is 'specific'

        Return:
            comment(dict): The comment event that was inserted


Check if the variant is in the interval given by the coordinates

        Args:
            chromosome(str): Variant chromosome
            pos(int): Variant position
            coordinates(dict): Dictionary with the region of interest


Render search box and view for HPO phenotype terms


Load exons into the scout database


Load all variants in a region to a existing case


Returns a queryset of events that will occur again after 'now'.
        Used to help generate a list of upcoming events.


Check if gene is already added to a panel.


Create a new gene panel.

    Args:
        store(scout.adapter.MongoAdapter)
        institute_id(str)
        panel_name(str)
        display_name(str)
        csv_lines(iterable(str)): Stream with genes

    Returns:
        panel_id: the ID of the new panel document created or None


Get information about a case from archive.


Migrate case information from archive.


Update all information that was manually annotated from a old instance.


Upload research variants to cases

        If a case is specified, all variants found for that case will be
        uploaded.

        If no cases are specified then all cases that have 'research_requested'
        will have there research variants uploaded


Load genes into the database

    link_genes will collect information from all the different sources and
    merge it into a dictionary with hgnc_id as key and gene information as values.

    Args:
        adapter(scout.adapter.MongoAdapter)
        genes(dict): If genes are already parsed
        ensembl_lines(iterable(str)): Lines formated with ensembl gene information
        hgnc_lines(iterable(str)): Lines with gene information from genenames.org
        exac_lines(iterable(str)): Lines with information pLi-scores from ExAC
        mim2gene(iterable(str)): Lines with map from omim id to gene symbol
        genemap_lines(iterable(str)): Lines with information of omim entries
        hpo_lines(iterable(str)): Lines information about map from hpo terms to genes
        build(str): What build to use. Defaults to '37'

    Returns:
        gene_objects(list): A list with all gene_objects that was loaded into database


Show all hpo terms in the database


Register Flask blueprints.


Show all alias symbols and how they map to ids


Build a gene_panel object

        Args:
            panel_info(dict): A dictionary with panel information
            adapter (scout.adapter.MongoAdapter)

        Returns:
            panel_obj(dict)

    gene_panel = dict(
        panel_id = str, # required
        institute = str, # institute_id, required
        version = float, # required
        date = datetime, # required
        display_name = str, # default is panel_name
        genes = list, # list of panel genes, sorted on panel_gene['symbol']
    )


Export variants which have been verified for an institute
        and write them to an excel file.

    Args:
        collaborator(str): institute id
        test(bool): True if the function is called for testing purposes
        outpath(str): path to output file

    Returns:
        written_files(int): number of written or simulated files


Export causatives for a collaborator in .vcf format


Generate an md5-key from a list of arguments.

    Args:
        list_of_arguments: A list of strings

    Returns:
        A md5-key object generated from the list of strings.


Setup via Flask.


Setup connection to database.


Create indexes for the database


Setup a scout database.


Setup a scout demo instance. This instance will be populated with a
       case, a gene panel and some variants.


Setup scout instances.


Show all institutes in the database


Parse the genetic models entry of a vcf

    Args:
        models_info(str): The raw vcf information
        case_id(str)

    Returns:
        genetic_models(list)


Add a institute to the database

            Args:
                institute_obj(Institute)


Featch a single institute from the backend

            Args:
                institute_id(str)

            Returns:
                Institute object


Return a datetime object if there is a valid date

        Raise exception if date is not valid
        Return todays date if no date where added

        Args:
            date(str)
            date_format(str)

        Returns:
            date_obj(datetime.datetime)


Export a list of genes based on hpo terms


Check if a connection could be made to the mongo process specified

    Args:
        host(str)
        port(int)
        username(str)
        password(str)
        authdb (str): database to to for authentication
        max_delay(int): Number of milliseconds to wait for connection

    Returns:
        bool: If connection could be established


Load a delivery report into a case in the database

    If the report already exists the function will exit.
    If the user want to load a report that is already in the database
    'update' has to be 'True'

    Args:
        adapter     (MongoAdapter): Connection to the database
        report_path (string):       Path to delivery report
        case_id     (string):       Optional case identifier
        update      (bool):         If an existing report should be replaced

    Returns:
        updated_case(dict)


Add a user object to the database

            Args:
                user_obj(scout.models.User): A dictionary with user information

            Returns:
                user_info(dict): a copy of what was inserted


Visualize BAM alignments.


Load all the exons

    Transcript information is from ensembl.
    Check that the transcript that the exon belongs to exists in the database

    Args:
        adapter(MongoAdapter)
        exon_lines(iterable): iterable with ensembl exon lines
        build(str)
        ensembl_transcripts(dict): Existing ensembl transcripts


Update all compounds for a case


Update a gene object with links

    Args:
        gene_obj(dict)
        build(int)

    Returns:
        gene_obj(dict): gene_obj updated with many links


Query the hgnc aliases


Parse an hgnc formated line

        Args:
            line(list): A list with hgnc gene info
            header(list): A list with the header info

        Returns:
            hgnc_info(dict): A dictionary with the relevant info


Parse lines with hgnc formated genes

        This is designed to take a dump with genes from HGNC.
        This is downloaded from:
        ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/tsv/hgnc_complete_set.txt

        Args:
            lines(iterable(str)): An iterable with HGNC formated genes
        Yields:
            hgnc_gene(dict): A dictionary with the relevant information


Retrieve the database id of an open clinvar submission for a user and institute,
           if none is available then create a new submission and return it

           Args:
                user_id(str): a user ID
                institute_id(str): an institute ID

           Returns:
                submission(obj) : an open clinvar submission object


saves an official clinvar submission ID in a clinvar submission object

            Args:
                clinvar_id(str): a string with a format: SUB[0-9]. It is obtained from clinvar portal when starting a new submission
                submission_id(str): submission_id(str) : id of the submission to be updated

            Returns:
                updated_submission(obj): a clinvar submission object, updated


Returns the official Clinvar submission ID for a submission object

            Args:
                submission_id(str): submission_id(str) : id of the submission

            Returns:
                clinvar_subm_id(str): a string with a format: SUB[0-9]. It is obtained from clinvar portal when starting a new submission


Collect all open and closed clinvar submission created by a user for an institute

            Args:
                user_id(str): a user ID
                institute_id(str): an institute ID

            Returns:
                submissions(list): a list of clinvar submission objects


Remove a variant object from clinvar database and update the relative submission object

            Args:
                object_id(str) : the id of an object to remove from clinvar_collection database collection (a variant of a case)
                object_type(str) : either 'variant_data' or 'case_data'. It's a key in the clinvar_submission object.
                submission_id(str): the _id key of a clinvar submission

            Returns:
                updated_submission(obj): an updated clinvar submission


Get all variants included in clinvar submissions for a case

        Args:
            case_id(str): a case _id

        Returns:
            submission_variants(dict): keys are variant ids and values are variant submission objects


Render seach box for genes.


Render information about a gene.


Return JSON data about genes.


Make sure that the gene panels exist in the database
        Also check if the default panels are defined in gene panels

        Args:
            adapter(MongoAdapter)
            panels(list(str)): A list with panel names

        Returns:
            panels_exists(bool)


Load all variants in a region defined by a HGNC id

    Args:
        adapter (MongoAdapter)
        case_id (str): Case id
        hgnc_id (int): If all variants from a gene should be uploaded
        chrom (str): If variants from coordinates should be uploaded
        start (int): Start position for region
        end (int): Stop position for region


Load a new case from a Scout config.

        Args:
            adapter(MongoAdapter)
            config(dict): loading info
            ped(Iterable(str)): Pedigree ingformation
            update(bool): If existing case should be updated


Fetch insitiute and case objects.


Preprocess institute objects.


Update a panel in the database


Load the omim phenotypes into the database

    Parse the phenotypes from genemap2.txt and find the associated hpo terms
    from ALL_SOURCES_ALL_FREQUENCIES_diseases_to_genes_to_phenotypes.txt.

    Args:
        adapter(MongoAdapter)
        genemap_lines(iterable(str))
        genes(dict): Dictionary with all genes found in database
        hpo_disease_lines(iterable(str))


Parse any frequency from the info dict

    Args:
        variant(cyvcf2.Variant)
        info_key(str)

    Returns:
        frequency(float): or None if frequency does not exist


Show all users in the database


Build a hgnc_gene object

        Args:
            gene_info(dict): Gene information

        Returns:
            gene_obj(dict)

            {
                '_id': ObjectId(),
                # This is the hgnc id, required:
                'hgnc_id': int,
                # The primary symbol, required
                'hgnc_symbol': str,
                'ensembl_id': str, # required
                'build': str, # '37' or '38', defaults to '37', required

                'chromosome': str, # required
                'start': int, # required
                'end': int, # required

                'description': str, # Gene description
                'aliases': list(), # Gene symbol aliases, includes hgnc_symbol, str
                'entrez_id': int,
                'omim_id': int,
                'pli_score': float,
                'primary_transcripts': list(), # List of refseq transcripts (str)
                'ucsc_id': str,
                'uniprot_ids': list(), # List of str
                'vega_id': str,
                'transcripts': list(), # List of hgnc_transcript

                # Inheritance information
                'inheritance_models': list(), # List of model names
                'incomplete_penetrance': bool, # Acquired from HPO

                # Phenotype information
                'phenotypes': list(), # List of dictionaries with phenotype information
            }


Load a gene panel based on the info sent
        A panel object is built and integrity checks are made.
        The panel object is then loaded into the database.

        Args:
            path(str): Path to panel file
            institute(str): Name of institute that owns the panel
            panel_id(str): Panel id
            date(datetime.datetime): Date of creation
            version(float)
            full_name(str): Option to have a long name

            panel_info(dict): {
                'file': <path to panel file>(str),
                'institute': <institute>(str),
                'type': <panel type>(str),
                'date': date,
                'version': version,
                'panel_name': panel_id,
                'full_name': name,
            }


Create and load the OMIM-AUTO panel


Add a gene panel to the database

            Args:
                panel_obj(dict)


Fetch a gene panel by '_id'.

        Args:
            panel_id (str, ObjectId): str or ObjectId of document ObjectId

        Returns:
            dict: panel object or `None` if panel not found


Fetch all gene panels and group them by gene

            Args:
                case_obj(scout.models.Case)
            Returns:
                gene_dict(dict): A dictionary with gene as keys and a set of
                                 panel names as value


Replace a existing gene panel with a new one

        Keeps the object id

        Args:
            panel_obj(dict)
            version(float)
            date_obj(datetime.datetime)

        Returns:
            updated_panel(dict)


Add a pending action to a gene panel

        Store the pending actions in panel.pending

        Args:
            panel_obj(dict): The panel that is about to be updated
            hgnc_gene(dict)
            action(str): choices=['add','delete','edit']
            info(dict): additional gene info (disease_associated_transcripts,
                        reduced_penetrance, mosaicism, database_entry_version ,
                        inheritance_models, comment)

        Returns:
            updated_panel(dict):


Apply the pending changes to an existing gene panel or create a new version of the same panel.

        Args:
            panel_obj(dict): panel in database to update
            version(double): panel version to update

        Returns:
            inserted_id(str): id of updated panel or the new one


Return all the clinical gene symbols for a case.


Interact with cases existing in the database.


Add the proper indexes to the scout instance.

        All indexes are specified in scout/constants/indexes.py

        If this method is utilised when new indexes are defined those should be added


Update the indexes

        If there are any indexes that are not added to the database, add those.


Build a mongo query

        These are the different query options:
            {
                'genetic_models': list,
                'chrom': str,
                'thousand_genomes_frequency': float,
                'exac_frequency': float,
                'clingen_ngi': int,
                'cadd_score': float,
                'cadd_inclusive": boolean,
                'genetic_models': list(str),
                'hgnc_symbols': list,
                'region_annotations': list,
                'functional_annotations': list,
                'clinsig': list,
                'clinsig_confident_always_returned': boolean,
                'variant_type': str(('research', 'clinical')),
                'chrom': str,
                'start': int,
                'end': int,
                'svtype': list,
                'size': int,
                'size_shorter': boolean,
                'gene_panels': list(str),
                'mvl_tag": boolean,
                'decipher": boolean,
            }

        Arguments:
            case_id(str)
            query(dict): a dictionary of query filters specified by the users
            variant_ids(list(str)): A list of md5 variant ids

        Returns:
            mongo_query : A dictionary in the mongo query format


Add clinsig filter values to the mongo query object

            Args:
                query(dict): a dictionary of query filters specified by the users
                mongo_query(dict): the query that is going to be submitted to the database

            Returns:
                clinsig_query(dict): a dictionary with clinsig key-values


Adds gene-related filters to the query object

        Args:
            query(dict): a dictionary of query filters specified by the users
            mongo_query(dict): the query that is going to be submitted to the database

        Returns:
            mongo_query(dict): returned object contains gene and panel-related filters


Drop the mongo database given.


Parse user submitted panel.


Load a bulk of hgnc gene objects

        Raises IntegrityError if there are any write concerns

        Args:
            gene_objs(iterable(scout.models.hgnc_gene))

        Returns:
            result (pymongo.results.InsertManyResult)


Load a bulk of transcript objects to the database

        Arguments:
            transcript_objs(iterable(scout.models.hgnc_transcript))


Load a bulk of exon objects to the database

        Arguments:
            exon_objs(iterable(scout.models.hgnc_exon))


Fetch a hgnc gene

            Args:
                hgnc_identifier(int)

            Returns:
                gene_obj(HgncGene)


Query the genes with a hgnc symbol and return the hgnc id

        Args:
            hgnc_symbol(str)
            build(str)

        Returns:
            hgnc_id(int)


Fetch all hgnc genes that match a hgnc symbol

            Check both hgnc_symbol and aliases

            Args:
                hgnc_symbol(str)
                build(str): The build in which to search
                search(bool): if partial searching should be used

            Returns:
                result()


Fetch all hgnc genes

            Returns:
                result()


Delete the genes collection


Delete the transcripts collection


Return a dictionary with hgnc symbols as keys and a list of hgnc ids
             as value.

        If a gene symbol is listed as primary the list of ids will only consist
        of that entry if not the gene can not be determined so the result is a list
        of hgnc_ids

        Args:
            build(str)
            genes(iterable(scout.models.HgncGene)):

        Returns:
            alias_genes(dict): {<hgnc_alias>: {'true': <hgnc_id>, 'ids': {<hgnc_id_1>, <hgnc_id_2>, ...}}}


Return a dictionary with ensembl ids as keys and gene objects as value.

        Args:
            build(str)

        Returns:
            genes(dict): {<ensg_id>: gene_obj, ...}


Add the correct hgnc id to a set of genes with hgnc symbols

        Args:
            genes(list(dict)): A set of genes with hgnc symbols only


Return a dictionary with chromosomes as keys and interval trees as values

        Each interval represents a coding region of overlapping genes.

        Args:
            build(str): The genome build
            genes(iterable(scout.models.HgncGene)):

        Returns:
            intervals(dict): A dictionary with chromosomes as keys and overlapping genomic intervals as values


Update the automate generated omim gene panel in the database.


Show all MatchMaker matches for a given case


Starts an internal match or a match against one or all MME external nodes


Visualize case report


Add or remove a diagnosis for a case.


Handle phenotypes.


Perform actions on multiple phenotypes.


Handle events.


Assign and unassign a user from a case.


Mark a variant as sanger validated.


Mark a variant as confirmed causative.


Display delivery report.


Share a case with a different institute.


Request a case to be rerun.


Open the research list for a case.


Download vcf2cytosure file for individual.


Load multiqc report for the case.


Preprocess case objects.

    Add the necessary information to display the 'cases' view

    Args:
        store(adapter.MongoAdapter)
        case_query(pymongo.Cursor)
        limit(int): Maximum number of cases to display

    Returns:
        data(dict): includes the cases, how many there are and the limit.


Gather contents to be visualized in a case report

    Args:
        store(adapter.MongoAdapter)
        institute_obj(models.Institute)
        case_obj(models.Case)

    Returns:
        data(dict)


Get all Clinvar submissions for a user and an institute


Collect MT variants and format line of a MT variant report
    to be exported in excel format

    Args:
        store(adapter.MongoAdapter)
        case_obj(models.Case)
        temp_excel_dir(os.Path): folder where the temp excel files are written to

    Returns:
        written_files(int): the number of files written to temp_excel_dir


vcf2cytosure CGH file for inidividual.


Add a patient to MatchMaker server

    Args:
        store(adapter.MongoAdapter)
        user_obj(dict) a scout user object (to be added as matchmaker contact)
        case_obj(dict) a scout case object
        add_gender(bool) if True case gender will be included in matchmaker
        add_features(bool) if True HPO features will be included in matchmaker
        add_disorders(bool) if True OMIM diagnoses will be included in matchmaker
        genes_only(bool) if True only genes and not variants will be shared
        mme_base_url(str) base url of the MME server
        mme_accepts(str) request content accepted by MME server
        mme_token(str) auth token of the MME server

    Returns:
        submitted_info(dict) info submitted to MatchMaker and its responses


Initiate a MatchMaker match against either other Scout patients or external nodes

    Args:
        case_obj(dict): a scout case object already submitted to MME
        match_type(str): 'internal' or 'external'
        mme_base_url(str): base url of the MME server
        mme_token(str): auth token of the MME server
        mme_accepts(str): request content accepted by MME server (only for internal matches)

    Returns:
        matches(list): a list of eventual matches


Parse how the different variant callers have performed

        Args:
            variant (cyvcf2.Variant): A variant object

        Returns:
            callers (dict): A dictionary on the format
            {'gatk': <filter>,'freebayes': <filter>,'samtools': <filter>}


Load a institute into the database

        Args:
            adapter(MongoAdapter)
            internal_id(str)
            display_name(str)
            sanger_recipients(list(email))


Load a case into the database.

    A case can be loaded without specifying vcf files and/or bam files


Update compounds for a variant.

        This will add all the necessary information of a variant on a compound object.

        Args:
            variant(scout.models.Variant)
            variant_objs(dict): A dictionary with _ids as keys and variant objs as values.

        Returns:
            compound_objs(list(dict)): A dictionary with updated compound objects.


Update the compounds for a set of variants.

        Args:
            variants(dict): A dictionary with _ids as keys and variant objs as values


Load a variant object

        Args:
            variant_obj(dict)

        Returns:
            inserted_id


Load a variant object, if the object already exists update compounds.

        Args:
            variant_obj(dict)

        Returns:
            result


Load a bulk of variants

        Args:
            variants(iterable(scout.models.Variant))

        Returns:
            object_ids


Assign a user to a case.

        This function will create an Event to log that a person has been assigned
        to a case. Also the user will be added to case "assignees".

        Arguments:
            institute (dict): A institute
            case (dict): A case
            user (dict): A User object
            link (str): The url to be used in the event

        Returns:
            updated_case(dict)


Share a case with a new institute.

        Arguments:
            institute (dict): A Institute object
            case (dict): Case object
            collaborator_id (str): A instute id
            user (dict): A User object
            link (str): The url to be used in the event

        Return:
            updated_case


Diagnose a case using OMIM ids.

        Arguments:
            institute (dict): A Institute object
            case (dict): Case object
            user (dict): A User object
            link (str): The url to be used in the event
            level (str): choices=('phenotype','gene')

        Return:
            updated_case


Create an event for a variant verification for a variant
        and an event for a variant verification for a case

        Arguments:
            institute (dict): A Institute object
            case (dict): Case object
            user (dict): A User object
            link (str): The url to be used in the event
            variant (dict): A variant object

        Returns:
            updated_variant(dict)


Get all variants with validations ever ordered.

        Args:
            institute_id(str) : The id of an institute
            user_id(str) : The id of an user

        Returns:
            sanger_ordered(list) : a list of dictionaries, each with "case_id" as keys and list of variant ids as values


Create an event for marking a variant causative.

        Arguments:
          institute (dict): A Institute object
          case (dict): Case object
          user (dict): A User object
          link (str): The url to be used in the event
          variant (variant): A variant object

        Returns:
            updated_case(dict)


Create an event for updating the manual dismiss variant entry

          This function will create a event and update the dismiss variant
          field of the variant.

        Arguments:
            institute (dict): A Institute object
            case (dict): Case object
            user (dict): A User object
            link (str): The url to be used in the event
            variant (dict): A variant object
            dismiss_variant (list): The new dismiss variant list

        Return:
            updated_variant


Create an event for updating the ACMG classification of a variant.

        Arguments:
            institute_obj (dict): A Institute object
            case_obj (dict): Case object
            user_obj (dict): A User object
            link (str): The url to be used in the event
            variant_obj (dict): A variant object
            acmg_str (str): The new ACMG classification string

        Returns:
            updated_variant


Construct the necessary ids for a variant

    Args:
        chrom(str): Variant chromosome
        pos(int): Variant position
        ref(str): Variant reference
        alt(str): Variant alternative
        case_id(str): Unique case id
        variant_type(str): 'clinical' or 'research'

    Returns:
        ids(dict): Dictionary with the relevant ids


Parse the simple id for a variant

    Simple id is used as a human readable reference for a position, it is
    in no way unique.

    Args:
        chrom(str)
        pos(str)
        ref(str)
        alt(str)

    Returns:
        simple_id(str): The simple human readable variant id


Fetches a single case from database

        Use either the _id or combination of institute_id and display_name

        Args:
            case_id(str): _id for a caes
            institute_id(str):
            display_name(str)

        Yields:
            A single Case


Add a case to the database
           If the case already exists exception is raised

            Args:
                case_obj(Case)


Replace a existing case with a new one

        Keeps the object id

        Args:
            case_obj(dict)

        Returns:
            updated_case(dict)


Submit an evaluation to the database

        Get all the relevant information, build a evaluation_obj

        Args:
            variant_obj(dict)
            user_obj(dict)
            institute_obj(dict)
            case_obj(dict)
            link(str): variant url
            criteria(list(dict)):

                [
            {
            'term': str,
            'comment': str,
            'links': list(str)
            },
            .
            .
        ]


Parse and massage the transcript information

    There could be multiple lines with information about the same transcript.
    This is why it is necessary to parse the transcripts first and then return a dictionary
    where all information has been merged.

    Args:
        transcript_lines(): This could be an iterable with strings or a pandas.DataFrame

    Returns:
        parsed_transcripts(dict): Map from enstid -> transcript info


Parse a dataframe with ensembl transcript information

    Args:
        res(pandas.DataFrame)

    Yields:
        transcript_info(dict)


Parse an ensembl formated line

        Args:
            line(list): A list with ensembl gene info
            header(list): A list with the header info

        Returns:
            ensembl_info(dict): A dictionary with the relevant info


Parse lines with ensembl formated genes

        This is designed to take a biomart dump with genes from ensembl.
        Mandatory columns are:
        'Gene ID' 'Chromosome' 'Gene Start' 'Gene End' 'HGNC symbol

        Args:
            lines(iterable(str)): An iterable with ensembl formated genes
        Yields:
            ensembl_gene(dict): A dictionary with the relevant information


Parse lines with ensembl formated exons

        This is designed to take a biomart dump with exons from ensembl.
        Check documentation for spec for download

        Args:
            lines(iterable(str)): An iterable with ensembl formated exons
        Yields:
            ensembl_gene(dict): A dictionary with the relevant information


Parse a dataframe with ensembl exon information

    Args:
        res(pandas.DataFrame)

    Yields:
        gene_info(dict)


Initializes the log file in the proper format.

    Arguments:

        filename (str): Path to a file. Or None if logging is to
                         be disabled.
        loglevel (str): Determines the level of the log output.


docstring for parse_omim_morbid


Get a dictionary with phenotypes

    Use the mim numbers for phenotypes as keys and phenotype information as
    values.

    Args:
        genemap_lines(iterable(str))

    Returns:
        phenotypes_found(dict): A dictionary with mim_numbers as keys and
        dictionaries with phenotype information as values.

        {
             'description': str, # Description of the phenotype
             'hgnc_symbols': set(), # Associated hgnc symbols
             'inheritance': set(),  # Associated phenotypes
             'mim_number': int, # mim number of phenotype
        }


Parse the omim files


Convert a string to number
    If int convert to int otherwise float

    If not possible return None


Return a formatted month as a table.


Set some commonly used variables.


Change colspan to "5", add "today" button, and return a month
        name as a table row.


Populate variables used to build popovers.


Parse metadata for a gene panel

    For historical reasons it is possible to include all information about a gene panel in the
    header of a panel file. This function parses the header.

    Args:
        panel_lines(iterable(str))

    Returns:
        panel_info(dict): Dictionary with panel information


Parse a gene line with information from a panel file

        Args:
            gene_info(dict): dictionary with gene info

        Returns:
            gene(dict): A dictionary with the gene information
                {
                'hgnc_id': int,
                'hgnc_symbol': str,
                'disease_associated_transcripts': list(str),
                'inheritance_models': list(str),
                'mosaicism': bool,
                'reduced_penetrance': bool,
                'database_entry_version': str,
                }


Parse the panel info and return a gene panel

        Args:
            path(str): Path to panel file
            institute(str): Name of institute that owns the panel
            panel_id(str): Panel id
            date(datetime.datetime): Date of creation
            version(float)
            full_name(str): Option to have a long name

        Returns:
            gene_panel(dict)


Update the hpo terms in the database. Fetch the latest release and update terms.


Returns a JSON response, transforming 'context' to make the payload.


Get the year and month. First tries from kwargs, then from
        querystrings. If none, or if cal_ignore qs is specified,
        sets year and month to this year and this month.


Check if any events are cancelled on the given date 'd'.


Fetch a hpo term

        Args:
            hpo_id(str)

        Returns:
            hpo_obj(dict)


Return all HPO terms

        If a query is sent hpo_terms will try to match with regex on term or
        description.

        Args:
            query(str): Part of a hpoterm or description
            hpo_term(str): Search for a specific hpo term
            limit(int): the number of desired results

        Returns:
            result(pymongo.Cursor): A cursor with hpo terms


Return all disease terms that overlaps a gene

            If no gene, return all disease terms

        Args:
            hgnc_id(int)

        Returns:
            iterable(dict): A list with all disease terms that match


r'''Beat tracking evaluation

    Parameters
    ----------
    ref : jams.Annotation
        Reference annotation object
    est : jams.Annotation
        Estimated annotation object
    kwargs
        Additional keyword arguments

    Returns
    -------
    scores : dict
        Dictionary of scores, where the key is the metric name (str) and
        the value is the (float) score achieved.

    See Also
    --------
    mir_eval.beat.evaluate

    Examples
    --------
    >>> # Load in the JAMS objects
    >>> ref_jam = jams.load('reference.jams')
    >>> est_jam = jams.load('estimated.jams')
    >>> # Select the first relevant annotations
    >>> ref_ann = ref_jam.search(namespace='beat')[0]
    >>> est_ann = est_jam.search(namespace='beat')[0]
    >>> scores = jams.eval.beat(ref_ann, est_ann)


r'''Chord evaluation

    Parameters
    ----------
    ref : jams.Annotation
        Reference annotation object
    est : jams.Annotation
        Estimated annotation object
    kwargs
        Additional keyword arguments

    Returns
    -------
    scores : dict
        Dictionary of scores, where the key is the metric name (str) and
        the value is the (float) score achieved.

    See Also
    --------
    mir_eval.chord.evaluate

    Examples
    --------
    >>> # Load in the JAMS objects
    >>> ref_jam = jams.load('reference.jams')
    >>> est_jam = jams.load('estimated.jams')
    >>> # Select the first relevant annotations
    >>> ref_ann = ref_jam.search(namespace='chord')[0]
    >>> est_ann = est_jam.search(namespace='chord')[0]
    >>> scores = jams.eval.chord(ref_ann, est_ann)


Flatten a multi_segment annotation into mir_eval style.

    Parameters
    ----------
    annotation : jams.Annotation
        An annotation in the `multi_segment` namespace

    Returns
    -------
    hier_intervalss : list
        A list of lists of intervals, ordered by increasing specificity.

    hier_labels : list
        A list of lists of labels, ordered by increasing specificity.


r'''Multi-level segmentation evaluation

    Parameters
    ----------
    ref : jams.Annotation
        Reference annotation object
    est : jams.Annotation
        Estimated annotation object
    kwargs
        Additional keyword arguments

    Returns
    -------
    scores : dict
        Dictionary of scores, where the key is the metric name (str) and
        the value is the (float) score achieved.

    See Also
    --------
    mir_eval.hierarchy.evaluate

    Examples
    --------
    >>> # Load in the JAMS objects
    >>> ref_jam = jams.load('reference.jams')
    >>> est_jam = jams.load('estimated.jams')
    >>> # Select the first relevant annotations
    >>> ref_ann = ref_jam.search(namespace='multi_segment')[0]
    >>> est_ann = est_jam.search(namespace='multi_segment')[0]
    >>> scores = jams.eval.hierarchy(ref_ann, est_ann)


r'''Melody extraction evaluation

    Parameters
    ----------
    ref : jams.Annotation
        Reference annotation object
    est : jams.Annotation
        Estimated annotation object
    kwargs
        Additional keyword arguments

    Returns
    -------
    scores : dict
        Dictionary of scores, where the key is the metric name (str) and
        the value is the (float) score achieved.

    See Also
    --------
    mir_eval.melody.evaluate

    Examples
    --------
    >>> # Load in the JAMS objects
    >>> ref_jam = jams.load('reference.jams')
    >>> est_jam = jams.load('estimated.jams')
    >>> # Select the first relevant annotations
    >>> ref_ann = ref_jam.search(namespace='pitch_contour')[0]
    >>> est_ann = est_jam.search(namespace='pitch_contour')[0]
    >>> scores = jams.eval.melody(ref_ann, est_ann)


Add a namespace definition to our working set.

    Namespace files consist of partial JSON schemas defining the behavior
    of the `value` and `confidence` fields of an Annotation.

    Parameters
    ----------
    filename : str
        Path to json file defining the namespace object


Return the allowed values for an enumerated namespace.

    Parameters
    ----------
    ns_key : str
        Namespace key identifier

    Returns
    -------
    values : list

    Raises
    ------
    NamespaceError
        If `ns_key` is not found, or does not have enumerated values

    Examples
    --------
    >>> jams.schema.values('tag_gtzan')
    ['blues', 'classical', 'country', 'disco', 'hip-hop', 'jazz',
     'metal', 'pop', 'reggae', 'rock']


Get the dtypes associated with the value and confidence fields
    for a given namespace.

    Parameters
    ----------
    ns_key : str
        The namespace key in question

    Returns
    -------
    value_dtype, confidence_dtype : numpy.dtype
        Type identifiers for value and confidence fields.


Print out a listing of available namespaces


Load the schema file from the package.


Expand a list of relative paths to a give base directory.

    Parameters
    ----------
    base_dir : str
        The target base directory

    rel_paths : list (or list-like)
        Collection of relative path strings

    Returns
    -------
    expanded_paths : list
        `rel_paths` rooted at `base_dir`

    Examples
    --------
    >>> jams.util.expand_filepaths('/data', ['audio', 'beat', 'seglab'])
    ['/data/audio', '/data/beat', '/data/seglab']


Safely make a full directory path if it doesn't exist.

    Parameters
    ----------
    dpath : str
        Path of directory/directories to create

    mode : int [default=0777]
        Permissions for the new directories

    See also
    --------
    os.makedirs


Get the metadata from a jam and an annotation, combined as a string.

    Parameters
    ----------
    jam : JAMS
        The jams object

    ann : Annotation
        An annotation object

    Returns
    -------
    comments : str
        The jam.file_metadata and ann.annotation_metadata, combined and serialized


Parse arguments from the command line


A decorator to register namespace conversions.

    Usage
    -----
    >>> @conversion('tag_open', 'tag_.*')
    ... def tag_to_open(annotation):
    ...     annotation.namespace = 'tag_open'
    ...     return annotation


Convert a given annotation to the target namespace.

    Parameters
    ----------
    annotation : jams.Annotation
        An annotation object

    target_namespace : str
        The target namespace

    Returns
    -------
    mapped_annotation : jams.Annotation
        if `annotation` already belongs to `target_namespace`, then
        it is returned directly.

        otherwise, `annotation` is copied and automatically converted
        to the target namespace.

    Raises
    ------
    SchemaError
        if the input annotation fails to validate

    NamespaceError
        if no conversion is possible

    Examples
    --------
    Convert frequency measurements in Hz to MIDI

    >>> ann_midi = jams.convert(ann_hz, 'note_midi')

    And back to Hz

    >>> ann_hz2 = jams.convert(ann_midi, 'note_hz')


Test if an annotation can be mapped to a target namespace

    Parameters
    ----------
    annotation : jams.Annotation
        An annotation object

    target_namespace : str
        The target namespace

    Returns
    -------
    True
        if `annotation` can be automatically converted to
        `target_namespace`

    False
        otherwise


Convert a pitch_hz annotation to a contour


Convert a pitch_hz annotation to pitch_midi


Convert scaper annotations to tag_open


This is a decorator which can be used to mark functions
    as deprecated.

    It will result in a warning being emitted when the function is used.


Pop a prefix from a query string.

    Parameters
    ----------
    query : str
        The query string

    prefix : str
        The prefix string to pop, if it exists

    sep : str
        The string to separate fields

    Returns
    -------
    popped : str
        `query` with a `prefix` removed from the front (if found)
        or `query` if the prefix was not found

    Examples
    --------
    >>> query_pop('Annotation.namespace', 'Annotation')
    'namespace'
    >>> query_pop('namespace', 'Annotation')
    'namespace'


Test if a string matches a query.

    Parameters
    ----------
    string : str
        The string to test

    query : string, callable, or object
        Either a regular expression, callable function, or object.

    Returns
    -------
    match : bool
        `True` if:
        - `query` is a callable and `query(string) == True`
        - `query` is a regular expression and `re.match(query, string)`
        - or `string == query` for any other query

        `False` otherwise


Helper function to format repr strings for JObjects and friends.

    Parameters
    ----------
    obj
        The object to repr

    indent : int >= 0
        indent each new line by `indent` spaces

    Returns
    -------
    r : str
        If `obj` has a `__summary__` method, it is used.

        If `obj` is a `SortedKeyList`, then it returns a description
        of the length of the list.

        Otherwise, `repr(obj)`.


Update the attributes of a JObject.

        Parameters
        ----------
        kwargs
            Keyword arguments of the form `attribute=new_value`

        Examples
        --------
        >>> J = jams.JObject(foo=5)
        >>> J.dumps()
        '{"foo": 5}'
        >>> J.update(bar='baz')
        >>> J.dumps()
        '{"foo": 5, "bar": "baz"}'


Validate a JObject against its schema

        Parameters
        ----------
        strict : bool
            Enforce strict schema validation

        Returns
        -------
        valid : bool
            True if the jam validates
            False if not, and `strict==False`

        Raises
        ------
        SchemaError
            If `strict==True` and `jam` fails validation


Append an observation to the data field

        Parameters
        ----------
        time : float >= 0
        duration : float >= 0
            The time and duration of the new observation, in seconds
        value
        confidence
            The value and confidence of the new observations.

            Types and values should conform to the namespace of the
            Annotation object.

        Examples
        --------
        >>> ann = jams.Annotation(namespace='chord')
        >>> ann.append(time=3, duration=2, value='E#')


Validate this annotation object against the JAMS schema,
        and its data against the namespace schema.

        Parameters
        ----------
        strict : bool
            If `True`, then schema violations will cause an Exception.
            If `False`, then schema violations will issue a warning.

        Returns
        -------
        valid : bool
            `True` if the object conforms to schema.
            `False` if the object fails to conform to schema,
            but `strict == False`.

        Raises
        ------
        SchemaError
            If `strict == True` and the object fails validation

        See Also
        --------
        JObject.validate


Trim the annotation and return as a new `Annotation` object.

        Trimming will result in the new annotation only containing observations
        that occur in the intersection of the time range spanned by the
        annotation and the time range specified by the user. The new annotation
        will span the time range ``[trim_start, trim_end]`` where
        ``trim_start = max(self.time, start_time)`` and ``trim_end =
        min(self.time + self.duration, end_time)``.

        If ``strict=False`` (default) observations that start before
        ``trim_start`` and end after it will be trimmed such that they start at
        ``trim_start``, and similarly observations that start before
        ``trim_end`` and end after it will be trimmed to end at ``trim_end``.
        If ``strict=True`` such borderline observations will be discarded.

        The new duration of the annotation will be ``trim_end - trim_start``.

        Note that if the range defined by ``[start_time, end_time]``
        doesn't intersect with the original time range spanned by the
        annotation the resulting annotation will contain no observations, will
        have the same start time as the original annotation and have duration
        0.

        This function also copies over all the annotation metadata from the
        original annotation and documents the trim operation by adding a list
        of tuples to the annotation's sandbox keyed by
        ``Annotation.sandbox.trim`` which documents each trim operation with a
        tuple ``(start_time, end_time, trim_start, trim_end)``.

        Parameters
        ----------
        start_time : float
            The desired start time for the trimmed annotation in seconds.
        end_time
            The desired end time for the trimmed annotation in seconds. Must be
            greater than ``start_time``.
        strict : bool
            When ``False`` (default) observations that lie at the boundaries of
            the trimming range (given by ``[trim_start, trim_end]`` as
            described above), i.e. observations that start before and end after
            either the trim start or end time, will have their time and/or
            duration adjusted such that only the part of the observation that
            lies within the trim range is kept. When ``True`` such observations
            are discarded and not included in the trimmed annotation.

        Returns
        -------
        ann_trimmed : Annotation
            The trimmed annotation, returned as a new jams.Annotation object.
            If the trim range specified by ``[start_time, end_time]`` does not
            intersect at all with the original time range of the annotation a
            warning will be issued and the returned annotation will be empty.

        Raises
        ------
        ParameterError
            If ``end_time`` is not greater than ``start_time``.

        Examples
        --------
        >>> ann = jams.Annotation(namespace='tag_open', time=2, duration=8)
        >>> ann.append(time=2, duration=2, value='one')
        >>> ann.append(time=4, duration=2, value='two')
        >>> ann.append(time=6, duration=2, value='three')
        >>> ann.append(time=7, duration=2, value='four')
        >>> ann.append(time=8, duration=2, value='five')
        >>> ann_trim = ann.trim(5, 8, strict=False)
        >>> print(ann_trim.time, ann_trim.duration)
        (5, 3)
        >>> ann_trim.to_dataframe()
           time  duration  value confidence
        0     5         1    two       None
        1     6         2  three       None
        2     7         1   four       None
        >>> ann_trim_strict = ann.trim(5, 8, strict=True)
        >>> print(ann_trim_strict.time, ann_trim_strict.duration)
        (5, 3)
        >>> ann_trim_strict.to_dataframe()
           time  duration  value confidence
        0     6         2  three       None


Sample the annotation at specified times.

        Parameters
        ----------
        times : np.ndarray, non-negative, ndim=1
            The times (in seconds) to sample the annotation

        confidence : bool
            If `True`, return both values and confidences.
            If `False` (default) only return values.

        Returns
        -------
        values : list
            `values[i]` is a list of observation values for intervals
            that cover `times[i]`.

        confidence : list (optional)
            `confidence` values corresponding to `values`


Render this annotation list in HTML

        Returns
        -------
        rendered : str
            An HTML table containing this annotation's data.


Trim every annotation contained in the annotation array using
        `Annotation.trim` and return as a new `AnnotationArray`.

        See `Annotation.trim` for details about trimming. This function does
        not modify the annotations in the original annotation array.

        Parameters
        ----------
        start_time : float
            The desired start time for the trimmed annotations in seconds.
        end_time
            The desired end time for trimmed annotations in seconds. Must be
            greater than ``start_time``.
        strict : bool
            When ``False`` (default) observations that lie at the boundaries of
            the trimming range (see `Annotation.trim` for details) will have
            their time and/or duration adjusted such that only the part of the
            observation that lies within the trim range is kept. When ``True``
            such observations are discarded and not included in the trimmed
            annotation.

        Returns
        -------
        trimmed_array : AnnotationArray
            An annotation array where every annotation has been trimmed.


Slice every annotation contained in the annotation array using
        `Annotation.slice`
        and return as a new AnnotationArray

        See `Annotation.slice` for details about slicing. This function does
        not modify the annotations in the original annotation array.

        Parameters
        ----------
        start_time : float
            The desired start time for slicing in seconds.
        end_time
            The desired end time for slicing in seconds. Must be greater than
            ``start_time``.
        strict : bool
            When ``False`` (default) observations that lie at the boundaries of
            the slicing range (see `Annotation.slice` for details) will have
            their time and/or duration adjusted such that only the part of the
            observation that lies within the trim range is kept. When ``True``
            such observations are discarded and not included in the sliced
            annotation.

        Returns
        -------
        sliced_array : AnnotationArray
            An annotation array where every annotation has been sliced.


Add the contents of another jam to this object.

        Note that, by default, this method fails if file_metadata is not
        identical and raises a ValueError; either resolve this manually
        (because conflicts should almost never happen), force an 'overwrite',
        or tell the method to 'ignore' the metadata of the object being added.

        Parameters
        ----------
        jam: JAMS object
            Object to add to this jam

        on_conflict: str, default='fail'
            Strategy for resolving metadata conflicts; one of
                ['fail', 'overwrite', or 'ignore'].

        Raises
        ------
        ParameterError
            if `on_conflict` is an unknown value

        JamsError
            If a conflict is detected and `on_conflict='fail'`


Serialize annotation as a JSON formatted stream to file.

        Parameters
        ----------
        path_or_file : str or file-like
            Path to save the JAMS object on disk
            OR
            An open file descriptor to write into

        strict : bool
            Force strict schema validation

        fmt : str ['auto', 'jams', 'jamz']
            The output encoding format.

            If `auto`, it is inferred from the file name.

            If the input is an open file handle, `jams` encoding
            is used.

        Raises
        ------
        SchemaError
            If `strict == True` and the JAMS object fails schema
            or namespace validation.

        See also
        --------
        validate


Plotting wrapper for pitch contours


Plotting wrapper for events


Plotting wrapper for beat-position data


Plotting wrapper for piano rolls


Visualize a jams annotation through mir_eval

    Parameters
    ----------
    annotation : jams.Annotation
        The annotation to display

    meta : bool
        If `True`, include annotation metadata in the figure

    kwargs
        Additional keyword arguments to mir_eval.display functions

    Returns
    -------
    ax
        Axis handles for the new display

    Raises
    ------
    NamespaceError
        If the annotation cannot be visualized


Display multiple annotations with shared axes

    Parameters
    ----------
    annotations : jams.AnnotationArray
        A collection of annotations to display

    fig_kw : dict
        Keyword arguments to `plt.figure`

    meta : bool
        If `True`, display annotation metadata for each annotation

    kwargs
        Additional keyword arguments to the `mir_eval.display` routines

    Returns
    -------
    fig
        The created figure
    axs
        List of subplot axes corresponding to each displayed annotation


Generate a click sample.

    This replicates functionality from mir_eval.sonify.clicks,
    but exposes the target frequency and duration.


Sonify events with clicks.

    This uses mir_eval.sonify.clicks, and is appropriate for instantaneous
    events such as beats or segment boundaries.


Sonify beats and downbeats together.


Sonify a piano-roll

    This uses mir_eval.sonify.time_frequency, and is appropriate
    for sparse transcription data, e.g., annotations in the `note_midi`
    namespace.


Setup time axis.


Blank DC bins in coarse channels.

        Note: currently only works if entire file is read


Setup ploting edges.


Plot waterfall of data

        Args:
            f_start (float): start frequency, in MHz
            f_stop (float): stop frequency, in MHz
            logged (bool): Plot in linear (False) or dB units (True),
            cb (bool): for plotting the colorbar
            kwargs: keyword args to be passed to matplotlib imshow()


Plot the time series.

         Args:
            f_start (float): start frequency, in MHz
            f_stop (float): stop frequency, in MHz
            logged (bool): Plot in linear (False) or dB units (True),
            kwargs: keyword args to be passed to matplotlib imshow()


Converts a data array with length n_chans to an array of length n_coarse_chans
    by averaging over the coarse channels


Returns calibrated Stokes parameters for an observation given an array
    of differential gains and phase differences.


Output fractional linear and circular polarizations for a
    rawspec cross polarization .fil file. NOT STANDARD USE


Writes two new filterbank files containing fractional linear and
    circular polarization data


Return the index of the closest in xarr to value val


Rebin data by averaging bins together

    Args:
    d (np.array): data
    n_x (int): number of bins in x dir to rebin into one
    n_y (int): number of bins in y dir to rebin into one

    Returns:
    d: rebinned data with shape (n_x, n_y)


upgrade data from nbits to 8bits

    Notes: Pretty sure this function is a little broken!


Plots the uncalibrated full stokes spectrum of the noise diode.
    Use diff=False to plot both ON and OFF, or diff=True for ON-OFF


Plots the calculated gain offsets of each coarse channel along with
    the time averaged power spectra of the X and Y feeds


Open a HDF5 or filterbank file

    Returns instance of a Reader to read data from file.

    ================== ==================================================
    Filename extension File type
    ================== ==================================================
    h5, hdf5           HDF5 format
    fil                fil format
    *other*            Will raise NotImplementedError
    ================== ==================================================


Calculate size of data of interest.


Calculate shape of data of interest.


Setup channel borders


Updating frequency borders from channel values


Populate time axis.
            IF update_header then only return tstart


Populate frequency axis


Given the blob dimensions, calculate how many fit in the data selection.


Check if the current selection is too large.


Read data.


Read a block of data. The number of samples per row is set in self.channels
            If reverse=True the x axis is flipped.


Write data to .fil file.
            It check the file size then decides how to write the file.

        Args:
            filename_out (str): Name of output file


Write data to HDF5 file.
            It check the file size then decides how to write the file.

        Args:
            filename_out (str): Name of output file


Sets the blob dimmentions, trying to read around 1024 MiB at a time.
            This is assuming a chunk is about 1 MiB.


Extract a portion of data by frequency range.

        Args:
            f_start (float): start frequency in MHz
            f_stop (float): stop frequency in MHz
            if_id (int): IF input identification (req. when multiple IFs in file)

        Returns:
            (freqs, data) (np.arrays): frequency axis in MHz and data subset


Command line tool for plotting and viewing info on guppi raw files


Read first header in file

        Returns:
            header (dict): keyword:value pairs of header metadata


Compute some basic stats on the next block of data


Plot a histogram of data values


Generate a blimpy header dictionary


Command line tool to make a md5sum comparison of two .fil files.


Command line tool for converting guppi raw into HDF5 versions of guppi raw


Returns time-averaged spectra of the ON and OFF measurements in a
    calibrator measurement with flickering noise diode

    Parameters
    ----------
    data : 2D Array object (float)
        2D dynamic spectrum for data (any Stokes parameter) with flickering noise diode.
    tsamp : float
        Sampling time of data in seconds
    diode_p : float
        Period of the flickering noise diode in seconds
    numsamps : int
        Number of samples over which to average noise diode ON and OFF
    switch : boolean
        Use switch=True if the noise diode "skips" turning from OFF to ON once or vice versa
    inds : boolean
        Use inds=True to also return the indexes of the time series where the ND is ON and OFF


Given properties of the calibrator source, calculate fluxes of the source
    in a particular frequency range

    Parameters
    ----------
    calflux : float
        Known flux of calibrator source at a particular frequency
    calfreq : float
        Frequency where calibrator source has flux calflux (see above)
    spec_in : float
        Known power-law spectral index of calibrator source. Use convention flux(frequency) = constant * frequency^(spec_in)
    centerfreqs : 1D Array (float)
        Central frequency values of each coarse channel
    oneflux : boolean
        Use oneflux to choose between calculating the flux for each core channel (False)
        or using one value for the entire frequency range (True)


Returns central frequency of each coarse channel

    Parameters
    ----------
    freqs : 1D Array (float)
        Frequency values for each bin of the spectrum
    chan_per_coarse: int
        Number of frequency bins per coarse channel


Returns frequency dependent system temperature given observations on and off a calibrator source

    Parameters
    ----------
    (See diode_spec())


Produce calibrated Stokes I for an observation given a noise diode
    measurement on the source and a diode spectrum with the same number of
    coarse channels

    Parameters
    ----------
    main_obs_name : str
        Path to filterbank file containing final data to be calibrated
    dio_name : str
        Path to filterbank file for observation on the target source with flickering noise diode
    dspec : 1D Array (float) or float
        Coarse channel spectrum (or average) of the noise diode in Jy (obtained from diode_spec())
    Tsys : 1D Array (float) or float
        Coarse channel spectrum (or average) of the system temperature in Jy
    fullstokes: boolean
        Use fullstokes=True if data is in IQUV format or just Stokes I, use fullstokes=False if
        it is in cross_pols format


Return the length of the blimpy header, in bytes

    Args:
        filename (str): name of file to open

    Returns:
        idx_end (int): length of header, in bytes


Open file and confirm if it is a filterbank file or not.


Generate a serialzed sigproc header which can be written to disk.

    Args:
        f (Filterbank object): Filterbank object for which to generate header

    Returns:
        header_str (str): Serialized string corresponding to header


Calculate number of integrations in a given file


Check authorization id and other properties returned by the
        authentication mechanism.

        [receiving entity only]

        Allow only no authzid or authzid equal to current username@domain

        FIXME: other rules in s2s

        :Parameters:
            - `properties`: data obtained during authentication
        :Types:
            - `properties`: mapping

        :return: `True` if user is authorized to use a provided authzid
        :returntype: `bool`


Start SASL authentication process.

        [initiating entity only]

        :Parameters:
            - `username`: user name.
            - `authzid`: authorization ID.
            - `mechanism`: SASL mechanism to use.


Make a RosterItem from an XML element.

        :Parameters:
            - `element`: the XML element
        :Types:
            - `element`: :etree:`ElementTree.Element`

        :return: a freshly created roster item
        :returntype: `cls`


Make an XML element from self.

        :Parameters:
            - `parent`: Parent element
        :Types:
            - `parent`: :etree:`ElementTree.Element`


Check if `self` is valid roster push item.

        Valid item must have proper `subscription` value other and valid value
        for 'ask'.

        :Parameters:
            - `fix`: if `True` than replace invalid 'subscription' and 'ask'
              values with the defaults
        :Types:
            - `fix`: `bool`

        :Raise: `ValueError` if the item is invalid.


Check if `self` is valid roster set item.

        For use on server to validate incoming roster sets.

        Valid item must have proper `subscription` value other and valid value
        for 'ask'. The lengths of name and group names must fit the configured
        limits.

        :Parameters:
            - `fix`: if `True` than replace invalid 'subscription' and 'ask'
              values with right defaults
            - `settings`: settings object providing the name limits
        :Types:
            - `fix`: `bool`
            - `settings`: `XMPPSettings`

        :Raise: `BadRequestProtocolError` if the item is invalid.


Set of groups defined in the roster.

        :Return: the groups
        :ReturnType: `set` of `unicode`


Return a list of items within a given group.

        :Parameters:
            - `name`: name to look-up
            - `case_sensitive`: if `False` the matching will be case
              insensitive.
        :Types:
            - `name`: `unicode`
            - `case_sensitive`: `bool`

        :Returntype: `list` of `RosterItem`


Add an item to the roster.

        This will not automatically update the roster on the server.

        :Parameters:
            - `item`: the item to add
            - `replace`: if `True` then existing item will be replaced,
              otherwise a `ValueError` will be raised on conflict
        :Types:
            - `item`: `RosterItem`
            - `replace`: `bool`


Remove item from the roster.

        :Parameters:
            - `jid`: JID of the item to remove
        :Types:
            - `jid`: `JID`


Request roster upon login.


Request roster from server.

        :Parameters:
            - `version`: if not `None` versioned roster will be requested
              for given local version. Use "" to request full roster.
        :Types:
            - `version`: `unicode`


Handle failure of the roster request.


Handle a roster push received from server.


Add a contact to the roster.

        :Parameters:
            - `jid`: contact's jid
            - `name`: name for the contact
            - `groups`: sequence of group names the contact should belong to
            - `callback`: function to call when the request succeeds. It should
              accept a single argument - a `RosterItem` describing the
              requested change
            - `error_callback`: function to call when the request fails. It
              should accept a single argument - an error stanza received
              (`None` in case of timeout)
        :Types:
            - `jid`: `JID`
            - `name`: `unicode`
            - `groups`: sequence of `unicode`


Modify a contact in the roster.

        :Parameters:
            - `jid`: contact's jid
            - `name`: a new name for the contact
            - `groups`: a sequence of group names the contact should belong to
            - `callback`: function to call when the request succeeds. It should
              accept a single argument - a `RosterItem` describing the
              requested change
            - `error_callback`: function to call when the request fails. It
              should accept a single argument - an error stanza received
              (`None` in case of timeout)
        :Types:
            - `jid`: `JID`
            - `name`: `unicode`
            - `groups`: sequence of `unicode`


Unlink and free the XML node owned by `self`.


Set history parameters.

        Types:
            - `parameters`: `HistoryParameters`


Return history parameters carried by the stanza.

        :returntype: `HistoryParameters`


Set password for the MUC request.

        :Parameters:
            - `password`: password
        :Types:
            - `password`: `unicode`


Get password from the MUC request.

        :returntype: `unicode`


Initialize a `MucItem` object from an XML node.

        :Parameters:
            - `xmlnode`: the XML node.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`


Get a list of objects describing the content of `self`.

        :return: the list of objects.
        :returntype: `list` of `MucItemBase` (`MucItem` and/or `MucStatus`)


Add an item to `self`.

        :Parameters:
            - `item`: the item to add.
        :Types:
            - `item`: `MucItemBase`


Get the MUC specific payload element.

        :return: the object describing the stanza payload in MUC namespace.
        :returntype: `MucX` or `MucUserX` or `MucAdminQuery` or `MucOwnerX`


Make the presence stanza a MUC room join request.

        :Parameters:
            - `password`: password to the room.
            - `history_maxchars`: limit of the total number of characters in
              history.
            - `history_maxstanzas`: limit of the total number of messages in
              history.
            - `history_seconds`: send only messages received in the last
              `seconds` seconds.
            - `history_since`: Send only the messages received since the
              dateTime specified (UTC).
        :Types:
            - `password`: `unicode`
            - `history_maxchars`: `int`
            - `history_maxstanzas`: `int`
            - `history_seconds`: `int`
            - `history_since`: `datetime.datetime`


Make the iq stanza a MUC room participant kick request.

        :Parameters:
            - `nick`: nickname of user to kick.
            - `reason`: reason of the kick.
        :Types:
            - `nick`: `unicode`
            - `reason`: `unicode`

        :return: object describing the kick request details.
        :returntype: `MucItem`


Modify stringprep cache size.

    :Parameters:
        - `size`: new cache size


Mapping part of string preparation.


Checks for prohibited characters.


Checks for unassigned character codes.


Decorator for glib callback methods of GLibMainLoop used to store the
    exception raised.


Timeout callback called to try prepare an IOHandler again.


Call the timeout handler due.


Stops the loop after the time specified in the `loop` call.


Creates Iq, Message or Presence object for XML stanza `element`

    :Parameters:
        - `element`: the stanza XML element
        - `return_path`: object through which responses to this stanza should
          be sent (will be weakly referenced by the stanza object).
        - `language`: default language for the stanza
    :Types:
        - `element`: :etree:`ElementTree.Element`
        - `return_path`: `StanzaRoute`
        - `language`: `unicode`


Examines out the response returned by a stanza handler and sends all
        stanzas provided.

        :Parameters:
            - `response`: the response to process. `None` or `False` means 'not
              handled'. `True` means 'handled'. Stanza or stanza list means
              handled with the stanzas to send back
        :Types:
            - `response`: `bool` or `Stanza` or iterable of `Stanza`

        :Returns:
            - `True`: if `response` is `Stanza`, iterable or `True` (meaning
              the stanza was processed).
            - `False`: when `response` is `False` or `None`

        :returntype: `bool`


Process IQ stanza of type 'response' or 'error'.

        :Parameters:
            - `stanza`: the stanza received
        :Types:
            - `stanza`: `Iq`

        If a matching handler is available pass the stanza to it.  Otherwise
        ignore it if it is "error" or "result" stanza or return
        "feature-not-implemented" error if it is "get" or "set".


Process IQ stanza received.

        :Parameters:
            - `stanza`: the stanza received
        :Types:
            - `stanza`: `Iq`

        If a matching handler is available pass the stanza to it.  Otherwise
        ignore it if it is "error" or "result" stanza or return
        "feature-not-implemented" error if it is "get" or "set".


Process stanza not addressed to us.

        Return "recipient-unavailable" return if it is not
        "error" nor "result" stanza.

        This method should be overriden in derived classes if they
        are supposed to handle stanzas not addressed directly to local
        stream endpoint.

        :Parameters:
            - `stanza`: presence stanza to be processed


Process stanza received from the stream.

        First "fix" the stanza with `self.fix_in_stanza()`,
        then pass it to `self.route_stanza()` if it is not directed
        to `self.me` and `self.process_all_stanzas` is not True. Otherwise
        stanza is passwd to `self.process_iq()`, `self.process_message()`
        or `self.process_presence()` appropriately.

        :Parameters:
            - `stanza`: the stanza received.

        :returns: `True` when stanza was handled


Set response handler for an IQ "get" or "set" stanza.

        This should be called before the stanza is sent.

        :Parameters:
            - `stanza`: an IQ stanza
            - `res_handler`: result handler for the stanza. Will be called
              when matching <iq type="result"/> is received. Its only
              argument will be the stanza received. The handler may return
              a stanza or list of stanzas which should be sent in response.
            - `err_handler`: error handler for the stanza. Will be called
              when matching <iq type="error"/> is received. Its only
              argument will be the stanza received. The handler may return
              a stanza or list of stanzas which should be sent in response
              but this feature should rather not be used (it is better not to
              respond to 'error' stanzas).
            - `timeout_handler`: timeout handler for the stanza. Will be called
              (with no arguments) when no matching <iq type="result"/> or <iq
              type="error"/> is received in next `timeout` seconds.
            - `timeout`: timeout value for the stanza. After that time if no
              matching <iq type="result"/> nor <iq type="error"/> stanza is
              received, then timeout_handler (if given) will be called.


Same as `set_response_handlers` but assume `self.lock` is
        acquired.


Send a stanza somwhere.

        The default implementation sends it via the `uplink` if it is defined
        or raises the `NoRouteError`.

        :Parameters:
            - `stanza`: the stanza to send.
        :Types:
            - `stanza`: `pyxmpp.stanza.Stanza`


Call the event dispatcher.

        Quit the main loop when the `QUIT` event is reached.

        :Return: `True` if `QUIT` was reached.


Create error response for any non-error message stanza.

        :Parameters:
            - `cond`: error condition name, as defined in XMPP specification.

        :return: new message stanza with the same "id" as self, "from" and
            "to" attributes swapped, type="error" and containing <error />
            element plus payload of `self`.
        :returntype: `Message`


Find a SessionHandler instance in the list and move it to the beginning.


Schedule a new XMPP c2s connection.


Gracefully disconnect from the server.


Same as `close_stream` but with the `lock` acquired.


Handle the `AuthenticatedEvent`.


Handle the `AuthorizedEvent`.


Default base client handlers factory.

        Subclasses can provide different behaviour by overriding this.

        :Return: list of handlers


Return a payload class for given element name.


Unquote quoted value from DIGEST-MD5 challenge or response.

    If `data` doesn't start or doesn't end with '"' then return it unchanged,
    remove the quotes and escape backslashes otherwise.

    :Parameters:
        - `data`: a quoted string.
    :Types:
        - `data`: `bytes`

    :return: the unquoted string.
    :returntype: `bytes`


Prepare a string for quoting for DIGEST-MD5 challenge or response.

    Don't add the quotes, only escape '"' and "\\" with backslashes.

    :Parameters:
        - `data`: a raw string.
    :Types:
        - `data`: `bytes`

    :return: `data` with '"' and "\\" escaped using "\\".
    :returntype: `bytes`


Initialize a `VCardAdr` object from and XML element.

        :Parameters:
            - `value`: field value as an XML node
        :Types:
            - `value`: `libxml2.xmlNode`


Initialize the mandatory `self.fn` from `self.n`.

        This is a workaround for buggy clients which set only one of them.


Initialize a VCard object from XML node.

        :Parameters:
            - `data`: vcard to parse.
        :Types:
            - `data`: `libxml2.xmlNode`


Get the RFC2426 representation of `self`.

        :return: the UTF-8 encoded RFC2426 representation.
        :returntype: `str`


Update current status of the item and compute time of the next
        state change.

        :return: the new state.
        :returntype: :std:`datetime`


Remove the fetcher from cache and mark it not active.


Handle a successfull retrieval and call apriopriate handler.

        Should be called when retrieval succeeds.

        Do nothing when the fetcher is not active any more (after
        one of handlers was already called).

        :Parameters:
            - `value`: fetched object.
            - `state`: initial state of the object.
        :Types:
            - `value`: any
            - `state`: `str`


Handle a retrieval error and call apriopriate handler.

        Should be called when retrieval fails.

        Do nothing when the fetcher is not active any more (after
        one of handlers was already called).

        :Parameters:
            - `error_data`: additional information about the error (e.g. `StanzaError` instance).
        :Types:
            - `error_data`: fetcher dependant


Handle fetcher timeout and call apriopriate handler.

        Is called by the cache object and should _not_ be called by fetcher or
        application.

        Do nothing when the fetcher is not active any more (after
        one of handlers was already called).


Check if a backup item is available in cache and call
        the item handler if it is.

        :return: `True` if backup item was found.
        :returntype: `bool`


Get an item from the cache.

        :Parameters:
            - `address`: its address.
            - `state`: the worst state that is acceptable.
        :Types:
            - `address`: any hashable
            - `state`: `str`

        :return: the item or `None` if it was not found.
        :returntype: `CacheItem`


Update state of an item in the cache.

        Update item's state and remove the item from the cache
        if its new state is 'purged'

        :Parameters:
            - `item`: item to update.
        :Types:
            - `item`: `CacheItem`

        :return: new state of the item.
        :returntype: `str`


Remove purged and overlimit items from the cache.

        TODO: optimize somehow.

        Leave no more than 75% of `self.max_items` items in the cache.


Remove a running fetcher from the list of active fetchers.

        :Parameters:
            - `fetcher`: fetcher instance.
        :Types:
            - `fetcher`: `CacheFetcher`


Set the fetcher class.

        :Parameters:
            - `fetcher_class`: the fetcher class.
        :Types:
            - `fetcher_class`: `CacheFetcher` based class


Register a fetcher class for an object class.

        :Parameters:
            - `object_class`: class to be retrieved by the fetcher.
            - `fetcher_class`: the fetcher class.
        :Types:
            - `object_class`: `classobj`
            - `fetcher_class`: `CacheFetcher` based class


Unregister a fetcher class for an object class.

        :Parameters:
            - `object_class`: class retrieved by the fetcher.
        :Types:
            - `object_class`: `classobj`


Add a client authenticator class to `SERVER_MECHANISMS_D`,
    `SERVER_MECHANISMS` and, optionally, to `SECURE_SERVER_MECHANISMS`


Class decorator generator for `ClientAuthenticator` or
    `ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl
    mechanism registry.

    :Parameters:
        - `name`: SASL mechanism name
        - `secure`: if the mechanims can be considered secure - `True`
          if it can be used over plain-text channel
        - `preference`: mechanism preference level (the higher the better)
    :Types:
        - `name`: `unicode`
        - `secure`: `bool`
        - `preference`: `int`


Send session esteblishment request if the feature was advertised by
        the server.


Convert ASN.1 string to a Unicode string.


Get human-readable subject name derived from the SubjectName
        or SubjectAltName field.


Verify certificate for a server.

        :Parameters:
            - `server_name`: name of the server presenting the cerificate
            - `srv_type`: service type requested, as used in the SRV record
        :Types:
            - `server_name`: `unicode` or `JID`
            - `srv_type`: `unicode`

        :Return: `True` if the certificate is valid for given name, `False`
        otherwise.


Return `True` if jid is listed in the certificate commonName.

        :Parameters:
            - `jid`: JID requested (domain part only)
        :Types:
            - `jid`: `JID`

        :Returntype: `bool`


Check if the cerificate is valid for given domain-only JID
        and a service type.

        :Parameters:
            - `jid`: JID requested (domain part only)
            - `srv_type`: service type, e.g. 'xmpp-client'
        :Types:
            - `jid`: `JID`
            - `srv_type`: `unicode`
        :Returntype: `bool`


Verify certificate for a client.

        Please note that `client_jid` is only a hint to choose from the names,
        other JID may be returned if `client_jid` is not included in the
        certificate.

        :Parameters:
            - `client_jid`: client name requested. May be `None` to allow
              any name in one of the `domains`.
            - `domains`: list of domains we can handle.
        :Types:
            - `client_jid`: `JID`
            - `domains`: `list` of `unicode`

        :Return: one of the jids in the certificate or `None` is no authorized
        name is found.


Load certificate data from an SSL socket.


Get certificate data from an SSL socket.


Decode DER-encoded certificate.

        :Parameters:
            - `data`: the encoded certificate
        :Types:
            - `data`: `bytes`

        :Return: decoded certificate data
        :Returntype: ASN1CertificateData


Load data from a ASN.1 subject.


Load data from a ASN.1 validity value.


Load SubjectAltName from a ASN.1 GeneralNames value.

        :Values:
            - `alt_names`: the SubjectAltNama extension value
        :Types:
            - `alt_name`: `GeneralNames`


Request client connection and start the main loop.


Add a handler object.

        :Parameters:
            - `handler`: the object providing event handler methods
        :Types:
            - `handler`: `EventHandler`


Remove a handler object.

        :Parameters:
            - `handler`: the object to remove


Read all events currently in the queue and dispatch them to the
        handlers unless `dispatch` is `False`.

        Note: If the queue contains `QUIT` the events after it won't be
        removed.

        :Parameters:
            - `dispatch`: if the events should be handled (`True`) or ignored
              (`False`)

        :Return: `QUIT` if the `QUIT` event was reached.


Make a response for the first challenge from the server.

        :return: the response or a failure indicator.
        :returntype: `sasl.Response` or `sasl.Failure`


Process the second challenge from the server and return the
        response.

        :Parameters:
            - `challenge`: the challenge from server.
        :Types:
            - `challenge`: `bytes`

        :return: the response or a failure indicator.
        :returntype: `sasl.Response` or `sasl.Failure`


Decorating attaching a feature URI (for Service Discovery or Capability
    to a XMPPFeatureHandler class.


Class decorator generator for decorationg
    `StanzaPayload` subclasses.

    :Parameters:
        - `element_name`: XML element qname handled by the class
    :Types:
        - `element_name`: `unicode`


Method decorator generator for decorating stream element
    handler methods in `StreamFeatureHandler` subclasses.

    :Parameters:
        - `element_name`: stream element QName
        - `usage_restriction`: optional usage restriction: "initiator" or
          "receiver"
    :Types:
        - `element_name`: `unicode`
        - `usage_restriction`: `unicode`


Create a new `Option` object from an XML element.

        :Parameters:
            - `xmlnode`: the XML element.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`

        :return: the object created.
        :returntype: `Option`


Add an option for the field.

        :Parameters:
            - `value`: option values.
            - `label`: option label (human-readable description).
        :Types:
            - `value`: `list` of `unicode`
            - `label`: `unicode`


Create a new `Field` object from an XML element.

        :Parameters:
            - `xmlnode`: the XML element.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`

        :return: the object created.
        :returntype: `Field`


Add a field to the item.

        :Parameters:
            - `name`: field name.
            - `values`: raw field values. Not to be used together with `value`.
            - `field_type`: field type.
            - `label`: field label.
            - `options`: optional values for the field.
            - `required`: `True` if the field is required.
            - `desc`: natural-language description of the field.
            - `value`: field value or values in a field_type-specific type. May be used only
              if `values` parameter is not provided.
        :Types:
            - `name`: `unicode`
            - `values`: `list` of `unicode`
            - `field_type`: `str`
            - `label`: `unicode`
            - `options`: `list` of `Option`
            - `required`: `bool`
            - `desc`: `unicode`
            - `value`: `bool` for "boolean" field, `JID` for "jid-single", `list` of `JID`
              for "jid-multi", `list` of `unicode` for "list-multi" and "text-multi"
              and `unicode` for other field types.

        :return: the field added.
        :returntype: `Field`


Create a new `Item` object from an XML element.

        :Parameters:
            - `xmlnode`: the XML element.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`

        :return: the object created.
        :returntype: `Item`


Make a "submit" form using data in `self`.

        Remove uneeded information from the form. The information removed
        includes: title, instructions, field labels, fixed fields etc.

        :raise ValueError: when any required field has no value.

        :Parameters:
            - `keep_types`: when `True` field type information will be included
              in the result form. That is usually not needed.
        :Types:
            - `keep_types`: `bool`

        :return: the form created.
        :returntype: `Form`


Initialize a `Form` object from an XML element.

        :Parameters:
            - `xmlnode`: the XML element.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`


Register Service Discovery cache fetchers into given
    cache suite and using the stream provided.

    :Parameters:
        - `cache_suite`: the cache suite where the fetchers are to be
          registered.
        - `stream`: the stream to be used by the fetchers.
    :Types:
        - `cache_suite`: `cache.CacheSuite`
        - `stream`: `pyxmpp.stream.Stream`


Get the category of the item.

        :return: the category of the item.
        :returntype: `unicode`


Set the category of the item.

        :Parameters:
            - `category`: the new category.
        :Types:
            - `category`: `unicode`


Set the type of the item.

        :Parameters:
            - `item_type`: the new type.
        :Types:
            - `item_type`: `unicode`


Check if `self` contains an item.

        :Parameters:
            - `jid`: JID of the item.
            - `node`: node name of the item.
        :Types:
            - `jid`: `JID`
            - `node`: `libxml2.xmlNode`

        :return: `True` if the item is found in `self`.
        :returntype: `bool`


Get the features contained in `self`.

        :return: the list of features.
        :returntype: `list` of `unicode`


Check if `self` contains the named feature.

        :Parameters:
            - `var`: the feature name.
        :Types:
            - `var`: `unicode`

        :return: `True` if the feature is found in `self`.
        :returntype: `bool`


Remove a feature from `self`.

        :Parameters:
            - `var`: the feature name.
        :Types:
            - `var`: `unicode`


List the identity objects contained in `self`.

        :return: the list of identities.
        :returntype: `list` of `DiscoIdentity`


Check if the item described by `self` belongs to the given category
        and type.

        :Parameters:
            - `item_category`: the category name.
            - `item_type`: the type name. If `None` then only the category is
              checked.
        :Types:
            - `item_category`: `unicode`
            - `item_type`: `unicode`

        :return: `True` if `self` contains at least one <identity/> object with
            given type and category.
        :returntype: `bool`