text:
@testset "EBIProteins" begin

    @testset "ebiproteins" begin
        @testset "ebiproteins" begin
            res = ebiproteins(reviewed = true, keywords = "kinase", size = 1, seqLength = 813,
                              organism = "Oryza sativa subsp. indica", contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "entry")
            @test isa(body["entry"], XMLDict.XMLDictElement)
            @test haskey(body["entry"], "accession")
            @test body["entry"]["accession"][1] == "A0A075F7E9"
        end

        @testset "ebiproteins accession" begin
            accession = "P08069"
            res = ebiproteins(accession = accession, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "accession")
            @test body["accession"][1] == accession
        end

        @testset "ebiproteins interaction" begin
            accession = "P08069"
            res = ebiproteins(accession = accession, operation = "interaction", contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "upInteraction")
        end

        @testset "ebiproteins isoforms" begin
            accession = "Q9NXB0"
            res = ebiproteins(accession = accession, subset = "isoforms", contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "entry")
            @test isa(body["entry"][1], XMLDict.XMLDictElement)
            @test haskey(body["entry"][1], "accession")
            @test body["entry"][1]["accession"] == accession * "-1"
        end

        @testset "ebiproteins dbtype/dbid" begin
            dbtype = "Ensembl"
            dbid = "ENSP00000351276"
            res = ebiproteins(dbtype = dbtype, dbid = dbid, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "entry")
            @test isa(body["entry"], XMLDict.XMLDictElement)
            @test haskey(body["entry"], "accession")
            @test body["entry"]["accession"][1] == "P21802"
        end
    end

    @testset "ebifeatures" begin
        @testset "ebifeatures" begin
            types = "domain"
            res = ebifeatures(reviewed = true, types = types, keywords = "kinase", size = 1, seqLength = 813,
                              organism = "Oryza sativa subsp. indica", contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "entryFeature")
            @test isa(body["entryFeature"], XMLDict.XMLDictElement)
            @test haskey(body["entryFeature"], "accession")
            @test body["entryFeature"]["accession"] == "A0A075F7E9"
            @test haskey(body["entryFeature"], "feature")
            @test isa(body["entryFeature"]["feature"][1], XMLDict.XMLDictElement)
            @test body["entryFeature"]["feature"][1][:type] == types
        end

        @testset "ebifeatures accession" begin
            accession = "P08069"
            res = ebifeatures(accession = accession, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "accession")
            @test body["accession"] == accession
            @test haskey(body, "feature")
            @test isa(body["feature"][1], XMLDict.XMLDictElement)
        end

        @testset "ebifeatures type" begin
            type = "domain"
            res = ebifeatures(type = type, size = 1, terms = "Kinase", contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "entryFeature")
            @test isa(body["entryFeature"], XMLDict.XMLDictElement)
            @test isa(body["entryFeature"]["feature"], XMLDict.XMLDictElement)
            @test body["entryFeature"]["feature"][:type] == type
        end
    end

    @testset "ebivariation" begin
        @testset "ebivariation" begin
            res = ebivariation(omim = 104300, size = 1, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "entryFeature")
            @test isa(body["entryFeature"], XMLDict.XMLDictElement)
            @test haskey(body["entryFeature"], "accession")
            @test body["entryFeature"]["accession"] == "A0A087X152"
            @test haskey(body["entryFeature"], "feature")
            @test isa(body["entryFeature"]["feature"], XMLDict.XMLDictElement)
            @test body["entryFeature"]["feature"][:type] == "Variant"
        end

        @testset "ebivariation accession" begin
            accession = "P08069"
            res = ebivariation(accession = accession, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "accession")
            @test body["accession"] == accession
            @test haskey(body, "feature")
            @test body["feature"][1][:type] == "Variant"
        end

        @testset "ebivariation hgvs" begin
            res = ebivariation(hgvs = "NC_000017.11:g.58219213C>T", contenttype="application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "entryFeature")
            @test isa(body["entryFeature"][1], XMLDict.XMLDictElement)
            @test haskey(body["entryFeature"][1], "accession")
            @test body["entryFeature"][1]["accession"] == "A0A6Q8PG98"
            @test haskey(body["entryFeature"][1], "feature")
            @test body["entryFeature"][1]["feature"][:type] == "Variant"
        end

        @testset "ebivariation dbid" begin
            res = ebivariation(dbid = "rs121918508", contenttype="application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "entryFeature")
            @test isa(body["entryFeature"][1], XMLDict.XMLDictElement)
            @test haskey(body["entryFeature"][1], "accession")
            @test body["entryFeature"][1]["accession"] == "A0A0A0MR25"
            @test haskey(body["entryFeature"][1], "feature")
            @test body["entryFeature"][1]["feature"][1][:type] == "Variant"
        end
    end

    @testset "ebiproteomics" begin
        @testset "ebiproteomics" begin
            accession = "P08069"
            peptide = "ACTENNECCHPECLGSCSAPDNDTACVACR"
            res = ebiproteomics(accession = accession, peptide = peptide,
                                contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "entryFeature")
            @test isa(body["entryFeature"], XMLDict.XMLDictElement)
            @test haskey(body["entryFeature"], "accession")
            @test body["entryFeature"]["accession"] == accession
            @test haskey(body["entryFeature"], "feature")
            @test isa(body["entryFeature"]["feature"], XMLDict.XMLDictElement)
            @test haskey(body["entryFeature"]["feature"], "peptide")
            @test isa(body["entryFeature"]["feature"]["peptide"], XMLDict.XMLDictElement)
            @test haskey(body["entryFeature"]["feature"]["peptide"], "peptideSequence")
            @test body["entryFeature"]["feature"]["peptide"]["peptideSequence"] == peptide
        end

        @testset "ebiproteomics accession" begin
            accession = "P08069"
            res = ebiproteomics(accession = accession, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "accession")
            @test body["accession"] == accession
            @test haskey(body, "feature")
            @test haskey(body["feature"][1], "peptide")
        end
    end

    @testset "ebiantigen" begin
        @testset "ebiantigen" begin
            accession = "P08069"
            antigen_sequence = "YIVRWQRQPQDGYLYRHNYCSKDKIPIRKYADGTIDIEEVTENPKTEVCGGEKGPCCACPKTEAEKQAEKEEA"
            res = ebiantigen(accession = accession, antigen_sequence = antigen_sequence,
                             contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "entryFeature")
            @test isa(body["entryFeature"], XMLDict.XMLDictElement)
            @test haskey(body["entryFeature"], "accession")
            @test body["entryFeature"]["accession"] == accession
            @test haskey(body["entryFeature"], "feature")
            @test isa(body["entryFeature"]["feature"], XMLDict.XMLDictElement)
            @test haskey(body["entryFeature"]["feature"], "antigen")
            @test isa(body["entryFeature"]["feature"]["antigen"], XMLDict.XMLDictElement)
            @test haskey(body["entryFeature"]["feature"]["antigen"], "antigenSequence")
            @test body["entryFeature"]["feature"]["antigen"]["antigenSequence"] == antigen_sequence
        end

        @testset "ebiantigen accession" begin
            accession = "P08069"
            res = ebiantigen(accession = accession, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "accession")
            @test body["accession"] == accession
            @test haskey(body, "feature")
            @test haskey(body["feature"], "antigen")
        end
    end

    @testset "ebiproteomes" begin
        @testset "ebiproteomes" begin
            name = "Caenorhabditis elegans (Bristol N2)"
            res = ebiproteomes(size = 1, name = name,
                               contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "proteome")
            @test isa(body["proteome"], XMLDict.XMLDictElement)
            @test haskey(body["proteome"], "name")
            @test body["proteome"]["name"] == name
        end

        @testset "ebiproteomes upid" begin
            upid = "UP000001940"
            res = ebiproteomes(upid = upid, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, :upid)
            @test body[:upid] == upid
        end

        @testset "ebiproteomes upid proteins" begin
            upid = "UP000001940"
            res = ebiproteomes(upid = upid, operation = "proteins", reviewed = true,
                               contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, :upid)
            @test body[:upid] == upid
        end
    end

    @testset "ebigenecentric" begin
        @testset "ebigenecentric" begin
            gene = "DLK1"
            res = ebigenecentric(size = 1, gene = gene, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "canonicalGene")
            @test isa(body["canonicalGene"], XMLDict.XMLDictElement)
            @test haskey(body["canonicalGene"], "relatedGene")
            @test isa(body["canonicalGene"]["relatedGene"], XMLDict.XMLDictElement)
            @test haskey(body["canonicalGene"]["relatedGene"], :geneName)
            @test body["canonicalGene"]["relatedGene"][:geneName] == gene
        end

        @testset "ebigenecentric accession" begin
            accession = "P08069"
            res = ebigenecentric(accession = accession, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "gene")
            @test isa(body["gene"], XMLDict.XMLDictElement)
            @test haskey(body["gene"], :accession)
            @test body["gene"][:accession] == accession
        end
    end

    @testset "ebitaxonomy" begin
        @testset "ebitaxonomy ancestor" begin
            res = ebitaxonomy(operation = "ancestor", ids = "9606,9615", contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomyId")
            @test body["taxonomyId"] == "1437010"
        end

        @testset "ebitaxonomy id" begin
            ids = "9606"
            res = ebitaxonomy(operation = "id", ids = ids, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomyId")
            @test body["taxonomyId"] == ids
        end

        @testset "ebitaxonomy id node" begin
            ids = "9606"
            res = ebitaxonomy(operation = "id", ids = ids, getnode = true, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomyId")
            @test body["taxonomyId"] == ids
        end

        @testset "ebitaxonomy id parent" begin
            ids = "9606"
            res = ebitaxonomy(operation = "id", ids = ids, subset = "parent", contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomyId")
            @test body["taxonomyId"] == "9605"
        end

        @testset "ebitaxonomy id parent node" begin
            ids = "9606"
            res = ebitaxonomy(operation = "id", ids = ids, subset = "parent", getnode = true,
                              contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomyId")
            @test body["taxonomyId"] == "9605"
        end

        @testset "ebitaxonomy id children" begin
            ids = "9606"
            res = ebitaxonomy(operation = "id", ids = ids, subset = "children", contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomies")
            @test isa(body["taxonomies"], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"], "taxonomy")
            @test isa(body["taxonomies"]["taxonomy"][1], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"]["taxonomy"][1], "taxonomyId")
            @test body["taxonomies"]["taxonomy"][1]["taxonomyId"] == "741158"
        end

        @testset "ebitaxonomy id children node" begin
            ids = "9606"
            res = ebitaxonomy(operation = "id", ids = ids, subset = "children", getnode = true,
                              contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomies")
            @test isa(body["taxonomies"], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"], "taxonomy")
            @test isa(body["taxonomies"]["taxonomy"][1], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"]["taxonomy"][1], "taxonomyId")
            @test body["taxonomies"]["taxonomy"][1]["taxonomyId"] == "741158"
        end

        @testset "ebitaxonomy id siblings" begin
            ids = "9606"
            res = ebitaxonomy(operation = "id", ids = ids, subset = "siblings", contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomies")
            @test isa(body["taxonomies"], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"], "taxonomy")
            @test isa(body["taxonomies"]["taxonomy"][1], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"]["taxonomy"][1], "taxonomyId")
            @test body["taxonomies"]["taxonomy"][1]["taxonomyId"] == "1425170"
        end

        @testset "ebitaxonomy id siblings node" begin
            ids = "9606"
            res = ebitaxonomy(operation = "id", ids = ids, subset = "siblings", getnode = true,
                              contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomies")
            @test isa(body["taxonomies"], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"], "taxonomy")
            @test isa(body["taxonomies"]["taxonomy"][1], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"]["taxonomy"][1], "taxonomyId")
            @test body["taxonomies"]["taxonomy"][1]["taxonomyId"] == "1425170"
        end

        @testset "ebitaxonomy lineage" begin
            ids = "9606"
            res = ebitaxonomy(operation = "lineage", ids = ids, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomies")
            @test isa(body["taxonomies"], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"], "taxonomy")
            @test isa(body["taxonomies"]["taxonomy"][2], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"]["taxonomy"][2], "taxonomyId")
            @test body["taxonomies"]["taxonomy"][2]["taxonomyId"] == "9605"
        end

        @testset "ebitaxonomy name" begin
            ids = "Homo sapiens"
            res = ebitaxonomy(operation = "name", ids = ids, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomies")
            @test isa(body["taxonomies"], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"], "taxonomy")
            @test isa(body["taxonomies"]["taxonomy"], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"]["taxonomy"], "taxonomyId")
            @test body["taxonomies"]["taxonomy"]["taxonomyId"] == "9606"
        end

        @testset "ebitaxonomy name node" begin
            ids = "Homo sapiens"
            res = ebitaxonomy(operation = "name", ids = ids, getnode = true,
                              contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomies")
            @test isa(body["taxonomies"], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"], "taxonomy")
            @test isa(body["taxonomies"]["taxonomy"], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"]["taxonomy"], "taxonomyId")
            @test body["taxonomies"]["taxonomy"]["taxonomyId"] == "9606"
        end

        @testset "ebitaxonomy path" begin
            ids = "9606"
            res = ebitaxonomy(operation = "path", ids = ids, depth = 2, direction = "BOTTOM",
                              contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomyId")
            @test haskey(body, "children")
        end

        @testset "ebitaxonomy path node" begin
            ids = "9606"
            res = ebitaxonomy(operation = "path", ids = ids, depth = 2, direction = "BOTTOM",
                              getnode = true, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomies")
            @test isa(body["taxonomies"], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"], "taxonomy")
            @test isa(body["taxonomies"]["taxonomy"][2], XMLDict.XMLDictElement)
            @test haskey(body["taxonomies"]["taxonomy"][2], "taxonomyId")
            @test body["taxonomies"]["taxonomy"][2]["taxonomyId"] == "63221"
        end

        @testset "ebitaxonomy relationship" begin
            from = "9606"
            to = "9615"
            res = ebitaxonomy(operation = "relationship", from = "9606", to = "9615",
                              contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomyId")
            @test body["taxonomyId"] == from
            while haskey(body, "parent")
                body = body["parent"]
            end
            while haskey(body, "children")
                body = body["children"]["child"]
            end
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "taxonomyId")
            @test body["taxonomyId"] == to
        end
    end

    @testset "ebicoordinates" begin
        @testset "ebicoordinates" begin
            res = ebicoordinates(size = 1, taxid = 9606, gene = "DLK1", contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "gnEntry")
            @test isa(body["gnEntry"], XMLDict.XMLDictElement)
            @test haskey(body["gnEntry"], "accession")
            @test body["gnEntry"]["accession"] == "G3V2R7"
            @test haskey(body["gnEntry"], "gnCoordinate")
        end

        @testset "ebicoordinates accession" begin
            accession = "P08069"
            res = ebicoordinates(accession = accession, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "accession")
            @test body["accession"] == accession
            @test haskey(body, "gnCoordinate")
        end

        @testset "ebicoordinates accession pPosition" begin
            accession = "P08069"
            res = ebicoordinates(accession = accession, pPosition = 1, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "locations")
            @test haskey(body["locations"], "accession")
            @test body["locations"]["accession"] == accession
            @test haskey(body["locations"], "geneStart")
            @test body["locations"]["geneStart"] == "98649582"
        end

        @testset "ebicoordinates accession pStart pEnd" begin
            accession = "P08069"
            res = ebicoordinates(accession = accession, pStart = 1, pEnd = 10, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "locations")
            @test haskey(body["locations"], "accession")
            @test body["locations"]["accession"] == accession
            @test haskey(body["locations"], "geneEnd")
            @test body["locations"]["geneEnd"] == "98649611"
        end

        @testset "ebicoordinates dbtype dbid" begin
            dbtype = "Ensembl"
            dbid = "ENSP00000351276"
            res = ebicoordinates(dbtype = dbtype, dbid = dbid, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "gnEntry")
            @test isa(body["gnEntry"], XMLDict.XMLDictElement)
            @test haskey(body["gnEntry"], "gnCoordinate")
        end

        @testset "ebicoordinates taxonomy" begin
            locations = "98649582-98649611"
            res = ebicoordinates(taxonomy = 9606, locations = locations, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "gnEntry")
            @test isa(body["gnEntry"][1], XMLDict.XMLDictElement)
            @test haskey(body["gnEntry"][1], "gnCoordinate")
        end

        @testset "ebicoordinates taxonomy feature" begin
            locations = "98649582-98649611"
            res = ebicoordinates(taxonomy = 9606, locations = locations, getfeature = true,
                                 contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "gnEntry")
            @test isa(body["gnEntry"][1], XMLDict.XMLDictElement)
            @test haskey(body["gnEntry"][1], "gnCoordinate")
        end
    end

    @testset "ebiuniparc" begin
        @testset "ebiuniparc" begin
            sequencechecksum = "9A2813B2801A98BD"
            res = ebiuniparc(sequencechecksum = sequencechecksum, size = 1, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "entry")
            @test isa(body["entry"], XMLDict.XMLDictElement)
            @test haskey(body["entry"], "accession")
            @test body["entry"]["accession"] == "UPI00001AFE16"
        end

        @testset "ebiuniparc accession" begin
            accession = "P08069"
            res = ebiuniparc(accession = accession, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "accession")
            @test body["accession"] == "UPI000012D3EA"
        end

        @testset "ebiuniparc bestguess" begin
            res = ebiuniparc(gene = "DLK1", taxid = 9606, bestguess = true, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "accession")
            @test body["accession"] == "UPI00001AFE16"
        end

        @testset "ebiuniparc dbid" begin
            dbid = "AAC02967"
            res = ebiuniparc(dbid = dbid, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "entry")
            @test isa(body["entry"], XMLDict.XMLDictElement)
            @test haskey(body["entry"], "accession")
            @test body["entry"]["accession"] == "UPI0000000114"
        end

        @testset "ebiuniparc upid" begin
            upid = "UP000001940"
            res = ebiuniparc(upid = upid, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "entry")
            @test isa(body["entry"][1], XMLDict.XMLDictElement)
            @test haskey(body["entry"][1], "accession")
        end

        @testset "ebiuniparc sequence" begin
            sequence = "MAAFSKYLTARNTSLAGAAFLLLCLLHKRRRALGLHG"
            res = ebiuniparc(sequence = sequence, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "accession")
            @test body["accession"] == "UPI0000000114"
        end

        @testset "ebiuniparc upi" begin
            upi = "UPI0000000114"
            res = ebiuniparc(upi = upi, contenttype = "application/xml")
            @test res.status == 200
            @test startswith(Dict(res.headers)["Content-Type"], "application/xml")
            body = parse_xml(String(res.body))
            @test isa(body, XMLDict.XMLDictElement)
            @test haskey(body, "accession")
            @test body["accession"] == "UPI0000000114"
        end
    end
end

max_stars_repo_name: BioJulia/BioServices

max_issues_repo_name: BioJulia/BioServices

max_forks_repo_name: BioJulia/BioServices


text:
module TestGenerateJS

using Test
using Matte

function register_session_vars()
    Dict(
        :counter => 0
    )
end

module Server

function foo(slider)
    slider + 1
end

function bar(slider, textinput)
    "textinput $slider"
end

function baz(slider, session)
    session.counter += slider
    session.counter
end

end

@test Matte.reverse_dependency_tree(Server) == Dict("slider" => ["bar", "baz", "foo"], "textinput" => ["bar"])
@test Matte.dependency_tree(Server) == Dict("foo" => ["slider"], "bar" => ["slider", "textinput"], "baz" => ["slider"])

end

module TestUnAttachedModel

using Matte

title = "Test"

function ui()
    button("test", "Push me")
end

module Server

end

end

ext: jl


text:
ROS.@include std_msgs: Float64MultiArray
@ROS.include geometry_msgs: PoseStamped
@ROS.include sensor_msgs: Image
@ROS.include nav_msgs: Path

function testPublisher()
    ROS.init("testPub")
    nh = ROS.NodeHandle()

    pub = ROS.advertise(nh, "test_sub", ROS.std_msgs_Float64MultiArray, 1)

    robotp = ROS.geometry_msgs_PoseStamped()
    robotp.pose.position.x = 0
    robotp.pose.position.y = 0
    robotp.pose.position.z = 3
    robotp.pose.orientation.x = 0
    robotp.pose.orientation.y = 0
    robotp.pose.orientation.z = 0
    robotp.pose.orientation.w = 1

    path = ROS.nav_msgs_Path()
    path.header.stamp = ROS.now()
    path.header.frame_id = "world"
    v = []
    push!(v, robotp)
    path.poses = v
    img = ROS.sensor_msgs_Image()
    img.data = UInt8.([1,2,3,4,5])

    ROS.getNumSubscribers(pub)
    @test ROS.getTopic(pub) == "/test_sub"
    @test ! ROS.isLatched(pub)

    loop = 50
    while loop > 0
        loop -= 1
        ROS.sleep(ROS.Rate(10))
        ROS.publish(pub, ROS.std_msgs_Float64MultiArray())
        ROS.spinOnce()
    end
    ROS.shutdown(pub)
    ROS.shutdown(nh)
    println("All $(basename(@__FILE__)) tests passed.")
end


text:
using TemporalGPs: RegularInTime

@testset "regular_in_time" begin
    T = 11
    Nts = [rand(1:4) for _ in 1:T]
    xs = [randn(Nt) for Nt in Nts]
    ts = RegularSpacing(0.0, 0.3, T)
    x = RegularInTime(ts, xs)

    @test prod(size(x)) == length(collect(x))

    @test all([getindex(x, n) for n in 1:length(x)] .== collect(x))
end


text:
```
Functions and packages for visualizing structural analysis
```

# define custom colors for tension/compression
const keithBlue = colorant"#2F5597"
const keithGreen = colorant"#0D5E00"
const mitGray = colorant"#C2C0BF"
const mitRed = colorant"#A31F34"
const red2blue = cgrad([mitRed, mitGray, keithBlue])
const redBlackBlue = cgrad([mitRed, colorant"#000000", keithBlue])
const redWhiteBlue = cgrad([mitRed, colorant"#FFFFFF", keithBlue])
const blueWhiteRed = cgrad([keithBlue, colorant"#FFFFFF", mitRed])
const gray2blue = cgrad([mitGray, keithBlue])
const white2blue = cgrad([:white, keithBlue])
const caitlinBlue = colorant"#00B0F0"
const allWhite = cgrad([:white, :white])
const whiteTransparentWhite = cgrad([:white, :transparent, :white])
const transparent2white = cgrad([:transparent, :white])
# custom arrowheads for support conditions
const pin = load(joinpath(@__DIR__, "customObjects", "pinSupport.obj"))
const fix = load(joinpath(@__DIR__, "customObjects", "fixSupport.obj"))

function fixedArrow(N)
    if N == 2
        return '■'
    else
        return fix
    end
end

function pinArrow(N)
    if N == 2
        return '▲'
    else
        return pin
    end
end

# converts loads to proper position + vector for plotting
function loadConverter(structure::Structure; scaleFactor = :auto)
    loads = vcat([load.load for load in structure.loads]...)

    denom = maximum(abs.(loads))

    if scaleFactor == :auto
        lengths = [element.length for element in structure.elements]
        scaleFactor = mean(lengths) * 0.3
    end

    positions = [load.position for load in structure.loads]

    if structure.dims == 2
        loads = [load.load[1:2] ./ denom .* scaleFactor for load in structure.loads]
        return [[p[1] for p in positions], [p[2] for p in positions], [0.0 for p in positions], [l[1] for l in loads], [l[2] for l in loads], [0.0 for l in loads]]
    else
        loads = [load.load[1:3] ./ denom .* scaleFactor for load in structure.loads]
        return [[p[1] for p in positions], [p[2] for p in positions], [p[3] for p in positions], [l[1] for l in loads], [l[2] for l in loads], [l[3] for l in loads]]
    end
end

# converting supports to plottable vectors (to be optimized)
function pinDofConverter(structure::Structure)
    positions = [node.position for node in structure.nodes]
    dofs = [node.DOFS for node in structure.nodes]

    l = length(positions)

    x = Float64[]
    y = Float64[]
    z = Float64[]
    u = Float64[]
    v = Float64[]
    w = Float64[]

    if structure.dims == 2
        for i = 1:l
            if all(dofs[i])
                continue
            else
                if dofs[i][1] == false
                    push!(x, positions[i][1] - 1)
                    push!(y, positions[i][2])
                    push!(z, 0)
                    push!(u, 1)
                    push!(v, 0)
                    push!(w, 0)
                end
                if dofs[i][2] == false
                    push!(x, positions[i][1])
                    push!(y, positions[i][2] - 1)
                    push!(z, 0)
                    push!(u, 0)
                    push!(v, 1)
                    push!(w, 0)
                end
            end
        end

        return x, y, z, u, v, w
    else
        for i = 1:l
            if all(dofs[i])
                continue
            else
                if dofs[i][1] == false
                    push!(x, positions[i][1] - 1)
                    push!(y, positions[i][2])
                    push!(z, positions[i][3])
                    push!(u, 1)
                    push!(v, 0)
                    push!(w, 0)
                end
                if dofs[i][2] == false
                    push!(x, positions[i][1])
                    push!(y, positions[i][2] - 1)
                    push!(z, positions[i][3])
                    push!(u, 0)
                    push!(v, 1)
                    push!(w, 0)
                end
                if dofs[i][3] == false
                    push!(x, positions[i][1])
                    push!(y, positions[i][2])
                    push!(z, positions[i][3] - 1)
                    push!(u, 0)
                    push!(v, 0)
                    push!(w, 1)
                end
            end
        end

        return x, y, z, u, v, w
    end
end

function fixDofConverter(structure::Structure)
    positions = [node.position for node in structure.nodes]
    dofs = [node.DOFS for node in structure.nodes]

    l = length(positions)

    x = Float64[]
    y = Float64[]
    z = Float64[]
    u = Float64[]
    v = Float64[]
    w = Float64[]

    if structure.dims == 2
        for i = 1:l
            if all(dofs[i]) || length(dofs[i]) == 2
                continue
            else
                if dofs[i][3] == false
                    push!(x, positions[i][1])
                    push!(y, positions[i][2])
                    push!(z, -1)
                    push!(u, 0)
                    push!(v, 0)
                    push!(w, 1)
                end
            end
        end

        return x, y, z, u, v, w
    else
        for i = 1:l
            if all(dofs[i]) || length(dofs[i]) == 3
                continue
            else
                if dofs[i][4] == false
                    push!(x, positions[i][1] - 1)
                    push!(y, positions[i][2])
                    push!(z, positions[i][3])
                    push!(u, 1)
                    push!(v, 0)
                    push!(w, 0)
                end
                if dofs[i][5] == false
                    push!(x, positions[i][1])
                    push!(y, positions[i][2] - 1)
                    push!(z, positions[i][3])
                    push!(u, 0)
                    push!(v, 1)
                    push!(w, 0)
                end
                if dofs[i][6] == false
                    push!(x, positions[i][1])
                    push!(y, positions[i][2])
                    push!(z, positions[i][3] - 1)
                    push!(u, 0)
                    push!(v, 0)
                    push!(w, 1)
                end
            end
        end

        return x, y, z, u, v, w
    end

end

function reactionConverter(structure::Structure)
    if structure.dims == 2
        if structure.elements[1].type == :truss
            gap = 2
        else
            gap = 3
        end
        group = 1
        reactions = Vec3.([[structure.reactions[i:i+group]; 0.0] for i = 1:gap:structure.nDOFS])
    else
        if structure.elements[1].type == :truss
            gap = 3
        else
            gap = 6
        end
        group = 2
        reactions = Vec3.([structure.reactions[i:i+group] for i = 1:gap:structure.nDOFS])
    end
    reactions ./= maximum(norm.(reactions))
    reactions .*= 0.5mean([element.length for element in structure.elements])
    return reactions
end

######################

function axo(geo::Geometry;
    cmforce = redWhiteBlue,
    mode = :undisplaced,
    forces = true,
    scale = false,
    elev = pi/6,
    az = pi/4,
    lw = 2,
    lcoverride = nothing,
    bgc = :transparent,
    arrowSize = 0.15,
    res = (3000,3000))

    fig = Figure(resolution = res, backgroundcolor = bgc)

    if scale == false
        ax1 = Axis3(fig[1,1],
            backgroundcolor = bgc,
            elevation = elev,
            azimuth = az,
            aspect = :data)
        hidedecorations!(ax1)
        hidespines!(ax1)
    else
        ax1 = Axis3(fig[1,1],
            backgroundcolor = bgc,
            elevation = elev,
            azimuth = az,
            aspect = :data)
    end

    if mode == :undisplaced
        els = geo.elements
        normalizedAreas = [e.A for e in geo.structure.elements]
        normalizedAreas ./= maximum(normalizedAreas)
        thickness = lw .* normalizedAreas
        lc = - ones(geo.structure.nElements)
        cm = :grays
        cr = (-1,1)
    else
        els = geo.displacedElements
        peakforce = maximum(abs.(geo.axialForce))
        thickness = 5 .* lw .* abs.(geo.axialForce) ./ peakforce
        lc = geo.axialForce
        cm = cmforce
        cr = (-peakforce, peakforce)
    end

    # override linecolor if desired
    if !isnothing(lcoverride)
        lc = lcoverride
    end

    linesegments!(vcat(els...),
        color = lc,
        colormap = cm,
        colorrange = cr,
        linewidth = thickness)

    # arrows!(geo.pinDOFS...,
    #     arrowhead = pin,
    #     arrowcolor = (:black,0.6),
    #     arrowsize = 2 * arrowSize,
    #     linewidth = 0)

    if mode == :undisplaced && forces
        arrows!(geo.loads...,
            color = (:red, 0.5),
            arrowsize = arrowSize,
            linewidth = arrowSize / 3)
    end

    ax = Axis3(fig[2,1],
        backgroundcolor = bgc,
        elevation = 0,
        azimuth = 0,
        aspect = :data)

    hidespines!(ax)
    hidedecorations!(ax)

    linesegments!(vcat(els...),
        color = lc,
        colormap = cm,
        colorrange = cr,
        linewidth = thickness)

    # arrows!(geo.pinDOFS...,
    #     arrowhead = pin,
    #     arrowcolor = (:black,0.6),
    #     arrowsize = 2 * arrowSize,
    #     linewidth = 0)

    ax3 = Axis3(fig[2,2],
        backgroundcolor = bgc,
        elevation = 0,
        azimuth = pi/2,
        aspect = :data)

    hidedecorations!(ax3)
    hidespines!(ax3)

    linesegments!(vcat(els...),
        color = lc,
        colormap = cm,
        colorrange = cr,
        linewidth = thickness)

    # arrows!(geo.pinDOFS...,
    #     arrowhead = pin,
    #     arrowcolor = (:black,0.6),
    #     arrowsize = 2 * arrowSize,
    #     linewidth = 0)

    ax4 = Axis3(fig[1,2],
        backgroundcolor = bgc,
        elevation = pi/2,
        azimuth = pi/2,
        aspect = :data)

    hidedecorations!(ax4)
    hidespines!(ax4)

    linesegments!(vcat(els...),
        color = lc,
        colormap = cm,
        colorrange = cr,
        linewidth = thickness)

    # arrows!(geo.pinDOFS...,
    #     arrowhead = pin,
    #     arrowcolor = (:black,0.6),
    #     arrowsize = 2 * arrowSize,
    #     linewidth = 0)

    return fig
end

#######################

function structurePlot(geo::Geometry;
        res = (1200,800),
        lineSize = 2,
        lineColor = :black,
        backgroundColor = :transparent,
        colorMap = red2blue,
        nodeColor = :green,
        elementColor = :black,
        lineSizeRange = 0.1:0.1:10,
        arrowSize = 0.3,
        arrowSizeRange = 0.05:0.05:5,
        textSize = 1,
        textSizeRange = 0.1:0.1:10,
        scaleToForce = false,
        constructionPath = false)

    # Initialize
    fig, ax = scatter(geo.nodes,
        markersize = 0,
        figure = (resolution = res,
        backgroundcolor = backgroundColor),
        show_axis = false)

    # Alternative method using Axis3... provides orthographic viewmode
    # fig = Figure(resolution = res)

    # ax, nds = meshscatter(fig[1,1],
    #     geo.nodes, markersize = 0,
    #     axis = (type = Axis3, perspective = 0))
    # hidedecorations!(ax)
    # hidespines!(ax)

    # create colorrange
    colorLimit = maximum(abs.(geo.axialForce))

    # Create adjustment sliders
    lsgrid = labelslidergrid!(
        fig,
        ["Line Scale", "Arrow Scale", "Text Size"],
        [lineSizeRange, arrowSizeRange, textSizeRange];
        width = Auto(),
        # height = Auto(),
        # tellheight = false
    )

    areas = geo.areas ./ maximum(geo.areas)
    # Variables for sliders
    element_thickness = lift(s-> lineSize .* areas .* s, lsgrid.sliders[1].value)
    if scaleToForce
        displaced_thickness = lift(s -> lineSize .* abs.(geo.axialForce) ./ maximum(geo.axialForce) .* s, lsgrid.sliders[1].value)
    else
        displaced_thickness = lift(s-> 2 .* areas .* s, lsgrid.sliders[1].value)
    end
    arrow_thickness = lift(s-> s / 3, lsgrid.sliders[2].value)
    arrow_size = lift(s-> s, lsgrid.sliders[2].value)
    ts = lift(s-> 10 * s, lsgrid.sliders[3].value)

    if constructionPath
        path_thickness = lift(s -> 4 .* s, lsgrid.sliders[1].value)
    end

    # Set defaults
    set_close_to!(lsgrid.sliders[1], lineSize)
    set_close_to!(lsgrid.sliders[2], arrowSize)
    set_close_to!(lsgrid.sliders[3], textSize)

    # Add sliders
    fig[2,1] = lsgrid.layout

    # Variables for toggles
    if constructionPath
        toggles = [Toggle(fig, active = active) for active in [false, true, false, true, false]]
        labels = [Label(fig, x)  for x in ["Displaced", "Loads", "Labels", "DOFs", "Path"]]
        opposite = lift(t -> !t[], toggles[1].active)
    else
        toggles = [Toggle(fig, active = active) for active in [false, true, false, true]]
        labels = [Label(fig, x)  for x in ["Displaced", "Loads", "Labels", "DOFs"]]
        opposite = lift(t -> !t[], toggles[1].active)
    end

    # Add toggles
    fig[1,2] = grid!(hcat(toggles, labels), tellheight = false)

    # Plot features
    bars = linesegments!(vcat(geo.elements...),
        color = lineColor,
        linewidth= element_thickness,
        visible = opposite)
    loadArrows = arrows!(geo.loads...,
        color = (:red, 0.5),
        arrowsize = arrow_size,
        linewidth = arrow_thickness)
    reactionArrows = arrows!(geo.nodes .- geo.reactions, geo.reactions,
        color = keithGreen,
        arrowsize = arrow_size,
        linewidth = arrow_thickness)
    nodeLabels = text!(geo.nodeLabels, position = geo.nodes,
        align = (:center, :bottom),
        color = nodeColor,
        textsize=  ts)
    elementLabels = text!(geo.elementLabels, position = geo.midpoints,
        color = elementColor,
        textsize = ts)
    displacedShape = linesegments!(vcat(geo.displacedElements...),
        linewidth = displaced_thickness,
        color = geo.axialForce,
        colormap = colorMap,
        colorrange = (-colorLimit, colorLimit),
        visible = false)
    pinDofs = arrows!(geo.pinDOFS...,
        arrowhead = pin,
        arrowsize = arrow_size,
        arrowcolor = (:black,0.6),
        linewidth = 0)
    fixDofs = arrows!(geo.fixDOFS...,
        arrowhead = fix,
        arrowsize = arrow_size,
        arrowcolor = (:black,0.6),
        linewidth = 0)

    # plot node construction path (only relevant if assembly sequence is of interest and/or list of nodes was ordered)
    if constructionPath
        cp = vcat([geo.nodes[1]], [[geo.nodes[i], geo.nodes[i]] for i = 2:length(geo.nodes)-1]..., [geo.nodes[end]])
        path = linesegments!(cp,
            color = 0:length(cp)-1,
            colormap = gray2blue,
            linewidth = path_thickness)
        connect!(path.visible, toggles[5].active)
    end

    # Connect toggles to features
    connect!(displacedShape.visible, toggles[1].active)
    connect!(loadArrows.visible, toggles[2].active)
    connect!(reactionArrows.visible, toggles[2].active)
    connect!(nodeLabels.visible, toggles[3].active)
    connect!(elementLabels.visible, toggles[3].active)
    connect!(pinDofs.visible, toggles[4].active)
    connect!(fixDofs.visible, toggles[4].active)

    # show figure
    display(fig)
    return fig
end

# Alternative method of Geometry structure is not created
function structurePlot(structure::Structure)
    geo = Geometry(structure)
    structurePlot(geo)
end

# Plotting before analysis (useful when creating structure piece by piece to check for errors)
function prePlot(structure::Structure; lineSize = 2,
    lineColor = :black,
    lineSizeRange = 0.1:0.1:10,
    arrowSize = 0.15,
    arrowSizeRange = 0.05:0.05:5,
    textSize = 1,
    textSizeRange = 0.1:0.1:10,
    scaleToForce = false)

    # initialize geometry
    geo = Geometry(structure)

    if isdefined(structure, :loads)
        # Initialize
        fig, ax = scatter(geo.nodes,
        figure = (resolution = (1200,800),),
        show_axis = false)

        # Create adjustment sliders
        lsgrid = labelslidergrid!(
            fig,
            ["Line Scale", "Arrow Scale", "Text Size"],
            [lineSizeRange, arrowSizeRange, textSizeRange];
            width = Auto(),
            # height = Auto(),
            # tellheight = false
        )

        # Variables for sliders
        element_thickness = lift(s-> geo.areas .* s, lsgrid.sliders[1].value)
        if scaleToForce
            displaced_thickness = lift(s -> lineSize .* abs.(geo.axialForce) ./ maximum(geo.axialForce) .* s, lsgrid.sliders[1].value)
        else
            displaced_thickness = lift(s-> 2 .* geo.areas .* s, lsgrid.sliders[1].value)
        end
        arrow_thickness = lift(s-> s / 3, lsgrid.sliders[2].value)
        arrow_size = lift(s-> s, lsgrid.sliders[2].value)
        ts = lift(s-> 10 * s, lsgrid.sliders[3].value)

        # Set defaults
        set_close_to!(lsgrid.sliders[1], lineSize)
        set_close_to!(lsgrid.sliders[2], arrowSize)
        set_close_to!(lsgrid.sliders[3], textSize)

        # Add sliders
        fig[2,1] = lsgrid.layout

        # Variables for toggles
        toggles = [Toggle(fig, active = active) for active in [true, false, true]]
        labels = [Label(fig, x)  for x in ["Loads", "Labels", "DOFs"]]

        # Add toggles
        fig[1,2] = grid!(hcat(toggles, labels), tellheight = false)

        # Plot features
        bars = linesegments!(vcat(geo.elements...),
            color = lineColor,
            linewidth= element_thickness)
        loadArrows = arrows!(geo.loads...,
            color = (:red, 0.5),
            arrowsize = arrow_size,
            linewidth = arrow_thickness)
        nodeLabels = text!(geo.nodeLabels, position = geo.nodes, align = (:center, :bottom),
            color = :green,
            textsize=  ts)
        elementLabels = text!(geo.elementLabels,
            position = geo.midpoints,
            color = :black,
            textsize = ts)
        pinDofs = arrows!(geo.pinDOFS...,
            arrowhead = pin,
            arrowsize = arrow_size,
            arrowcolor = (:black, 0.8),
            linewidth = 0)
        fixDofs = arrows!(geo.fixDOFS...,
            arrowhead = fix,
            arrowsize = arrow_size,
            arrowcolor = (:black, 0.8),
            linewidth = 0)

        # Connect toggles to features
        connect!(loadArrows.visible, toggles[1].active)
        connect!(nodeLabels.visible, toggles[2].active)
        connect!(elementLabels.visible, toggles[2].active)
        connect!(pinDofs.visible, toggles[3].active)
        connect!(fixDofs.visible, toggles[3].active)

        display(fig)
    else
        # Initialize
        fig, ax = scatter(geo.nodes,
        figure = (resolution = (1200,800),),
        show_axis = false)

        # Create adjustment sliders
        lsgrid = labelslidergrid!(
            fig,
            ["Line Scale", "DOF Scale", "Text Size"],
            [lineSizeRange, arrowSizeRange, textSizeRange];
            width = Auto(),
            # height = Auto(),
            # tellheight = false
        )

        # Variables for sliders
        element_thickness = lift(s-> geo.areas .* s, lsgrid.sliders[1].value)
        arrow_size = lift(s-> s, lsgrid.sliders[2].value)
        ts = lift(s-> 10 * s, lsgrid.sliders[3].value)

        # Set defaults
        set_close_to!(lsgrid.sliders[1], lineSize)
        set_close_to!(lsgrid.sliders[2], arrowSize)
        set_close_to!(lsgrid.sliders[3], textSize)

        # Add sliders
        fig[2,1] = lsgrid.layout

        # Variables for toggles
        toggles = [Toggle(fig, active = active) for active in [false, true]]
        labels = [Label(fig, x)  for x in ["Labels", "DOFs"]]

        # Add toggles
        fig[1,2] = grid!(hcat(toggles, labels), tellheight = false)

        # Plot features
        bars = linesegments!(vcat(geo.elements...),
            color = lineColor,
            linewidth= element_thickness,
            visible = opposite)
        nodeLabels = text!(geo.nodeLabels,
            position = geo.nodes,
            align = (:center, :bottom),
            color = :green,
            textsize=  ts)
        elementLabels = text!(geo.elementLabels,
            position = geo.midpoints,
            color = :black,
            textsize = ts)
        pinDofs = arrows!(geo.pinDOFS...,
            arrowhead = pin,
            arrowsize = arrow_size,
            arrowcolor = (:black, 0.8),
            linewidth = 0)
        fixDofs = arrows!(geo.fixDOFS...,
            arrowhead = fix,
            arrowsize = arrow_size,
            arrowcolor = (:black, 0.8),
            linewidth = 0)

        # Connect toggles to features
        connect!(nodeLabels.visible, toggles[1].active)
        connect!(elementLabels.visible, toggles[1].active)
        connect!(pinDofs.visible, toggles[2].active)
        connect!(fixDofs.visible, toggles[2].active)

        display(fig)

    end
end

max_stars_repo_name: keithjlee/Asap

max_issues_repo_name: keithjlee/Asap

max_forks_repo_name: keithjlee/Asap


text:
using Compose
import Cairo, Fontconfig

imgs = [SVG("arc_sector.svg", 7cm, 7cm),
        PDF("arc_sector.pdf", 7cm, 7cm)]

a = range(-0.5π, stop=1.5π, length=13)
    colv = repeat(["white","black"], outer=6)

img = compose(context(),
    (context(), sector([0.5], [0.5], [0.4], a[1:12], a[2:13]), fill(colv)),
    (context(order=2), arc([0.5], [0.5], [0.2], [0, π], [π,0]),
            fill(["black","white"]), stroke(["white","black"]), linewidth(6pt))
    )

draw.(imgs, [img])


text:
# Copyright (c) 2014, Dreki Þórgísl <dreki@billo.systems>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#  * Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#  * Neither the name of the copyright holders nor the names of its
#    contributors may be used to endorse or promote products derived from this
#    software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
module CLI

end


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

include("model_Access.jl")
include("model_CircuitConnectionStatus.jl")
include("model_CloudError.jl")
include("model_CloudErrorBody.jl")
include("model_ExpressRouteCircuitConnection.jl")
include("model_ExpressRouteCircuitConnectionPropertiesFormat.jl")
include("model_ExpressRouteCircuitPeering.jl")
include("model_ExpressRouteCircuitPeeringConfig.jl")
include("model_ExpressRouteCircuitPeeringPropertiesFormat.jl")
include("model_ExpressRouteCircuitStats.jl")
include("model_ExpressRouteConnectionId.jl")
include("model_ExpressRoutePeeringState.jl")
include("model_ExpressRoutePeeringType.jl")
include("model_Ipv6CircuitConnectionConfig.jl")
include("model_Ipv6ExpressRouteCircuitPeeringConfig.jl")
include("model_PatchRouteFilter.jl")
include("model_PatchRouteFilterRule.jl")
include("model_PeerExpressRouteCircuitConnection.jl")
include("model_PeerExpressRouteCircuitConnectionPropertiesFormat.jl")
include("model_ProvisioningState.jl")
include("model_Resource.jl")
include("model_RouteFilter.jl")
include("model_RouteFilterListResult.jl")
include("model_RouteFilterPropertiesFormat.jl")
include("model_RouteFilterRule.jl")
include("model_RouteFilterRuleListResult.jl")
include("model_RouteFilterRulePropertiesFormat.jl")
include("model_SubResource.jl")
include("model_TagsObject.jl")


text:
# https://github.com/spencerlyon2/PlotlyJS.jl

# --------------------------------------------------------------------------------------

function _create_backend_figure(plt::Plot{PlotlyJSBackend})
    if !isplotnull() && plt[:overwrite_figure] && isa(current().o, PlotlyJS.SyncPlot)
        PlotlyJS.SyncPlot(PlotlyJS.Plot(), options = current().o.options)
    else
        PlotlyJS.plot()
    end
end

function _series_added(plt::Plot{PlotlyJSBackend}, series::Series)
    syncplot = plt.o
    pdicts = plotly_series(plt, series)
    for pdict in pdicts
        typ = pop!(pdict, :type)
        gt = PlotlyJS.GenericTrace(typ; pdict...)
        PlotlyJS.addtraces!(syncplot, gt)
    end
end

function _series_updated(plt::Plot{PlotlyJSBackend}, series::Series)
    xsym, ysym = (ispolar(series) ? (:t,:r) : (:x,:y))
    kw = KW(xsym => (series.plotattributes[:x],), ysym => (series.plotattributes[:y],))
    z = series[:z]
    if z != nothing
        kw[:z] = (isa(z,Surface) ? transpose_z(series, series[:z].surf, false) : z,)
    end
    PlotlyJS.restyle!(
        plt.o,
        findfirst(isequal(series), plt.series_list),
        kw
    )
end

# ----------------------------------------------------------------

function _update_plot_object(plt::Plot{PlotlyJSBackend})
    pdict = plotly_layout(plt)
    syncplot = plt.o
    w,h = plt[:size]
    PlotlyJS.relayout!(syncplot, pdict, width = w, height = h)
end

# ----------------------------------------------------------------

function _show(io::IO, ::MIME"text/html", plt::Plot{PlotlyJSBackend})
    if isijulia() && !_use_remote[]
        write(io, PlotlyJS.html_body(PlotlyJS.JupyterPlot(plt.o)))
    else
        show(io, MIME("text/html"), plt.o)
    end
end

function plotlyjs_save_hack(io::IO, plt::Plot{PlotlyJSBackend}, ext::String)
    tmpfn = tempname() * "." * ext
    PlotlyJS.savefig(plt.o, tmpfn)
    write(io, read(open(tmpfn)))
end
_show(io::IO, ::MIME"image/svg+xml", plt::Plot{PlotlyJSBackend}) = plotlyjs_save_hack(io, plt, "svg")
_show(io::IO, ::MIME"image/png", plt::Plot{PlotlyJSBackend}) = plotlyjs_save_hack(io, plt, "png")
_show(io::IO, ::MIME"application/pdf", plt::Plot{PlotlyJSBackend}) = plotlyjs_save_hack(io, plt, "pdf")
_show(io::IO, ::MIME"image/eps", plt::Plot{PlotlyJSBackend}) = plotlyjs_save_hack(io, plt, "eps")

function write_temp_html(plt::Plot{PlotlyJSBackend})
    filename = string(tempname(), ".html")
    savefig(plt, filename)
    filename
end

function _display(plt::Plot{PlotlyJSBackend})
    if get(ENV, "PLOTS_USE_ATOM_PLOTPANE", true) in (true, 1, "1", "true", "yes")
        display(plt.o)
    else
        standalone_html_window(plt)
    end
end

@require WebIO = "0f1e0344-ec1d-5b48-a673-e5cf874b6c29" begin
    function WebIO.render(plt::Plot{PlotlyJSBackend})
        prepare_output(plt)
        WebIO.render(plt.o)
    end
end

function closeall(::PlotlyJSBackend)
    if !isplotnull() && isa(current().o, PlotlyJS.SyncPlot)
        close(current().o)
    end
end


text:
"""
Individual representing the solution from the Pareto set.
"""
struct FrontierIndividual{F} <: ArchivedIndividual{F}
    fitness::F
    params::AbstractIndividual
    tag::Int                            # tag of the individual (e.g. gen.op. ID)
    num_fevals::Int                     # number of fitness evaluations so far
    n_restarts::Int                     # the number of method restarts so far
    timestamp::Float64                  # when archived

    FrontierIndividual{F}(fitness::F,
                   params, tag, num_fevals, n_restarts, timestamp=time()) where F =
        new{F}(fitness, params, tag, num_fevals, n_restarts, timestamp)

    FrontierIndividual(fitness::F,
                   params, tag, num_fevals, n_restarts, timestamp=time()) where F =
        new{F}(fitness, params, tag, num_fevals, n_restarts, timestamp)
end

tag(indi::FrontierIndividual) = indi.tag

"""
Individual stored in `EpsBoxArchive`.
"""
const EpsBoxFrontierIndividual{N,F<:Number} = FrontierIndividual{IndexedTupleFitness{N,F}}
const FrontierSpatialIndex{N,F<:Number} = SI.SpatialIndex{Int,N,EpsBoxFrontierIndividual{N,F}}
const FrontierRTree{N,F<:Number} = SI.RTree{Int,N,EpsBoxFrontierIndividual{N,F}}

# traits for spatial indexing
SI.mbrtrait(::Type{EpsBoxFrontierIndividual{N,F}}) where {N,F} = SI.HasMBR{SI.Rect{Int,N}}
SI.mbr(indi::EpsBoxFrontierIndividual{N,F}) where {N,F} = SI.Rect(indi.fitness.index, indi.fitness.index)
SI.idtrait(::Type{<:EpsBoxFrontierIndividual}) = SI.HasID{Int}
SI.id(indi::EpsBoxFrontierIndividual) = indi.num_fevals

EpsBoxFrontierIndividual(fitness::IndexedTupleFitness{N,F},
               params, tag, num_fevals, n_restarts, timestamp=time()) where {N,F} =
    FrontierIndividual(fitness, params, tag, num_fevals, n_restarts, timestamp)

"""
ϵ-box archive saves only the solutions that are not ϵ-box
dominated by any other solutions in the archive.

It also counts the number of candidate solutions that have been added
and how many ϵ-box progresses have been made.
"""
mutable struct EpsBoxArchive{N,F,FS<:EpsBoxDominanceFitnessScheme} <: Archive{IndexedTupleFitness{N,F},FS}
    fit_scheme::FS        # Fitness scheme used
    start_time::Float64   # Time when archive created, we use this to approximate the starting time for the opt...

    num_candidates::Int               # Number of calls to add_candidate!()
    best_front_elem::EpsBoxFrontierIndividual{N,F} # best frontier element: the candidate with the best aggregated fitness
    last_progress::Int                # when (wrt num_candidates) last ϵ-progress has occured
    last_restart::Int                 # when (wrt num_dlast) last restart has occured
    n_restarts::Int                   # the counter of the method restarts
    n_oversize_inserts::Int           # how many times the candidates were inserted into oversized archive

    max_size::Int         # maximal frontier size
    # TODO allow different frontier containers?
    # see e.g. Altwaijry & Menai "Data Structures in Multi-Objective Evolutionary Algorithms", 2012
    frontier::FrontierRTree{N,F}  # candidates along the fitness Pareto frontier

    EpsBoxArchive(fit_scheme::EpsBoxDominanceFitnessScheme{N,F};
                  max_size::Integer = 1_000_000,
                  leaf_capacity::Integer = 10,
                  branch_capacity::Integer = 10) where {N,F} =
        new{N,F,typeof(fit_scheme)}(fit_scheme, time(), 0,
                                    EpsBoxFrontierIndividual{N,F}(nafitness(fit_scheme), Individual(), 0, 0, 0, NaN), #FIXME does not respect the SearchSpace datatype
                                    0, 0, 0, 0, max_size,
                                    FrontierRTree{N,F}(leaf_capacity=leaf_capacity,
                                                       branch_capacity=branch_capacity))
end

EpsBoxArchive(fit_scheme::EpsBoxDominanceFitnessScheme, params::Parameters) =
    EpsBoxArchive(fit_scheme, max_size=params[:MaxArchiveSize],
                  leaf_capacity=params[:LeafCapacity],
                  branch_capacity=params[:BranchCapacity])

const EpsBoxArchive_DefaultParameters = ParamsDict(
    :MaxArchiveSize => 100_000,
    :LeafCapacity => 10,
    :BranchCapacity => 10
)

Base.eltype(::Type{EpsBoxArchive{N,F}}) where {N,F} = EpsBoxFrontierIndividual{N,F}

Base.length(a::EpsBoxArchive) = length(a.frontier)
Base.isempty(a::EpsBoxArchive) = isempty(a.frontier)
capacity(a::EpsBoxArchive) = a.max_size
numdims(a::EpsBoxArchive) = !isempty(a.frontier) ? length(a.frontier[1].params) : 0

"""
    pareto_frontier(a::EpsBoxArchive)

Get the iterator to the individuals on the Pareto frontier.
"""
pareto_frontier(a::EpsBoxArchive) = a.frontier

"""
    rand_front_elem(a::EpsBoxArchive)

Get random Pareto frontier element.

Returns `nothing` if frontier is empty.
"""
function rand_front_elem(a::EpsBoxArchive)
    isempty(a) && return nothing

    node = a.frontier.root
    while SI.level(node) > 1
        # descend to a random child
        node = node[rand(eachindex(SI.children(node)))]
    end
    return node[rand(eachindex(SI.children(node)))]
end

"""
    noprogress_streak(a::EpsBoxArchive, [since_restart])

Get the number of `add_candidate!()` calls since the last ϵ-progress.
If `since_restart` is specified, the number is relative to the last
restart.
"""
noprogress_streak(a::EpsBoxArchive; since_restart::Bool=false) =
    since_restart ?
        a.num_candidates - max(a.last_progress, a.last_restart) :
        a.num_candidates - a.last_progress

has_best_front_elem(a::EpsBoxArchive) = isfinite(a.best_front_elem.timestamp)
best_front_elem(a::EpsBoxArchive) = has_best_front_elem(a) ? a.best_front_elem : nothing
best_candidate(a::EpsBoxArchive) = has_best_front_elem(a) ? params(a.best_front_elem) : nothing
best_fitness(a::EpsBoxArchive) = has_best_front_elem(a) ? fitness(a.best_front_elem) : nafitness(a.fit_scheme)

function rebuild_frontier!(a::EpsBoxArchive)
    # bulk-reload R-tree (leave leaves underfilled to postpone reinserts)
    a.frontier = SI.load!(similar(a.frontier), a.frontier,
                          leaf_fill = floor(Int, a.frontier.fill_factor * SI.capacity(SI.Leaf, a.frontier)))
    return a
end

function notify!(a::EpsBoxArchive, event::Symbol)
    if event == :restart
        a.n_restarts += 1
        a.last_restart = a.num_candidates
        a.n_restarts == 1 && rebuild_frontier!(a)
    end
    return a
end

"""
    tagcounts(a::EpsBoxArchive)

Count the tags of individuals on the ϵ-box frontier.
Each restart the individual remains in the frontier discounts it by `θ`.

Returns the `tag`→`count` dictionary.
"""
function tagcounts(a::EpsBoxArchive, θ::Number = 1.0)
    (0.0 < θ <= 1.0) || throw(ArgumentError("θ ($θ) should be in (0.0, 1.0] range"))
    res = Dict{Int,Float64}()
    for indi in pareto_frontier(a)
        curtag = tag(indi)
        if curtag > 0
            curcounts = get!(res, curtag, 0.0)
            res[curtag] = curcounts+θ^(a.n_restarts-indi.n_restarts)
        end
    end
    return res
end

function add_candidate!(a::EpsBoxArchive{N,F}, cand_fitness::IndexedTupleFitness{N,F},
                        candidate, tag::Int=0, num_fevals::Int=-1) where {N,F}
    a.num_candidates += 1
    if num_fevals == -1
        num_fevals = a.num_candidates
    end
    #@debug "New fitness: $(cand_fitness.orig) agg=$(cand_fitness.agg)"
    #@debug "Params: $candidate"
    # TODO don't traverse the tree twice: some SpatialIndexing API to combine isempty() with the follow-up findfirst() call?
    if !isempty(a.frontier, DominanceCone{is_minimizing(a.fit_scheme)}(cand_fitness.index)) # candidate is dominated by frontier
        if length(a.frontier) <= a.max_size
            a.n_oversize_inserts = 0 # reset the counter since the size is ok
        end
        return a
    end
    # find the Pareto front element with exactly the same indexed fitness as the candidate
    frontix = findfirst(a.frontier, SI.Point(cand_fitness.index))
    if frontix !== nothing # found front element, no eps-progress
        front_leaf, frontel_pos = frontix
        frontel = front_leaf[frontel_pos]
        front_fitness = fitness(frontel)
        hat, index_match = hat_compare(cand_fitness, front_fitness, a.fit_scheme)
        @assert index_match # should have the same indexed fitness since that's how it was found
        if hat < 0 # new fitness dominates (but not eps-dominates) the one in archive, replace the element
            SI.children(front_leaf)[frontel_pos] = frontel =
                EpsBoxFrontierIndividual(cand_fitness, copyto!(frontel.params, candidate), tag, num_fevals, a.n_restarts)
        end
    else # eps-progress: non-dominated solution that has some eps-indices different from all current ones
        a.last_progress = a.num_candidates
        hat = -1
        # remove all dominated frontier elements, if any
        SI.subtract!(a.frontier, DominanceCone{!is_minimizing(a.fit_scheme)}(cand_fitness.index))
        #@debug "Appended non-dominated element to the frontier"
        frontel = EpsBoxFrontierIndividual(cand_fitness, copy(candidate), tag, num_fevals, a.n_restarts)
        insert!(a.frontier, frontel)
        if length(a.frontier) > a.max_size
            a.n_oversize_inserts += 1 # throw(error("Pareto frontier exceeds maximum size"))
        end
        # rebuild the frontier if it has changed significantly since the last rebuild
        if a.n_restarts > 1 && a.frontier.nelem_insertions > 3length(a.frontier)
            rebuild_frontier!(a)
        end
    end
    # check if the new candidate has better aggregate score
    if !has_best_front_elem(a) # initialize best element
        a.best_front_elem = frontel
    elseif hat < 0 # candidate replaced frontier element
        # update best_front_elem if it was replaced or if the new aggscore is better
        # NOTE: when the old best element is replaced, the new aggscore might be
        #       worse due to differences in aggscore and eps-progress metrics
        d = a.best_front_elem.fitness.agg - frontel.fitness.agg
        if  a.best_front_elem.fitness.index == frontel.fitness.index ||
           (d > zero(d) && is_minimizing(a.fit_scheme)) ||
           (d < zero(d) && !is_minimizing(a.fit_scheme))
            #@debug "New best candidate"
            a.best_front_elem = frontel
        end
    end
    if length(a.frontier) <= a.max_size
        a.n_oversize_inserts = 0 # reset the counter since the size is ok
    end
    return a
end

# actually this methods should never be called because the fitness
# is already indexes within the method
add_candidate!(a::EpsBoxArchive{N,F}, cand_fitness::NTuple{N,F},
               candidate::AbstractIndividual, tag::Int=0, num_fevals::Int=-1) where {N,F} =
    add_candidate!(a, archived_fitness(cand_fitness, a), candidate, tag, num_fevals)

# called by check_stop_condition(e::Evaluator, ctrl)
function check_stop_condition(a::EpsBoxArchive, p::OptimizationProblem, ctrl)
    if ctrl.max_steps_without_progress > 0 &&
        noprogress_streak(a, since_restart=false) > ctrl.max_steps_without_progress
        return "No epsilon-progress for more than $(ctrl.max_steps_without_progress) iterations"
    elseif a.n_oversize_inserts >= 10
        # notify that the last 10 inserts were to the oversized archive
        # that means that the ϵ quantization steps are too small
        return "Pareto frontier size ($(length(a.frontier))) exceeded maximum ($(a.max_size))"
    else
        return ""
    end
end


text:
function simplefcn(z)
    w = (z - 1)*(z - im)^2*(z + 1)^3/(z + im)
end

# Analysis parameters
xb = -2  # real part begin
xe = 2  # real part end
yb = -2  # imag part begin
ye = 2  # imag part end
r = 0.1  # initial mesh step

origcoords = rectangulardomain(complex(xb, yb), complex(xe, ye), r)

# matlab results from https://github.com/PioKow/GRPF for comparison
matlab_zroots = [-0.999999999951224 - 0.000000000028656im,
                  0.000000000253637 + 1.000000000074506im,
                  1.000000000317046 - 0.000000000062088im]

matlab_zpoles = [0.000000000380455 - 0.999999999701977im]

zroots, zpoles = grpf(simplefcn, origcoords)

@test length(zroots) == 3
@test length(zpoles) == 1

@test approxmatch(zroots, matlab_zroots)
@test approxmatch(zpoles, matlab_zpoles)

pzroots, pzpoles, quadrants, phasediffs, tess, g2f = grpf(simplefcn, origcoords, PlotData())

@test approxmatch(pzroots, matlab_zroots)
@test approxmatch(pzpoles, matlab_zpoles)

# Test with big origcoords
xb = big"-2"  # real part begin
xe = big"2"  # real part end
yb = big"-2"  # imag part begin
ye = big"2"  # imag part end
r = big"0.1"  # initial mesh step

origcoords = rectangulardomain(complex(xb, yb), complex(xe, ye), r)

bzroots, bzpoles = grpf(simplefcn, origcoords)

@test all(isa.(bzroots, Complex{BigFloat}))
@test all(isa.(bzpoles, Complex{BigFloat}))

@test approxmatch(bzroots, zroots)
@test approxmatch(bzpoles, zpoles)


text:
module AWSCorePrototype

using AWSCore

include("AWSMetadata.jl")

mutable struct RestXMLService
    name::String
    api_version::String
end

mutable struct QueryService
    name::String
    api_version::String
end

mutable struct JSONService
    name::String
    api_version::String

    json_version::String
    target::String
end

mutable struct RestJSONService
    name::String
    api_version::String
end

function (service::RestXMLService)(aws::AWSConfig, request_method::String, request_uri::String, args=[])
    return AWSCore.service_rest_xml(
        aws;
        service=service.name,
        version=service.api_version,
        verb=request_method,
        resource=request_uri,
        args=args
    )
end
(service::RestXMLService)(operation, args=[]) = service(default_aws_config(), operation, args)
(service::RestXMLService)(a...; b...) = service(a..., b)

function (service::QueryService)(aws::AWSConfig, operation, args=[])
    return AWSCore.service_query(
        aws;
        service=service.name,
        version=service.api_version,
        operation=operation,
        args=args
    )
end
(service::QueryService)(operation, args=[]) = service(default_aws_config(), operation, args)
(service::QueryService)(a...; b...) = service(a..., b)

function (service::JSONService)(aws::AWSConfig, operation, args=[])
    return AWSCore.service_json(
        aws;
        service=service.name,
        version=service.api_version,
        json_version=service.json_version,
        target=service.target,
        operation=operation,
        args=args
    )
end
(service::JSONService)(operation, args=[]) = service(default_aws_config(), operation, args)
(service::JSONService)(a...; b...) = service(a..., b)

function (service::RestJSONService)(aws::AWSConfig, request_method::String, request_uri::String, args=[])
    return AWSCore.service_rest_json(
        aws;
        service=service.name,
        version=service.api_version,
        verb=request_method,
        resource=request_uri,
        args=args
    )
end
(service::RestJSONService)(request_method::String, request_uri::String, args=[]) = service(default_aws_config(), request_method, request_uri, args)
(service::RestJSONService)(a...; b...) = service(a..., b)

end  # module AWSCorePrototype

max_stars_repo_name: nicoleepp/JuliaCloud-AWS-State

max_issues_repo_name: nicoleepp/JuliaCloud-AWS-State

max_forks_repo_name: nicoleepp/JuliaCloud-AWS-State


text:
"""
types : stores types / objects used.
	Mostly just bags of parameters for different models and different sequences with various properties we want to maintain.
"""

module types

mutable struct GremModel #MRF model.
	w1::Array{Float32, 2}
	w2::Array{Float32, 2}
	nNodes::Int
	batch_size::Int
end

mutable struct MRF_nuc #from simulated_annealing_dna_clean.
	nucs::String #no reason not to use letters
	skip_sam::Array{Int64, 1}
	skip_trn::Array{Int64, 1}
	#You should guarantee gaps are in sorted order
	gap_pos::Array{Tuple{Int64, Int64}, 1}
end

mutable struct Chromosome #another type
	path::Array{Tuple{Int64, Int64, Int64}}
	full_sequence::AbstractString
	deg_nuc::MRF_nuc
	deg_map::Dict{Int64, Int64}
	deg_trns::Int64
	deg_trne::Int64
	deg_d::AbstractString #this is direction, +/-
	deg_skip::Array{Int64}
	deg_insert::Array{Tuple{Int64, Int64}}

	mark_nuc::MRF_nuc
	mark_map::Dict{Int64, Int64}
	mark_trns::Int64
	mark_trne::Int64
	mark_d::AbstractString
	mark_skip::Array{Int64}
	mark_insert::Array{Tuple{Int64, Int64}}

	deg_prob::Float32
	mark_prob::Float32
end

mutable struct SampleNucs
	final_seq::AbstractString
	deg_trns::Int64
	deg_trne::Int64
	mark_trns::Int64
	mark_trne::Int64
	path #An array of tuples.
end

mutable struct ExtendedSampleNucs
	final_seq::AbstractString
	deg_trns::Int64
	deg_trne::Int64
	deg_d::AbstractString
	mark_trns::Int64
	mark_trne::Int64
	mark_d::AbstractString
	path #An array of tuples.
	deg_skip
	deg_insert
	mark_skip
	mark_insert
end

mutable struct ExChrome #extended chromosome.
	path::Array{Tuple{Int64, Int64, Int64}}
	full_sequence::AbstractString
	deg_nuc::Any
	deg_map::Dict{Int64, Int64}
	deg_trns::Int64
	deg_trne::Int64
	deg_d::AbstractString
	deg_skip::Array{Int64}
	deg_insert::Array{Tuple{Int64, Int64}}

	mark_nuc::Any
	mark_map::Dict{Int64, Int64}
	mark_trns::Int64
	mark_trne::Int64
	mark_d::AbstractString
	mark_skip::Array{Int64}
	mark_insert::Array{Tuple{Int64, Int64}}

	deg_prob::Float32
	deg_base_E::Float32
	deg_vec
	deg_seq::AbstractString
	deg_ull::Float32
	deg_pv_w1::Float32
	deg_pv_w2::Array{Float32, 2}

	mark_prob::Float32
	mark_base_E::Float32
	mark_vec
	mark_seq::AbstractString
	mark_ull::Float32
	mark_pv_w1::Float32
	mark_pv_w2::Array{Float32, 2}

	first_weight::Float32
end

mutable struct SaveChrome #extended chromosome in saveable form (discard matrices which are easily re-calculable)
	path::Array{Tuple{Int64, Int64, Int64}}
	full_sequence::AbstractString
	deg_nuc::Any #MRF_nuc
	deg_map::Dict{Int64, Int64}
	deg_trns::Int64
	deg_trne::Int64
	deg_d::AbstractString
	deg_skip::Array{Int64}
	deg_insert::Array{Tuple{Int64, Int64}}

	mark_nuc::Any #MRF_nuc
	mark_map::Dict{Int64, Int64}
	mark_trns::Int64
	mark_trne::Int64
	mark_d::AbstractString
	mark_skip::Array{Int64}
	mark_insert::Array{Tuple{Int64, Int64}}

	deg_prob::Float32
	deg_base_E::Float32
	#deg_vec
	deg_seq::AbstractString
	#deg_ull::Float32
	#deg_pv_w1::Float32
	#deg_pv_w2::Array{Float32, 2}

	mark_prob::Float32
	mark_base_E::Float32
	#mark_vec
	mark_seq::AbstractString
	#mark_ull::Float32
	#mark_pv_w1::Float32
	#mark_pv_w2::Array{Float32, 2}

	first_weight::Float32
end

mutable struct wholeHMM
	state_probs::Array{Float64, 2}
	insert_probs::Array{Float64, 2}
	match_probs::Array{Float64, 2}
end

end


text:
module ClangSA
    using Cxx

    # Avoid C++ side code-reuse when re-loading the package
    tok = join(rand('a':'z', 5))
    hack = """
      #undef JuliaAnalysisAction
      #undef GCChecker
      #undef GCDepth
      #undef GCDisabledAt
      #undef GCValueMap
      #undef GCValueMapTy
      #undef registerGCChecker
      #undef GCRootMap
      #undef GCRootMapTy
      #undef Helpers
      #define JuliaAnalysisAction JuliaAnalysisAction$tok
      #define GCChecker GCChecker$tok
      #define GCDepth GCDepth$tok
      #define GCDisabledAt GCDisabledAt$tok
      #define GCValueMap GCValueMap$tok
      #define GCValueMapTy GCValueMap$(tok)Ty
      #define GCRootMap GCRootMap$tok
      #define GCRootMapTy GCRootMap$(tok)Ty
      #define Helpers Helpers$(tok)
      #define registerGCChecker registerGCChecker$tok
    """
    Cxx.cxxparse(hack)

    cxx"""
        #include "clang/Tooling/Tooling.h"
        #include "clang/Tooling/CompilationDatabase.h"
        #include "clang/Frontend/FrontendActions.h"
        #include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
        #include "clang/StaticAnalyzer/Core/Checker.h"
        #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
        #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
        #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
        #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
        #include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
        #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
        #include "clang/StaticAnalyzer/Checkers/SValExplainer.h"
        #include <iostream>
    """

    # The analysis
    # N.B.: The use of cxxparse here avoids Clang's include caching
    Cxx.cxxparse(__current_compiler__, readstring(joinpath(dirname(@__FILE__), "GCChecker.cpp")))

    # Frontend Action that registers the above analysis action
    cxx"""
    class JuliaAnalysisAction : public ASTFrontendAction {
        AnalysisASTConsumer *TheConsumer;
    protected:
        std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
                                                       StringRef InFile) override;
        void ExecuteAction () override;
    };

    std::unique_ptr<ASTConsumer> JuliaAnalysisAction::CreateASTConsumer(
        CompilerInstance &CI, StringRef InFile) {
        auto Consumer = clang::ento::CreateAnalysisConsumer(CI);
        TheConsumer = Consumer.get();
        return Consumer;
    }

    namespace clang {
        namespace ento {
            void registerNoReturnFunctionChecker(CheckerManager &mgr);
        }
    }
    void JuliaAnalysisAction::ExecuteAction() {
        registerGCChecker(TheConsumer->GetCheckerManager());
        registerNoReturnFunctionChecker(TheConsumer->GetCheckerManager());
        return this->ASTFrontendAction::ExecuteAction();
    }
    """

    #=
     = TODO: Custom Frontend action that registers an AnalysisConsumer and adds
     =       the above checker.
     =#

    function loadDatabase(directory)
        icxx"""
            std::string Err;
            auto database = clang::tooling::CompilationDatabase::loadFromDirectory($directory, Err);
            if (!database)
              $:(error(unsafe_string(icxx"return Err;")));
            database.release();
        """
    end

    function julia_strings_to_cpp(strings)
        cppstrings = icxx"std::vector<std::string>{};"
        for string in strings
            icxx"$cppstrings.push_back($string);"
        end
        cppstrings
    end

    function runTool(database, sources, action; verify = false)
        cxxsources = julia_strings_to_cpp(sources)
        extra_arg1 = "-isystem"
        extra_arg2 = Cxx.getClangHeadersDir()
        failed = icxx"""
            clang::tooling::ClangTool tool(*$database, $cxxsources);
            tool.clearArgumentsAdjusters();
            tool.appendArgumentsAdjuster(clang::tooling::getClangStripOutputAdjuster());
            tool.appendArgumentsAdjuster(
                getInsertArgumentAdjuster($extra_arg2, clang::tooling::ArgumentInsertPosition::BEGIN));
            tool.appendArgumentsAdjuster(
                getInsertArgumentAdjuster($extra_arg1, clang::tooling::ArgumentInsertPosition::BEGIN));
            std::vector<std::string> args{"--analyze","-Xanalyzer","-analyzer-output=text","--analyzer-no-default-checks","-Xanalyzer","-fcolor-diagnostics"};
            tool.appendArgumentsAdjuster(
                getInsertArgumentAdjuster(args, clang::tooling::ArgumentInsertPosition::BEGIN));
            if ($verify) {
                std::vector<std::string> more_args{"-Xanalyzer","-verify"};
                tool.appendArgumentsAdjuster(
                    getInsertArgumentAdjuster(more_args, clang::tooling::ArgumentInsertPosition::END));
            }
            tool.run($action);
        """
        (failed == 1) && error("Processing failed")
    end

    function createFixedCompileDatabase(directory, cmd_args)
        args = julia_strings_to_cpp(cmd_args)
        icxx"new clang::tooling::FixedCompilationDatabase($directory,$args);"
    end

    function getAnalysisAction()
        icxx"clang::tooling::newFrontendActionFactory<JuliaAnalysisAction>().release();"
    end

end # module


text:
#=
# Quasi-1D flow in a converging-diverging nozzle
In this notebook we will explore the flow in a converging-diverging nozzle.
The objective of this notebook is to explore the effect of *back pressure*
relative to the upstream stagnation pressure.
=#

# ### Set up the module
using Gasdynamics1D
#-
using Plots

#=
### Set up a nozzle
First, we will set up a nozzle. For this, we will create a representative
nozzle shape: a bell-shaped converging inlet and a slowly increasing diverging
section. We set the inlet area, the throat area, and the exit area:
=#
Ai = Area(100u"cm^2")
At = Area(30u"cm^2")
Ae = Area(60u"cm^2")
noz = Nozzle(Ai,At,Ae)

# Let's plot this nozzle to see its shape
nozzleplot(noz)

#=
### Create a flow through the nozzle
Let's set the conditions to create a flow through this nozzle. We need
to set the stagnation conditions upstream of the nozzle. We will use stagnation
pressure and temperature.
=#
p0 = StagnationPressure(700u"kPa")
T0 = StagnationTemperature(30u"°C")

#=
We also need a back pressure, outside of the nozzle exit. Let's try setting it
to 660 kPa, a little bit below the stagnation pressure
=#
pb = Pressure(660u"kPa")

#=
Now we have enough information to solve this flow. Let's plot it. We
need to specify which quantities we wish to show. We will show pressure
and Mach number. We could also show temperature and density.

The plot below shows that the pressure reaches a minimum in the throat
and the Mach number reaches a maximum there. However, it does not quite
get to sonic conditions.
=#
nozzleplot(noz,pb,p0,T0,fields=("pressure","machnumber"))

# One note on the last plots: We could have specified the gas, but it defaults to air.

#=
### Lowering the back pressure
What happens if we lower the back pressure further? Let's try this.
For several back pressures, we get a *shock* in the diverging section.
As back pressure gets smaller, this shock appears closer to the exit.
Finally, the shock leaves the nozzle entirely.
=#
nozzleplot(noz,Pressure(660u"kPa"),p0,T0,fields=("pressure","mach"))
nozzleplot!(noz,Pressure(600u"kPa"),p0,T0,fields=("pressure","mach"))
nozzleplot!(noz,Pressure(500u"kPa"),p0,T0,fields=("pressure","mach"))
nozzleplot!(noz,Pressure(400u"kPa"),p0,T0,fields=("pressure","mach"))
nozzleplot!(noz,Pressure(360u"kPa"),p0,T0,fields=("pressure","mach"))
nozzleplot!(noz,Pressure(300u"kPa"),p0,T0,fields=("pressure","mach"))

#=
### Mass flow rate
What is the mass flow rate through the nozzle? Let's inspect this value
for a few back pressures. First, the case with 660 kPa:
=#
nozproc = NozzleProcess(noz,Pressure(660u"kPa"),p0,T0)
massflowrate(nozproc)

# Now with 600 kPa
nozproc = NozzleProcess(noz,Pressure(600u"kPa"),p0,T0)
massflowrate(nozproc)

# And now with 500 kPa
nozproc = NozzleProcess(noz,Pressure(500u"kPa"),p0,T0)
massflowrate(nozproc)

#=
Notice that the mass flow rate is stuck. No matter how much we
lower the back pressure, we cannot increase the mass flow rate.
The flow is *choked*.
=#

#=
We can classify the type of flow with the `flow_quality` function:
=#
nozproc = NozzleProcess(noz,Pressure(600u"kPa"),p0,T0)
flow_quality(nozproc)
# There is a normal shock in the diverging section
nozproc = NozzleProcess(noz,Pressure(100u"kPa"),p0,T0)
flow_quality(nozproc)
# This is over-expanded: the exit pressure is too small and the flow needs to pass
# through shocks outside the nozzle to get up to the back pressure.
nozproc = NozzleProcess(noz,Pressure(60u"kPa"),p0,T0)
flow_quality(nozproc)
# This is under-expanded: the exit pressure is not low enough and the flow needs
# to pass through an *expansion fan* outside the nozzle to lower its pressure
# further to get down to the back pressure.

#=
When we seek to generate a supersonic exit flow, as is often the case,
then our goal is to design it so that the flow is *perfectly expanded*.
We can find the required back pressure easily, using isentropic relations:
=#
Ae = nozzleexit(noz)
Astar = throat(noz)
pb = Pressure(SupersonicPOverP0(Ae,Astar,Isentropic)*p0)


text:
__precompile__()

module FunctionalDataUtils

LOGFILE = ""
LOGTOFILE = false

function __init__()
    global LOGFILE
    LOGFILE = joinpath(pwd(), "julia.log")
end

FDU = FunctionalDataUtils
export FDU

using Reexport
import FunctionalData.apply
@reexport using FunctionalData, Colors
using SHA, Compat
import FactCheck

isinstalled(a) = isa(Pkg.installed(a), VersionNumber)
if isinstalled("Images")
    import Images: AbstractImage, raw, grayim, colorim
end

include("computing.jl")
include("numerical.jl")
include("computervision.jl")
include("fmIO.jl")
include("graphics.jl")
include("machinelearning.jl")
# include("matlab.jl")
include("numerical.jl")
include("output.jl")
include("utils.jl")
include("system.jl")
include("sampler.jl")

end # module


text:
using PGFPlots

x = [1., 3., 4.5]
y = [1.5, 3., 1.]
r = 2
pts = Plots.Scatter(x, y, markSize=3);
c1 = Plots.Circle(x[1], y[1], r, style="black,very thick");
c2 = Plots.Circle(x[2], y[2], r, style="black,very thick");
c3 = Plots.Circle(x[3], y[3], r, style="black,very thick");
tri = Plots.Patch2D(hcat(x,y)', style="fill, fill opacity=0.3, draw opacity=0");
a = Axis([pts, c1, c2, c3, tri], xmin=-10,ymin=-10,xmax=10,ymax=10, hideAxis=true, width="7in", height="7in")
save("ceck.pdf", a)