Remove xdmp:log line

Remove xdmp:log line

(:
  Copyright 2012-2018 MarkLogic Corporation

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
:)
xquery version "1.0-ml";

module namespace hent = "http://marklogic.com/data-hub/hub-entities";

import module namespace es = "http://marklogic.com/entity-services"
  at "/MarkLogic/entity-services/entity-services.xqy";

declare namespace search = "http://marklogic.com/appservices/search";

declare variable $ENTITY-MODEL-COLLECTION := "http://marklogic.com/entity-services/models";

declare option xdmp:mapping "false";

declare function hent:get-model($entity-name as xs:string)
{
  hent:get-model($entity-name, ())
};

declare function hent:get-model($entity-name as xs:string, $used-models as xs:string*)
{
  let $model := fn:collection($ENTITY-MODEL-COLLECTION)[info/title = $entity-name]
  where fn:exists($model)
  return
    let $model-map as map:map? := $model
    let $refs := $model//*[fn:local-name(.) = '$ref'][fn:starts-with(., "#/definitions")] ! fn:replace(., "#/definitions/", "")
    let $_ :=
      let $definitions := map:get($model-map, "definitions")
      for $ref in $refs[fn:not(. = $used-models)]
      let $other-model as map:map? := hent:get-model($ref, ($used-models, $entity-name))
      let $other-defs := map:get($other-model, "definitions")
      for $key in map:keys($other-defs)
      return
        map:put($definitions, $key, map:get($other-defs, $key))
    return
      $model-map
};

declare function hent:uber-model() as map:map
{
  hent:uber-model(fn:collection($ENTITY-MODEL-COLLECTION)/object-node())
};

declare function hent:uber-model($models as object-node()*) as map:map
{
  let $uber-model := map:map()
  let $definitions :=
    let $m := map:map()
    let $_ :=
      for $model as map:map in $models
      let $defs := map:get($model, "definitions")
      for $key in map:keys($defs)
      return
        map:put($m, $key, map:get($defs, $key))
    return
      map:put($uber-model, "definitions", $m)
  return
    $uber-model
};

declare function hent:wrap-duplicates(
    $duplicate-map as map:map,
    $property-name as xs:string,
    $item as element()
) as item()
{
    if (map:contains($duplicate-map, $property-name))
    then
        comment { "This item is a duplicate and is commented out so as to create a valid artifact.
",
            xdmp:quote($item),
            "
"
        }
    else (
        map:put($duplicate-map, $property-name, true()),
        $item)
};

(:
  this method doctors the output from ES
  because of https://github.com/marklogic/entity-services/issues/359
:)
declare %private function hent:fix-options($nodes as node()*)
{
  for $n in $nodes
  return
    typeswitch($n)
      case element(search:options) return
        element { fn:node-name($n) } {
          <search:constraint name="Collection">
            <search:collection/>
          </search:constraint>,
          hent:fix-options(($n/@*, $n/node()))
        }
      case element(search:additional-query) return ()
      case element(search:return-facets) return <search:return-facets>true</search:return-facets>
      case element() return
        element { fn:node-name($n) } { hent:fix-options(($n/@*, $n/node())) }
      case text() return
        fn:replace($n, "es:", "*:")
      default return $n
};

declare function hent:dump-search-options($entities as json:array)
{
  let $uber-model := hent:uber-model(json:array-values($entities) ! xdmp:to-json(.)/object-node())
  return
    (: call fix-options because of https://github.com/marklogic/entity-services/issues/359 :)
    hent:fix-options(es:search-options-generate($uber-model))
};

declare function hent:dump-pii($entities as json:array)
{
  let $uber-model := hent:uber-model(json:array-values($entities) ! xdmp:to-json(.)/object-node())
  return es:pii-generate($uber-model)
};

declare function hent:dump-indexes($entities as json:array)
{
  let $uber-model := hent:uber-model(json:array-values($entities) ! xdmp:to-json(.)/object-node())
  let $o := xdmp:from-json(es:database-properties-generate($uber-model))
  let $_ :=
    for $x in ("database-name", "schema-database", "triple-index", "collection-lexicon")
    return
      map:delete($o, $x)
  let $_ :=
    for $idx in map:get($o, "range-path-index") ! json:array-values(.)
    return
      map:put($idx, "path-expression", fn:replace(map:get($idx, "path-expression"), "es:", "*:"))
  return
    xdmp:to-json($o)
};

(:
  Copyright 2012-2018 MarkLogic Corporation

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
:)
xquery version "1.0-ml";

module namespace hent = "http://marklogic.com/data-hub/hub-entities";

import module namespace es = "http://marklogic.com/entity-services"
  at "/MarkLogic/entity-services/entity-services.xqy";

declare namespace search = "http://marklogic.com/appservices/search";

declare variable $ENTITY-MODEL-COLLECTION := "http://marklogic.com/entity-services/models";

declare option xdmp:mapping "false";

declare function hent:get-model($entity-name as xs:string)
{
  hent:get-model($entity-name, ())
};

declare function hent:get-model($entity-name as xs:string, $used-models as xs:string*)
{
  let $model := fn:collection($ENTITY-MODEL-COLLECTION)[info/title = $entity-name]
  where fn:exists($model)
  return
    let $model-map as map:map? := $model
    let $refs := $model//*[fn:local-name(.) = '$ref'][fn:starts-with(., "#/definitions")] ! fn:replace(., "#/definitions/", "")
    let $_ :=
      let $definitions := map:get($model-map, "definitions")
      for $ref in $refs[fn:not(. = $used-models)]
      let $other-model as map:map? := hent:get-model($ref, ($used-models, $entity-name))
      let $other-defs := map:get($other-model, "definitions")
      for $key in map:keys($other-defs)
      return
        map:put($definitions, $key, map:get($other-defs, $key))
    return
      $model-map
};

declare function hent:uber-model() as map:map
{
  hent:uber-model(fn:collection($ENTITY-MODEL-COLLECTION)/object-node())
};

declare function hent:uber-model($models as object-node()*) as map:map
{
  let $uber-model := map:map()
  let $definitions :=
    let $m := map:map()
    let $_ :=
      for $model as map:map in $models
      let $defs := map:get($model, "definitions")
      for $key in map:keys($defs)
      return
        map:put($m, $key, map:get($defs, $key))
    return
      map:put($uber-model, "definitions", $m)
  return
    $uber-model
};

declare function hent:wrap-duplicates(
    $duplicate-map as map:map,
    $property-name as xs:string,
    $item as element()
) as item()
{
    if (map:contains($duplicate-map, $property-name))
    then
        comment { "This item is a duplicate and is commented out so as to create a valid artifact.
",
            xdmp:quote($item),
            "
"
        }
    else (
        map:put($duplicate-map, $property-name, true()),
        $item)
};

(:
  this method doctors the output from ES
  because of https://github.com/marklogic/entity-services/issues/359
:)
declare %private function hent:fix-options($nodes as node()*)
{
  for $n in $nodes
  return
    typeswitch($n)
      case element(search:options) return
        element { fn:node-name($n) } {
          <search:constraint name="Collection">
            <search:collection/>
          </search:constraint>,
          hent:fix-options(($n/@*, $n/node()))
        }
      case element(search:additional-query) return ()
      case element(search:return-facets) return <search:return-facets>true</search:return-facets>
      case element() return
        element { fn:node-name($n) } { hent:fix-options(($n/@*, $n/node())) }
      case text() return
        fn:replace($n, "es:", "*:")
      default return $n
};

declare function hent:dump-search-options($entities as json:array)
{
  let $uber-model := hent:uber-model(json:array-values($entities) ! xdmp:to-json(.)/object-node())
  return
    (: call fix-options because of https://github.com/marklogic/entity-services/issues/359 :)
    hent:fix-options(es:search-options-generate($uber-model))
};

declare function hent:dump-pii($entities as json:array)
{
  let $uber-model := hent:uber-model(json:array-values($entities) ! xdmp:to-json(.)/object-node())
let $_ := xdmp:log(("UBER", $uber-model))
  return es:pii-generate($uber-model)
};

declare function hent:dump-indexes($entities as json:array)
{
  let $uber-model := hent:uber-model(json:array-values($entities) ! xdmp:to-json(.)/object-node())
  let $o := xdmp:from-json(es:database-properties-generate($uber-model))
  let $_ :=
    for $x in ("database-name", "schema-database", "triple-index", "collection-lexicon")
    return
      map:delete($o, $x)
  let $_ :=
    for $idx in map:get($o, "range-path-index") ! json:array-values(.)
    return
      map:put($idx, "path-expression", fn:replace(map:get($idx, "path-expression"), "es:", "*:"))
  return
    xdmp:to-json($o)
};


[bug-fix] removed syntax error in webapp/admin/setup.xqm introduced by commmenting out expressions.

svn path=/trunk/eXist/; revision=9992

xquery version "1.0";
(: $Id$ :)
(:
    Module: examples setup
:)

module namespace setup="http://exist-db.org/xquery/admin-interface/setup";

declare namespace xdb="http://exist-db.org/xquery/xmldb";
declare namespace request="http://exist-db.org/xquery/request";
declare namespace session="http://exist-db.org/xquery/session";
declare namespace util="http://exist-db.org/xquery/util";
declare namespace system="http://exist-db.org/xquery/system";

declare function setup:main() as element()
{

Examples Setup

        {
let $action := request:get-parameter("action", ()) return
		if($action) then
		                (
		                    if($action eq "Import Example Data") then
		                    (
		                        setup:importLocal()
		                    )
		                    else if($action eq "Import Files") then
		                    (
		                        setup:importFromURLs()
		                    )
		                    else
		                    (
		                        setup:report()
		                    )
		                )
		                else
		                (
		                    setup:select()
		                )

        }

};

declare function setup:importLocal() as element()+
{
    let $home := system:get-exist-home(),
    $pathSep := util:system-property("file.separator"),
    $dir := if (doc-available(concat("file:///", $home, "/exist-samples/examples.xml"))) then
        (
            concat($home, $pathSep, "exist-samples")
        )
        else if(ends-with($home, "WEB-INF")) then
        (
            concat(substring-before($home, "WEB-INF"), "samples")
        )
        else
        (
            concat($home, $pathSep, "samples")
        ),
    $webapp := if (doc-available(concat("file:///", $home, "/webapp/index.xml"))) then
        (
            concat($home, $pathSep, "webapp")
        )
        else if(ends-with($home, "WEB-INF")) then
        (
            substring-before($home, "WEB-INF")
        )
        else
        (
            concat($home, $pathSep, "webapp")
        )
    return (
                setup:create-collection("/db/system/config", "db"),
                setup:create-collection("/db/system/config/db", "shakespeare"),
                setup:store-files("/db/system/config/db/shakespeare", $dir,
                    "shakespeare/collection.xconf", "text/xml"),
                setup:create-collection("/db", "shakespeare"),
                setup:create-collection("/db/shakespeare", "plays"),
                setup:store-files("/db/shakespeare/plays", $dir,  "shakespeare/*.xml", "text/xml"),
                setup:store-files("/db/shakespeare/plays", $dir, "shakespeare/*.xsl", "text/xml"),
                setup:store-files("/db/shakespeare/plays", $dir, "shakespeare/*.css", "text/css"),
                setup:create-collection("/db", "xinclude"),
                setup:create-collection("/db/xinclude", "styles"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.xsl", "text/xml"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.xml", "text/xml"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.xq", "application/xquery"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.jpg", "image/jpeg"),
                setup:store-files("/db/xinclude/styles", $dir, "xinclude/styles/*", "text/css"),
                setup:create-collection("/db/xinclude", "scripts"),
                setup:create-collection("/db/xinclude/scripts", "syntax"),
                setup:store-files("/db/xinclude/scripts/syntax", $dir, "xinclude/scripts/syntax/*.js", "application/x-javascript"),
                setup:create-collection("/db", "library"),
                setup:store-files("/db/library", $dir, "*.rdf", "text/xml"),
                setup:create-collection("/db", "mods"),
                setup:store-files("/db/mods", $dir, "mods/*.xml", "text/xml"),
                setup:store-files("/db", $dir, "*.xml", "text/xml"),
                setup:create-collection("/db/system/config/db", "mondial"),
                setup:store-files("/db/system/config/db/mondial", $dir, "mondial.xconf", "text/xml"),
                setup:create-collection("/db", "xproc"),
                setup:create-collection("/db/xproc", "unit-test"),
                setup:create-collection("/db/xproc", "xml"),
                setup:create-collection("/db/xproc", "xslt"),
                setup:create-collection("/db/xproc", "result"),
                setup:create-collection("/db/xproc", "examples"),
                setup:create-collection("/db/xproc", "pipelines"),
                setup:store-files("/db/xproc/unit-test", $webapp, "xproc/unit-test/*.xml", "text/xml"),
                setup:store-files("/db/xproc/unit-test", $webapp, "xproc/unit-test/*.xql", "application/xquery"),
                setup:store-files("/db/xproc/unit-test", $webapp, "xproc/unit-test/*.xsl", "text/xml"),

                setup:store-files("/db/xproc/pipelines", $webapp, "xproc/pipelines/*.xml", "text/xml"),
                setup:store-files("/db/xproc/xml", $webapp, "xproc/xml/*.xml", "text/xml"),
                setup:store-files("/db/xproc/xslt", $webapp, "xproc/xml/*.xsl", "text/xml"),

                setup:store-files("/db/xproc/examples", $webapp, "xproc/examples/*.xproc", "application/xml+xproc"),
                setup:store-files("/db/xproc/examples", $webapp, "xproc/examples/*.xml", "text/xml"),

                setup:store-files("/db/xproc/examples", $webapp, "xproc/examples/*.xql", "application/xquery"),
                setup:store-files("/db/xproc", $webapp, "xproc/*.xml", "text/xml"),
                setup:store-files("/db/xproc", $webapp, "xproc/*.xql", "application/xquery") (:,

                (: Storing XForms in the db won't work right now :)

                setup:create-collection("/db", "xforms"),
                setup:store-files("/db/xforms", $webapp, "xforms/*.xml", "text/html"),
                setup:store-files("/db/xforms", $webapp, "xforms/*.xq*", "application/xquery"),
                setup:create-collection("/db/xforms", "xsltforms"),
                setup:create-collection("/db/xforms", "data"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.properties", "text/plain"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.png", "image/png"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.gif", "image/gif"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.xsl","text/xml"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.js","application/x-javascript"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.css","text/css")
                :)
    )
};

declare function setup:importFromURLs() as element()+
{
    (
        setup:report(),

Actions:

            {
                let $includeXmlad := request:get-parameter("xmlad", ()),
                $includeMondial := request:get-parameter("mondial", ()),
 				$includeLocal := request:get-parameter("local", ()) return
                (
					if($includeLocal) then
					( setup:importLocal()
					)
					else (),
                    if($includeXmlad) then
                    (
                        setup:create-collection("/db", "xmlad"),
                        setup:load-URL("/db/xmlad", xs:anyURI("http://surfnet.dl.sourceforge.net/sourceforge/xmlad/xmlad.xml"), "xmlad.xml")
                    )else (),
                    if($includeMondial) then
                    (
                        setup:create-collection("/db", "mondial"),
                        setup:load-URL("/db/mondial", xs:anyURI("http://www.dbis.informatik.uni-goettingen.de/Mondial/mondial-europe.xml"), "mondial.xml")
                    )else ()
                )
            }

    )
};

declare function setup:load-URL($collection as xs:string, $url as xs:anyURI, $docName as xs:string) as element()
{
    let $x := xdb:store($collection, $docName, $url) return

File {$docName} imported from url: {$url}

};

declare function setup:store-files($collection as xs:string, $home as xs:string, $patterns as xs:string, $mimeType as xs:string) as element()*
{
    let $stored := xdb:store-files-from-pattern($collection, $home, $patterns, $mimeType)
    for $doc in $stored return

Uploaded: {$doc}

};

declare function setup:create-collection($parent as xs:string, $name as xs:string) as element()
{
    let $col := xdb:create-collection($parent, $name) return

Created collection: {$col}

};

declare function setup:select() as element()
{
    <form action="{session:encode-url(request:get-uri())}" method="post">

eXist ships with a number of XQuery examples. Some of these
        require certain documents to be stored in the database. The XQuery examples also use some
		XML data not included with the distribution which can be downloaded by selecting
		the checkboxes below.

		<input type="checkbox" name="local" checked="true"/>
		eXist-db shipped files

        <input type="checkbox" name="xmlad"/>
        The XML Acronym Demystifier
        (approx. 384K)

        <input type="checkbox" name="mondial"/>
        The Mondial Database (Europe)
        (approx. 410K)

<input type="submit" name="action" value="Import Files"/>
        <input type="submit" name="action" value="Skip"/>

        <input type="hidden" name="panel" value="setup"/>
    </form>
};

declare function setup:report() as element()
{

Files have been loaded. You can now go to the
    examples page.

};

xquery version "1.0";
(: $Id$ :)
(:
    Module: examples setup
:)

module namespace setup="http://exist-db.org/xquery/admin-interface/setup";

declare namespace xdb="http://exist-db.org/xquery/xmldb";
declare namespace request="http://exist-db.org/xquery/request";
declare namespace session="http://exist-db.org/xquery/session";
declare namespace util="http://exist-db.org/xquery/util";
declare namespace system="http://exist-db.org/xquery/system";

declare function setup:main() as element()
{

Examples Setup

        {
let $action := request:get-parameter("action", ()) return
		if($action) then
		                (
		                    if($action eq "Import Example Data") then
		                    (
		                        setup:importLocal()
		                    )
		                    else if($action eq "Import Files") then
		                    (
		                        setup:importFromURLs()
		                    )
		                    else
		                    (
		                        setup:report()
		                    )
		                )
		                else
		                (
		                    setup:select()
		                )

        }

};

declare function setup:importLocal() as element()+
{
    let $home := system:get-exist-home(),
    $pathSep := util:system-property("file.separator"),
    $dir := if (doc-available(concat("file:///", $home, "/exist-samples/examples.xml"))) then
        (
            concat($home, $pathSep, "exist-samples")
        )
        else if(ends-with($home, "WEB-INF")) then
        (
            concat(substring-before($home, "WEB-INF"), "samples")
        )
        else
        (
            concat($home, $pathSep, "samples")
        ),
    $webapp := if (doc-available(concat("file:///", $home, "/webapp/index.xml"))) then
        (
            concat($home, $pathSep, "webapp")
        )
        else if(ends-with($home, "WEB-INF")) then
        (
            substring-before($home, "WEB-INF")
        )
        else
        (
            concat($home, $pathSep, "webapp")
        )
    return (
                setup:create-collection("/db/system/config", "db"),
                setup:create-collection("/db/system/config/db", "shakespeare"),
                setup:store-files("/db/system/config/db/shakespeare", $dir,
                    "shakespeare/collection.xconf", "text/xml"),
                setup:create-collection("/db", "shakespeare"),
                setup:create-collection("/db/shakespeare", "plays"),
                setup:store-files("/db/shakespeare/plays", $dir,  "shakespeare/*.xml", "text/xml"),
                setup:store-files("/db/shakespeare/plays", $dir, "shakespeare/*.xsl", "text/xml"),
                setup:store-files("/db/shakespeare/plays", $dir, "shakespeare/*.css", "text/css"),
                setup:create-collection("/db", "xinclude"),
                setup:create-collection("/db/xinclude", "styles"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.xsl", "text/xml"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.xml", "text/xml"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.xq", "application/xquery"),
                setup:store-files("/db/xinclude", $dir, "xinclude/*.jpg", "image/jpeg"),
                setup:store-files("/db/xinclude/styles", $dir, "xinclude/styles/*", "text/css"),
                setup:create-collection("/db/xinclude", "scripts"),
                setup:create-collection("/db/xinclude/scripts", "syntax"),
                setup:store-files("/db/xinclude/scripts/syntax", $dir, "xinclude/scripts/syntax/*.js", "application/x-javascript"),
                setup:create-collection("/db", "library"),
                setup:store-files("/db/library", $dir, "*.rdf", "text/xml"),
                setup:create-collection("/db", "mods"),
                setup:store-files("/db/mods", $dir, "mods/*.xml", "text/xml"),
                setup:store-files("/db", $dir, "*.xml", "text/xml"),
                setup:create-collection("/db/system/config/db", "mondial"),
                setup:store-files("/db/system/config/db/mondial", $dir, "mondial.xconf", "text/xml"),
                setup:create-collection("/db", "xproc"),
                setup:create-collection("/db/xproc", "unit-test"),
                setup:create-collection("/db/xproc", "xml"),
                setup:create-collection("/db/xproc", "xslt"),
                setup:create-collection("/db/xproc", "result"),
                setup:create-collection("/db/xproc", "examples"),
                setup:create-collection("/db/xproc", "pipelines"),
                setup:store-files("/db/xproc/unit-test", $webapp, "xproc/unit-test/*.xml", "text/xml"),
                setup:store-files("/db/xproc/unit-test", $webapp, "xproc/unit-test/*.xql", "application/xquery"),
                setup:store-files("/db/xproc/unit-test", $webapp, "xproc/unit-test/*.xsl", "text/xml"),

                setup:store-files("/db/xproc/pipelines", $webapp, "xproc/pipelines/*.xml", "text/xml"),
                setup:store-files("/db/xproc/xml", $webapp, "xproc/xml/*.xml", "text/xml"),
                setup:store-files("/db/xproc/xslt", $webapp, "xproc/xml/*.xsl", "text/xml"),

                setup:store-files("/db/xproc/examples", $webapp, "xproc/examples/*.xproc", "application/xml+xproc"),
                setup:store-files("/db/xproc/examples", $webapp, "xproc/examples/*.xml", "text/xml"),

                setup:store-files("/db/xproc/examples", $webapp, "xproc/examples/*.xql", "application/xquery"),
                setup:store-files("/db/xproc", $webapp, "xproc/*.xml", "text/xml"),
                setup:store-files("/db/xproc", $webapp, "xproc/*.xql", "application/xquery"),

                (: Storing XForms in the db won't work right now :)
                (:
                setup:create-collection("/db", "xforms"),
                setup:store-files("/db/xforms", $webapp, "xforms/*.xml", "text/html"),
                setup:store-files("/db/xforms", $webapp, "xforms/*.xq*", "application/xquery"),
                setup:create-collection("/db/xforms", "xsltforms"),
                setup:create-collection("/db/xforms", "data"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.properties", "text/plain"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.png", "image/png"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.gif", "image/gif"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.xsl","text/xml"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.js","application/x-javascript"),
                setup:store-files("/db/xforms/xsltforms", $webapp, "xforms/xsltforms/*.css","text/css")
                :)
    )
};

declare function setup:importFromURLs() as element()+
{
    (
        setup:report(),

Actions:

            {
                let $includeXmlad := request:get-parameter("xmlad", ()),
                $includeMondial := request:get-parameter("mondial", ()),
 				$includeLocal := request:get-parameter("local", ()) return
                (
					if($includeLocal) then
					( setup:importLocal()
					)
					else (),
                    if($includeXmlad) then
                    (
                        setup:create-collection("/db", "xmlad"),
                        setup:load-URL("/db/xmlad", xs:anyURI("http://surfnet.dl.sourceforge.net/sourceforge/xmlad/xmlad.xml"), "xmlad.xml")
                    )else (),
                    if($includeMondial) then
                    (
                        setup:create-collection("/db", "mondial"),
                        setup:load-URL("/db/mondial", xs:anyURI("http://www.dbis.informatik.uni-goettingen.de/Mondial/mondial-europe.xml"), "mondial.xml")
                    )else ()
                )
            }

    )
};

declare function setup:load-URL($collection as xs:string, $url as xs:anyURI, $docName as xs:string) as element()
{
    let $x := xdb:store($collection, $docName, $url) return

File {$docName} imported from url: {$url}

};

declare function setup:store-files($collection as xs:string, $home as xs:string, $patterns as xs:string, $mimeType as xs:string) as element()*
{
    let $stored := xdb:store-files-from-pattern($collection, $home, $patterns, $mimeType)
    for $doc in $stored return

Uploaded: {$doc}

};

declare function setup:create-collection($parent as xs:string, $name as xs:string) as element()
{
    let $col := xdb:create-collection($parent, $name) return

Created collection: {$col}

};

declare function setup:select() as element()
{
    <form action="{session:encode-url(request:get-uri())}" method="post">

eXist ships with a number of XQuery examples. Some of these
        require certain documents to be stored in the database. The XQuery examples also use some
		XML data not included with the distribution which can be downloaded by selecting
		the checkboxes below.

		<input type="checkbox" name="local" checked="true"/>
		eXist-db shipped files

        <input type="checkbox" name="xmlad"/>
        The XML Acronym Demystifier
        (approx. 384K)

        <input type="checkbox" name="mondial"/>
        The Mondial Database (Europe)
        (approx. 410K)

<input type="submit" name="action" value="Import Files"/>
        <input type="submit" name="action" value="Skip"/>

        <input type="hidden" name="panel" value="setup"/>
    </form>
};

declare function setup:report() as element()
{

Files have been loaded. You can now go to the
    examples page.

};


improved documentation of the http-cient module

(:
 : Copyright 2006-2009 The FLWOR Foundation.
 :
 : Licensed under the Apache License, Version 2.0 (the "License");
 : you may not use this file except in compliance with the License.
 : You may obtain a copy of the License at
 :
 : http://www.apache.org/licenses/LICENSE-2.0
 :
 : Unless required by applicable law or agreed to in writing, software
 : distributed under the License is distributed on an "AS IS" BASIS,
 : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 : See the License for the specific language governing permissions and
 : limitations under the License.
:)

(:~
 :

 : This module provides an implementation of the
 : EXPath Http Client.
 : It provides functions for making HTTP requests and is a superset of the
 : module specified by EXPath.
 : Specifically, it implements the http:send-request() functions
 : as specified by EXPath. Moreover, it adds an additional function
 : http:read() (with several arities for the sake of ease).
 :

 :
 :

 : In general, both functions take a description of the HTTP request to make
 : as parameter, execute the request, and return a representation of the HTTP
 : response.
 :

 :
 :

 : The http:send-request() functions are declared as sequential.
 : Sequential functions are allowed to have side effects. For example, most probably,
 : an HTTP POST request is a request that has side effects because it adds/changes
 : a remote resource. Sequential functions are specified in the
 : XQuery Scripting Extension,
 : which is an extension of XQuery.
 : Sequential functions are only allowed to be invoked in certain places (e.g.
 : only from functions which are declared as sequential themselves).
 : In contrast, the http:read() functions are not declared as sequential -
 : they are declared as nondeterministic though (see
 : XQuery 1.1), which
 : means that several calls may return different results.
 : HTTP requests performed using these functions are not allowed to have
 : side effects.
 :

 :
 :

 : For all functions (except read with one parameter),
 : the request is represented by an http:request
 : element, specifying the URI, the HTTP method, the headers, and the body
 : content (for POST and PUT methods) of the HTTP request to make.
 :

 :
 :

 : The response is returned as a sequence of one or more items. The first
 : one is an http:response element with quite the same
 : structure as an http:request, but without the content itself.
 : The content is returned as the second item (or several items in case of
 : a multipart response) as a string, a document node, or a binary item.
 : This depends on the content-type returned.
 : Specifically, the rules are as follows:
 :
 :

 :
A document node is returned if the media type has a MIME type of
 :     text/xml, application/xml, text/xml-external-parsed-entity, or
 :     application/xml-external-parsed-entity, as defined in [RFC 3023]
 :     (except that application/xml-dtd is considered a text media type).
 :     MIME types ending by +xml are also XML media types.

 :
A document node is returned if the media type has a MIME type of
 :      text/html. In order to be able to make HTML parseable, tidy is automatically
 :      invoked. If you want to prevent that, you can also set your own content-type
 :      by setting the override-media-type attribute in the request element.
 :       For tidying, the following options
 :       will be used:
 :

 :
TidyXmlOut=yes

 :
TidyDoctypeMode=TidyDoctypeOmit

 :
TidyQuoteNbsp=yes

 :
TidyCharEncoding="utf8"

 :
TidyNewline="LF"

 :

 :

 :
An xs:string item is returned if the media type has a text MIME type,
 :     i.e. beginning with text/.

 :
An xs:base64Binary item is returned for all the other media types.

 :

 :

 :
 : Simple GET Request (retrieving HTML)
 :
 :
 :

 :   http:read( "www.example.com" )
 :

 :
 :
 : returns
 :
 :
 :

 :   <response xmlns="http://expath.org/ns/http-client" status="200" message="OK">
 :     <header name="Content-Type" value="text/html; charset=UTF-8"/>
 :     <header name="Content-Length" value="574"/>
 :     ...
 :     <body media-type="text/html"/>
 :   </response>
 :   <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 :   <html>
 :     <head>
 :       <meta http-equiv="Content-Type"
 :       content="text/html; charset=utf-8" />
 :       <title>Example Web Page</title>
 :     </head>
 :     <body>
 :       <p>You have reached this web page by typing "example.com",
 :       "example.net", or "example.org" into your web browser.</p>
 :       <p>These domain names are reserved for use in documentation and are
 :       Not available for registration. See
 :       <a href="http://www.rfc-editor.org/rfc/rfc2606.txt">RFC 2606</a>,
 :       Section 3.</p>
 :     </body>
 :   </html>
 :

 :
 :
 : Simple GET Request (retrieving XHTML)
 :
 :
 :

 :   declare namespace xhtml="http://www.w3.org/1999/xhtml";
 :
 :   http:read( <http:request href="www.w3.org" method="get"/>, () )[2]//xhtml:body
 :

 :
 :
 :

 : This example shows how to retrieve an XHTML resource. Note, that the node test
 : that is looking for the body element in the result requires the xhtml
 : namespace to be specified.
 :

 :
 : Simple POST Request
 :
 :

 : Here is a simple example which sends a text content by making an HTTP POST
 : request.
 :

 :
 :
 :

 :   http:send-request(
 :      <http:request href="..." method="post">
 :         <http:body content-type="text/plain">
 :            Hello, world!
 :         </http:body>
 :      </http:request>
 :   )
 :

 :
 :
 : The response of this request can look as follows:
 :
 :

 :
 :   <http:response status="200" message="Ok">
 :      <http:header name="Content-Type" value="text/html"/>
 :      <http:header name="Server" value="Apache ..."/>
 :      ...
 :      <http:body content-type="text/html"/>
 :   </http:response>
 :
 :

 :
 :

 : The structure of a request element is defined in the schema that is imported
 : by this module. The details are described in the
 : specification.
 : Analogously, the response element is also described in this
 : specification.
 :

 :
 : @author Markus Pilman
 :)
module namespace http = "http://expath.org/ns/http-client";

import module namespace httpclientimpl = "http://expath.org/ns/httpclientimpl";
import module namespace err = "http://expath.org/ns/error";

import schema namespace https = "http://expath.org/ns/http-client";

(:~
 : This function sends an HTTP request and returns the corresponding response.
 :
 :

 : This function is declared as sequential (see XQuery Scripting).
 : Sequential functions are allowed to have side effects. For example, most probably,
 : an HTTP POST request is a request that has side effects because it adds/changes
 : a remote resource.
 :

 :
 : @param $request Contains the various parameters of the request.
 :   See the
 :   specification.
 :   for a full description of the structure of this element.
 : @param $href is the HTTP or HTTPS URI to send the request to. It must be a valid
 :  xs:anyURI, but is declared as a string to be able to pass literal strings
 :  (without requiring to explicitly cast it to an xs:anyURI.)
 : @param $content is the request body content, for HTTP methods that can
 :  contain a body in the request (i.e. POST and PUT). It is an error, if this
 :  param is not the empty sequence for methods other then DELETE, GET, HEAD
 :  and OPTIONS.
 : @return a sequence of items, where the first item is a element of type
 :  http:responseType. The response element is also described in the
 :  specification.
 :  If there is one (or several, in case of multipart) response body, the response bodies
 :  are the next items in the sequence.
 :)
declare sequential function http:send-request(
  $request as element(https:request)?,
  $href as xs:string?,
  $bodies as item()*) as item()+ {
  if (http:check-params($request, $href, $bodies))
  then
    let $req := if ($request) then http:set-content-type($request) else ()
    let $result := httpclientimpl:http-send-request-impl($req,
                                                         $href,
                                                         $bodies)
    return ($result[1], fn:subsequence($result, 2))
  else ()
};

(:~
 : Function for convenience.
 :
 : Calling this function is equivalent to calling
 :
 :
 : http:send-request($request, (), ())
 :
 :
 : @see documentation of send-request with three parameters.
 :
 : @param $request see request parameter of the sequential
 :  send-request function with three parameters.
 : @return see return value of the sequential
 :  send-request function with three parameters.
 :)
declare sequential function http:send-request (
  $request as element(https:request)) as item()+ {
  http:send-request($request, (), ())
};

(:~
 : Function for convenience.
 :
 : Calling this function is equivalent to calling
 :
 :
 : http:send-request($request, $href, ())
 :
 :
 : @see documentation of send-request with three parameters.
 :
 : @param $request see request parameter of the sequential
 :  send-request function with three parameters.
 : @param $href see href parameter of the sequential
 :  send-request function with three parameters.
 : @return see return of
 :  send-request
 :)
declare sequential function http:send-request(
  $request as element(https:request)?,
  $href as xs:string?) as item()+ {
  http:send-request($request, $href, ())
};

(:~
 : This function sends an HTTP request and returns the corresponding response.
 :
 :

 : This function is not sequential. It is used for retrieving resources and may only
 : be used to send requests which are known to have no side effects, i.e.,
 : usually GET or HEAD.
 :

 :
 : @param $request Contains the various parameters of the request.
 :   See the
 :   specification.
 :   for a full description of the structure of this element.
 : @param $href is the HTTP or HTTPS URI to send the request to. It must be a valid
 :  xs:anyURI, but is declared as a string to be able to pass literal strings
 :  (without requiring to explicitly cast it to an xs:anyURI.)
 : @param $bodies is the request body content, for HTTP methods that can
 :  contain a body in the request (i.e. POST and PUT). It is an error, if this
 :  param is not the empty sequence for methods other then DELETE, GET, HEAD
 :  and OPTIONS.
 : @return a sequence of items, where the first item is a element of type
 :  http:responseType. The response element is also described in the
 :  specification.
 :  If there is one (or several, in case of multipart) response body, the response bodies
 :  are the next items in the sequence.
 :)
declare function http:read(
  $request as element(https:request)?,
  $href as xs:string?,
  $bodies as item()*) as item()+ {
  if (http:check-params($request, $href, $bodies))
  then
    let $req := if ($request) then http:set-content-type($request) else ()
    let $result := httpclientimpl:http-read-impl($req, $href, $bodies)
    return ($result[1], fn:subsequence($result, 2))
  else ()
};

(:~
 : Function for convenience.
 :
 : Calling this function is equivalent to calling
 :
 :
 : http:read($request, $href, ())
 :
 :
 : @see documentation of read
 :      with three parameters.
 :
 : @param $request see parameter $request of read with three parameters
 : @param $href see parameter $href of read with three parameters
 : @return see return of read with three parameters
 :)
declare function http:read(
  $request as element(https:request)?,
  $href as xs:string?) as item()+ {
  http:read($request, $href, ())
};

(:~
 : Function for convenience.
 :
 : Calling this function is equivalent to calling
 :
 :
 : http:read((), $href, ())
 :
 :
 : @see documentation of read with three parameters.
 :
 : @param $href see parameter $href of read with three parameters
 : @return see return of read with three parameters
 :)
declare function http:read(
  $href as xs:string) as item()+ {
  http:read((), $href, ())
};

(:~
 : Helper function.
 :
 : This function takes an https:body element, copies it, and
 : adds a method attribute to the copy if there is none
 : in the original element.
 :
 : @param $body is the original https:body element
 : @return a https:body element with a corresponding @method
 :   attribute
 :)
declare function http:create-body (
  $body as element(https:body))
    as element(https:body) {
  <https:body>{$body/@*}
  {
    if ($body/@method) then
      ()
    else
      attribute method {
        if ($body/@media-type eq "text/xml" or
            $body/@media-type eq "application/xml" or
            $body/@media-type eq "text/xml-external-parsed-entity" or
            $body/@media-type eq "application/xml-external-parsed-entity") then
              "xml"
         else if ($body/@media-type eq "text/html") then "html"
         else if (fn:starts-with($body/@media-type/data(.), "text/")) then "text"
         else "binary"
      }
  }
  {$body/node()}
  </https:body>
};

(:~
 : Helper function.
 :
 : This function takes an https:multipart element, copies it and
 : adds a @method attribute to all body elements which don't have
 : one.
 :
 : @param $multipart the original https:multipart
 : @return a copy of $multipart with all $multipart/body/@method set
 :)
declare function http:create-multipart (
  $multipart as element(https:multipart))
    as element(https:multipart) {
    <https:multipart>{$multipart/@*}
    {
    for $x in $multipart/node()
    return
      typeswitch($x)
        case element(https:body) return http:create-body($x)
        default return $x
    }
    </https:multipart>
};

(:~
 : Helper function.
 :
 : This adds a default method attribute to all body elements which
 : don't contain a method attribute.
 :
 : @param $request The request which need to be copied.
 : @return A copy of $request with all request//body/@method set.
 :)
declare function http:set-content-type(
  $request as element(https:request)?)
    as element(https:request)? {
  if ($request) then
    <http:request>{$request/@*}
    {
    for $x in $request/node()
    return
      typeswitch($x)
        case element(https:body) return http:create-body($x)
        case element(https:multipart) return http:create-multipart($x)
        default return $x
    }
    </http:request>
  else ()
};

(:~
 : Private helper function used internally by this module.
 :
 : This function checks if the request, href, and bodies parameters
 : are consistent.
 :
 : @param $request The request which needs to be checked.
 : @param $href The href which needs to be checked.
 : @param $bodies The bodies element which needs to be checked.
 : @return true if the parameters are consistent. Otherwise,
 :         this function raises an error.
 :)
declare function http:check-params(
  $request as element(https:request)?,
  $href as xs:string?,
  $bodies as item()*) as xs:boolean {
  if (fn:empty($href) and fn:empty($request)) then
    fn:error($err:HCV01, "Not all required arguments are set.")
  else if ($href eq "") then
    fn:error($err:HCV01,
      "The href value is set to the empty string")
  else if (not(count($request//body[not(exists(node()))]) eq count($bodies))) then
    fn:error($err:HCV01,
      "The number of bodies without children is not equal the size of the bodies sequence")
  else
    fn:true()
};

(:
 : Copyright 2006-2009 The FLWOR Foundation.
 :
 : Licensed under the Apache License, Version 2.0 (the "License");
 : you may not use this file except in compliance with the License.
 : You may obtain a copy of the License at
 :
 : http://www.apache.org/licenses/LICENSE-2.0
 :
 : Unless required by applicable law or agreed to in writing, software
 : distributed under the License is distributed on an "AS IS" BASIS,
 : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 : See the License for the specific language governing permissions and
 : limitations under the License.
:)

(:~
 :

 : This module provides an implementation of the
 : EXPath Http Client.
 : It provides functions for making HTTP requests and is a superset of the
 : module specified by EXPath.
 : Specifically, it implements the http:send-request() functions
 : as specified by EXPath. Moreover, it adds an additional function
 : http:read() (with several arities for the sake of ease).
 :

 :
 :

 : In general, both functions take a description of the HTTP request to make
 : as parameter, execute the request, and return a representation of the HTTP
 : response.
 :

 :
 :

 : The http:send-request() functions are declared as sequential.
 : Sequential functions are allowed to have side effects. For example, most probably,
 : an HTTP POST request is a request that has side effects because it adds/changes
 : a remote resource. Such functions are an extension of XQuery and are specified in
 : the XQuery Scripting Extension.
 : Sequential functions are only allowed to be invoked in certain places (e.g.
 : only from functions which are declared as sequential themselves).
 : In contrast, the http:read() functions are declared as
 : nondeterministic (see XQuery 1.1).
 : HTTP requests performed using these functions are not allowed to have
 : side effects.
 :

 :
 :

 : For almost all functions (except read with one parameter),
 : the request is represented by an http:request
 : element, specifying the URI, the HTTP method, the headers, and the body
 : content (for POST and PUT methods) of the HTTP request to make.
 :

 :
 :

 : The response is returned as a sequence of one or more items. The first
 : one is an http:response element with quite the same
 : structure as an http:request, but without the content itself.
 : The content is returned as the second item (or several items in case of
 : a multipart response) as a string, a document node, or a binary item.
 : This depends on the content-type returned.
 : Specifically, the rules are as follows:
 :
 :

 :
A document node is returned if the media type has a MIME type of
 :     text/xml, application/xml, text/xml-external-parsed-entity, or
 :     application/xml-external-parsed-entity, as defined in [RFC 3023]
 :     (except that application/xml-dtd is considered a text media type).
 :     MIME types ending by +xml are also XML media types.

 :
A document node is returned if the media type has a MIME type of
 :      text/html. In order to be able to make HTML parseable, tidy is automatically
 :      invoked. If you want to prevent that, you can also set your own content-type
 :      by setting the override-media-type attribute in the request element.
 :       For tidying, the following options
 :       will be used:
 :

 :
TidyXmlOut=yes

 :
TidyDoctypeMode=TidyDoctypeOmit

 :
TidyQuoteNbsp=yes

 :
TidyCharEncoding="utf8"

 :
TidyNewline="LF"

 :

 :

 :
A xs:string item is returned if the media type has a text MIME type,
 :     i.e. beginning with text/.

 :
A xs:base64Binary item is returned for all the other media types.

 :

 :

 :
 : Simple GET Request (retrieving HTML)
 :
 :
 :

 :   http:read( <http:request href="www.example.com" method="get"/>, () )
 :

 :
 :
 : returns
 :
 :
 :

 :   <response xmlns="http://expath.org/ns/http-client" status="200" message="OK">
 :     <header name="Content-Type" value="text/html; charset=UTF-8"/>
 :     <header name="Content-Length" value="574"/>
 :     ...
 :     <body media-type="text/html"/>
 :   </response>
 :   <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 :   <html>
 :     <head>
 :       <meta http-equiv="Content-Type"
 :       content="text/html; charset=utf-8" />
 :       <title>Example Web Page</title>
 :     </head>
 :     <body>
 :       <p>You have reached this web page by typing "example.com",
 :       "example.net", or "example.org" into your web browser.</p>
 :       <p>These domain names are reserved for use in documentation and are
 :       Not available for registration. See
 :       <a href="http://www.rfc-editor.org/rfc/rfc2606.txt">RFC 2606</a>,
 :       Section 3.</p>
 :     </body>
 :   </html>
 :

 :
 :
 : Simple GET Request (retrieving XHTML)
 :
 :
 :

 :   declare namespace xhtml="http://www.w3.org/1999/xhtml";
 :
 :   http:read( <http:request href="www.w3.org" method="get"/>, () )[2]//xhtml:body
 :

 :
 :
 :

 : This example shows how to retrieve an XHTML resource. Note, that the node test
 : that is looking for the body element in the result requires the xhtml
 : namespace to be specified.
 :

 :
 : Simple POST Request
 :
 :

 : Here is a simple example which sends a text content by making an HTTP POST
 : request.
 :

 :
 :
 :

 :   http:send-request(
 :      <http:request href="..." method="post">
 :         <http:body content-type="text/plain">
 :            Hello, world!
 :         </http:body>
 :      </http:request>
 :   )
 :

 :
 :
 : The response of this request can look as follows:
 :
 :

 :
 :   <http:response status="200" message="Ok">
 :      <http:header name="Content-Type" value="text/html"/>
 :      <http:header name="Server" value="Apache ..."/>
 :      ...
 :      <http:body content-type="text/html"/>
 :   </http:response>
 :
 :

 :
 :

 : The structure of a request element is defined in the schema that is imported
 : by this module. The details are described in the
 : specification.
 : Analogously, the response element is also described in this
 : specification.
 :

 :
 : @author Markus Pilman
 :)
module namespace http = "http://expath.org/ns/http-client";

import module namespace httpclientimpl = "http://expath.org/ns/httpclientimpl";
import module namespace err = "http://expath.org/ns/error";

import schema namespace https = "http://expath.org/ns/http-client";

(:~
 : This function sends an HTTP request and returns the corresponding response.
 :
 :

 : This function is declared as sequential (see XQuery Scripting).
 : Sequential functions are allowed to have side effects. For example, most probably,
 : an HTTP POST request is a request that has side effects because it adds/changes
 : a remote resource.
 :

 :
 : @param $request Contains the various parameters of the request.
 :   See the
 :   specification.
 :   for a full description of the structure of this element.
 : @param $href is the HTTP or HTTPS URI to send the request to. It must be a valid
 :  xs:anyURI, but is declared as a string to be able to pass literal strings
 :  (without requiring to explicitly cast it to an xs:anyURI.)
 : @param $content is the request body content, for HTTP methods that can
 :  contain a body in the request (i.e. POST and PUT). It is an error, if this
 :  param is not the empty sequence for methods other then DELETE, GET, HEAD
 :  and OPTIONS.
 : @return a sequence of items, where the first item is a element of type
 :  http:responseType. The response element is also described in the
 :  specification.
 :  If there is one (or several, in case of multipart) response body, the response bodies
 :  are the next items in the sequence.
 :)
declare sequential function http:send-request(
  $request as element(https:request)?,
  $href as xs:string?,
  $bodies as item()*) as item()+ {
  if (http:check-params($request, $href, $bodies))
  then
    let $req := if ($request) then http:set-content-type($request) else ()
    let $result := httpclientimpl:http-send-request-impl($req,
                                                         $href,
                                                         $bodies)
    return ($result[1], fn:subsequence($result, 2))
  else ()
};

(:~
 : Function for convenience.
 :
 : The result of this function is equal to calling the send-request function
 : as follows:
 :
 :
 : http:send-request($request, (), ())
 :
 :
 : @see documentation of send-request with three parameters.
 :
 : @param $request see request parameter of the sequential
 :  send-request function with three parameters.
 : @return see return value of the sequential
 :  send-request function with three parameters.
 :)
declare sequential function http:send-request (
  $request as element(https:request)) as item()+ {
  http:send-request($request, (), ())
};

(:~
 : Function for convenience.
 :
 : The result of this function is equal to calling the send-request function
 : as follows:
 :
 :
 : http:send-request($request, $href, ())
 :
 :
 : @see documentation of send-request with three parameters.
 :
 : @param $request see request parameter of the sequential
 :  send-request function with three parameters.
 : @param $href see href parameter of the sequential
 :  send-request function with three parameters.
 : @return see return of
 :  send-request
 :)
declare sequential function http:send-request(
  $request as element(https:request)?,
  $href as xs:string?) as item()+ {
  http:send-request($request, $href, ())
};

(:~
 : This function sends an HTTP request and returns the corresponding response.
 :
 :

 : This function is not sequential. Usually, this function should be used
 : for retrieving resources using HTTP GET or HEAD (i.e. HTTP requests which
 : are known to not have any side effects.
 :

 :
 : @param $request Contains the various parameters of the request.
 :   See the
 :   specification.
 :   for a full description of the structure of this element.
 : @param $href is the HTTP or HTTPS URI to send the request to. It must be a valid
 :  xs:anyURI, but is declared as a string to be able to pass literal strings
 :  (without requiring to explicitly cast it to an xs:anyURI.)
 : @param $bodies is the request body content, for HTTP methods that can
 :  contain a body in the request (i.e. POST and PUT). It is an error, if this
 :  param is not the empty sequence for methods other then DELETE, GET, HEAD
 :  and OPTIONS.
 : @return a sequence of items, where the first item is a element of type
 :  http:responseType. The response element is also described in the
 :  specification.
 :  If there is one (or several, in case of multipart) response body, the response bodies
 :  are the next items in the sequence.
 :)
declare function http:read(
  $request as element(https:request)?,
  $href as xs:string?,
  $bodies as item()*) as item()+ {
  if (http:check-params($request, $href, $bodies))
  then
    let $req := if ($request) then http:set-content-type($request) else ()
    let $result := httpclientimpl:http-read-impl($req, $href, $bodies)
    return ($result[1], fn:subsequence($result, 2))
  else ()
};

(:~
 : Function for convenience.
 :
 : The result of this function is equal to calling the read function as follows:
 :
 :
 : http:read($request, $href, ())
 :
 :
 : @see documentation of read
 :      with three parameters.
 :
 : @param $request see parameter $request of read with three parameters
 : @param $href see parameter $href of read with three parameters
 : @return see return of read with three parameters
 :)
declare function http:read(
  $request as element(https:request)?,
  $href as xs:string?) as item()+ {
  http:read($request, $href, ())
};

(:~
 : Function for convenience.
 :
 : The result of this function is equal to calling the read function
 : as follows:
 :
 :
 : http:read((), $href, ())
 :
 :
 : @see documentation of read with three parameters.
 :
 : @param $href see parameter $href of read with three parameters
 : @return see return of read with three parameters
 :)
declare function http:read(
  $href as xs:string) as item()+ {
  http:read((), $href, ())
};

(:~
 : Helper function.
 :
 : This function takes an https:body element, copies it, and
 : adds a method attribute to the copy if there is none
 : in the original element.
 :
 : @param $body is the original https:body element
 : @return a https:body element with a corresponding @method
 :   attribute
 :)
declare function http:create-body (
  $body as element(https:body))
    as element(https:body) {
  <https:body>{$body/@*}
  {
    if ($body/@method) then
      ()
    else
      attribute method {
        if ($body/@media-type eq "text/xml" or
            $body/@media-type eq "application/xml" or
            $body/@media-type eq "text/xml-external-parsed-entity" or
            $body/@media-type eq "application/xml-external-parsed-entity") then
              "xml"
         else if ($body/@media-type eq "text/html") then "html"
         else if (fn:starts-with($body/@media-type/data(.), "text/")) then "text"
         else "binary"
      }
  }
  {$body/node()}
  </https:body>
};

(:~
 : Helper function.
 :
 : This function takes an https:multipart element, copies it and
 : adds a @method attribute to all body elements which don't have
 : one.
 :
 : @param $multipart the original https:multipart
 : @return a copy of $multipart with all $multipart/body/@method set
 :)
declare function http:create-multipart (
  $multipart as element(https:multipart))
    as element(https:multipart) {
    <https:multipart>{$multipart/@*}
    {
    for $x in $multipart/node()
    return
      typeswitch($x)
        case element(https:body) return http:create-body($x)
        default return $x
    }
    </https:multipart>
};

(:~
 : Helper function.
 :
 : This adds a default method attribute to all body elements which
 : don't contain a method attribute.
 :
 : @param $request The request which need to be copied.
 : @return A copy of $request with all request//body/@method set.
 :)
declare function http:set-content-type(
  $request as element(https:request)?)
    as element(https:request)? {
  if ($request) then
    <http:request>{$request/@*}
    {
    for $x in $request/node()
    return
      typeswitch($x)
        case element(https:body) return http:create-body($x)
        case element(https:multipart) return http:create-multipart($x)
        default return $x
    }
    </http:request>
  else ()
};

(:~
 : Private helper function used internally by this module.
 :
 : This function checks if the request, href, and bodies parameters
 : are consistent.
 :
 : @param $request The request which needs to be checked.
 : @param $href The href which needs to be checked.
 : @param $bodies The bodies element which needs to be checked.
 : @return true if the parameters are consistent. Otherwise,
 :         this function raises an error.
 :)
declare function http:check-params(
  $request as element(https:request)?,
  $href as xs:string?,
  $bodies as item()*) as xs:boolean {
  if (fn:empty($href) and fn:empty($request)) then
    fn:error($err:HCV01, "Not all required arguments are set.")
  else if ($href eq "") then
    fn:error($err:HCV01,
      "The href value is set to the empty string")
  else if (not(count($request//body[not(exists(node()))]) eq count($bodies))) then
    fn:error($err:HCV01,
      "The number of bodies without children is not equal the size of the bodies sequence")
  else
    fn:true()
};


removed extra include of jquery

removed extra include of jquery

module namespace layout = "http://luxdb.net/demo/layout";

import module namespace config="http://luxdb.net/demo/config" at "config.xqy";

declare function layout:render-nav ($current-url as xs:string)
{
let $nav := (
  <item url="index.xqy">search</item>,
  <item url="query.xqy">query</item>,
  <item url="read-ibiblio.xqy">load shakespeare</item>
)
return

{
  for $item in $nav
  return if ($item/@url eq $current-url)
    then
{$item/string()}

  else
{$item/string()}

}

};

declare function layout:outer ($current-url as xs:string, $body as node()*, $http as document-node(element(http)))
{
    layout:outer($current-url, $body, (), $http)
};

declare function layout:outer ($current-url as xs:string, $body as node()*, $header as node()*, $http as document-node())
{

    <title>Lux Demo</title>
    <link href="{config:path('styles.css', $http)}" rel="stylesheet" />

           Lux Demo

      { layout:render-nav ($current-url), $header}

{
      $body
    }

};


math.xqy: acos, asin and atan use $arg as their parameter name.

xquery version "3.0";

(:~
 : XPath and XQuery Functions and Operators 3.0
 : W3C Recommendation 08 April 2014
 :
 : @see https://www.w3.org/TR/2014/REC-xpath-functions-30-20140408/
 :)
module  namespace math = "http://www.w3.org/2005/xpath-functions/math";
declare namespace xs   = "http://www.w3.org/2001/XMLSchema";

declare function math:acos($arg as xs:double?) as xs:double? external; (: §4.8.12 :)
declare function math:asin($arg as xs:double?) as xs:double? external; (: §4.8.11 :)
declare function math:atan($arg as xs:double?) as xs:double? external; (: §4.8.13 :)
declare function math:atan2($y as xs:double, $x as xs:double) as xs:double external; (: §4.8.14 :)
declare function math:cos($θ as xs:double?) as xs:double? external; (: §4.8.9 :)
declare function math:exp($arg as xs:double?) as xs:double? external; (: §4.8.2 :)
declare function math:exp10($arg as xs:double?) as xs:double? external; (: §4.8.3 :)
declare function math:log($arg as xs:double?) as xs:double? external; (: §4.8.4 :)
declare function math:log10($arg as xs:double?) as xs:double? external; (: §4.8.5 :)
declare function math:pi() as xs:double external; (: §4.8.1 :)
declare function math:pow($x as xs:double?, $y as xs:numeric) as xs:double? external; (: §4.8.6 :)
declare function math:sin($θ as xs:double?) as xs:double? external; (: §4.8.8 :)
declare function math:sqrt($arg as xs:double?) as xs:double? external; (: §4.8.7 :)
declare function math:tan($θ as xs:double?) as xs:double? external; (: §4.8.10 :)

xquery version "3.0";

(:~
 : XPath and XQuery Functions and Operators 3.0
 : W3C Recommendation 08 April 2014
 :
 : @see https://www.w3.org/TR/2014/REC-xpath-functions-30-20140408/
 :)
module  namespace math = "http://www.w3.org/2005/xpath-functions/math";
declare namespace xs   = "http://www.w3.org/2001/XMLSchema";

declare function math:acos($θ as xs:double?) as xs:double? external; (: §4.8.12 :)
declare function math:asin($θ as xs:double?) as xs:double? external; (: §4.8.11 :)
declare function math:atan($θ as xs:double?) as xs:double? external; (: §4.8.13 :)
declare function math:atan2($y as xs:double, $x as xs:double) as xs:double external; (: §4.8.14 :)
declare function math:cos($θ as xs:double?) as xs:double? external; (: §4.8.9 :)
declare function math:exp($arg as xs:double?) as xs:double? external; (: §4.8.2 :)
declare function math:exp10($arg as xs:double?) as xs:double? external; (: §4.8.3 :)
declare function math:log($arg as xs:double?) as xs:double? external; (: §4.8.4 :)
declare function math:log10($arg as xs:double?) as xs:double? external; (: §4.8.5 :)
declare function math:pi() as xs:double external; (: §4.8.1 :)
declare function math:pow($x as xs:double?, $y as xs:numeric) as xs:double? external; (: §4.8.6 :)
declare function math:sin($θ as xs:double?) as xs:double? external; (: §4.8.8 :)
declare function math:sqrt($arg as xs:double?) as xs:double? external; (: §4.8.7 :)
declare function math:tan($θ as xs:double?) as xs:double? external; (: §4.8.10 :)


quick switch between main and lib

quick switch between main and lib

module
(: declare :)
namespace su = "sudoku";

declare variable $su:boardHard as xs:integer+ :=
  ( 5,3,0, 0,7,0, 0,0,0,
    6,0,0, 1,9,5, 0,0,0,
    0,9,8, 0,0,0, 0,6,0,
    8,0,0, 0,6,0, 0,0,3,
    4,0,0, 8,0,3, 0,0,1,
    7,0,0, 0,2,0, 0,0,6,
    0,6,0, 0,0,0, 2,8,0,
    0,0,0, 4,1,9, 0,0,5,
    0,0,0, 0,8,0, 0,7,9 );

declare variable $su:boardEasy as xs:integer+ :=
  ( 1,0,0, 3,0,0, 6,0,0,
    0,2,0, 5,0,0, 0,0,4,
    0,0,9, 0,0,0, 5,2,0,
    0,0,0, 9,6,3, 0,0,0,
    7,1,6, 0,0,0, 0,0,0,
    0,0,0, 0,8,0, 0,4,0,
    9,0,0, 0,0,5, 3,0,7,
    8,0,0, 4,0,6, 0,0,0,
    3,5,0, 0,0,0, 0,0,1 );

declare variable $su:rowStarts as xs:integer+ :=
  ( 1, 10, 19, 28, 37, 46, 55, 64, 73 );

declare variable $su:groups as xs:integer+ :=
  ( 1,1,1, 2,2,2, 3,3,3,
    1,1,1, 2,2,2, 3,3,3,
    1,1,1, 2,2,2, 3,3,3,
    4,4,4, 5,5,5, 6,6,6,
    4,4,4, 5,5,5, 6,6,6,
    4,4,4, 5,5,5, 6,6,6,
    7,7,7, 8,8,8, 9,9,9,
    7,7,7, 8,8,8, 9,9,9,
    7,7,7, 8,8,8, 9,9,9 );

declare function su:getRow($board as xs:integer+,
                           $index as xs:integer) as xs:integer+
{
  let $rowStart as xs:integer := xs:integer(floor(($index - 1) div 9) * 9)
  return
  $board[position() > $rowStart and
         position() <= $rowStart + 9] => one-or-more()
};

declare function su:getCol($board as xs:integer+,
                           $index as xs:integer) as xs:integer+
{
  let $gap := ($index - 1) mod 9
    , $colIndexes := $su:rowStarts ! (. + $gap)
  return
  $board[position() = $colIndexes] => one-or-more()
};

declare function su:getGroup($board as xs:integer+,
                             $index as xs:integer) as xs:integer+
{
  (
    let $group := $su:groups[$index]
    for $y at $x in $board
    where $su:groups[$x] = $group
    return
    $y
  ) => one-or-more()
};

declare function su:getAllowedValues($board as xs:integer+,
                                     $index as xs:integer) as xs:integer*
{
  let $existingValues := ( su:getRow($board, $index),
                           su:getCol($board, $index),
                           su:getGroup($board, $index) )
  for $x in (1 to 9)
  return
  if (not($x = $existingValues)) then
    $x
  else
    ()
};

declare function su:tryValues($board as xs:integer+,
                              $emptyCells as xs:integer+,
                              $possibleValues as xs:integer+) as xs:integer*
{
  let $index as xs:integer := head($emptyCells)
    , $newBoard as xs:integer+ := ( subsequence($board, 1, $index - 1),
                                    head($possibleValues),
                                    subsequence($board, $index + 1) )
    , $result as xs:integer* := su:populateValues($newBoard, tail($emptyCells))
  return
  if (empty($result)) then
    if (count($possibleValues) > 1) then
      su:tryValues( $board,
                    $emptyCells,
                    tail($possibleValues) => one-or-more() )
    else ()
  else
    $result
};

declare function su:populateValues($board as xs:integer+,
                                   $emptyCells as xs:integer*) as xs:integer*
{
  if (not(empty($emptyCells))) then
    let $index as xs:integer := head($emptyCells)
      , $possibleValues as xs:integer* := su:getAllowedValues($board, $index)
                                          => distinct-values()
    return
    if (count($possibleValues) > 1) then
      su:tryValues( $board,
                    $emptyCells => one-or-more(),
                    $possibleValues => one-or-more() )
    else if (count($possibleValues) = 1) then
      let $newBoard as xs:integer+ := ( subsequence($board, 1, $index - 1),
                                        exactly-one($possibleValues[1]),
                                        subsequence($board, $index + 1) )
      return
      su:populateValues($newBoard, tail($emptyCells))
    else ()
  else
    $board
};

declare function su:solveSudoku($startBoard as xs:integer+) as xs:integer+
{
  let $filter := function($i, $p) { if ($i eq 0) then $p else () }
    , $emptyCells as xs:integer* := for-each-pair($startBoard, 1 to 81, $filter)
    , $endBoard as xs:integer* := su:populateValues($startBoard, $emptyCells)
  return
  if (empty($endBoard)) then
    $startBoard
  else
    one-or-more($endBoard)
};

declare function su:jsonResult($board as xs:integer+) as map(*)
{
  map {
    'board' :
      (
        let $ar := array { $board }
        for $rs at $rp in $su:rowStarts
        let $sa := array:subarray($ar, $rs, 9)
        return
        map {
          'row' || $rp : $sa
        }
      ) => map:merge()
  }
};

declare function su:drawResult($board as xs:integer+) as element()
{
  element html {
    element head {
      element title {
        'Sudoku - XQuery 3.1'
      },
      element style {
        'body { font-family: Arial, Helvetica, sans-serif;} '||
        'table { border-collapse: collapse; border: 1px solid black; margin: 35px;} '||
        'td { padding: 10px 15px 10px 15px; } '||
        '.norm { border-left: 1px solid #CCC; border-top: 1px solid #CCC; } '||
        '.red  { color: red; } '||
        '.bold { font-weight: bold; } '||
        '.csep { border-left: 1px solid black; } '||
        '.rsep { border-top: 1px solid black; }'
      }
    },
    element body {
      su:drawBoard($board)
    }
  }
};

declare function su:drawBoard($board as xs:integer+) as element()
{
  element table {
    for $i in 1 to 9
    return
    element tr {
      for $j at $p in 1 to 9
      let $pos := (($i - 1) * 9) + $j
      let $val := $board[$pos]
      return
      element td {
        attribute class {
          if ($p mod 3 = 1) then 'csep' else 'norm',
          if ($i mod 3 = 1) then 'rsep' else 'norm',
          if ($val eq 0)    then 'red'  else 'bold'
        },
        $val
      }
    }
  }
};

declare
  %rest:GET
  %rest:path("sudoku/{$level}")
  %rest:query-param("solve", "{$solve}", "no")
  %rest:produces("text/html")
  %output:method("html")
  %output:omit-xml-declaration("yes")
function su:draw($level as xs:string, $solve as xs:string)
{
  if ($level eq 'hard' and $solve eq 'yes') then
    $su:boardHard => su:solveSudoku() => su:drawResult()
  else if ($level eq 'hard') then
    $su:boardHard => su:drawResult()
  else if ($level eq 'easy' and $solve eq 'yes') then
    $su:boardEasy => su:solveSudoku() => su:drawResult()
  else if ($level eq 'easy') then
    $su:boardEasy => su:drawResult()
  else
    error('unknown')
};

declare
  %rest:GET
  %rest:path("jsudoku/{$level}")
  %rest:query-param("solve", "{$solve}", "no")
  %rest:produces("application/json")
  %output:method("json")
  %output:indent("yes")
function su:json($level as xs:string, $solve as xs:string)
{
  if ($level eq 'hard' and $solve eq 'yes') then
    $su:boardHard => su:solveSudoku() => su:jsonResult()
  else if ($level eq 'hard') then
    $su:boardHard => su:jsonResult()
  else if ($level eq 'easy' and $solve eq 'yes') then
    $su:boardEasy => su:solveSudoku() => su:jsonResult()
  else if ($level eq 'easy') then
    $su:boardEasy => su:jsonResult()
  else
    error('unknown')
};

(: $su:boardEasy => su:solveSudoku() => su:drawResult() :)

module namespace su = "sudoku";

declare variable $su:boardHard as xs:integer+ :=
  ( 5,3,0, 0,7,0, 0,0,0,
    6,0,0, 1,9,5, 0,0,0,
    0,9,8, 0,0,0, 0,6,0,
    8,0,0, 0,6,0, 0,0,3,
    4,0,0, 8,0,3, 0,0,1,
    7,0,0, 0,2,0, 0,0,6,
    0,6,0, 0,0,0, 2,8,0,
    0,0,0, 4,1,9, 0,0,5,
    0,0,0, 0,8,0, 0,7,9 );

declare variable $su:boardEasy as xs:integer+ :=
  ( 1,0,0, 3,0,0, 6,0,0,
    0,2,0, 5,0,0, 0,0,4,
    0,0,9, 0,0,0, 5,2,0,
    0,0,0, 9,6,3, 0,0,0,
    7,1,6, 0,0,0, 0,0,0,
    0,0,0, 0,8,0, 0,4,0,
    9,0,0, 0,0,5, 3,0,7,
    8,0,0, 4,0,6, 0,0,0,
    3,5,0, 0,0,0, 0,0,1 );

declare variable $su:rowStarts as xs:integer+ :=
  ( 1, 10, 19, 28, 37, 46, 55, 64, 73 );

declare variable $su:groups as xs:integer+ :=
  ( 1,1,1, 2,2,2, 3,3,3,
    1,1,1, 2,2,2, 3,3,3,
    1,1,1, 2,2,2, 3,3,3,
    4,4,4, 5,5,5, 6,6,6,
    4,4,4, 5,5,5, 6,6,6,
    4,4,4, 5,5,5, 6,6,6,
    7,7,7, 8,8,8, 9,9,9,
    7,7,7, 8,8,8, 9,9,9,
    7,7,7, 8,8,8, 9,9,9 );

declare function su:getRow($board as xs:integer+,
                           $index as xs:integer) as xs:integer+
{
  let $rowStart := floor(($index - 1) div 9) * 9
  return
  $board[position() > $rowStart and
         position() <= $rowStart + 9] => one-or-more()
};

declare function su:getCol($board as xs:integer+,
                           $index as xs:integer) as xs:integer+
{
  let $gap := ($index - 1) mod 9
    , $colIndexes := $su:rowStarts ! (. + $gap)
  return
  $board[position() = $colIndexes] => one-or-more()
};

declare function su:getGroup($board as xs:integer+,
                             $index as xs:integer) as xs:integer+
{
  (
    let $group := $su:groups[$index]
    for $y at $x in $board
    where $su:groups[$x] = $group
    return
    $y
  ) => one-or-more()
};

declare function su:getAllowedValues($board as xs:integer+,
                                     $index as xs:integer) as xs:integer*
{
  let $existingValues := ( su:getRow($board, $index),
                           su:getCol($board, $index),
                           su:getGroup($board, $index) )
  for $x in (1 to 9)
  return
  if (not($x = $existingValues)) then
    $x
  else
    ()
};

declare function su:tryValues($board as xs:integer+,
                              $emptyCells as xs:integer+,
                              $possibleValues as xs:integer+) as xs:integer*
{
  let $index as xs:integer := head($emptyCells)
    , $newBoard as xs:integer+ := ( subsequence($board, 1, $index - 1),
                                    head($possibleValues),
                                    subsequence($board, $index + 1) )
    , $result as xs:integer* := su:populateValues($newBoard, tail($emptyCells))
  return
  if (empty($result)) then
    if (count($possibleValues) > 1) then
      su:tryValues( $board,
                    $emptyCells,
                    tail($possibleValues) => one-or-more() )
    else ()
  else
    $result
};

declare function su:populateValues($board as xs:integer+,
                                   $emptyCells as xs:integer*) as xs:integer*
{
  if (not(empty($emptyCells))) then
    let $index as xs:integer := head($emptyCells)
      , $possibleValues as xs:integer* := su:getAllowedValues($board, $index)
                                          => distinct-values()
    return
    if (count($possibleValues) > 1) then
      su:tryValues( $board,
                    $emptyCells => one-or-more(),
                    $possibleValues => one-or-more() )
    else if (count($possibleValues) = 1) then
      let $newBoard as xs:integer+ := ( subsequence($board, 1, $index - 1),
                                        exactly-one($possibleValues[1]),
                                        subsequence($board, $index + 1) )
      return
      su:populateValues($newBoard, tail($emptyCells))
    else ()
  else
    $board
};

declare function su:solveSudoku($startBoard as xs:integer+) as xs:integer+
{
  let $filter := function($i, $p) { if ($i eq 0) then $p else () }
    , $emptyCells as xs:integer* := for-each-pair($startBoard, 1 to 81, $filter)
    , $endBoard as xs:integer* := su:populateValues($startBoard, $emptyCells)
  return
  if (empty($endBoard)) then
    $startBoard
  else
    one-or-more($endBoard)
};

declare function su:jsonResult($board as xs:integer+) as map(*)
{
  map {
    'board' :
      (
        let $ar := array { $board }
        for $rs at $rp in $su:rowStarts
        let $sa := array:subarray($ar, $rs, 9)
        return
        map {
          'row' || $rp : $sa
        }
      ) => map:merge()
  }
};

declare function su:drawResult($board as xs:integer+) as element()
{
  element html {
    element head {
      element title {
        'Sudoku - XQuery 3.1'
      },
      element style {
        'body { font-family: Arial, Helvetica, sans-serif;} '||
        'table { border-collapse: collapse; border: 1px solid black; margin: 35px;} '||
        'td { padding: 10px 15px 10px 15px; } '||
        '.norm { border-left: 1px solid #CCC; border-top: 1px solid #CCC; } '||
        '.red  { color: red; } '||
        '.bold { font-weight: bold; } '||
        '.csep { border-left: 1px solid black; } '||
        '.rsep { border-top: 1px solid black; }'
      }
    },
    element body {
      su:drawBoard($board)
    }
  }
};

declare function su:drawBoard($board as xs:integer+) as element()
{
  element table {
    for $i in 1 to 9
    return
    element tr {
      for $j at $p in 1 to 9
      let $pos := (($i - 1) * 9) + $j
      let $val := $board[$pos]
      return
      element td {
        attribute class {
          if ($p mod 3 = 1) then 'csep' else 'norm',
          if ($i mod 3 = 1) then 'rsep' else 'norm',
          if ($val eq 0)    then 'red'  else 'bold'
        },
        $val
      }
    }
  }
};

declare
  %rest:GET
  %rest:path("sudoku/{$level}")
  %rest:query-param("solve", "{$solve}", "no")
  %rest:produces("text/html")
  %output:method("html")
  %output:omit-xml-declaration("yes")
function su:draw($level as xs:string, $solve as xs:string)
{
  if ($level eq 'hard' and $solve eq 'yes') then
    $su:boardHard => su:solveSudoku() => su:drawResult()
  else if ($level eq 'hard') then
    $su:boardHard => su:drawResult()
  else if ($level eq 'easy' and $solve eq 'yes') then
    $su:boardEasy => su:solveSudoku() => su:drawResult()
  else if ($level eq 'easy') then
    $su:boardEasy => su:drawResult()
  else
    error('unknown')
};

declare
  %rest:GET
  %rest:path("jsudoku/{$level}")
  %rest:query-param("solve", "{$solve}", "no")
  %rest:produces("application/json")
  %output:method("json")
  %output:indent("yes")
function su:json($level as xs:string, $solve as xs:string)
{
  if ($level eq 'hard' and $solve eq 'yes') then
    $su:boardHard => su:solveSudoku() => su:jsonResult()
  else if ($level eq 'hard') then
    $su:boardHard => su:jsonResult()
  else if ($level eq 'easy' and $solve eq 'yes') then
    $su:boardEasy => su:solveSudoku() => su:jsonResult()
  else if ($level eq 'easy') then
    $su:boardEasy => su:jsonResult()
  else
    error('unknown')
};


fixed ordering by count of matching records

declare   namespace   csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;
let $doc := /.

let $xpaths := map{
    "Posting/Facility": "csd:facilities/csd:facility",
    "ID Number": "csd:otherID/@code",
    "ID Date of Issue":"csd:otherID/@issueDate/text()",
    "ID Date of Expiration":"csd:otherID/@expirationDate/text()",
    "Place of Issue": "csd:otherID/@assigningAuthorityName/text()",
    "First name": "csd:demographic/csd:name/csd:forename/text()",
    "Last name": "csd:demographic/csd:name/csd:surname/text()",
    "Middle name":"csd:demographic/csd:name/csd:otherNames[@type='middle']/text()",
    "Maiden name": "csd:demographic/csd:name/csd:otherNames[@type='maiden']/text()",
    "Other name 1" : "csd:demographic/csd:name/csd:otherNames[@type='other_1']/text()",
    "Other name 2" :"csd:demographic/csd:name/csd:otherNames[@type='other_2']/text()",
    "Other name 3" : "csd:demographic/csd:name/csd:otherNames[@type='other_3']/text()",
    "Place of birth country":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:country/text()",
    "Place of birth town": "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:town/text()",
    "Father’s name":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:fatherName/text()",
    "Mother’s name":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:motherName/text()",
    "Photograph" :    "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds'  and @type='photograph']/csd:image/text()",
    "Date of birth" :  "csd:demographic/csd:dateOfBirth/text()",
    "Sex at birth " : "csd:demographic/csd:gender/text()",
    "Citizenship at birth" : "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='citizenship']/csd:birth/text()" ,
    "Citizenship at present country of residence":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='citizenship']/csd:residence/text()",
    "Ability in written languages":"csd:language[@code]/@written-ability",
    "Ability in spoken languages": "csd:language[@code]/@spoken-ability",
    "Address Country":"csd:demographic/csd:address/csd:addressLine[@component='country']/text()",
    "Address City": "csd:demographic/csd:address/csd:addressLine[@component='city']/text()" ,
    "Street Address": "csd:demographic/csd:address/csd:addressLine[@component='streetAddress']/text()",
    "Address Postal Code" :"csd:demographic/csd:address/csd:addressLine[@component='postalCode']/text()" ,
    "Telephone number" : "csd:demographic/csd:contactPoint/csd:codedType[@code='BP'  and @codingScheme='urn:ihe:iti:csd:2013:contactPoint']/text()",
    "Email address" : "csd:demographic/csd:contactPoint/csd:codedType[@code='EMAIL' and @codingScheme='urn:ihe:iti:csd:2013:contactPoint']/text()",
    "Emergency contact name" : "csd:demographic/csd:contactPoint/csd:codedType[@code='EMERGENCY'  and @codingScheme= 'urn:who.int:hrh:mds']/text()",
    "Professional License and Certification Document Type" : "csd:credential/csd:codedType/@code",
    "Professional License and Certification Document Category" : "csd:credential/csd:codedType/@category",
    "Professional License and Certification Issuing Institution": "csd:credential/csd:issuingAuthority/text()",
    "Professional License and Certification Date of Issue" : "csd:credential/csd:credentialIssueDate/text()",
    "Professional License and Certification Date of Expiration" : "csd:credential/csd:credentialRenewalDate/text()" ,
    "Professional License and Certification Scan/Photograph" :  "csd:credential/csd:extension[@urn ='urn:who.int:hrh:mds' and @type='photograph']/csd:image/text()" ,
    "Employment status" : "csd:record/@status" ,
    "Occupational category" : "csd:codedType/@code" ,
    "Employment title" : "csd:codedType[@code]/text()",
    "Complaints" : "csd:credential/csd:extension[@urn = 'urn:who.int:hrh:mds' and @type='complaints']/@value",
    "Data submission  institution ": "csd:record/@sourceDirectory",
    "Data submission date" : "csd:record/@updated"
}

let $total := count($doc/csd:CSD/csd:providerDirectory/csd:provider)

let $stats :=
  map:for-each($xpaths,
    function($label,$xpath) {
      let $matches :=
        for $provider in $doc/csd:CSD/csd:providerDirectory/csd:provider
        let $bindings := map{"provider":$provider}
	let $expr := " declare namespace csd = 'urn:ihe:iti:csd:2013'; declare variable $provider external; $provider/" || $xpath
	let $result := xquery:eval($expr,$bindings)
	where exists($result)
	return 	$provider
      let $count:=count($matches)
      return
{$label}	{$count}	{$count div $total * 100} %

    })

return

Data Field	Number of Records
Total of {$total}	Percentage

   {
     for $stat in $stats
     order by number($stat/@count) descending
     return $stat
   }

declare   namespace   csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;
let $doc := /.

let $xpaths := map{
    "Posting/Facility": "csd:facilities/csd:facility",
    "ID Number": "csd:otherID/@code",
    "ID Date of Issue":"csd:otherID/@issueDate/text()",
    "ID Date of Expiration":"csd:otherID/@expirationDate/text()",
    "Place of Issue": "csd:otherID/@assigningAuthorityName/text()",
    "First name": "csd:demographic/csd:name/csd:forename/text()",
    "Last name": "csd:demographic/csd:name/csd:surname/text()",
    "Middle name":"csd:demographic/csd:name/csd:otherNames[@type='middle']/text()",
    "Maiden name": "csd:demographic/csd:name/csd:otherNames[@type='maiden']/text()",
    "Other name 1" : "csd:demographic/csd:name/csd:otherNames[@type='other_1']/text()",
    "Other name 2" :"csd:demographic/csd:name/csd:otherNames[@type='other_2']/text()",
    "Other name 3" : "csd:demographic/csd:name/csd:otherNames[@type='other_3']/text()",
    "Place of birth country":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:country/text()",
    "Place of birth town": "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:town/text()",
    "Father’s name":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:fatherName/text()",
    "Mother’s name":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:motherName/text()",
    "Photograph" :    "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds'  and @type='photograph']/csd:image/text()",
    "Date of birth" :  "csd:demographic/csd:dateOfBirth/text()",
    "Sex at birth " : "csd:demographic/csd:gender/text()",
    "Citizenship at birth" : "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='citizenship']/csd:birth/text()" ,
    "Citizenship at present country of residence":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='citizenship']/csd:residence/text()",
    "Ability in written languages":"csd:language[@code]/@written-ability",
    "Ability in spoken languages": "csd:language[@code]/@spoken-ability",
    "Address Country":"csd:demographic/csd:address/csd:addressLine[@component='country']/text()",
    "Address City": "csd:demographic/csd:address/csd:addressLine[@component='city']/text()" ,
    "Street Address": "csd:demographic/csd:address/csd:addressLine[@component='streetAddress']/text()",
    "Address Postal Code" :"csd:demographic/csd:address/csd:addressLine[@component='postalCode']/text()" ,
    "Telephone number" : "csd:demographic/csd:contactPoint/csd:codedType[@code='BP'  and @codingScheme='urn:ihe:iti:csd:2013:contactPoint']/text()",
    "Email address" : "csd:demographic/csd:contactPoint/csd:codedType[@code='EMAIL' and @codingScheme='urn:ihe:iti:csd:2013:contactPoint']/text()",
    "Emergency contact name" : "csd:demographic/csd:contactPoint/csd:codedType[@code='EMERGENCY'  and @codingScheme= 'urn:who.int:hrh:mds']/text()",
    "Professional License and Certification Document Type" : "csd:credential/csd:codedType/@code",
    "Professional License and Certification Document Category" : "csd:credential/csd:codedType/@category",
    "Professional License and Certification Issuing Institution": "csd:credential/csd:issuingAuthority/text()",
    "Professional License and Certification Date of Issue" : "csd:credential/csd:credentialIssueDate/text()",
    "Professional License and Certification Date of Expiration" : "csd:credential/csd:credentialRenewalDate/text()" ,
    "Professional License and Certification Scan/Photograph" :  "csd:credential/csd:extension[@urn ='urn:who.int:hrh:mds' and @type='photograph']/csd:image/text()" ,
    "Employment status" : "csd:record/@status" ,
    "Occupational category" : "csd:codedType/@code" ,
    "Employment title" : "csd:codedType[@code]/text()",
    "Complaints" : "csd:credential/csd:extension[@urn = 'urn:who.int:hrh:mds' and @type='complaints']/@value",
    "Data submission  institution ": "csd:record/@sourceDirectory",
    "Data submission date" : "csd:record/@updated"
}

let $total := count($doc/csd:CSD/csd:providerDirectory/csd:provider)

let $stats :=
  map:for-each($xpaths,
    function($label,$xpath) {
      let $matches :=
        for $provider in $doc/csd:CSD/csd:providerDirectory/csd:provider
        let $bindings := map{"provider":$provider}
	let $expr := " declare namespace csd = 'urn:ihe:iti:csd:2013'; declare variable $provider external; $provider/" || $xpath
	let $result := xquery:eval($expr,$bindings)
	where exists($result)
	return 	$provider
      let $count:=count($matches)
      return
{$label}	{$count}	{$count div $total * 100} %

    })

return

Data Field	Number of Records
Total of {$total}	Percentage

   {
     for $stat in $stats
     order by $stat/@count descending
     return $stat
   }