entities listlengths 1 44.6k | max_stars_repo_path stringlengths 6 160 | max_stars_repo_name stringlengths 6 66 | max_stars_count int64 0 47.9k | content stringlengths 18 1.04M | id stringlengths 1 6 | new_content stringlengths 18 1.04M | modified bool 1 class | references stringlengths 32 1.52M |
|---|---|---|---|---|---|---|---|---|
[
{
"context": " 8080\n :ssl-host \"0.0.0.0\"\n :ssl-port 8081\n ",
"end": 812,
"score": 0.9858319163322449,
"start": 805,
"tag": "IP_ADDRESS",
"value": "0.0.0.0"
},
{
"context": "/truststore.jks\"\n :key-password \"Kq8lG9LkISky9cDIYysiadxRx\"\n :trust-password \"Kq8lG9LkISky9cD",
"end": 1071,
"score": 0.9103571176528931,
"start": 1046,
"tag": "KEY",
"value": "Kq8lG9LkISky9cDIYysiadxRx"
},
{
"context": "ky9cDIYysiadxRx\"\n :trust-password \"Kq8lG9LkISky9cDIYysiadxRx\"}})\n\n(def jetty-ssl-pem-config\n {:webserver {:po",
"end": 1131,
"score": 0.9686243534088135,
"start": 1106,
"tag": "PASSWORD",
"value": "Kq8lG9LkISky9cDIYysiadxRx"
},
{
"context": "r {:port 8080\n :ssl-host \"0.0.0.0\"\n :ssl-port 8081\n ",
"end": 1232,
"score": 0.9883291125297546,
"start": 1225,
"tag": "IP_ADDRESS",
"value": "0.0.0.0"
},
{
"context": "-resources/config/jetty/ssl/private_keys/localhost.pem\"\n :ssl-ca-cert \"./dev-resources/con",
"end": 1438,
"score": 0.7894178032875061,
"start": 1435,
"tag": "KEY",
"value": "pem"
},
{
"context": "m\"\n :ssl-key \"./dev-resources/config/jetty/ssl/private_keys/localhost.pem\"\n :ssl-ca-cert \"./dev-resour",
"end": 1989,
"score": 0.5601505041122437,
"start": 1982,
"tag": "KEY",
"value": "private"
},
{
"context": "-resources/config/jetty/ssl/private_keys/localhost.pem\"\n :ssl-ca-cert \"./dev-resources/config/jetty/ss",
"end": 2008,
"score": 0.9551892280578613,
"start": 2005,
"tag": "KEY",
"value": "pem"
}
] | test/clj/puppetlabs/trapperkeeper/testutils/webserver/common.clj | jonathannewman/trapperkeeper-webserver-jetty9 | 0 | (ns puppetlabs.trapperkeeper.testutils.webserver.common
(:require
[puppetlabs.http.client.sync :as http-client])
(:import
(appender TestListAppender)))
(defn http-get
([url]
(http-get url {:as :text}))
([url options]
(http-client/get url options)))
(defn http-put
[url options]
(http-client/put url options))
(def jetty-plaintext-config
{:webserver {:port 8080}})
(def jetty-plaintext-large-request-config
{:webserver {:port 8080
:request-header-max-size 16192}})
(def jetty-multiserver-plaintext-config
{:webserver {:foo {:port 8085}
:bar {:port 8080
:default-server true}}})
(def jetty-ssl-jks-config
{:webserver {:port 8080
:ssl-host "0.0.0.0"
:ssl-port 8081
:keystore "./dev-resources/config/jetty/ssl/keystore.jks"
:truststore "./dev-resources/config/jetty/ssl/truststore.jks"
:key-password "Kq8lG9LkISky9cDIYysiadxRx"
:trust-password "Kq8lG9LkISky9cDIYysiadxRx"}})
(def jetty-ssl-pem-config
{:webserver {:port 8080
:ssl-host "0.0.0.0"
:ssl-port 8081
:ssl-cert "./dev-resources/config/jetty/ssl/certs/localhost.pem"
:ssl-key "./dev-resources/config/jetty/ssl/private_keys/localhost.pem"
:ssl-ca-cert "./dev-resources/config/jetty/ssl/certs/ca.pem"}})
(def jetty-ssl-client-need-config
(assoc-in jetty-ssl-pem-config [:webserver :client-auth] "need"))
(def jetty-ssl-client-want-config
(assoc-in jetty-ssl-pem-config [:webserver :client-auth] "want"))
(def jetty-ssl-client-none-config
(assoc-in jetty-ssl-pem-config [:webserver :client-auth] "none"))
(def default-options-for-https-client
{:ssl-cert "./dev-resources/config/jetty/ssl/certs/localhost.pem"
:ssl-key "./dev-resources/config/jetty/ssl/private_keys/localhost.pem"
:ssl-ca-cert "./dev-resources/config/jetty/ssl/certs/ca.pem"
:as :text})
(def absurdly-large-cookie
(apply str (repeat 8192 "a")))
(def dev-resources-dir "./dev-resources/")
(defmacro with-test-access-logging
"Executes a test block and clears any messages saved to the TestListAppender
before and afterwards."
[& body]
`(do
(.clear (TestListAppender/list))
(try
(do ~@body)
(finally
(.clear (TestListAppender/list))))))
| 111991 | (ns puppetlabs.trapperkeeper.testutils.webserver.common
(:require
[puppetlabs.http.client.sync :as http-client])
(:import
(appender TestListAppender)))
(defn http-get
([url]
(http-get url {:as :text}))
([url options]
(http-client/get url options)))
(defn http-put
[url options]
(http-client/put url options))
(def jetty-plaintext-config
{:webserver {:port 8080}})
(def jetty-plaintext-large-request-config
{:webserver {:port 8080
:request-header-max-size 16192}})
(def jetty-multiserver-plaintext-config
{:webserver {:foo {:port 8085}
:bar {:port 8080
:default-server true}}})
(def jetty-ssl-jks-config
{:webserver {:port 8080
:ssl-host "0.0.0.0"
:ssl-port 8081
:keystore "./dev-resources/config/jetty/ssl/keystore.jks"
:truststore "./dev-resources/config/jetty/ssl/truststore.jks"
:key-password "<KEY>"
:trust-password "<KEY>"}})
(def jetty-ssl-pem-config
{:webserver {:port 8080
:ssl-host "0.0.0.0"
:ssl-port 8081
:ssl-cert "./dev-resources/config/jetty/ssl/certs/localhost.pem"
:ssl-key "./dev-resources/config/jetty/ssl/private_keys/localhost.<KEY>"
:ssl-ca-cert "./dev-resources/config/jetty/ssl/certs/ca.pem"}})
(def jetty-ssl-client-need-config
(assoc-in jetty-ssl-pem-config [:webserver :client-auth] "need"))
(def jetty-ssl-client-want-config
(assoc-in jetty-ssl-pem-config [:webserver :client-auth] "want"))
(def jetty-ssl-client-none-config
(assoc-in jetty-ssl-pem-config [:webserver :client-auth] "none"))
(def default-options-for-https-client
{:ssl-cert "./dev-resources/config/jetty/ssl/certs/localhost.pem"
:ssl-key "./dev-resources/config/jetty/ssl/<KEY>_keys/localhost.<KEY>"
:ssl-ca-cert "./dev-resources/config/jetty/ssl/certs/ca.pem"
:as :text})
(def absurdly-large-cookie
(apply str (repeat 8192 "a")))
(def dev-resources-dir "./dev-resources/")
(defmacro with-test-access-logging
"Executes a test block and clears any messages saved to the TestListAppender
before and afterwards."
[& body]
`(do
(.clear (TestListAppender/list))
(try
(do ~@body)
(finally
(.clear (TestListAppender/list))))))
| true | (ns puppetlabs.trapperkeeper.testutils.webserver.common
(:require
[puppetlabs.http.client.sync :as http-client])
(:import
(appender TestListAppender)))
(defn http-get
([url]
(http-get url {:as :text}))
([url options]
(http-client/get url options)))
(defn http-put
[url options]
(http-client/put url options))
(def jetty-plaintext-config
{:webserver {:port 8080}})
(def jetty-plaintext-large-request-config
{:webserver {:port 8080
:request-header-max-size 16192}})
(def jetty-multiserver-plaintext-config
{:webserver {:foo {:port 8085}
:bar {:port 8080
:default-server true}}})
(def jetty-ssl-jks-config
{:webserver {:port 8080
:ssl-host "0.0.0.0"
:ssl-port 8081
:keystore "./dev-resources/config/jetty/ssl/keystore.jks"
:truststore "./dev-resources/config/jetty/ssl/truststore.jks"
:key-password "PI:KEY:<KEY>END_PI"
:trust-password "PI:PASSWORD:<KEY>END_PI"}})
(def jetty-ssl-pem-config
{:webserver {:port 8080
:ssl-host "0.0.0.0"
:ssl-port 8081
:ssl-cert "./dev-resources/config/jetty/ssl/certs/localhost.pem"
:ssl-key "./dev-resources/config/jetty/ssl/private_keys/localhost.PI:KEY:<KEY>END_PI"
:ssl-ca-cert "./dev-resources/config/jetty/ssl/certs/ca.pem"}})
(def jetty-ssl-client-need-config
(assoc-in jetty-ssl-pem-config [:webserver :client-auth] "need"))
(def jetty-ssl-client-want-config
(assoc-in jetty-ssl-pem-config [:webserver :client-auth] "want"))
(def jetty-ssl-client-none-config
(assoc-in jetty-ssl-pem-config [:webserver :client-auth] "none"))
(def default-options-for-https-client
{:ssl-cert "./dev-resources/config/jetty/ssl/certs/localhost.pem"
:ssl-key "./dev-resources/config/jetty/ssl/PI:KEY:<KEY>END_PI_keys/localhost.PI:KEY:<KEY>END_PI"
:ssl-ca-cert "./dev-resources/config/jetty/ssl/certs/ca.pem"
:as :text})
(def absurdly-large-cookie
(apply str (repeat 8192 "a")))
(def dev-resources-dir "./dev-resources/")
(defmacro with-test-access-logging
"Executes a test block and clears any messages saved to the TestListAppender
before and afterwards."
[& body]
`(do
(.clear (TestListAppender/list))
(try
(do ~@body)
(finally
(.clear (TestListAppender/list))))))
|
[
{
"context": "in (:username distro)\n (:password distro)\n (:url distro)))))\n\n(defn creat",
"end": 24934,
"score": 0.9722012281417847,
"start": 24928,
"tag": "PASSWORD",
"value": "distro"
}
] | ch16/swarmpit/src/clj/swarmpit/api.clj | vincestorm/Docker-on-Amazon-Web-Services | 0 | (ns swarmpit.api
(:require [clojure.set :refer [rename-keys]]
[buddy.hashers :as hashers]
[digest :refer [digest]]
[swarmpit.utils :refer [merge-data]]
[swarmpit.config :as cfg]
[swarmpit.stats :as stats]
[swarmpit.yaml :as yaml :refer [->yaml]]
[swarmpit.docker.utils :as du]
[swarmpit.docker.engine.client :as dc]
[swarmpit.docker.engine.cli :as dcli]
[swarmpit.docker.engine.log :as dl]
[swarmpit.docker.engine.mapper.inbound :as dmi]
[swarmpit.docker.engine.mapper.outbound :as dmo]
[swarmpit.docker.engine.mapper.compose :refer [->compose]]
[swarmpit.docker.auth.client :as dac]
[swarmpit.docker.registry.client :as drc]
[swarmpit.docker.hub.client :as dhc]
[swarmpit.docker.hub.mapper.inbound :as dhmi]
[swarmpit.registry.client :as rc]
[swarmpit.registry.mapper.inbound :as rmi]
[swarmpit.couchdb.client :as cc]
[swarmpit.couchdb.mapper.inbound :as cmi]
[swarmpit.couchdb.mapper.outbound :as cmo]
[clojure.core.memoize :as memo]
[clojure.tools.logging :as log]
[clojure.string :as str]
[cemerick.url :refer [url]]
[swarmpit.token :as token]))
;;; User API
(defn users
[]
(-> (cc/users)
(cmi/->users)))
(defn user
[user-id]
(-> (cc/user user-id)
(cmi/->user)))
(defn user-by-username
[username]
(cc/user-by-username username))
(defn user-exist?
[user]
(some? (user-by-username (:username user))))
(defn delete-user
[user-id]
(->> (user user-id)
(cc/delete-user)))
(defn create-user
[user]
(if (not (user-exist? user))
(->> (cmo/->user user)
(cc/create-user))))
(defn update-user
[user-id user-delta]
(->> (cc/update-user (cc/user user-id) user-delta)
(cmi/->user)))
(defn change-password
[user password]
(->> (cmo/->password password)
(cc/change-password user)))
(def password-check hashers/check)
(defn password-check-upgrade
[password hash upgrade-f]
(try
(password-check password hash)
(catch Exception e
(if (= hash (digest "sha-256" password))
(do (upgrade-f) true)
false))))
(defn user-by-credentials
[{:keys [username password]}]
(let [user (user-by-username username)]
(when
(password-check-upgrade password (:password user)
#(change-password user password))
user)))
(defn generate-api-token
[user]
(let [jti (swarmpit.uuid/uuid)
token (token/generate-jwt user {:exp nil :jti jti :iss "swarmpit-api"})]
(cc/set-api-token user {:jti jti :mask (subs token (- (count token) 5))})
{:token token}))
(defn remove-api-token
[user]
(cc/set-api-token user nil))
;;; Secret API
(defn secrets
([]
(secrets nil))
([label]
(-> (dc/secrets label)
(dmi/->secrets))))
(defn secret
[secret-id]
(-> (dc/secret secret-id)
(dmi/->secret)))
(defn delete-secret
[secret-id]
(dc/delete-secret secret-id))
(defn create-secret
[secret]
(-> (dmo/->secret secret)
(dc/create-secret)
(rename-keys {:ID :id})))
(defn update-secret
[secret-id secret]
(let [secret-version (:version secret)]
(->> (dmo/->secret secret)
(dc/update-secret secret-id secret-version))))
;;; Config API
(defn configs
([]
(configs nil))
([label]
(try (-> (dc/configs label)
(dmi/->configs))
(catch Exception _ []))))
(defn config
[config-id]
(-> (dc/config config-id)
(dmi/->config)))
(defn delete-config
[config-id]
(dc/delete-config config-id))
(defn create-config
[config]
(-> (dmo/->config config)
(dc/create-config)
(rename-keys {:ID :id})))
;;; Network API
(defn networks
([]
(networks nil))
([label]
(-> (dc/networks label)
(dmi/->networks))))
(defn network
[network-id]
(-> (dc/network network-id)
(dmi/->network)))
(defn delete-network
[network-id]
(dc/delete-network network-id))
(defn create-network
[network]
(-> (dmo/->network network)
(dc/create-network)
(rename-keys {:Id :id})))
;;; Volume API
(defn volumes
([]
(volumes nil))
([label]
(-> (dc/volumes label)
(dmi/->volumes))))
(defn volume
[volume-name]
(-> (dc/volume volume-name)
(dmi/->volume)))
(defn delete-volume
[volume-name]
(dc/delete-volume volume-name))
(defn create-volume
[volume]
(->> (dmo/->volume volume)
(dc/create-volume)
(dmi/->volume)))
;;; Stackfile API
(defn stackfiles
[]
(cc/stackfiles))
(defn stackfile
[stack-name]
(cc/stackfile stack-name))
(defn delete-stackfile
[stack-name]
(-> (cc/stackfile stack-name)
(cc/delete-stackfile)))
(defn- stackfile-json
[stackfile-spec]
(try
(yaml/->json (:compose stackfile-spec))
(catch Exception _ nil)))
(defn- stackfile-services
[stackfile-spec]
(->> (stackfile-json stackfile-spec)
:services
(vals)
(map #(dmi/->service-image-details (:image %)))))
(defn- stackfile-distibutions
[stackfile-spec filter-fx]
(->> (stackfile-services stackfile-spec)
(filter #(filter-fx (:name %)))
(map #(du/distribution-id (:name %)))
(into (hash-set))))
(defn- stackfile-dockerhub-distributions
[stackfile-spec]
(stackfile-distibutions stackfile-spec du/dockerhub?))
(defn- stackfile-registry-distributions
[stackfile-spec]
(stackfile-distibutions stackfile-spec du/registry?))
;;; Dockerhub distribution API
(defn dockerusers
[owner]
(-> (cc/dockerusers owner)
(cmi/->dockerusers)))
(defn dockeruser-info
[dockeruser]
(dhc/info dockeruser))
(defn dockeruser-namespace
[dockeruser-token]
(-> (dhc/namespaces dockeruser-token)
:namespaces))
(defn dockeruser-login
[dockeruser]
(dhc/login dockeruser))
(defn dockeruser-exist?
[dockeruser]
(cc/dockeruser-exist? dockeruser))
(defn dockeruser
[dockeruser-id]
(-> (cc/dockeruser dockeruser-id)
(cmi/->dockeruser)))
(defn- dockeruser-by-namespace
[owner dockeruser-namespace]
(->> (cc/dockerusers owner)
(filter #(contains? (set (:namespaces %)) dockeruser-namespace))
(first)))
(defn- dockeruser-by-stackfile
"Return best matching dockerhub account for given stackfile spec"
[owner stackfile-spec]
(let [namespaces (stackfile-dockerhub-distributions stackfile-spec)]
(->> (cc/dockerusers owner)
(map #(hash-map
:user-id (:_id %)
:matches (get
(->> (:namespaces %)
(map (fn [ns] (contains? namespaces ns)))
(frequencies))
true)))
(filter #(some? (:matches %)))
(sort-by :matches)
(last)
:user-id
(cc/dockeruser))))
(defn create-dockeruser
[dockeruser dockeruser-info dockeruser-namespace]
(if (not (dockeruser-exist? dockeruser))
(->> (cmo/->docker-user dockeruser dockeruser-info dockeruser-namespace)
(cc/create-dockeruser))))
(defn update-dockeruser
[dockeruser-id dockeruser-delta]
(->> (cc/update-dockeruser (cc/dockeruser dockeruser-id) dockeruser-delta)
(cmi/->dockeruser)))
(defn delete-dockeruser
[dockeruser-id]
(-> (dockeruser dockeruser-id)
(cc/delete-dockeruser)))
(defn dockeruser-repositories
[dockeruser-id]
(let [dockeruser (cc/dockeruser dockeruser-id)
dockeruser-token (:token (dhc/login dockeruser))]
(->> (dhc/namespaces dockeruser-token)
:namespaces
(map #(:results (dhc/repositories-by-namespace dockeruser-token %)))
(flatten)
(dhmi/->user-repositories))))
;; Public distribution API
(defn public-repositories
[repository-query repository-page]
(-> (dhc/repositories repository-query repository-page)
(dhmi/->repositories repository-query repository-page)))
;;; Registry distribution API
(defn registries
[owner]
(-> (cc/registries owner)
(cmi/->registries)))
(defn- registries-by-stackfile
"Return registry accounts for given stackfile spec"
[owner stackfile-spec]
(let [urls (stackfile-registry-distributions stackfile-spec)]
(->> (cc/registries owner)
(filter #(contains? urls (-> % :url url :host))))))
(defn registry
[registry-id]
(-> (cc/registry registry-id)
(cmi/->registry)))
(defn- registry-by-url
[owner registry-address]
(let [registry (->> (cc/registries owner)
(filter #(.contains (:url %) registry-address))
(first))]
(if (nil? registry)
(throw
(ex-info "Registry error: authentication required"
{:status 401
:body {:error "authentication required"}}))
registry)))
(defn registry-exist?
[registry]
(cc/registry-exist? registry))
(defn registry-info
[registry]
(rc/info registry))
(defn delete-registry
[registry-id]
(->> (registry registry-id)
(cc/delete-registry)))
(defn create-registry
[registry]
(when (not (registry-exist? registry))
(cc/create-registry registry)))
(defn update-registry
[registry-id registry-delta]
(->> (cc/update-registry (cc/registry registry-id) registry-delta)
(cmi/->registry)))
(defn registry-repositories
[registry-id]
(->> (cc/registry registry-id)
(rc/repositories)
(rmi/->repositories)))
;;; Repository Tags API
(defn- registry-repository-tags
[owner repository-name]
(let [registry-address (du/distribution-id repository-name)
repository-name (du/registry-repository repository-name registry-address)]
(-> (registry-by-url owner registry-address)
(rc/tags repository-name)
:tags)))
(defn- dockeruser-repository-tags
[owner repository-name]
(let [dockeruser-namespace (du/distribution-id repository-name)]
(-> (dockeruser-by-namespace owner dockeruser-namespace)
(dac/token repository-name)
:token
(drc/tags repository-name)
:tags)))
(defn- library-repository-tags
[repository-name]
(let [repository-name (du/library-repository repository-name)]
(-> (dac/token nil repository-name)
:token
(drc/tags repository-name)
:tags)))
(defn repository-tags
[owner repository-name]
(cond
(du/library? repository-name) (library-repository-tags repository-name)
(du/dockerhub? repository-name) (dockeruser-repository-tags owner repository-name)
:else (registry-repository-tags owner repository-name)))
;;; Repository Ports API
(defn- registry-repository-ports
[owner repository-name repository-tag]
(let [registry-address (du/distribution-id repository-name)
repository-name (du/registry-repository repository-name registry-address)]
(-> (registry-by-url owner registry-address)
(rc/manifest repository-name repository-tag)
(rmi/->repository-config)
:config
(dmi/->image-ports))))
(defn- dockeruser-repository-ports
[owner repository-name repository-tag]
(let [dockeruser-namespace (du/distribution-id repository-name)]
(-> (dockeruser-by-namespace owner dockeruser-namespace)
(dac/token repository-name)
:token
(drc/manifest repository-name repository-tag)
(rmi/->repository-config)
:config
(dmi/->image-ports))))
(defn- library-repository-ports
[repository-name repository-tag]
(let [repository-name (du/library-repository repository-name)]
(-> (dac/token nil repository-name)
:token
(drc/manifest repository-name repository-tag)
(rmi/->repository-config)
:config
(dmi/->image-ports))))
(defn repository-ports
[owner repository-name repository-tag]
(cond
(du/library? repository-name) (library-repository-ports repository-name repository-tag)
(du/dockerhub? repository-name) (dockeruser-repository-ports owner repository-name repository-tag)
:else (registry-repository-ports owner repository-name repository-tag)))
;;; Repository Digest API
(defn- registry-repository-digest
[owner repository-name repository-tag]
(let [registry-address (du/distribution-id repository-name)
repository-name (du/registry-repository repository-name registry-address)]
(-> (registry-by-url owner registry-address)
(rc/digest repository-name repository-tag))))
(defn- dockeruser-repository-digest
[owner repository-name repository-tag]
(let [dockeruser-namespace (du/distribution-id repository-name)]
(-> (dockeruser-by-namespace owner dockeruser-namespace)
(dac/token repository-name)
:token
(drc/digest repository-name repository-tag))))
(defn- library-repository-digest
[repository-name repository-tag]
(let [repository-name (du/library-repository repository-name)]
(-> (dac/token nil repository-name)
:token
(drc/digest repository-name repository-tag))))
(defn repository-digest
[owner repository-name repository-tag]
(cond
(du/library? repository-name) (library-repository-digest repository-name repository-tag)
(du/dockerhub? repository-name) (dockeruser-repository-digest owner repository-name repository-tag)
:else (registry-repository-digest owner repository-name repository-tag)))
;;; Task API
(defn task-stats
[task]
(let [stats (apply dissoc (stats/task task) [:name :id])]
(assoc task :stats stats)))
(defn tasks
[]
(->> (dmi/->tasks (dc/tasks)
(dc/nodes)
(dc/services))
(map #(task-stats %))))
(def tasks-memo (memo/ttl tasks :ttl/threshold 1000))
(defn task
[task-id]
(-> (dmi/->task (dc/task task-id)
(dc/nodes)
(dc/services))
(task-stats)))
;;; Service API
(defn services
([]
(services nil))
([label]
(services label (dc/networks)))
([label networks]
(dmi/->services (dc/services label)
(dc/tasks)
networks)))
(defn resources-by-services
[services resource source]
(let [ids (->> services
(map resource)
(flatten)
(map :id)
(set))]
(->> (source)
(filter #(contains? ids (:id %)))
(vec))))
(defn volumes-by-services
[services]
(let [volumes (->> (volumes)
(group-by :id))]
(->> services
(map :mounts)
(flatten)
(filter #(= "volume" (:type %)))
(map #(merge % {:volumeName (:host %)
:driver (-> % :volumeOptions :driver :name)
:options (-> % :volumeOptions :options)}))
(map #(merge (first (get volumes (:id %))) %)))))
(def services-memo (memo/ttl services :ttl/threshold 1000))
(defn- services-by
[service-filter]
(dmi/->services (filter #(service-filter %) (dc/services))
(dc/tasks)
(dc/networks)))
(defn services-by-network
[network-name]
(services-by #(contains? (->> (get-in % [:Spec :TaskTemplate :Networks])
(map :Target)
(set)) (:id (network network-name)))))
(defn services-by-volume
[volume-name]
(services-by #(contains? (->> (get-in % [:Spec :TaskTemplate :ContainerSpec :Mounts])
(map :Source)
(set)) volume-name)))
(defn services-by-secret
[secret-name]
(services-by #(contains? (->> (get-in % [:Spec :TaskTemplate :ContainerSpec :Secrets])
(map :SecretName)
(set)) secret-name)))
(defn services-by-config
[config-name]
(services-by #(contains? (->> (get-in % [:Spec :TaskTemplate :ContainerSpec :Configs])
(map :ConfigName)
(set)) config-name)))
(defn service
[service-id]
(dmi/->service (dc/service service-id)
(dc/service-tasks service-id)
(dc/networks)))
(defn service-networks
[service-id]
(dmi/->service-networks (dc/service service-id)
(dc/networks)))
(defn service-tasks
[service-id]
(->> (dmi/->tasks (dc/service-tasks service-id)
(dc/nodes)
(dc/services))
(map #(task-stats %))))
(defn service-logs
[service-id from-timestamp]
(letfn [(log-task [log tasks] (->> tasks
(filter #(= (:task log) (:id %)))
(first)))]
(let [tasks (tasks)]
(->> (dc/service-logs service-id)
(dl/parse-log)
(filter #(= 1 (compare (:timestamp %) from-timestamp)))
(map
(fn [i]
(let [task (log-task i tasks)]
(-> i
(assoc :taskName (:taskName task))
(assoc :taskNode (:nodeName task))))))))))
(defn delete-service
[service-id]
(dc/delete-service service-id))
(defn- standardize-service-configs
[service]
(if (<= 1.30 (read-string (cfg/config :docker-api)))
(assoc-in service [:configs] (dmo/->service-configs service (configs)))
service))
(defn- standardize-service-secrets
[service]
(assoc-in service [:secrets] (dmo/->service-secrets service (secrets))))
(defn- standardize-repository-tag
[repository-tag]
(if (str/blank? repository-tag)
"latest"
repository-tag))
(defn- standardize-service
[owner service]
(let [repository-name (get-in service [:repository :name])
repository-tag (standardize-repository-tag (get-in service [:repository :tag]))]
(-> service
(standardize-service-secrets)
(standardize-service-configs)
(assoc-in [:repository :tag] repository-tag)
(assoc-in [:repository :imageDigest] (repository-digest owner
repository-name
repository-tag)))))
(defn- service-auth
[owner service]
(let [repository-name (get-in service [:repository :name])
distribution-id (du/distribution-id repository-name)]
(dmo/->auth-config
(cond
(du/library? repository-name) nil
(du/dockerhub? repository-name) (dockeruser-by-namespace owner distribution-id)
:else (registry-by-url owner distribution-id)))))
(defn create-service
[owner service]
(rename-keys
(->> (standardize-service owner service)
(dmo/->service)
(dc/create-service (service-auth owner service))) {:ID :id}))
(defn- merge-service
[service-origin service-delta]
(-> (merge-data service-origin service-delta)
(assoc-in [:Labels] (:Labels service-delta))))
(defn update-service
[owner service]
(let [standardized-service (standardize-service owner service)
service-origin (-> (dc/service (:id service)) :Spec)
service-delta (dmo/->service standardized-service)]
(dc/update-service (service-auth owner service)
(:id service)
(:version service)
(merge-service service-origin service-delta))))
(defn redeploy-service
[owner service-id]
(let [service-origin (dc/service service-id)
service (dmi/->service service-origin)
repository-name (get-in service [:repository :name])
repository-tag (get-in service [:repository :tag])
image-digest (repository-digest owner repository-name repository-tag)
image (str repository-name ":" repository-tag "@" image-digest)]
(dc/update-service
(service-auth owner service)
service-id
(get-in service-origin [:Version :Index])
(-> service-origin
:Spec
(update-in [:TaskTemplate :ForceUpdate] inc)
(assoc-in [:TaskTemplate :ContainerSpec :Image] image)))))
(defn rollback-service
[owner service-id]
(let [service-origin (dc/service service-id)
service (dmi/->service service-origin)]
(dc/update-service
(service-auth owner service)
service-id
(get-in service-origin [:Version :Index])
(-> service-origin
:PreviousSpec))))
;;; Node API
(defn node-stats
[node]
(let [stats (apply dissoc (stats/node (:id node)) [:id :tasks])]
(assoc node :stats stats)))
(defn nodes
[]
(->> (dc/nodes)
(dmi/->nodes)
(map #(node-stats %))))
(defn node
[node-id]
(-> (dc/node node-id)
(dmi/->node)
(node-stats)))
(defn update-node
[node]
(dc/update-node (:id node)
(:version node)
node))
(defn update-node
[node-id node]
(let [node-version (:version node)]
(->> (dmo/->node node)
(dc/update-node node-id node-version))))
(defn node-tasks
[node-id]
(->> (dmi/->tasks (dc/node-tasks node-id)
(dc/nodes)
(dc/services))
(map #(task-stats %))))
;; Labels API
(defn labels-service
[]
(->> (services)
(map #(->> % :labels
(map :name)
(map str/trim)
(set)))
(apply clojure.set/union)))
;; Plugin API
(defn plugins
[]
(->> (dc/nodes)
(map #(get-in % [:Description :Engine :Plugins]))
(flatten)
(distinct)
(group-by :Type)))
(defn plugins-by-type
[type]
(->> (get (plugins) type)
(map :Name)))
;; Placement API
(defn- placement-rule
[nodes-attribute node-rule-fn]
(->> nodes-attribute
(map #(for [x [" == " " != "]]
(node-rule-fn x %)))
(flatten)))
(defn placement
[]
(let [nodes (nodes)
nodes-id (map :id nodes)
nodes-role '("manager" "worker")
nodes-hostname (map :nodeName nodes)
nodes-label (set (flatten (map :labels nodes)))]
(concat
(placement-rule
nodes-id
(fn [matcher item]
(str "node.id" matcher item)))
(placement-rule
nodes-role
(fn [matcher item]
(str "node.role" matcher item)))
(placement-rule
nodes-hostname
(fn [matcher item]
(str "node.hostname" matcher item)))
(placement-rule
nodes-label
(fn [matcher item]
(str "node.labels." (:name item) matcher (:value item)))))))
;; Stack API
(defn stack-label
[stack-name]
(str "com.docker.stack.namespace=" stack-name))
(defn stack-services
[stack-name]
(-> (stack-label stack-name)
(services)))
(defn stack
([stack-name services]
(when (not-empty services)
{:stackName stack-name
:stackFile (some? (stackfile stack-name))
:services services
:networks (resources-by-services services :networks networks)
:volumes (volumes-by-services services)
:configs (resources-by-services services :configs configs)
:secrets (resources-by-services services :secrets secrets)}))
([stack-name]
(stack stack-name (stack-services stack-name))))
(defn stack-compose
[stack-name]
(some-> (stack stack-name) (->compose) (->yaml)))
(defn service-compose
[service-name]
(some->> [(service service-name)]
(stack nil)
(->compose)
(->yaml)))
(defn stacks
[]
(->> (dissoc (group-by :stack (services)) nil)
(map (fn [s]
(letfn [(distinct-resources [r]
(->> (dissoc (group-by :id r) nil)
(vals)
(map first)
(map #(dissoc % :serviceAliases))))]
(let [stack-name (key s)
stack-services (val s)
stack-networks (flatten (map :networks stack-services))
stack-volumes (flatten (map :mounts stack-services))
stack-configs (flatten (map :configs stack-services))
stack-secrets (flatten (map :secrets stack-services))]
(when (not-empty stack-services)
{:stackName stack-name
:stackFile (some? (stackfile stack-name))
:services stack-services
:networks (distinct-resources stack-networks)
:volumes (distinct-resources stack-volumes)
:configs (distinct-resources stack-configs)
:secrets (distinct-resources stack-secrets)})))))))
(defn stack-login
[owner stackfile-spec]
(let [distributions (remove nil?
(conj (registries-by-stackfile owner stackfile-spec)
(dockeruser-by-stackfile owner stackfile-spec)))]
(doseq [distro distributions]
(dcli/login (:username distro)
(:password distro)
(:url distro)))))
(defn create-stack
"Create application stack and link stackfile"
[owner {:keys [name spec] :as stackfile}]
(let [stackfile-origin (cc/stackfile name)]
(stack-login owner spec)
(dcli/stack-deploy name (:compose spec))
(if (some? stackfile-origin)
(cc/update-stackfile stackfile-origin stackfile)
(cc/create-stackfile stackfile))))
(defn update-stack
"Update application stack and stackfile accordingly"
[owner {:keys [name spec] :as stackfile}]
(let [stackfile-origin (cc/stackfile name)]
(stack-login owner spec)
(dcli/stack-deploy name (:compose spec))
(if (some? stackfile-origin)
(cc/update-stackfile stackfile-origin {:spec spec
:previousSpec (:spec stackfile-origin)})
(cc/create-stackfile stackfile))))
(defn redeploy-stack
"Redeploy application stack"
[owner name]
(let [{:keys [name spec]} (cc/stackfile name)]
(stack-login owner spec)
(dcli/stack-deploy name (:compose spec))))
(defn rollback-stack
"Rollback application stack and update stackfile accordingly"
[owner name]
(let [{:keys [name spec previousSpec] :as stackfile-origin} (cc/stackfile name)]
(stack-login owner previousSpec)
(dcli/stack-deploy name (:compose previousSpec))
(cc/update-stackfile stackfile-origin {:spec previousSpec
:previousSpec spec})))
(defn delete-stack
[stack-name]
(dcli/stack-remove stack-name)) | 31746 | (ns swarmpit.api
(:require [clojure.set :refer [rename-keys]]
[buddy.hashers :as hashers]
[digest :refer [digest]]
[swarmpit.utils :refer [merge-data]]
[swarmpit.config :as cfg]
[swarmpit.stats :as stats]
[swarmpit.yaml :as yaml :refer [->yaml]]
[swarmpit.docker.utils :as du]
[swarmpit.docker.engine.client :as dc]
[swarmpit.docker.engine.cli :as dcli]
[swarmpit.docker.engine.log :as dl]
[swarmpit.docker.engine.mapper.inbound :as dmi]
[swarmpit.docker.engine.mapper.outbound :as dmo]
[swarmpit.docker.engine.mapper.compose :refer [->compose]]
[swarmpit.docker.auth.client :as dac]
[swarmpit.docker.registry.client :as drc]
[swarmpit.docker.hub.client :as dhc]
[swarmpit.docker.hub.mapper.inbound :as dhmi]
[swarmpit.registry.client :as rc]
[swarmpit.registry.mapper.inbound :as rmi]
[swarmpit.couchdb.client :as cc]
[swarmpit.couchdb.mapper.inbound :as cmi]
[swarmpit.couchdb.mapper.outbound :as cmo]
[clojure.core.memoize :as memo]
[clojure.tools.logging :as log]
[clojure.string :as str]
[cemerick.url :refer [url]]
[swarmpit.token :as token]))
;;; User API
(defn users
[]
(-> (cc/users)
(cmi/->users)))
(defn user
[user-id]
(-> (cc/user user-id)
(cmi/->user)))
(defn user-by-username
[username]
(cc/user-by-username username))
(defn user-exist?
[user]
(some? (user-by-username (:username user))))
(defn delete-user
[user-id]
(->> (user user-id)
(cc/delete-user)))
(defn create-user
[user]
(if (not (user-exist? user))
(->> (cmo/->user user)
(cc/create-user))))
(defn update-user
[user-id user-delta]
(->> (cc/update-user (cc/user user-id) user-delta)
(cmi/->user)))
(defn change-password
[user password]
(->> (cmo/->password password)
(cc/change-password user)))
(def password-check hashers/check)
(defn password-check-upgrade
[password hash upgrade-f]
(try
(password-check password hash)
(catch Exception e
(if (= hash (digest "sha-256" password))
(do (upgrade-f) true)
false))))
(defn user-by-credentials
[{:keys [username password]}]
(let [user (user-by-username username)]
(when
(password-check-upgrade password (:password user)
#(change-password user password))
user)))
(defn generate-api-token
[user]
(let [jti (swarmpit.uuid/uuid)
token (token/generate-jwt user {:exp nil :jti jti :iss "swarmpit-api"})]
(cc/set-api-token user {:jti jti :mask (subs token (- (count token) 5))})
{:token token}))
(defn remove-api-token
[user]
(cc/set-api-token user nil))
;;; Secret API
(defn secrets
([]
(secrets nil))
([label]
(-> (dc/secrets label)
(dmi/->secrets))))
(defn secret
[secret-id]
(-> (dc/secret secret-id)
(dmi/->secret)))
(defn delete-secret
[secret-id]
(dc/delete-secret secret-id))
(defn create-secret
[secret]
(-> (dmo/->secret secret)
(dc/create-secret)
(rename-keys {:ID :id})))
(defn update-secret
[secret-id secret]
(let [secret-version (:version secret)]
(->> (dmo/->secret secret)
(dc/update-secret secret-id secret-version))))
;;; Config API
(defn configs
([]
(configs nil))
([label]
(try (-> (dc/configs label)
(dmi/->configs))
(catch Exception _ []))))
(defn config
[config-id]
(-> (dc/config config-id)
(dmi/->config)))
(defn delete-config
[config-id]
(dc/delete-config config-id))
(defn create-config
[config]
(-> (dmo/->config config)
(dc/create-config)
(rename-keys {:ID :id})))
;;; Network API
(defn networks
([]
(networks nil))
([label]
(-> (dc/networks label)
(dmi/->networks))))
(defn network
[network-id]
(-> (dc/network network-id)
(dmi/->network)))
(defn delete-network
[network-id]
(dc/delete-network network-id))
(defn create-network
[network]
(-> (dmo/->network network)
(dc/create-network)
(rename-keys {:Id :id})))
;;; Volume API
(defn volumes
([]
(volumes nil))
([label]
(-> (dc/volumes label)
(dmi/->volumes))))
(defn volume
[volume-name]
(-> (dc/volume volume-name)
(dmi/->volume)))
(defn delete-volume
[volume-name]
(dc/delete-volume volume-name))
(defn create-volume
[volume]
(->> (dmo/->volume volume)
(dc/create-volume)
(dmi/->volume)))
;;; Stackfile API
(defn stackfiles
[]
(cc/stackfiles))
(defn stackfile
[stack-name]
(cc/stackfile stack-name))
(defn delete-stackfile
[stack-name]
(-> (cc/stackfile stack-name)
(cc/delete-stackfile)))
(defn- stackfile-json
[stackfile-spec]
(try
(yaml/->json (:compose stackfile-spec))
(catch Exception _ nil)))
(defn- stackfile-services
[stackfile-spec]
(->> (stackfile-json stackfile-spec)
:services
(vals)
(map #(dmi/->service-image-details (:image %)))))
(defn- stackfile-distibutions
[stackfile-spec filter-fx]
(->> (stackfile-services stackfile-spec)
(filter #(filter-fx (:name %)))
(map #(du/distribution-id (:name %)))
(into (hash-set))))
(defn- stackfile-dockerhub-distributions
[stackfile-spec]
(stackfile-distibutions stackfile-spec du/dockerhub?))
(defn- stackfile-registry-distributions
[stackfile-spec]
(stackfile-distibutions stackfile-spec du/registry?))
;;; Dockerhub distribution API
(defn dockerusers
[owner]
(-> (cc/dockerusers owner)
(cmi/->dockerusers)))
(defn dockeruser-info
[dockeruser]
(dhc/info dockeruser))
(defn dockeruser-namespace
[dockeruser-token]
(-> (dhc/namespaces dockeruser-token)
:namespaces))
(defn dockeruser-login
[dockeruser]
(dhc/login dockeruser))
(defn dockeruser-exist?
[dockeruser]
(cc/dockeruser-exist? dockeruser))
(defn dockeruser
[dockeruser-id]
(-> (cc/dockeruser dockeruser-id)
(cmi/->dockeruser)))
(defn- dockeruser-by-namespace
[owner dockeruser-namespace]
(->> (cc/dockerusers owner)
(filter #(contains? (set (:namespaces %)) dockeruser-namespace))
(first)))
(defn- dockeruser-by-stackfile
"Return best matching dockerhub account for given stackfile spec"
[owner stackfile-spec]
(let [namespaces (stackfile-dockerhub-distributions stackfile-spec)]
(->> (cc/dockerusers owner)
(map #(hash-map
:user-id (:_id %)
:matches (get
(->> (:namespaces %)
(map (fn [ns] (contains? namespaces ns)))
(frequencies))
true)))
(filter #(some? (:matches %)))
(sort-by :matches)
(last)
:user-id
(cc/dockeruser))))
(defn create-dockeruser
[dockeruser dockeruser-info dockeruser-namespace]
(if (not (dockeruser-exist? dockeruser))
(->> (cmo/->docker-user dockeruser dockeruser-info dockeruser-namespace)
(cc/create-dockeruser))))
(defn update-dockeruser
[dockeruser-id dockeruser-delta]
(->> (cc/update-dockeruser (cc/dockeruser dockeruser-id) dockeruser-delta)
(cmi/->dockeruser)))
(defn delete-dockeruser
[dockeruser-id]
(-> (dockeruser dockeruser-id)
(cc/delete-dockeruser)))
(defn dockeruser-repositories
[dockeruser-id]
(let [dockeruser (cc/dockeruser dockeruser-id)
dockeruser-token (:token (dhc/login dockeruser))]
(->> (dhc/namespaces dockeruser-token)
:namespaces
(map #(:results (dhc/repositories-by-namespace dockeruser-token %)))
(flatten)
(dhmi/->user-repositories))))
;; Public distribution API
(defn public-repositories
[repository-query repository-page]
(-> (dhc/repositories repository-query repository-page)
(dhmi/->repositories repository-query repository-page)))
;;; Registry distribution API
(defn registries
[owner]
(-> (cc/registries owner)
(cmi/->registries)))
(defn- registries-by-stackfile
"Return registry accounts for given stackfile spec"
[owner stackfile-spec]
(let [urls (stackfile-registry-distributions stackfile-spec)]
(->> (cc/registries owner)
(filter #(contains? urls (-> % :url url :host))))))
(defn registry
[registry-id]
(-> (cc/registry registry-id)
(cmi/->registry)))
(defn- registry-by-url
[owner registry-address]
(let [registry (->> (cc/registries owner)
(filter #(.contains (:url %) registry-address))
(first))]
(if (nil? registry)
(throw
(ex-info "Registry error: authentication required"
{:status 401
:body {:error "authentication required"}}))
registry)))
(defn registry-exist?
[registry]
(cc/registry-exist? registry))
(defn registry-info
[registry]
(rc/info registry))
(defn delete-registry
[registry-id]
(->> (registry registry-id)
(cc/delete-registry)))
(defn create-registry
[registry]
(when (not (registry-exist? registry))
(cc/create-registry registry)))
(defn update-registry
[registry-id registry-delta]
(->> (cc/update-registry (cc/registry registry-id) registry-delta)
(cmi/->registry)))
(defn registry-repositories
[registry-id]
(->> (cc/registry registry-id)
(rc/repositories)
(rmi/->repositories)))
;;; Repository Tags API
(defn- registry-repository-tags
[owner repository-name]
(let [registry-address (du/distribution-id repository-name)
repository-name (du/registry-repository repository-name registry-address)]
(-> (registry-by-url owner registry-address)
(rc/tags repository-name)
:tags)))
(defn- dockeruser-repository-tags
[owner repository-name]
(let [dockeruser-namespace (du/distribution-id repository-name)]
(-> (dockeruser-by-namespace owner dockeruser-namespace)
(dac/token repository-name)
:token
(drc/tags repository-name)
:tags)))
(defn- library-repository-tags
[repository-name]
(let [repository-name (du/library-repository repository-name)]
(-> (dac/token nil repository-name)
:token
(drc/tags repository-name)
:tags)))
(defn repository-tags
[owner repository-name]
(cond
(du/library? repository-name) (library-repository-tags repository-name)
(du/dockerhub? repository-name) (dockeruser-repository-tags owner repository-name)
:else (registry-repository-tags owner repository-name)))
;;; Repository Ports API
(defn- registry-repository-ports
[owner repository-name repository-tag]
(let [registry-address (du/distribution-id repository-name)
repository-name (du/registry-repository repository-name registry-address)]
(-> (registry-by-url owner registry-address)
(rc/manifest repository-name repository-tag)
(rmi/->repository-config)
:config
(dmi/->image-ports))))
(defn- dockeruser-repository-ports
[owner repository-name repository-tag]
(let [dockeruser-namespace (du/distribution-id repository-name)]
(-> (dockeruser-by-namespace owner dockeruser-namespace)
(dac/token repository-name)
:token
(drc/manifest repository-name repository-tag)
(rmi/->repository-config)
:config
(dmi/->image-ports))))
(defn- library-repository-ports
[repository-name repository-tag]
(let [repository-name (du/library-repository repository-name)]
(-> (dac/token nil repository-name)
:token
(drc/manifest repository-name repository-tag)
(rmi/->repository-config)
:config
(dmi/->image-ports))))
(defn repository-ports
[owner repository-name repository-tag]
(cond
(du/library? repository-name) (library-repository-ports repository-name repository-tag)
(du/dockerhub? repository-name) (dockeruser-repository-ports owner repository-name repository-tag)
:else (registry-repository-ports owner repository-name repository-tag)))
;;; Repository Digest API
(defn- registry-repository-digest
[owner repository-name repository-tag]
(let [registry-address (du/distribution-id repository-name)
repository-name (du/registry-repository repository-name registry-address)]
(-> (registry-by-url owner registry-address)
(rc/digest repository-name repository-tag))))
(defn- dockeruser-repository-digest
[owner repository-name repository-tag]
(let [dockeruser-namespace (du/distribution-id repository-name)]
(-> (dockeruser-by-namespace owner dockeruser-namespace)
(dac/token repository-name)
:token
(drc/digest repository-name repository-tag))))
(defn- library-repository-digest
[repository-name repository-tag]
(let [repository-name (du/library-repository repository-name)]
(-> (dac/token nil repository-name)
:token
(drc/digest repository-name repository-tag))))
(defn repository-digest
[owner repository-name repository-tag]
(cond
(du/library? repository-name) (library-repository-digest repository-name repository-tag)
(du/dockerhub? repository-name) (dockeruser-repository-digest owner repository-name repository-tag)
:else (registry-repository-digest owner repository-name repository-tag)))
;;; Task API
(defn task-stats
[task]
(let [stats (apply dissoc (stats/task task) [:name :id])]
(assoc task :stats stats)))
(defn tasks
[]
(->> (dmi/->tasks (dc/tasks)
(dc/nodes)
(dc/services))
(map #(task-stats %))))
(def tasks-memo (memo/ttl tasks :ttl/threshold 1000))
(defn task
[task-id]
(-> (dmi/->task (dc/task task-id)
(dc/nodes)
(dc/services))
(task-stats)))
;;; Service API
(defn services
([]
(services nil))
([label]
(services label (dc/networks)))
([label networks]
(dmi/->services (dc/services label)
(dc/tasks)
networks)))
(defn resources-by-services
[services resource source]
(let [ids (->> services
(map resource)
(flatten)
(map :id)
(set))]
(->> (source)
(filter #(contains? ids (:id %)))
(vec))))
(defn volumes-by-services
[services]
(let [volumes (->> (volumes)
(group-by :id))]
(->> services
(map :mounts)
(flatten)
(filter #(= "volume" (:type %)))
(map #(merge % {:volumeName (:host %)
:driver (-> % :volumeOptions :driver :name)
:options (-> % :volumeOptions :options)}))
(map #(merge (first (get volumes (:id %))) %)))))
(def services-memo (memo/ttl services :ttl/threshold 1000))
(defn- services-by
[service-filter]
(dmi/->services (filter #(service-filter %) (dc/services))
(dc/tasks)
(dc/networks)))
(defn services-by-network
[network-name]
(services-by #(contains? (->> (get-in % [:Spec :TaskTemplate :Networks])
(map :Target)
(set)) (:id (network network-name)))))
(defn services-by-volume
[volume-name]
(services-by #(contains? (->> (get-in % [:Spec :TaskTemplate :ContainerSpec :Mounts])
(map :Source)
(set)) volume-name)))
(defn services-by-secret
[secret-name]
(services-by #(contains? (->> (get-in % [:Spec :TaskTemplate :ContainerSpec :Secrets])
(map :SecretName)
(set)) secret-name)))
(defn services-by-config
[config-name]
(services-by #(contains? (->> (get-in % [:Spec :TaskTemplate :ContainerSpec :Configs])
(map :ConfigName)
(set)) config-name)))
(defn service
[service-id]
(dmi/->service (dc/service service-id)
(dc/service-tasks service-id)
(dc/networks)))
(defn service-networks
[service-id]
(dmi/->service-networks (dc/service service-id)
(dc/networks)))
(defn service-tasks
[service-id]
(->> (dmi/->tasks (dc/service-tasks service-id)
(dc/nodes)
(dc/services))
(map #(task-stats %))))
(defn service-logs
[service-id from-timestamp]
(letfn [(log-task [log tasks] (->> tasks
(filter #(= (:task log) (:id %)))
(first)))]
(let [tasks (tasks)]
(->> (dc/service-logs service-id)
(dl/parse-log)
(filter #(= 1 (compare (:timestamp %) from-timestamp)))
(map
(fn [i]
(let [task (log-task i tasks)]
(-> i
(assoc :taskName (:taskName task))
(assoc :taskNode (:nodeName task))))))))))
(defn delete-service
[service-id]
(dc/delete-service service-id))
(defn- standardize-service-configs
[service]
(if (<= 1.30 (read-string (cfg/config :docker-api)))
(assoc-in service [:configs] (dmo/->service-configs service (configs)))
service))
(defn- standardize-service-secrets
[service]
(assoc-in service [:secrets] (dmo/->service-secrets service (secrets))))
(defn- standardize-repository-tag
[repository-tag]
(if (str/blank? repository-tag)
"latest"
repository-tag))
(defn- standardize-service
[owner service]
(let [repository-name (get-in service [:repository :name])
repository-tag (standardize-repository-tag (get-in service [:repository :tag]))]
(-> service
(standardize-service-secrets)
(standardize-service-configs)
(assoc-in [:repository :tag] repository-tag)
(assoc-in [:repository :imageDigest] (repository-digest owner
repository-name
repository-tag)))))
(defn- service-auth
[owner service]
(let [repository-name (get-in service [:repository :name])
distribution-id (du/distribution-id repository-name)]
(dmo/->auth-config
(cond
(du/library? repository-name) nil
(du/dockerhub? repository-name) (dockeruser-by-namespace owner distribution-id)
:else (registry-by-url owner distribution-id)))))
(defn create-service
[owner service]
(rename-keys
(->> (standardize-service owner service)
(dmo/->service)
(dc/create-service (service-auth owner service))) {:ID :id}))
(defn- merge-service
[service-origin service-delta]
(-> (merge-data service-origin service-delta)
(assoc-in [:Labels] (:Labels service-delta))))
(defn update-service
[owner service]
(let [standardized-service (standardize-service owner service)
service-origin (-> (dc/service (:id service)) :Spec)
service-delta (dmo/->service standardized-service)]
(dc/update-service (service-auth owner service)
(:id service)
(:version service)
(merge-service service-origin service-delta))))
(defn redeploy-service
[owner service-id]
(let [service-origin (dc/service service-id)
service (dmi/->service service-origin)
repository-name (get-in service [:repository :name])
repository-tag (get-in service [:repository :tag])
image-digest (repository-digest owner repository-name repository-tag)
image (str repository-name ":" repository-tag "@" image-digest)]
(dc/update-service
(service-auth owner service)
service-id
(get-in service-origin [:Version :Index])
(-> service-origin
:Spec
(update-in [:TaskTemplate :ForceUpdate] inc)
(assoc-in [:TaskTemplate :ContainerSpec :Image] image)))))
(defn rollback-service
[owner service-id]
(let [service-origin (dc/service service-id)
service (dmi/->service service-origin)]
(dc/update-service
(service-auth owner service)
service-id
(get-in service-origin [:Version :Index])
(-> service-origin
:PreviousSpec))))
;;; Node API
(defn node-stats
[node]
(let [stats (apply dissoc (stats/node (:id node)) [:id :tasks])]
(assoc node :stats stats)))
(defn nodes
[]
(->> (dc/nodes)
(dmi/->nodes)
(map #(node-stats %))))
(defn node
[node-id]
(-> (dc/node node-id)
(dmi/->node)
(node-stats)))
(defn update-node
[node]
(dc/update-node (:id node)
(:version node)
node))
(defn update-node
[node-id node]
(let [node-version (:version node)]
(->> (dmo/->node node)
(dc/update-node node-id node-version))))
(defn node-tasks
[node-id]
(->> (dmi/->tasks (dc/node-tasks node-id)
(dc/nodes)
(dc/services))
(map #(task-stats %))))
;; Labels API
(defn labels-service
[]
(->> (services)
(map #(->> % :labels
(map :name)
(map str/trim)
(set)))
(apply clojure.set/union)))
;; Plugin API
(defn plugins
[]
(->> (dc/nodes)
(map #(get-in % [:Description :Engine :Plugins]))
(flatten)
(distinct)
(group-by :Type)))
(defn plugins-by-type
[type]
(->> (get (plugins) type)
(map :Name)))
;; Placement API
(defn- placement-rule
[nodes-attribute node-rule-fn]
(->> nodes-attribute
(map #(for [x [" == " " != "]]
(node-rule-fn x %)))
(flatten)))
(defn placement
[]
(let [nodes (nodes)
nodes-id (map :id nodes)
nodes-role '("manager" "worker")
nodes-hostname (map :nodeName nodes)
nodes-label (set (flatten (map :labels nodes)))]
(concat
(placement-rule
nodes-id
(fn [matcher item]
(str "node.id" matcher item)))
(placement-rule
nodes-role
(fn [matcher item]
(str "node.role" matcher item)))
(placement-rule
nodes-hostname
(fn [matcher item]
(str "node.hostname" matcher item)))
(placement-rule
nodes-label
(fn [matcher item]
(str "node.labels." (:name item) matcher (:value item)))))))
;; Stack API
(defn stack-label
[stack-name]
(str "com.docker.stack.namespace=" stack-name))
(defn stack-services
[stack-name]
(-> (stack-label stack-name)
(services)))
(defn stack
([stack-name services]
(when (not-empty services)
{:stackName stack-name
:stackFile (some? (stackfile stack-name))
:services services
:networks (resources-by-services services :networks networks)
:volumes (volumes-by-services services)
:configs (resources-by-services services :configs configs)
:secrets (resources-by-services services :secrets secrets)}))
([stack-name]
(stack stack-name (stack-services stack-name))))
(defn stack-compose
[stack-name]
(some-> (stack stack-name) (->compose) (->yaml)))
(defn service-compose
[service-name]
(some->> [(service service-name)]
(stack nil)
(->compose)
(->yaml)))
(defn stacks
[]
(->> (dissoc (group-by :stack (services)) nil)
(map (fn [s]
(letfn [(distinct-resources [r]
(->> (dissoc (group-by :id r) nil)
(vals)
(map first)
(map #(dissoc % :serviceAliases))))]
(let [stack-name (key s)
stack-services (val s)
stack-networks (flatten (map :networks stack-services))
stack-volumes (flatten (map :mounts stack-services))
stack-configs (flatten (map :configs stack-services))
stack-secrets (flatten (map :secrets stack-services))]
(when (not-empty stack-services)
{:stackName stack-name
:stackFile (some? (stackfile stack-name))
:services stack-services
:networks (distinct-resources stack-networks)
:volumes (distinct-resources stack-volumes)
:configs (distinct-resources stack-configs)
:secrets (distinct-resources stack-secrets)})))))))
(defn stack-login
[owner stackfile-spec]
(let [distributions (remove nil?
(conj (registries-by-stackfile owner stackfile-spec)
(dockeruser-by-stackfile owner stackfile-spec)))]
(doseq [distro distributions]
(dcli/login (:username distro)
(:password <PASSWORD>)
(:url distro)))))
(defn create-stack
"Create application stack and link stackfile"
[owner {:keys [name spec] :as stackfile}]
(let [stackfile-origin (cc/stackfile name)]
(stack-login owner spec)
(dcli/stack-deploy name (:compose spec))
(if (some? stackfile-origin)
(cc/update-stackfile stackfile-origin stackfile)
(cc/create-stackfile stackfile))))
(defn update-stack
"Update application stack and stackfile accordingly"
[owner {:keys [name spec] :as stackfile}]
(let [stackfile-origin (cc/stackfile name)]
(stack-login owner spec)
(dcli/stack-deploy name (:compose spec))
(if (some? stackfile-origin)
(cc/update-stackfile stackfile-origin {:spec spec
:previousSpec (:spec stackfile-origin)})
(cc/create-stackfile stackfile))))
(defn redeploy-stack
"Redeploy application stack"
[owner name]
(let [{:keys [name spec]} (cc/stackfile name)]
(stack-login owner spec)
(dcli/stack-deploy name (:compose spec))))
(defn rollback-stack
"Rollback application stack and update stackfile accordingly"
[owner name]
(let [{:keys [name spec previousSpec] :as stackfile-origin} (cc/stackfile name)]
(stack-login owner previousSpec)
(dcli/stack-deploy name (:compose previousSpec))
(cc/update-stackfile stackfile-origin {:spec previousSpec
:previousSpec spec})))
(defn delete-stack
[stack-name]
(dcli/stack-remove stack-name)) | true | (ns swarmpit.api
(:require [clojure.set :refer [rename-keys]]
[buddy.hashers :as hashers]
[digest :refer [digest]]
[swarmpit.utils :refer [merge-data]]
[swarmpit.config :as cfg]
[swarmpit.stats :as stats]
[swarmpit.yaml :as yaml :refer [->yaml]]
[swarmpit.docker.utils :as du]
[swarmpit.docker.engine.client :as dc]
[swarmpit.docker.engine.cli :as dcli]
[swarmpit.docker.engine.log :as dl]
[swarmpit.docker.engine.mapper.inbound :as dmi]
[swarmpit.docker.engine.mapper.outbound :as dmo]
[swarmpit.docker.engine.mapper.compose :refer [->compose]]
[swarmpit.docker.auth.client :as dac]
[swarmpit.docker.registry.client :as drc]
[swarmpit.docker.hub.client :as dhc]
[swarmpit.docker.hub.mapper.inbound :as dhmi]
[swarmpit.registry.client :as rc]
[swarmpit.registry.mapper.inbound :as rmi]
[swarmpit.couchdb.client :as cc]
[swarmpit.couchdb.mapper.inbound :as cmi]
[swarmpit.couchdb.mapper.outbound :as cmo]
[clojure.core.memoize :as memo]
[clojure.tools.logging :as log]
[clojure.string :as str]
[cemerick.url :refer [url]]
[swarmpit.token :as token]))
;;; User API
(defn users
[]
(-> (cc/users)
(cmi/->users)))
(defn user
[user-id]
(-> (cc/user user-id)
(cmi/->user)))
(defn user-by-username
[username]
(cc/user-by-username username))
(defn user-exist?
[user]
(some? (user-by-username (:username user))))
(defn delete-user
[user-id]
(->> (user user-id)
(cc/delete-user)))
(defn create-user
[user]
(if (not (user-exist? user))
(->> (cmo/->user user)
(cc/create-user))))
(defn update-user
[user-id user-delta]
(->> (cc/update-user (cc/user user-id) user-delta)
(cmi/->user)))
(defn change-password
[user password]
(->> (cmo/->password password)
(cc/change-password user)))
(def password-check hashers/check)
(defn password-check-upgrade
[password hash upgrade-f]
(try
(password-check password hash)
(catch Exception e
(if (= hash (digest "sha-256" password))
(do (upgrade-f) true)
false))))
(defn user-by-credentials
[{:keys [username password]}]
(let [user (user-by-username username)]
(when
(password-check-upgrade password (:password user)
#(change-password user password))
user)))
(defn generate-api-token
[user]
(let [jti (swarmpit.uuid/uuid)
token (token/generate-jwt user {:exp nil :jti jti :iss "swarmpit-api"})]
(cc/set-api-token user {:jti jti :mask (subs token (- (count token) 5))})
{:token token}))
(defn remove-api-token
[user]
(cc/set-api-token user nil))
;;; Secret API
(defn secrets
([]
(secrets nil))
([label]
(-> (dc/secrets label)
(dmi/->secrets))))
(defn secret
[secret-id]
(-> (dc/secret secret-id)
(dmi/->secret)))
(defn delete-secret
[secret-id]
(dc/delete-secret secret-id))
(defn create-secret
[secret]
(-> (dmo/->secret secret)
(dc/create-secret)
(rename-keys {:ID :id})))
(defn update-secret
[secret-id secret]
(let [secret-version (:version secret)]
(->> (dmo/->secret secret)
(dc/update-secret secret-id secret-version))))
;;; Config API
(defn configs
([]
(configs nil))
([label]
(try (-> (dc/configs label)
(dmi/->configs))
(catch Exception _ []))))
(defn config
[config-id]
(-> (dc/config config-id)
(dmi/->config)))
(defn delete-config
[config-id]
(dc/delete-config config-id))
(defn create-config
[config]
(-> (dmo/->config config)
(dc/create-config)
(rename-keys {:ID :id})))
;;; Network API
(defn networks
([]
(networks nil))
([label]
(-> (dc/networks label)
(dmi/->networks))))
(defn network
[network-id]
(-> (dc/network network-id)
(dmi/->network)))
(defn delete-network
[network-id]
(dc/delete-network network-id))
(defn create-network
[network]
(-> (dmo/->network network)
(dc/create-network)
(rename-keys {:Id :id})))
;;; Volume API
(defn volumes
([]
(volumes nil))
([label]
(-> (dc/volumes label)
(dmi/->volumes))))
(defn volume
[volume-name]
(-> (dc/volume volume-name)
(dmi/->volume)))
(defn delete-volume
[volume-name]
(dc/delete-volume volume-name))
(defn create-volume
[volume]
(->> (dmo/->volume volume)
(dc/create-volume)
(dmi/->volume)))
;;; Stackfile API
(defn stackfiles
[]
(cc/stackfiles))
(defn stackfile
[stack-name]
(cc/stackfile stack-name))
(defn delete-stackfile
[stack-name]
(-> (cc/stackfile stack-name)
(cc/delete-stackfile)))
(defn- stackfile-json
[stackfile-spec]
(try
(yaml/->json (:compose stackfile-spec))
(catch Exception _ nil)))
(defn- stackfile-services
[stackfile-spec]
(->> (stackfile-json stackfile-spec)
:services
(vals)
(map #(dmi/->service-image-details (:image %)))))
(defn- stackfile-distibutions
[stackfile-spec filter-fx]
(->> (stackfile-services stackfile-spec)
(filter #(filter-fx (:name %)))
(map #(du/distribution-id (:name %)))
(into (hash-set))))
(defn- stackfile-dockerhub-distributions
[stackfile-spec]
(stackfile-distibutions stackfile-spec du/dockerhub?))
(defn- stackfile-registry-distributions
[stackfile-spec]
(stackfile-distibutions stackfile-spec du/registry?))
;;; Dockerhub distribution API
(defn dockerusers
[owner]
(-> (cc/dockerusers owner)
(cmi/->dockerusers)))
(defn dockeruser-info
[dockeruser]
(dhc/info dockeruser))
(defn dockeruser-namespace
[dockeruser-token]
(-> (dhc/namespaces dockeruser-token)
:namespaces))
(defn dockeruser-login
[dockeruser]
(dhc/login dockeruser))
(defn dockeruser-exist?
[dockeruser]
(cc/dockeruser-exist? dockeruser))
(defn dockeruser
[dockeruser-id]
(-> (cc/dockeruser dockeruser-id)
(cmi/->dockeruser)))
(defn- dockeruser-by-namespace
[owner dockeruser-namespace]
(->> (cc/dockerusers owner)
(filter #(contains? (set (:namespaces %)) dockeruser-namespace))
(first)))
(defn- dockeruser-by-stackfile
"Return best matching dockerhub account for given stackfile spec"
[owner stackfile-spec]
(let [namespaces (stackfile-dockerhub-distributions stackfile-spec)]
(->> (cc/dockerusers owner)
(map #(hash-map
:user-id (:_id %)
:matches (get
(->> (:namespaces %)
(map (fn [ns] (contains? namespaces ns)))
(frequencies))
true)))
(filter #(some? (:matches %)))
(sort-by :matches)
(last)
:user-id
(cc/dockeruser))))
(defn create-dockeruser
[dockeruser dockeruser-info dockeruser-namespace]
(if (not (dockeruser-exist? dockeruser))
(->> (cmo/->docker-user dockeruser dockeruser-info dockeruser-namespace)
(cc/create-dockeruser))))
(defn update-dockeruser
[dockeruser-id dockeruser-delta]
(->> (cc/update-dockeruser (cc/dockeruser dockeruser-id) dockeruser-delta)
(cmi/->dockeruser)))
(defn delete-dockeruser
[dockeruser-id]
(-> (dockeruser dockeruser-id)
(cc/delete-dockeruser)))
(defn dockeruser-repositories
[dockeruser-id]
(let [dockeruser (cc/dockeruser dockeruser-id)
dockeruser-token (:token (dhc/login dockeruser))]
(->> (dhc/namespaces dockeruser-token)
:namespaces
(map #(:results (dhc/repositories-by-namespace dockeruser-token %)))
(flatten)
(dhmi/->user-repositories))))
;; Public distribution API
(defn public-repositories
[repository-query repository-page]
(-> (dhc/repositories repository-query repository-page)
(dhmi/->repositories repository-query repository-page)))
;;; Registry distribution API
(defn registries
[owner]
(-> (cc/registries owner)
(cmi/->registries)))
(defn- registries-by-stackfile
"Return registry accounts for given stackfile spec"
[owner stackfile-spec]
(let [urls (stackfile-registry-distributions stackfile-spec)]
(->> (cc/registries owner)
(filter #(contains? urls (-> % :url url :host))))))
(defn registry
[registry-id]
(-> (cc/registry registry-id)
(cmi/->registry)))
(defn- registry-by-url
[owner registry-address]
(let [registry (->> (cc/registries owner)
(filter #(.contains (:url %) registry-address))
(first))]
(if (nil? registry)
(throw
(ex-info "Registry error: authentication required"
{:status 401
:body {:error "authentication required"}}))
registry)))
(defn registry-exist?
[registry]
(cc/registry-exist? registry))
(defn registry-info
[registry]
(rc/info registry))
(defn delete-registry
[registry-id]
(->> (registry registry-id)
(cc/delete-registry)))
(defn create-registry
[registry]
(when (not (registry-exist? registry))
(cc/create-registry registry)))
(defn update-registry
[registry-id registry-delta]
(->> (cc/update-registry (cc/registry registry-id) registry-delta)
(cmi/->registry)))
(defn registry-repositories
[registry-id]
(->> (cc/registry registry-id)
(rc/repositories)
(rmi/->repositories)))
;;; Repository Tags API
(defn- registry-repository-tags
[owner repository-name]
(let [registry-address (du/distribution-id repository-name)
repository-name (du/registry-repository repository-name registry-address)]
(-> (registry-by-url owner registry-address)
(rc/tags repository-name)
:tags)))
(defn- dockeruser-repository-tags
[owner repository-name]
(let [dockeruser-namespace (du/distribution-id repository-name)]
(-> (dockeruser-by-namespace owner dockeruser-namespace)
(dac/token repository-name)
:token
(drc/tags repository-name)
:tags)))
(defn- library-repository-tags
[repository-name]
(let [repository-name (du/library-repository repository-name)]
(-> (dac/token nil repository-name)
:token
(drc/tags repository-name)
:tags)))
(defn repository-tags
[owner repository-name]
(cond
(du/library? repository-name) (library-repository-tags repository-name)
(du/dockerhub? repository-name) (dockeruser-repository-tags owner repository-name)
:else (registry-repository-tags owner repository-name)))
;;; Repository Ports API
(defn- registry-repository-ports
[owner repository-name repository-tag]
(let [registry-address (du/distribution-id repository-name)
repository-name (du/registry-repository repository-name registry-address)]
(-> (registry-by-url owner registry-address)
(rc/manifest repository-name repository-tag)
(rmi/->repository-config)
:config
(dmi/->image-ports))))
(defn- dockeruser-repository-ports
[owner repository-name repository-tag]
(let [dockeruser-namespace (du/distribution-id repository-name)]
(-> (dockeruser-by-namespace owner dockeruser-namespace)
(dac/token repository-name)
:token
(drc/manifest repository-name repository-tag)
(rmi/->repository-config)
:config
(dmi/->image-ports))))
(defn- library-repository-ports
[repository-name repository-tag]
(let [repository-name (du/library-repository repository-name)]
(-> (dac/token nil repository-name)
:token
(drc/manifest repository-name repository-tag)
(rmi/->repository-config)
:config
(dmi/->image-ports))))
(defn repository-ports
[owner repository-name repository-tag]
(cond
(du/library? repository-name) (library-repository-ports repository-name repository-tag)
(du/dockerhub? repository-name) (dockeruser-repository-ports owner repository-name repository-tag)
:else (registry-repository-ports owner repository-name repository-tag)))
;;; Repository Digest API
(defn- registry-repository-digest
[owner repository-name repository-tag]
(let [registry-address (du/distribution-id repository-name)
repository-name (du/registry-repository repository-name registry-address)]
(-> (registry-by-url owner registry-address)
(rc/digest repository-name repository-tag))))
(defn- dockeruser-repository-digest
[owner repository-name repository-tag]
(let [dockeruser-namespace (du/distribution-id repository-name)]
(-> (dockeruser-by-namespace owner dockeruser-namespace)
(dac/token repository-name)
:token
(drc/digest repository-name repository-tag))))
(defn- library-repository-digest
[repository-name repository-tag]
(let [repository-name (du/library-repository repository-name)]
(-> (dac/token nil repository-name)
:token
(drc/digest repository-name repository-tag))))
(defn repository-digest
[owner repository-name repository-tag]
(cond
(du/library? repository-name) (library-repository-digest repository-name repository-tag)
(du/dockerhub? repository-name) (dockeruser-repository-digest owner repository-name repository-tag)
:else (registry-repository-digest owner repository-name repository-tag)))
;;; Task API
(defn task-stats
[task]
(let [stats (apply dissoc (stats/task task) [:name :id])]
(assoc task :stats stats)))
(defn tasks
[]
(->> (dmi/->tasks (dc/tasks)
(dc/nodes)
(dc/services))
(map #(task-stats %))))
(def tasks-memo (memo/ttl tasks :ttl/threshold 1000))
(defn task
[task-id]
(-> (dmi/->task (dc/task task-id)
(dc/nodes)
(dc/services))
(task-stats)))
;;; Service API
(defn services
([]
(services nil))
([label]
(services label (dc/networks)))
([label networks]
(dmi/->services (dc/services label)
(dc/tasks)
networks)))
(defn resources-by-services
[services resource source]
(let [ids (->> services
(map resource)
(flatten)
(map :id)
(set))]
(->> (source)
(filter #(contains? ids (:id %)))
(vec))))
(defn volumes-by-services
[services]
(let [volumes (->> (volumes)
(group-by :id))]
(->> services
(map :mounts)
(flatten)
(filter #(= "volume" (:type %)))
(map #(merge % {:volumeName (:host %)
:driver (-> % :volumeOptions :driver :name)
:options (-> % :volumeOptions :options)}))
(map #(merge (first (get volumes (:id %))) %)))))
(def services-memo (memo/ttl services :ttl/threshold 1000))
(defn- services-by
[service-filter]
(dmi/->services (filter #(service-filter %) (dc/services))
(dc/tasks)
(dc/networks)))
(defn services-by-network
[network-name]
(services-by #(contains? (->> (get-in % [:Spec :TaskTemplate :Networks])
(map :Target)
(set)) (:id (network network-name)))))
(defn services-by-volume
[volume-name]
(services-by #(contains? (->> (get-in % [:Spec :TaskTemplate :ContainerSpec :Mounts])
(map :Source)
(set)) volume-name)))
(defn services-by-secret
[secret-name]
(services-by #(contains? (->> (get-in % [:Spec :TaskTemplate :ContainerSpec :Secrets])
(map :SecretName)
(set)) secret-name)))
(defn services-by-config
[config-name]
(services-by #(contains? (->> (get-in % [:Spec :TaskTemplate :ContainerSpec :Configs])
(map :ConfigName)
(set)) config-name)))
(defn service
[service-id]
(dmi/->service (dc/service service-id)
(dc/service-tasks service-id)
(dc/networks)))
(defn service-networks
[service-id]
(dmi/->service-networks (dc/service service-id)
(dc/networks)))
(defn service-tasks
[service-id]
(->> (dmi/->tasks (dc/service-tasks service-id)
(dc/nodes)
(dc/services))
(map #(task-stats %))))
(defn service-logs
[service-id from-timestamp]
(letfn [(log-task [log tasks] (->> tasks
(filter #(= (:task log) (:id %)))
(first)))]
(let [tasks (tasks)]
(->> (dc/service-logs service-id)
(dl/parse-log)
(filter #(= 1 (compare (:timestamp %) from-timestamp)))
(map
(fn [i]
(let [task (log-task i tasks)]
(-> i
(assoc :taskName (:taskName task))
(assoc :taskNode (:nodeName task))))))))))
(defn delete-service
[service-id]
(dc/delete-service service-id))
(defn- standardize-service-configs
[service]
(if (<= 1.30 (read-string (cfg/config :docker-api)))
(assoc-in service [:configs] (dmo/->service-configs service (configs)))
service))
(defn- standardize-service-secrets
[service]
(assoc-in service [:secrets] (dmo/->service-secrets service (secrets))))
(defn- standardize-repository-tag
[repository-tag]
(if (str/blank? repository-tag)
"latest"
repository-tag))
(defn- standardize-service
[owner service]
(let [repository-name (get-in service [:repository :name])
repository-tag (standardize-repository-tag (get-in service [:repository :tag]))]
(-> service
(standardize-service-secrets)
(standardize-service-configs)
(assoc-in [:repository :tag] repository-tag)
(assoc-in [:repository :imageDigest] (repository-digest owner
repository-name
repository-tag)))))
(defn- service-auth
[owner service]
(let [repository-name (get-in service [:repository :name])
distribution-id (du/distribution-id repository-name)]
(dmo/->auth-config
(cond
(du/library? repository-name) nil
(du/dockerhub? repository-name) (dockeruser-by-namespace owner distribution-id)
:else (registry-by-url owner distribution-id)))))
(defn create-service
[owner service]
(rename-keys
(->> (standardize-service owner service)
(dmo/->service)
(dc/create-service (service-auth owner service))) {:ID :id}))
(defn- merge-service
[service-origin service-delta]
(-> (merge-data service-origin service-delta)
(assoc-in [:Labels] (:Labels service-delta))))
(defn update-service
[owner service]
(let [standardized-service (standardize-service owner service)
service-origin (-> (dc/service (:id service)) :Spec)
service-delta (dmo/->service standardized-service)]
(dc/update-service (service-auth owner service)
(:id service)
(:version service)
(merge-service service-origin service-delta))))
(defn redeploy-service
[owner service-id]
(let [service-origin (dc/service service-id)
service (dmi/->service service-origin)
repository-name (get-in service [:repository :name])
repository-tag (get-in service [:repository :tag])
image-digest (repository-digest owner repository-name repository-tag)
image (str repository-name ":" repository-tag "@" image-digest)]
(dc/update-service
(service-auth owner service)
service-id
(get-in service-origin [:Version :Index])
(-> service-origin
:Spec
(update-in [:TaskTemplate :ForceUpdate] inc)
(assoc-in [:TaskTemplate :ContainerSpec :Image] image)))))
(defn rollback-service
[owner service-id]
(let [service-origin (dc/service service-id)
service (dmi/->service service-origin)]
(dc/update-service
(service-auth owner service)
service-id
(get-in service-origin [:Version :Index])
(-> service-origin
:PreviousSpec))))
;;; Node API
(defn node-stats
[node]
(let [stats (apply dissoc (stats/node (:id node)) [:id :tasks])]
(assoc node :stats stats)))
(defn nodes
[]
(->> (dc/nodes)
(dmi/->nodes)
(map #(node-stats %))))
(defn node
[node-id]
(-> (dc/node node-id)
(dmi/->node)
(node-stats)))
(defn update-node
[node]
(dc/update-node (:id node)
(:version node)
node))
(defn update-node
[node-id node]
(let [node-version (:version node)]
(->> (dmo/->node node)
(dc/update-node node-id node-version))))
(defn node-tasks
[node-id]
(->> (dmi/->tasks (dc/node-tasks node-id)
(dc/nodes)
(dc/services))
(map #(task-stats %))))
;; Labels API
(defn labels-service
[]
(->> (services)
(map #(->> % :labels
(map :name)
(map str/trim)
(set)))
(apply clojure.set/union)))
;; Plugin API
(defn plugins
[]
(->> (dc/nodes)
(map #(get-in % [:Description :Engine :Plugins]))
(flatten)
(distinct)
(group-by :Type)))
(defn plugins-by-type
[type]
(->> (get (plugins) type)
(map :Name)))
;; Placement API
(defn- placement-rule
[nodes-attribute node-rule-fn]
(->> nodes-attribute
(map #(for [x [" == " " != "]]
(node-rule-fn x %)))
(flatten)))
(defn placement
[]
(let [nodes (nodes)
nodes-id (map :id nodes)
nodes-role '("manager" "worker")
nodes-hostname (map :nodeName nodes)
nodes-label (set (flatten (map :labels nodes)))]
(concat
(placement-rule
nodes-id
(fn [matcher item]
(str "node.id" matcher item)))
(placement-rule
nodes-role
(fn [matcher item]
(str "node.role" matcher item)))
(placement-rule
nodes-hostname
(fn [matcher item]
(str "node.hostname" matcher item)))
(placement-rule
nodes-label
(fn [matcher item]
(str "node.labels." (:name item) matcher (:value item)))))))
;; Stack API
(defn stack-label
[stack-name]
(str "com.docker.stack.namespace=" stack-name))
(defn stack-services
[stack-name]
(-> (stack-label stack-name)
(services)))
(defn stack
([stack-name services]
(when (not-empty services)
{:stackName stack-name
:stackFile (some? (stackfile stack-name))
:services services
:networks (resources-by-services services :networks networks)
:volumes (volumes-by-services services)
:configs (resources-by-services services :configs configs)
:secrets (resources-by-services services :secrets secrets)}))
([stack-name]
(stack stack-name (stack-services stack-name))))
(defn stack-compose
[stack-name]
(some-> (stack stack-name) (->compose) (->yaml)))
(defn service-compose
[service-name]
(some->> [(service service-name)]
(stack nil)
(->compose)
(->yaml)))
(defn stacks
[]
(->> (dissoc (group-by :stack (services)) nil)
(map (fn [s]
(letfn [(distinct-resources [r]
(->> (dissoc (group-by :id r) nil)
(vals)
(map first)
(map #(dissoc % :serviceAliases))))]
(let [stack-name (key s)
stack-services (val s)
stack-networks (flatten (map :networks stack-services))
stack-volumes (flatten (map :mounts stack-services))
stack-configs (flatten (map :configs stack-services))
stack-secrets (flatten (map :secrets stack-services))]
(when (not-empty stack-services)
{:stackName stack-name
:stackFile (some? (stackfile stack-name))
:services stack-services
:networks (distinct-resources stack-networks)
:volumes (distinct-resources stack-volumes)
:configs (distinct-resources stack-configs)
:secrets (distinct-resources stack-secrets)})))))))
(defn stack-login
[owner stackfile-spec]
(let [distributions (remove nil?
(conj (registries-by-stackfile owner stackfile-spec)
(dockeruser-by-stackfile owner stackfile-spec)))]
(doseq [distro distributions]
(dcli/login (:username distro)
(:password PI:PASSWORD:<PASSWORD>END_PI)
(:url distro)))))
(defn create-stack
"Create application stack and link stackfile"
[owner {:keys [name spec] :as stackfile}]
(let [stackfile-origin (cc/stackfile name)]
(stack-login owner spec)
(dcli/stack-deploy name (:compose spec))
(if (some? stackfile-origin)
(cc/update-stackfile stackfile-origin stackfile)
(cc/create-stackfile stackfile))))
(defn update-stack
"Update application stack and stackfile accordingly"
[owner {:keys [name spec] :as stackfile}]
(let [stackfile-origin (cc/stackfile name)]
(stack-login owner spec)
(dcli/stack-deploy name (:compose spec))
(if (some? stackfile-origin)
(cc/update-stackfile stackfile-origin {:spec spec
:previousSpec (:spec stackfile-origin)})
(cc/create-stackfile stackfile))))
(defn redeploy-stack
"Redeploy application stack"
[owner name]
(let [{:keys [name spec]} (cc/stackfile name)]
(stack-login owner spec)
(dcli/stack-deploy name (:compose spec))))
(defn rollback-stack
"Rollback application stack and update stackfile accordingly"
[owner name]
(let [{:keys [name spec previousSpec] :as stackfile-origin} (cc/stackfile name)]
(stack-login owner previousSpec)
(dcli/stack-deploy name (:compose previousSpec))
(cc/update-stackfile stackfile-origin {:spec previousSpec
:previousSpec spec})))
(defn delete-stack
[stack-name]
(dcli/stack-remove stack-name)) |
[
{
"context": "; Copyright (c) Anna Shchiptsova, IIASA. All rights reserved.\r\n; The use and dis",
"end": 34,
"score": 0.9998904466629028,
"start": 18,
"tag": "NAME",
"value": "Anna Shchiptsova"
},
{
"context": "to string using a custom format.\"\r\n :author \"Anna Shchiptsova\"}\r\n utilities-clj.format\r\n (:require [utilities-",
"end": 546,
"score": 0.9998955130577087,
"start": 530,
"tag": "NAME",
"value": "Anna Shchiptsova"
}
] | src/utilities_clj/format.clj | shchipts/utilities-clj | 0 | ; Copyright (c) Anna Shchiptsova, IIASA. All rights reserved.
; The use and distribution terms for this software are covered by the
; MIT License (http://opensource.org/licenses/MIT)
; which can be found in the file LICENSE at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns ^{:doc "Type conversion to string using a custom format."
:author "Anna Shchiptsova"}
utilities-clj.format
(:require [utilities-clj.string-formatter :as string-formatter]))
(defn double-to-str
"Formats a string from a floating-point number. Value is converted
to string with the number of decimal places equal to digits. Formatting
is independent from locale with point used as decimal separator.
Returns string in the floating-point format: [+-]([0-9]*[.])?[0-9]+
## Usage
(require '[utilities.format :refer :all])
(double-to-str 1.9 4)
=> \"1.9000\"
(double-to-str -45.688 2)
=> \"-45.69\"
(double-to-str +45.688 2)
=> \"45.69\"
"
[value digits]
(-> (str "%."
digits
"f")
(format value)
string-formatter/to-numeric))
| 5184 | ; Copyright (c) <NAME>, IIASA. All rights reserved.
; The use and distribution terms for this software are covered by the
; MIT License (http://opensource.org/licenses/MIT)
; which can be found in the file LICENSE at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns ^{:doc "Type conversion to string using a custom format."
:author "<NAME>"}
utilities-clj.format
(:require [utilities-clj.string-formatter :as string-formatter]))
(defn double-to-str
"Formats a string from a floating-point number. Value is converted
to string with the number of decimal places equal to digits. Formatting
is independent from locale with point used as decimal separator.
Returns string in the floating-point format: [+-]([0-9]*[.])?[0-9]+
## Usage
(require '[utilities.format :refer :all])
(double-to-str 1.9 4)
=> \"1.9000\"
(double-to-str -45.688 2)
=> \"-45.69\"
(double-to-str +45.688 2)
=> \"45.69\"
"
[value digits]
(-> (str "%."
digits
"f")
(format value)
string-formatter/to-numeric))
| true | ; Copyright (c) PI:NAME:<NAME>END_PI, IIASA. All rights reserved.
; The use and distribution terms for this software are covered by the
; MIT License (http://opensource.org/licenses/MIT)
; which can be found in the file LICENSE at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns ^{:doc "Type conversion to string using a custom format."
:author "PI:NAME:<NAME>END_PI"}
utilities-clj.format
(:require [utilities-clj.string-formatter :as string-formatter]))
(defn double-to-str
"Formats a string from a floating-point number. Value is converted
to string with the number of decimal places equal to digits. Formatting
is independent from locale with point used as decimal separator.
Returns string in the floating-point format: [+-]([0-9]*[.])?[0-9]+
## Usage
(require '[utilities.format :refer :all])
(double-to-str 1.9 4)
=> \"1.9000\"
(double-to-str -45.688 2)
=> \"-45.69\"
(double-to-str +45.688 2)
=> \"45.69\"
"
[value digits]
(-> (str "%."
digits
"f")
(format value)
string-formatter/to-numeric))
|
[
{
"context": "\n(def ^:private dummy-factory-fn\n (fn [] {:name \"Alice\"}))\n\n(s/def ::name string?)\n(s/def ::with-name (s",
"end": 233,
"score": 0.9421542286872864,
"start": 228,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ild-args {:registered {:y 2020 :m 2 :d 29} :name \"Bob\"}}\n registered-2021 {:factory-fn dummy-fac",
"end": 4528,
"score": 0.9708006978034973,
"start": 4525,
"tag": "NAME",
"value": "Bob"
},
{
"context": " (fs/build-args registered-2020 {:name \"Bob\"}))))\n\n (testing \"override existing trait\"\n ",
"end": 4916,
"score": 0.9580879211425781,
"start": 4913,
"tag": "NAME",
"value": "Bob"
},
{
"context": "-fn\n :fields {:name {:first \"Bob\" :last \"Doe\"} :role \"Admin\"}}\n with-bob-ro",
"end": 5347,
"score": 0.9997004270553589,
"start": 5344,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :fields {:name {:first \"Bob\" :last \"Doe\"} :role \"Admin\"}}\n with-bob-roe {:factory-",
"end": 5359,
"score": 0.9985438585281372,
"start": 5356,
"tag": "NAME",
"value": "Doe"
},
{
"context": "-fn\n :fields {:name {:first \"Bob\" :last \"Roe\"} :role \"Editor\"}}]\n\n (testing \"on",
"end": 5478,
"score": 0.9995747208595276,
"start": 5475,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :fields {:name {:first \"Bob\" :last \"Roe\"} :role \"Editor\"}}]\n\n (testing \"on factory wit",
"end": 5490,
"score": 0.9979727268218994,
"start": 5487,
"tag": "NAME",
"value": "Roe"
},
{
"context": "b\n (fs/fields factory {:name {:first \"Bob\" :last \"Doe\"} :role \"Admin\"}))))\n\n (testing \"r",
"end": 5626,
"score": 0.9996047616004944,
"start": 5623,
"tag": "NAME",
"value": "Bob"
},
{
"context": " (fs/fields factory {:name {:first \"Bob\" :last \"Doe\"} :role \"Admin\"}))))\n\n (testing \"recursively m",
"end": 5638,
"score": 0.9981402158737183,
"start": 5635,
"tag": "NAME",
"value": "Doe"
},
{
"context": "e\n (fs/fields with-bob {:name {:last \"Roe\"} :role \"Editor\"}))))\n\n (testing \"test instrum",
"end": 5792,
"score": 0.9994987845420837,
"start": 5789,
"tag": "NAME",
"value": "Roe"
},
{
"context": "trait\n\n (let [fn1 (fn [p _] (update p :name str \" Doe\"))\n fn2 (fn [p _] (assoc p :role \"Admin\"))",
"end": 5987,
"score": 0.9978222846984863,
"start": 5984,
"tag": "NAME",
"value": "Doe"
},
{
"context": "rue}\n :fields {:name \"Alice\"}\n :post-build-fns [fn2 fn3]}",
"end": 6267,
"score": 0.999803900718689,
"start": 6262,
"tag": "NAME",
"value": "Alice"
},
{
"context": "n3]}\n bob-trait {:fields {:name \"Bob\"}}\n guest-trait {:build-args {:registe",
"end": 6366,
"score": 0.9996587038040161,
"start": 6363,
"tag": "NAME",
"value": "Bob"
},
{
"context": "a :role \"Admin\"}\n :fields {:name \"Carol\" :role \"Admin\"}\n :post-build-fns ",
"end": 6704,
"score": 0.999244213104248,
"start": 6699,
"tag": "NAME",
"value": "Carol"
},
{
"context": "true :role \"Admin\"}\n :fields {:name \"Alice\" :role \"Admin\"}\n :post-build-fns [fn",
"end": 7048,
"score": 0.9998484253883362,
"start": 7043,
"tag": "NAME",
"value": "Alice"
},
{
"context": ":n/a :role \"Admin\"}\n :fields {:name \"Bob\" :role \"Admin\"}\n :post-build-fns [fn",
"end": 7448,
"score": 0.999822199344635,
"start": 7445,
"tag": "NAME",
"value": "Bob"
},
{
"context": "alse :role \"Guest\"}\n :fields {:name \"Carol\" :role \"Admin\"}\n :post-build-fns [fn",
"end": 7788,
"score": 0.9990890026092529,
"start": 7783,
"tag": "NAME",
"value": "Carol"
},
{
"context": "g \"build from just factory-fn\"\n (is (= {:name \"Bob\"}\n (fs/build {:factory-fn (fn [_] {:nam",
"end": 8261,
"score": 0.9993491768836975,
"start": 8258,
"tag": "NAME",
"value": "Bob"
},
{
"context": " (fs/build {:factory-fn (fn [_] {:name \"Bob\"})}))))\n\n (testing \"build with build-args as sec",
"end": 8317,
"score": 0.9994574189186096,
"start": 8314,
"tag": "NAME",
"value": "Bob"
},
{
"context": "e product recursively\"\n (is (= {:name {:first \"Bob\" :last \"Roe\"}}\n (fs/build {:factory-fn ",
"end": 8659,
"score": 0.9995142817497253,
"start": 8656,
"tag": "NAME",
"value": "Bob"
},
{
"context": "cursively\"\n (is (= {:name {:first \"Bob\" :last \"Roe\"}}\n (fs/build {:factory-fn (fn [_] {:na",
"end": 8671,
"score": 0.9173864722251892,
"start": 8668,
"tag": "NAME",
"value": "Roe"
},
{
"context": " (fs/build {:factory-fn (fn [_] {:name {:first \"Bob\" :last \"Doe\"}})\n :fields {:n",
"end": 8736,
"score": 0.9997639060020447,
"start": 8733,
"tag": "NAME",
"value": "Bob"
},
{
"context": " {:factory-fn (fn [_] {:name {:first \"Bob\" :last \"Doe\"}})\n :fields {:name {:last \"",
"end": 8748,
"score": 0.9993199110031128,
"start": 8745,
"tag": "NAME",
"value": "Doe"
},
{
"context": "\"}})\n :fields {:name {:last \"Roe\"}}}))))\n\n (testing \"post-build-fns should be app",
"end": 8801,
"score": 0.9994036555290222,
"start": 8798,
"tag": "NAME",
"value": "Roe"
},
{
"context": "y\"\n (let [factory {:factory-fn (fn [_] {:name \"Bob\"})\n :post-build-fns [(fn [produ",
"end": 8920,
"score": 0.9996801614761353,
"start": 8917,
"tag": "NAME",
"value": "Bob"
},
{
"context": "roduct :name str \" Roe\"))]}]\n (is (= {:name \"Bob Doe Roe\"\n :factory factory}\n (fs",
"end": 9317,
"score": 0.9216461777687073,
"start": 9306,
"tag": "NAME",
"value": "Bob Doe Roe"
},
{
"context": " validate against the product\"\n (is (= {:name \"Bob\"}\n (fs/build {:factory-fn (fn [_] {:nam",
"end": 9475,
"score": 0.9998076558113098,
"start": 9472,
"tag": "NAME",
"value": "Bob"
},
{
"context": " (fs/build {:factory-fn (fn [_] {:name \"Bob\"})\n :spec ::with-name})))\n ",
"end": 9531,
"score": 0.9997608065605164,
"start": 9528,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :traits {:alice {:fields {:name \"Alice\"}}}\n :fields {:name \"Bob\"}\n ",
"end": 9990,
"score": 0.9997735619544983,
"start": 9985,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ame \"Alice\"}}}\n :fields {:name \"Bob\"}\n :post-build-fns [(fn [p _] p",
"end": 10033,
"score": 0.9997557997703552,
"start": 10030,
"tag": "NAME",
"value": "Bob"
},
{
"context": "[p _] p)]}]\n (is (= {:factory factory :name \"Bob\"}\n (fs/build factory)))))\n\n (testing",
"end": 10129,
"score": 0.9997930526733398,
"start": 10126,
"tag": "NAME",
"value": "Bob"
},
{
"context": "-args)\n {:name \"Alice\" :registered true} {}))\n :spec ",
"end": 10397,
"score": 0.999792218208313,
"start": 10392,
"tag": "NAME",
"value": "Alice"
},
{
"context": "{:alice? true}\n :fields {:name \"Bob\" :role \"Admin\"}\n :post-build-fn",
"end": 10543,
"score": 0.9997839331626892,
"start": 10540,
"tag": "NAME",
"value": "Bob"
},
{
"context": "roduct :name str \" Roe\"))]}]\n (is (= {:name \"Bob Doe Roe\" :registered true :role \"Admin\"}\n (fs",
"end": 10769,
"score": 0.9998836517333984,
"start": 10758,
"tag": "NAME",
"value": "Bob Doe Roe"
}
] | test/factory_squid/core_test.cljc | gavinkflam/factory-squid | 1 | (ns factory-squid.core-test
(:require [clojure.spec.alpha :as s]
[clojure.test :refer [deftest testing is]]
[factory-squid.core :as fs]))
;; Test data
(def ^:private dummy-factory-fn
(fn [] {:name "Alice"}))
(s/def ::name string?)
(s/def ::with-name (s/keys :req-un [::name]))
;; Utilities
(defmacro ^:private catch!
"Return the captured exception after executing the body.
Throw if no exceptions were encountered."
[& body]
`(try
~@body
(throw (Exception. "No exceptions caught"))
(catch Exception e# e#)))
(defn- instrument-failure?
"Return true if the given exception is a spec instrument failure.
Return false if otherwise."
[exception]
(= :instrument
(-> exception ex-data ::s/failure)))
(defn- spec-assertion-failure?
"Return true if the given exception is a spec assertion failure.
Return false if otherwise."
[exception]
(= :assertion-failed
(-> exception ex-data ::s/failure)))
;; Test deep merge
(deftest test-deep-merge
(testing "non-recursive merges"
(is (= {:a 1 :b 2 :c 3 :d 4}
(fs/deep-merge {:a 1 :b 2} {:c 3 :d 4})))
(is (= {:a 1}
(fs/deep-merge nil {:a 1})))
(is (= {:a 1}
(fs/deep-merge {:a 1} nil)))
(is (= {:a 11 :b 2 :c 3}
(fs/deep-merge {:a 1 :b 2} {:a 11 :c 3}))))
(testing "recursive merges"
(is (= {:a {:a1 11 :a2 12 :a3 13} :b 2 :c 3}
(fs/deep-merge {:a {:a1 11} :b 2}
{:a {:a2 12 :a3 13} :c 3})))
(is (= {:a {:a1 {:a11 111 :a12 112 :a13 113} :a2 12} :b 2 :c 3}
(fs/deep-merge {:a {:a1 {:a11 111 :a12 112}} :b 2}
{:a {:a1 {:a13 113} :a2 12} :c 3})))))
;; Test modification functions
(deftest test-add-trait
(let [factory {:factory-fn dummy-factory-fn}
with-bob {:factory-fn dummy-factory-fn
:traits {:bob {:fields {:name "Bob"}}}}
with-bobby {:factory-fn dummy-factory-fn
:traits {:bob {:fields {:name "Bobby"}}}}
with-bob-and-carol {:factory-fn dummy-factory-fn
:traits {:bob {:fields {:name "Bob"}}
:carol {:fields {:name "Carol"}}}}]
(testing "on factory with no traits"
(is (= with-bob
(fs/add-trait factory :bob {:fields {:name "Bob"}}))))
(testing "on factory with traits"
(is (= with-bob-and-carol
(fs/add-trait with-bob :carol {:fields {:name "Carol"}}))))
(testing "override existing trait"
(is (= with-bobby
(fs/add-trait with-bob :bob {:fields {:name "Bobby"}}))))
(testing "test instrumentation"
(is (instrument-failure?
(catch! (fs/add-trait "foobar" {:fields {:name "Bobby"}})))))))
(deftest test-add-post-build-fn
(let [factory {:factory-fn dummy-factory-fn}
fn1 (fn [_ _] {:a 1})
fn2 (fn [_ _] {:a 2})
with-fn1 {:factory-fn dummy-factory-fn
:post-build-fns [fn1]}
with-fn1-and-2 {:factory-fn dummy-factory-fn
:post-build-fns [fn1 fn2]}]
(testing "on factory with no post-build-fns"
(is (= with-fn1
(fs/add-post-build-fn factory fn1)))
(is (= with-fn1-and-2
(-> factory
(fs/add-post-build-fn fn1)
(fs/add-post-build-fn fn2)))))
(testing "append to existing post-build-fns"
(is (= with-fn1-and-2
(fs/add-post-build-fn with-fn1 fn2))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/add-post-build-fn "foobar")))))))
(deftest test-spec
(let [factory {:factory-fn dummy-factory-fn}
s1 (s/map-of keyword? some?)
s2 (s/map-of keyword? string?)
with-s1 {:factory-fn dummy-factory-fn :spec s1}
with-s2 {:factory-fn dummy-factory-fn :spec s2}]
(testing "on factory with no spec"
(is (= with-s1
(fs/spec factory s1))))
(testing "override existing spec"
(is (= with-s2
(fs/spec with-s1 s2))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/spec "foobar")))))))
(deftest test-build-args
(let [factory {:factory-fn dummy-factory-fn}
registered-2020 {:factory-fn dummy-factory-fn
:build-args {:registered {:y 2020 :m 2 :d 29}}}
bob-2020 {:factory-fn dummy-factory-fn
:build-args {:registered {:y 2020 :m 2 :d 29} :name "Bob"}}
registered-2021 {:factory-fn dummy-factory-fn
:build-args {:registered {:y 2021 :w 2}}}]
(testing "on factory with no traits"
(is (= registered-2020
(fs/build-args factory {:registered {:y 2020 :m 2 :d 29}}))))
(testing "on factory with traits"
(is (= bob-2020
(fs/build-args registered-2020 {:name "Bob"}))))
(testing "override existing trait"
(is (= registered-2021
(fs/build-args registered-2021 {:registered {:y 2021 :w 2}}))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/build-args "foobar")))))))
(deftest test-fields
(let [factory {:factory-fn dummy-factory-fn}
with-bob {:factory-fn dummy-factory-fn
:fields {:name {:first "Bob" :last "Doe"} :role "Admin"}}
with-bob-roe {:factory-fn dummy-factory-fn
:fields {:name {:first "Bob" :last "Roe"} :role "Editor"}}]
(testing "on factory with no fields"
(is (= with-bob
(fs/fields factory {:name {:first "Bob" :last "Doe"} :role "Admin"}))))
(testing "recursively merge with existing fields"
(is (= with-bob-roe
(fs/fields with-bob {:name {:last "Roe"} :role "Editor"}))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/fields "foobar")))))))
(deftest test-trait
(let [fn1 (fn [p _] (update p :name str " Doe"))
fn2 (fn [p _] (assoc p :role "Admin"))
fn3 (fn [p _] (assoc p :registered true))
map-s (s/keys)
alice-trait {:spec map-s
:build-args {:registered true}
:fields {:name "Alice"}
:post-build-fns [fn2 fn3]}
bob-trait {:fields {:name "Bob"}}
guest-trait {:build-args {:registered false :role "Guest"}}
factory {:factory-fn dummy-factory-fn
:spec ::with-name
:traits {:alice alice-trait :bob bob-trait :guest guest-trait}
:build-args {:registered :n/a :role "Admin"}
:fields {:name "Carol" :role "Admin"}
:post-build-fns [fn1]}]
(testing "apply trait of the given name"
(is (= {:factory-fn dummy-factory-fn
:spec map-s
:traits {:alice alice-trait :bob bob-trait :guest guest-trait}
:build-args {:registered true :role "Admin"}
:fields {:name "Alice" :role "Admin"}
:post-build-fns [fn1 fn2 fn3]}
(fs/trait factory :alice))))
(testing "apply traits with incomplete params"
(is (= {:factory-fn dummy-factory-fn
:spec ::with-name
:traits {:alice alice-trait :bob bob-trait :guest guest-trait}
:build-args {:registered :n/a :role "Admin"}
:fields {:name "Bob" :role "Admin"}
:post-build-fns [fn1]}
(fs/trait factory :bob)))
(is (= {:factory-fn dummy-factory-fn
:spec ::with-name
:traits {:alice alice-trait :bob bob-trait :guest guest-trait}
:build-args {:registered false :role "Guest"}
:fields {:name "Carol" :role "Admin"}
:post-build-fns [fn1]}
(fs/trait factory :guest))))
(testing "throw when trait does not exist"
(is (= {:failure :trait-not-exist :trait-name :carol}
(ex-data (catch! (fs/trait factory :carol))))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/trait factory "guest")))))))
;; Test build
(deftest test-build
(testing "build from just factory-fn"
(is (= {:name "Bob"}
(fs/build {:factory-fn (fn [_] {:name "Bob"})}))))
(testing "build with build-args as second argument"
(let [factory {:factory-fn (fn [f] {:factory f})}]
(is (= {:factory (assoc factory :build-args {:registered true})}
(fs/build factory {:registered true})))))
(testing "fields should be merged into the product recursively"
(is (= {:name {:first "Bob" :last "Roe"}}
(fs/build {:factory-fn (fn [_] {:name {:first "Bob" :last "Doe"}})
:fields {:name {:last "Roe"}}}))))
(testing "post-build-fns should be applied sequentially"
(let [factory {:factory-fn (fn [_] {:name "Bob"})
:post-build-fns [(fn [product f]
(-> product
(update :name str " Doe")
(assoc :factory f)))
(fn [product _]
(update product :name str " Roe"))]}]
(is (= {:name "Bob Doe Roe"
:factory factory}
(fs/build factory)))))
(testing "spec should be used to validate against the product"
(is (= {:name "Bob"}
(fs/build {:factory-fn (fn [_] {:name "Bob"})
:spec ::with-name})))
(is (spec-assertion-failure?
(catch! (fs/build {:factory-fn (fn [_] {:name nil})
:spec ::with-name})))))
(testing "all factory map fields should be passed to factory-fn"
(let [factory {:factory-fn (fn [f] {:factory f})
:spec ::with-name
:build-args {:registered true}
:traits {:alice {:fields {:name "Alice"}}}
:fields {:name "Bob"}
:post-build-fns [(fn [p _] p)]}]
(is (= {:factory factory :name "Bob"}
(fs/build factory)))))
(testing "build steps should be applied in the correct order"
(let [factory {:factory-fn (fn [{:keys [build-args]}]
(if (:alice? build-args)
{:name "Alice" :registered true} {}))
:spec ::with-name
:build-args {:alice? true}
:fields {:name "Bob" :role "Admin"}
:post-build-fns [(fn [product _] (update product :name str " Doe"))
(fn [product _] (update product :name str " Roe"))]}]
(is (= {:name "Bob Doe Roe" :registered true :role "Admin"}
(fs/build factory)))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/build {:spec ::with-name}))))))
| 23582 | (ns factory-squid.core-test
(:require [clojure.spec.alpha :as s]
[clojure.test :refer [deftest testing is]]
[factory-squid.core :as fs]))
;; Test data
(def ^:private dummy-factory-fn
(fn [] {:name "<NAME>"}))
(s/def ::name string?)
(s/def ::with-name (s/keys :req-un [::name]))
;; Utilities
(defmacro ^:private catch!
"Return the captured exception after executing the body.
Throw if no exceptions were encountered."
[& body]
`(try
~@body
(throw (Exception. "No exceptions caught"))
(catch Exception e# e#)))
(defn- instrument-failure?
"Return true if the given exception is a spec instrument failure.
Return false if otherwise."
[exception]
(= :instrument
(-> exception ex-data ::s/failure)))
(defn- spec-assertion-failure?
"Return true if the given exception is a spec assertion failure.
Return false if otherwise."
[exception]
(= :assertion-failed
(-> exception ex-data ::s/failure)))
;; Test deep merge
(deftest test-deep-merge
(testing "non-recursive merges"
(is (= {:a 1 :b 2 :c 3 :d 4}
(fs/deep-merge {:a 1 :b 2} {:c 3 :d 4})))
(is (= {:a 1}
(fs/deep-merge nil {:a 1})))
(is (= {:a 1}
(fs/deep-merge {:a 1} nil)))
(is (= {:a 11 :b 2 :c 3}
(fs/deep-merge {:a 1 :b 2} {:a 11 :c 3}))))
(testing "recursive merges"
(is (= {:a {:a1 11 :a2 12 :a3 13} :b 2 :c 3}
(fs/deep-merge {:a {:a1 11} :b 2}
{:a {:a2 12 :a3 13} :c 3})))
(is (= {:a {:a1 {:a11 111 :a12 112 :a13 113} :a2 12} :b 2 :c 3}
(fs/deep-merge {:a {:a1 {:a11 111 :a12 112}} :b 2}
{:a {:a1 {:a13 113} :a2 12} :c 3})))))
;; Test modification functions
(deftest test-add-trait
(let [factory {:factory-fn dummy-factory-fn}
with-bob {:factory-fn dummy-factory-fn
:traits {:bob {:fields {:name "Bob"}}}}
with-bobby {:factory-fn dummy-factory-fn
:traits {:bob {:fields {:name "Bobby"}}}}
with-bob-and-carol {:factory-fn dummy-factory-fn
:traits {:bob {:fields {:name "Bob"}}
:carol {:fields {:name "Carol"}}}}]
(testing "on factory with no traits"
(is (= with-bob
(fs/add-trait factory :bob {:fields {:name "Bob"}}))))
(testing "on factory with traits"
(is (= with-bob-and-carol
(fs/add-trait with-bob :carol {:fields {:name "Carol"}}))))
(testing "override existing trait"
(is (= with-bobby
(fs/add-trait with-bob :bob {:fields {:name "Bobby"}}))))
(testing "test instrumentation"
(is (instrument-failure?
(catch! (fs/add-trait "foobar" {:fields {:name "Bobby"}})))))))
(deftest test-add-post-build-fn
(let [factory {:factory-fn dummy-factory-fn}
fn1 (fn [_ _] {:a 1})
fn2 (fn [_ _] {:a 2})
with-fn1 {:factory-fn dummy-factory-fn
:post-build-fns [fn1]}
with-fn1-and-2 {:factory-fn dummy-factory-fn
:post-build-fns [fn1 fn2]}]
(testing "on factory with no post-build-fns"
(is (= with-fn1
(fs/add-post-build-fn factory fn1)))
(is (= with-fn1-and-2
(-> factory
(fs/add-post-build-fn fn1)
(fs/add-post-build-fn fn2)))))
(testing "append to existing post-build-fns"
(is (= with-fn1-and-2
(fs/add-post-build-fn with-fn1 fn2))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/add-post-build-fn "foobar")))))))
(deftest test-spec
(let [factory {:factory-fn dummy-factory-fn}
s1 (s/map-of keyword? some?)
s2 (s/map-of keyword? string?)
with-s1 {:factory-fn dummy-factory-fn :spec s1}
with-s2 {:factory-fn dummy-factory-fn :spec s2}]
(testing "on factory with no spec"
(is (= with-s1
(fs/spec factory s1))))
(testing "override existing spec"
(is (= with-s2
(fs/spec with-s1 s2))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/spec "foobar")))))))
(deftest test-build-args
(let [factory {:factory-fn dummy-factory-fn}
registered-2020 {:factory-fn dummy-factory-fn
:build-args {:registered {:y 2020 :m 2 :d 29}}}
bob-2020 {:factory-fn dummy-factory-fn
:build-args {:registered {:y 2020 :m 2 :d 29} :name "<NAME>"}}
registered-2021 {:factory-fn dummy-factory-fn
:build-args {:registered {:y 2021 :w 2}}}]
(testing "on factory with no traits"
(is (= registered-2020
(fs/build-args factory {:registered {:y 2020 :m 2 :d 29}}))))
(testing "on factory with traits"
(is (= bob-2020
(fs/build-args registered-2020 {:name "<NAME>"}))))
(testing "override existing trait"
(is (= registered-2021
(fs/build-args registered-2021 {:registered {:y 2021 :w 2}}))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/build-args "foobar")))))))
(deftest test-fields
(let [factory {:factory-fn dummy-factory-fn}
with-bob {:factory-fn dummy-factory-fn
:fields {:name {:first "<NAME>" :last "<NAME>"} :role "Admin"}}
with-bob-roe {:factory-fn dummy-factory-fn
:fields {:name {:first "<NAME>" :last "<NAME>"} :role "Editor"}}]
(testing "on factory with no fields"
(is (= with-bob
(fs/fields factory {:name {:first "<NAME>" :last "<NAME>"} :role "Admin"}))))
(testing "recursively merge with existing fields"
(is (= with-bob-roe
(fs/fields with-bob {:name {:last "<NAME>"} :role "Editor"}))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/fields "foobar")))))))
(deftest test-trait
(let [fn1 (fn [p _] (update p :name str " <NAME>"))
fn2 (fn [p _] (assoc p :role "Admin"))
fn3 (fn [p _] (assoc p :registered true))
map-s (s/keys)
alice-trait {:spec map-s
:build-args {:registered true}
:fields {:name "<NAME>"}
:post-build-fns [fn2 fn3]}
bob-trait {:fields {:name "<NAME>"}}
guest-trait {:build-args {:registered false :role "Guest"}}
factory {:factory-fn dummy-factory-fn
:spec ::with-name
:traits {:alice alice-trait :bob bob-trait :guest guest-trait}
:build-args {:registered :n/a :role "Admin"}
:fields {:name "<NAME>" :role "Admin"}
:post-build-fns [fn1]}]
(testing "apply trait of the given name"
(is (= {:factory-fn dummy-factory-fn
:spec map-s
:traits {:alice alice-trait :bob bob-trait :guest guest-trait}
:build-args {:registered true :role "Admin"}
:fields {:name "<NAME>" :role "Admin"}
:post-build-fns [fn1 fn2 fn3]}
(fs/trait factory :alice))))
(testing "apply traits with incomplete params"
(is (= {:factory-fn dummy-factory-fn
:spec ::with-name
:traits {:alice alice-trait :bob bob-trait :guest guest-trait}
:build-args {:registered :n/a :role "Admin"}
:fields {:name "<NAME>" :role "Admin"}
:post-build-fns [fn1]}
(fs/trait factory :bob)))
(is (= {:factory-fn dummy-factory-fn
:spec ::with-name
:traits {:alice alice-trait :bob bob-trait :guest guest-trait}
:build-args {:registered false :role "Guest"}
:fields {:name "<NAME>" :role "Admin"}
:post-build-fns [fn1]}
(fs/trait factory :guest))))
(testing "throw when trait does not exist"
(is (= {:failure :trait-not-exist :trait-name :carol}
(ex-data (catch! (fs/trait factory :carol))))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/trait factory "guest")))))))
;; Test build
(deftest test-build
(testing "build from just factory-fn"
(is (= {:name "<NAME>"}
(fs/build {:factory-fn (fn [_] {:name "<NAME>"})}))))
(testing "build with build-args as second argument"
(let [factory {:factory-fn (fn [f] {:factory f})}]
(is (= {:factory (assoc factory :build-args {:registered true})}
(fs/build factory {:registered true})))))
(testing "fields should be merged into the product recursively"
(is (= {:name {:first "<NAME>" :last "<NAME>"}}
(fs/build {:factory-fn (fn [_] {:name {:first "<NAME>" :last "<NAME>"}})
:fields {:name {:last "<NAME>"}}}))))
(testing "post-build-fns should be applied sequentially"
(let [factory {:factory-fn (fn [_] {:name "<NAME>"})
:post-build-fns [(fn [product f]
(-> product
(update :name str " Doe")
(assoc :factory f)))
(fn [product _]
(update product :name str " Roe"))]}]
(is (= {:name "<NAME>"
:factory factory}
(fs/build factory)))))
(testing "spec should be used to validate against the product"
(is (= {:name "<NAME>"}
(fs/build {:factory-fn (fn [_] {:name "<NAME>"})
:spec ::with-name})))
(is (spec-assertion-failure?
(catch! (fs/build {:factory-fn (fn [_] {:name nil})
:spec ::with-name})))))
(testing "all factory map fields should be passed to factory-fn"
(let [factory {:factory-fn (fn [f] {:factory f})
:spec ::with-name
:build-args {:registered true}
:traits {:alice {:fields {:name "<NAME>"}}}
:fields {:name "<NAME>"}
:post-build-fns [(fn [p _] p)]}]
(is (= {:factory factory :name "<NAME>"}
(fs/build factory)))))
(testing "build steps should be applied in the correct order"
(let [factory {:factory-fn (fn [{:keys [build-args]}]
(if (:alice? build-args)
{:name "<NAME>" :registered true} {}))
:spec ::with-name
:build-args {:alice? true}
:fields {:name "<NAME>" :role "Admin"}
:post-build-fns [(fn [product _] (update product :name str " Doe"))
(fn [product _] (update product :name str " Roe"))]}]
(is (= {:name "<NAME>" :registered true :role "Admin"}
(fs/build factory)))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/build {:spec ::with-name}))))))
| true | (ns factory-squid.core-test
(:require [clojure.spec.alpha :as s]
[clojure.test :refer [deftest testing is]]
[factory-squid.core :as fs]))
;; Test data
(def ^:private dummy-factory-fn
(fn [] {:name "PI:NAME:<NAME>END_PI"}))
(s/def ::name string?)
(s/def ::with-name (s/keys :req-un [::name]))
;; Utilities
(defmacro ^:private catch!
"Return the captured exception after executing the body.
Throw if no exceptions were encountered."
[& body]
`(try
~@body
(throw (Exception. "No exceptions caught"))
(catch Exception e# e#)))
(defn- instrument-failure?
"Return true if the given exception is a spec instrument failure.
Return false if otherwise."
[exception]
(= :instrument
(-> exception ex-data ::s/failure)))
(defn- spec-assertion-failure?
"Return true if the given exception is a spec assertion failure.
Return false if otherwise."
[exception]
(= :assertion-failed
(-> exception ex-data ::s/failure)))
;; Test deep merge
(deftest test-deep-merge
(testing "non-recursive merges"
(is (= {:a 1 :b 2 :c 3 :d 4}
(fs/deep-merge {:a 1 :b 2} {:c 3 :d 4})))
(is (= {:a 1}
(fs/deep-merge nil {:a 1})))
(is (= {:a 1}
(fs/deep-merge {:a 1} nil)))
(is (= {:a 11 :b 2 :c 3}
(fs/deep-merge {:a 1 :b 2} {:a 11 :c 3}))))
(testing "recursive merges"
(is (= {:a {:a1 11 :a2 12 :a3 13} :b 2 :c 3}
(fs/deep-merge {:a {:a1 11} :b 2}
{:a {:a2 12 :a3 13} :c 3})))
(is (= {:a {:a1 {:a11 111 :a12 112 :a13 113} :a2 12} :b 2 :c 3}
(fs/deep-merge {:a {:a1 {:a11 111 :a12 112}} :b 2}
{:a {:a1 {:a13 113} :a2 12} :c 3})))))
;; Test modification functions
(deftest test-add-trait
(let [factory {:factory-fn dummy-factory-fn}
with-bob {:factory-fn dummy-factory-fn
:traits {:bob {:fields {:name "Bob"}}}}
with-bobby {:factory-fn dummy-factory-fn
:traits {:bob {:fields {:name "Bobby"}}}}
with-bob-and-carol {:factory-fn dummy-factory-fn
:traits {:bob {:fields {:name "Bob"}}
:carol {:fields {:name "Carol"}}}}]
(testing "on factory with no traits"
(is (= with-bob
(fs/add-trait factory :bob {:fields {:name "Bob"}}))))
(testing "on factory with traits"
(is (= with-bob-and-carol
(fs/add-trait with-bob :carol {:fields {:name "Carol"}}))))
(testing "override existing trait"
(is (= with-bobby
(fs/add-trait with-bob :bob {:fields {:name "Bobby"}}))))
(testing "test instrumentation"
(is (instrument-failure?
(catch! (fs/add-trait "foobar" {:fields {:name "Bobby"}})))))))
(deftest test-add-post-build-fn
(let [factory {:factory-fn dummy-factory-fn}
fn1 (fn [_ _] {:a 1})
fn2 (fn [_ _] {:a 2})
with-fn1 {:factory-fn dummy-factory-fn
:post-build-fns [fn1]}
with-fn1-and-2 {:factory-fn dummy-factory-fn
:post-build-fns [fn1 fn2]}]
(testing "on factory with no post-build-fns"
(is (= with-fn1
(fs/add-post-build-fn factory fn1)))
(is (= with-fn1-and-2
(-> factory
(fs/add-post-build-fn fn1)
(fs/add-post-build-fn fn2)))))
(testing "append to existing post-build-fns"
(is (= with-fn1-and-2
(fs/add-post-build-fn with-fn1 fn2))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/add-post-build-fn "foobar")))))))
(deftest test-spec
(let [factory {:factory-fn dummy-factory-fn}
s1 (s/map-of keyword? some?)
s2 (s/map-of keyword? string?)
with-s1 {:factory-fn dummy-factory-fn :spec s1}
with-s2 {:factory-fn dummy-factory-fn :spec s2}]
(testing "on factory with no spec"
(is (= with-s1
(fs/spec factory s1))))
(testing "override existing spec"
(is (= with-s2
(fs/spec with-s1 s2))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/spec "foobar")))))))
(deftest test-build-args
(let [factory {:factory-fn dummy-factory-fn}
registered-2020 {:factory-fn dummy-factory-fn
:build-args {:registered {:y 2020 :m 2 :d 29}}}
bob-2020 {:factory-fn dummy-factory-fn
:build-args {:registered {:y 2020 :m 2 :d 29} :name "PI:NAME:<NAME>END_PI"}}
registered-2021 {:factory-fn dummy-factory-fn
:build-args {:registered {:y 2021 :w 2}}}]
(testing "on factory with no traits"
(is (= registered-2020
(fs/build-args factory {:registered {:y 2020 :m 2 :d 29}}))))
(testing "on factory with traits"
(is (= bob-2020
(fs/build-args registered-2020 {:name "PI:NAME:<NAME>END_PI"}))))
(testing "override existing trait"
(is (= registered-2021
(fs/build-args registered-2021 {:registered {:y 2021 :w 2}}))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/build-args "foobar")))))))
(deftest test-fields
(let [factory {:factory-fn dummy-factory-fn}
with-bob {:factory-fn dummy-factory-fn
:fields {:name {:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI"} :role "Admin"}}
with-bob-roe {:factory-fn dummy-factory-fn
:fields {:name {:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI"} :role "Editor"}}]
(testing "on factory with no fields"
(is (= with-bob
(fs/fields factory {:name {:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI"} :role "Admin"}))))
(testing "recursively merge with existing fields"
(is (= with-bob-roe
(fs/fields with-bob {:name {:last "PI:NAME:<NAME>END_PI"} :role "Editor"}))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/fields "foobar")))))))
(deftest test-trait
(let [fn1 (fn [p _] (update p :name str " PI:NAME:<NAME>END_PI"))
fn2 (fn [p _] (assoc p :role "Admin"))
fn3 (fn [p _] (assoc p :registered true))
map-s (s/keys)
alice-trait {:spec map-s
:build-args {:registered true}
:fields {:name "PI:NAME:<NAME>END_PI"}
:post-build-fns [fn2 fn3]}
bob-trait {:fields {:name "PI:NAME:<NAME>END_PI"}}
guest-trait {:build-args {:registered false :role "Guest"}}
factory {:factory-fn dummy-factory-fn
:spec ::with-name
:traits {:alice alice-trait :bob bob-trait :guest guest-trait}
:build-args {:registered :n/a :role "Admin"}
:fields {:name "PI:NAME:<NAME>END_PI" :role "Admin"}
:post-build-fns [fn1]}]
(testing "apply trait of the given name"
(is (= {:factory-fn dummy-factory-fn
:spec map-s
:traits {:alice alice-trait :bob bob-trait :guest guest-trait}
:build-args {:registered true :role "Admin"}
:fields {:name "PI:NAME:<NAME>END_PI" :role "Admin"}
:post-build-fns [fn1 fn2 fn3]}
(fs/trait factory :alice))))
(testing "apply traits with incomplete params"
(is (= {:factory-fn dummy-factory-fn
:spec ::with-name
:traits {:alice alice-trait :bob bob-trait :guest guest-trait}
:build-args {:registered :n/a :role "Admin"}
:fields {:name "PI:NAME:<NAME>END_PI" :role "Admin"}
:post-build-fns [fn1]}
(fs/trait factory :bob)))
(is (= {:factory-fn dummy-factory-fn
:spec ::with-name
:traits {:alice alice-trait :bob bob-trait :guest guest-trait}
:build-args {:registered false :role "Guest"}
:fields {:name "PI:NAME:<NAME>END_PI" :role "Admin"}
:post-build-fns [fn1]}
(fs/trait factory :guest))))
(testing "throw when trait does not exist"
(is (= {:failure :trait-not-exist :trait-name :carol}
(ex-data (catch! (fs/trait factory :carol))))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/trait factory "guest")))))))
;; Test build
(deftest test-build
(testing "build from just factory-fn"
(is (= {:name "PI:NAME:<NAME>END_PI"}
(fs/build {:factory-fn (fn [_] {:name "PI:NAME:<NAME>END_PI"})}))))
(testing "build with build-args as second argument"
(let [factory {:factory-fn (fn [f] {:factory f})}]
(is (= {:factory (assoc factory :build-args {:registered true})}
(fs/build factory {:registered true})))))
(testing "fields should be merged into the product recursively"
(is (= {:name {:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI"}}
(fs/build {:factory-fn (fn [_] {:name {:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI"}})
:fields {:name {:last "PI:NAME:<NAME>END_PI"}}}))))
(testing "post-build-fns should be applied sequentially"
(let [factory {:factory-fn (fn [_] {:name "PI:NAME:<NAME>END_PI"})
:post-build-fns [(fn [product f]
(-> product
(update :name str " Doe")
(assoc :factory f)))
(fn [product _]
(update product :name str " Roe"))]}]
(is (= {:name "PI:NAME:<NAME>END_PI"
:factory factory}
(fs/build factory)))))
(testing "spec should be used to validate against the product"
(is (= {:name "PI:NAME:<NAME>END_PI"}
(fs/build {:factory-fn (fn [_] {:name "PI:NAME:<NAME>END_PI"})
:spec ::with-name})))
(is (spec-assertion-failure?
(catch! (fs/build {:factory-fn (fn [_] {:name nil})
:spec ::with-name})))))
(testing "all factory map fields should be passed to factory-fn"
(let [factory {:factory-fn (fn [f] {:factory f})
:spec ::with-name
:build-args {:registered true}
:traits {:alice {:fields {:name "PI:NAME:<NAME>END_PI"}}}
:fields {:name "PI:NAME:<NAME>END_PI"}
:post-build-fns [(fn [p _] p)]}]
(is (= {:factory factory :name "PI:NAME:<NAME>END_PI"}
(fs/build factory)))))
(testing "build steps should be applied in the correct order"
(let [factory {:factory-fn (fn [{:keys [build-args]}]
(if (:alice? build-args)
{:name "PI:NAME:<NAME>END_PI" :registered true} {}))
:spec ::with-name
:build-args {:alice? true}
:fields {:name "PI:NAME:<NAME>END_PI" :role "Admin"}
:post-build-fns [(fn [product _] (update product :name str " Doe"))
(fn [product _] (update product :name str " Roe"))]}]
(is (= {:name "PI:NAME:<NAME>END_PI" :registered true :role "Admin"}
(fs/build factory)))))
(testing "test instrumentation"
(is (instrument-failure? (catch! (fs/build {:spec ::with-name}))))))
|
[
{
"context": ";;\n;; Copyright © 2020 Sam Ritchie.\n;; This work is based on the Scmutils system of ",
"end": 34,
"score": 0.9998251795768738,
"start": 23,
"tag": "NAME",
"value": "Sam Ritchie"
}
] | test/numerical/quadrature/riemann_test.cljc | dynamic-notebook/functional-numerics | 4 | ;;
;; Copyright © 2020 Sam Ritchie.
;; This work is based on the Scmutils system of MIT/GNU Scheme:
;; Copyright © 2002 Massachusetts Institute of Technology
;;
;; This is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or (at
;; your option) any later version.
;;
;; This software is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this code; if not, see <http://www.gnu.org/licenses/>.
;;
(ns sicmutils.numerical.quadrature.riemann-test
(:require [clojure.test :refer [is deftest testing]]
[same :refer [ish?]]
[sicmutils.numerical.interpolate.richardson :as ir]
[sicmutils.numerical.quadrature.riemann :as qr]
[sicmutils.generic :as g]
[sicmutils.numsymb]
[sicmutils.util :as u]
[sicmutils.value :as v]
[sicmutils.util.aggregate :as ua]
[sicmutils.util.stream :as us]))
(deftest windowed-sum-tests
(testing "windowed-sum makes for inefficient integrals, but they're
conceptually nice and simple."
(let [area-fn (fn [l r] 2)
estimator (qr/windowed-sum area-fn 0 10)]
(is (= 20.0 (estimator 10)) "10 blocks of 2 == 20.")
(is (= 40.0 (estimator 20)) "20 blocks of 2 == 40.")))
(testing "sum implementations with windowed-sum"
(let [example-sum (fn [sum-fn f n]
(->> (us/powers 2)
(map (sum-fn f 0 10))
(take n)))]
(is (ish? [0.0 125.0 218.75 273.4375 302.734375]
(example-sum @#'qr/left-sum g/square 5))
"Successively tighter left estimates.")
(is (ish? [1000.0 625.0 468.75 398.4375 365.234375]
(example-sum @#'qr/right-sum g/square 5))
"Successively tighter right estimates.")
(is (ish? (example-sum @#'qr/right-sum g/square 5)
(example-sum @#'qr/upper-sum g/square 5))
"for square, upper sum is always right.")
(is (ish? (example-sum @#'qr/left-sum g/square 5)
(example-sum @#'qr/lower-sum g/square 5))
"for square, lower sum is always left.")
(let [f (fn [x] (- (* x x)))]
(is (ish? (example-sum @#'qr/left-sum f 5)
(example-sum @#'qr/upper-sum f 5))
"left == upper if we negate square."))))
(testing "slow convergence of bare fns"
(let [sum (fn [sum-fn f]
(map (sum-fn f 0 10)
(us/powers 2)))]
(is (ish? {:converged? false
:terms-checked 16
:result 333.31807469949126}
(-> (sum @#'qr/left-sum g/square)
(us/seq-limit {:maxterms 16})))
"left-sum does not converge at 2^16 slices.")
(is (ish? {:converged? false
:terms-checked 16
:result 333.34859227761626}
(-> (sum @#'qr/right-sum g/square)
(us/seq-limit {:maxterms 16})))
"right-sum does not converge at 2^16 slices."))))
(deftest riemann-sum-tests
(is (ish? {:converged? true
:terms-checked 4
:result 333.3333333333333}
(let [f (fn [x] (* x x))]
(-> (map (@#'qr/left-sum f 0 10)
(us/powers 2))
(ir/richardson-sequence 2)
(us/seq-limit))))
"Richardson extrapolation speeds up convergence.")
(testing "incremental implementations"
;; left-sequence and right-sequence both internally rely on incremental
;; bumps for every even `n`.
(let [f g/square
n-seq (take 20 (iterate inc 1))]
(is (ish? (qr/left-sequence f 0 10 {:n n-seq})
(map (@#'qr/left-sum f 0 10) n-seq))
"Incremental implementation of left-sequence works.")
(is (ish? (qr/right-sequence f 0 10 {:n n-seq})
(map (@#'qr/right-sum f 0 10) n-seq))
"Incremental implementation of right-sequence works.")
(let [[counter1 f1] (u/counted g/square)
[counter2 f2] (u/counted g/square)]
;; run each sequence fully through, counting the function invocations
;; required by each.
(doall (qr/left-sequence f1 0 10 {:n n-seq}))
(doall (map (@#'qr/left-sum f2 0 10) n-seq))
(is (= 210
(int (ua/sum identity 1 21))
@counter2)
"The non-incremental version requires `n` evaluations for `n`
windows. 20 items requires 1 + 2 + ... + 20 = 210.")
(is (= 155
(int (- (ua/sum identity 1 21)
(ua/sum (map #(/ % 2) (range 2 21 2)))))
@counter1)
"every EVEN evaluation from 2 => n saves half of its function
evaluations. So the total is
(1 + 2 + ... 20) - (2/2 + 4/2 + ... 20/2) = 155")))))
(deftest interface-tests
(testing "left-integral"
(is (ish?
{:converged? true
:terms-checked 14
:result 2}
(qr/left-integral
g/sin 0 Math/PI {:accelerate? true
:tolerance v/machine-epsilon}))
"left-integral converges for sin over 0 => pi.")
(is (ish?
{:converged? false
:terms-checked 14
:result 10.333533164162947}
(qr/left-integral g/square 0 Math/PI {:maxterms 14}))
"left-integral does very poorly, non-accelerated."))
(testing "right-integral"
(is (ish?
{:converged? true
:terms-checked 14
:result 2}
(qr/right-integral
g/sin 0 Math/PI {:accelerate? true
:tolerance v/machine-epsilon}))
"right-integral converges for sin over 0 => pi.")
(is (ish?
{:converged? true
:terms-checked 15
:result 1.9999999938721431}
(qr/right-integral
g/sin 0 Math/PI {:maxterms 20}))
"right-integral does BETTER, converging to not quite the right
answer, with no acceleration."))
(testing "lower-integral"
(is (ish?
{:converged? true
:terms-checked 2
:result 0}
(qr/lower-integral g/sin 0 Math/PI))
"lower-integral breaks for this interval! BOTH of 1 and 2 have minimum
endpoints of 0, so the sequence converges after checking the minimum of
two terms.")
(is (ish?
{:converged? true
:terms-checked 14
:result 2}
(qr/lower-integral
g/sin 0 Math/PI {:accelerate? true
:minterms 3
:tolerance v/machine-epsilon}))
"lower-integral converges for sin over 0 => pi when you force it to
consider more than 3 terms."))
(testing "upper-integral"
(is (ish?
{:converged? true
:terms-checked #?(:cljs 15 :clj 13)
:result 2}
(qr/upper-integral
g/sin 0 Math/PI {:accelerate? true
:tolerance v/machine-epsilon}))
"upper-integral converges, with slightly different speeds on CLJS vs Clojure (at machine epsilon!).")))
| 28640 | ;;
;; Copyright © 2020 <NAME>.
;; This work is based on the Scmutils system of MIT/GNU Scheme:
;; Copyright © 2002 Massachusetts Institute of Technology
;;
;; This is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or (at
;; your option) any later version.
;;
;; This software is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this code; if not, see <http://www.gnu.org/licenses/>.
;;
(ns sicmutils.numerical.quadrature.riemann-test
(:require [clojure.test :refer [is deftest testing]]
[same :refer [ish?]]
[sicmutils.numerical.interpolate.richardson :as ir]
[sicmutils.numerical.quadrature.riemann :as qr]
[sicmutils.generic :as g]
[sicmutils.numsymb]
[sicmutils.util :as u]
[sicmutils.value :as v]
[sicmutils.util.aggregate :as ua]
[sicmutils.util.stream :as us]))
(deftest windowed-sum-tests
(testing "windowed-sum makes for inefficient integrals, but they're
conceptually nice and simple."
(let [area-fn (fn [l r] 2)
estimator (qr/windowed-sum area-fn 0 10)]
(is (= 20.0 (estimator 10)) "10 blocks of 2 == 20.")
(is (= 40.0 (estimator 20)) "20 blocks of 2 == 40.")))
(testing "sum implementations with windowed-sum"
(let [example-sum (fn [sum-fn f n]
(->> (us/powers 2)
(map (sum-fn f 0 10))
(take n)))]
(is (ish? [0.0 125.0 218.75 273.4375 302.734375]
(example-sum @#'qr/left-sum g/square 5))
"Successively tighter left estimates.")
(is (ish? [1000.0 625.0 468.75 398.4375 365.234375]
(example-sum @#'qr/right-sum g/square 5))
"Successively tighter right estimates.")
(is (ish? (example-sum @#'qr/right-sum g/square 5)
(example-sum @#'qr/upper-sum g/square 5))
"for square, upper sum is always right.")
(is (ish? (example-sum @#'qr/left-sum g/square 5)
(example-sum @#'qr/lower-sum g/square 5))
"for square, lower sum is always left.")
(let [f (fn [x] (- (* x x)))]
(is (ish? (example-sum @#'qr/left-sum f 5)
(example-sum @#'qr/upper-sum f 5))
"left == upper if we negate square."))))
(testing "slow convergence of bare fns"
(let [sum (fn [sum-fn f]
(map (sum-fn f 0 10)
(us/powers 2)))]
(is (ish? {:converged? false
:terms-checked 16
:result 333.31807469949126}
(-> (sum @#'qr/left-sum g/square)
(us/seq-limit {:maxterms 16})))
"left-sum does not converge at 2^16 slices.")
(is (ish? {:converged? false
:terms-checked 16
:result 333.34859227761626}
(-> (sum @#'qr/right-sum g/square)
(us/seq-limit {:maxterms 16})))
"right-sum does not converge at 2^16 slices."))))
(deftest riemann-sum-tests
(is (ish? {:converged? true
:terms-checked 4
:result 333.3333333333333}
(let [f (fn [x] (* x x))]
(-> (map (@#'qr/left-sum f 0 10)
(us/powers 2))
(ir/richardson-sequence 2)
(us/seq-limit))))
"Richardson extrapolation speeds up convergence.")
(testing "incremental implementations"
;; left-sequence and right-sequence both internally rely on incremental
;; bumps for every even `n`.
(let [f g/square
n-seq (take 20 (iterate inc 1))]
(is (ish? (qr/left-sequence f 0 10 {:n n-seq})
(map (@#'qr/left-sum f 0 10) n-seq))
"Incremental implementation of left-sequence works.")
(is (ish? (qr/right-sequence f 0 10 {:n n-seq})
(map (@#'qr/right-sum f 0 10) n-seq))
"Incremental implementation of right-sequence works.")
(let [[counter1 f1] (u/counted g/square)
[counter2 f2] (u/counted g/square)]
;; run each sequence fully through, counting the function invocations
;; required by each.
(doall (qr/left-sequence f1 0 10 {:n n-seq}))
(doall (map (@#'qr/left-sum f2 0 10) n-seq))
(is (= 210
(int (ua/sum identity 1 21))
@counter2)
"The non-incremental version requires `n` evaluations for `n`
windows. 20 items requires 1 + 2 + ... + 20 = 210.")
(is (= 155
(int (- (ua/sum identity 1 21)
(ua/sum (map #(/ % 2) (range 2 21 2)))))
@counter1)
"every EVEN evaluation from 2 => n saves half of its function
evaluations. So the total is
(1 + 2 + ... 20) - (2/2 + 4/2 + ... 20/2) = 155")))))
(deftest interface-tests
(testing "left-integral"
(is (ish?
{:converged? true
:terms-checked 14
:result 2}
(qr/left-integral
g/sin 0 Math/PI {:accelerate? true
:tolerance v/machine-epsilon}))
"left-integral converges for sin over 0 => pi.")
(is (ish?
{:converged? false
:terms-checked 14
:result 10.333533164162947}
(qr/left-integral g/square 0 Math/PI {:maxterms 14}))
"left-integral does very poorly, non-accelerated."))
(testing "right-integral"
(is (ish?
{:converged? true
:terms-checked 14
:result 2}
(qr/right-integral
g/sin 0 Math/PI {:accelerate? true
:tolerance v/machine-epsilon}))
"right-integral converges for sin over 0 => pi.")
(is (ish?
{:converged? true
:terms-checked 15
:result 1.9999999938721431}
(qr/right-integral
g/sin 0 Math/PI {:maxterms 20}))
"right-integral does BETTER, converging to not quite the right
answer, with no acceleration."))
(testing "lower-integral"
(is (ish?
{:converged? true
:terms-checked 2
:result 0}
(qr/lower-integral g/sin 0 Math/PI))
"lower-integral breaks for this interval! BOTH of 1 and 2 have minimum
endpoints of 0, so the sequence converges after checking the minimum of
two terms.")
(is (ish?
{:converged? true
:terms-checked 14
:result 2}
(qr/lower-integral
g/sin 0 Math/PI {:accelerate? true
:minterms 3
:tolerance v/machine-epsilon}))
"lower-integral converges for sin over 0 => pi when you force it to
consider more than 3 terms."))
(testing "upper-integral"
(is (ish?
{:converged? true
:terms-checked #?(:cljs 15 :clj 13)
:result 2}
(qr/upper-integral
g/sin 0 Math/PI {:accelerate? true
:tolerance v/machine-epsilon}))
"upper-integral converges, with slightly different speeds on CLJS vs Clojure (at machine epsilon!).")))
| true | ;;
;; Copyright © 2020 PI:NAME:<NAME>END_PI.
;; This work is based on the Scmutils system of MIT/GNU Scheme:
;; Copyright © 2002 Massachusetts Institute of Technology
;;
;; This is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or (at
;; your option) any later version.
;;
;; This software is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this code; if not, see <http://www.gnu.org/licenses/>.
;;
(ns sicmutils.numerical.quadrature.riemann-test
(:require [clojure.test :refer [is deftest testing]]
[same :refer [ish?]]
[sicmutils.numerical.interpolate.richardson :as ir]
[sicmutils.numerical.quadrature.riemann :as qr]
[sicmutils.generic :as g]
[sicmutils.numsymb]
[sicmutils.util :as u]
[sicmutils.value :as v]
[sicmutils.util.aggregate :as ua]
[sicmutils.util.stream :as us]))
(deftest windowed-sum-tests
(testing "windowed-sum makes for inefficient integrals, but they're
conceptually nice and simple."
(let [area-fn (fn [l r] 2)
estimator (qr/windowed-sum area-fn 0 10)]
(is (= 20.0 (estimator 10)) "10 blocks of 2 == 20.")
(is (= 40.0 (estimator 20)) "20 blocks of 2 == 40.")))
(testing "sum implementations with windowed-sum"
(let [example-sum (fn [sum-fn f n]
(->> (us/powers 2)
(map (sum-fn f 0 10))
(take n)))]
(is (ish? [0.0 125.0 218.75 273.4375 302.734375]
(example-sum @#'qr/left-sum g/square 5))
"Successively tighter left estimates.")
(is (ish? [1000.0 625.0 468.75 398.4375 365.234375]
(example-sum @#'qr/right-sum g/square 5))
"Successively tighter right estimates.")
(is (ish? (example-sum @#'qr/right-sum g/square 5)
(example-sum @#'qr/upper-sum g/square 5))
"for square, upper sum is always right.")
(is (ish? (example-sum @#'qr/left-sum g/square 5)
(example-sum @#'qr/lower-sum g/square 5))
"for square, lower sum is always left.")
(let [f (fn [x] (- (* x x)))]
(is (ish? (example-sum @#'qr/left-sum f 5)
(example-sum @#'qr/upper-sum f 5))
"left == upper if we negate square."))))
(testing "slow convergence of bare fns"
(let [sum (fn [sum-fn f]
(map (sum-fn f 0 10)
(us/powers 2)))]
(is (ish? {:converged? false
:terms-checked 16
:result 333.31807469949126}
(-> (sum @#'qr/left-sum g/square)
(us/seq-limit {:maxterms 16})))
"left-sum does not converge at 2^16 slices.")
(is (ish? {:converged? false
:terms-checked 16
:result 333.34859227761626}
(-> (sum @#'qr/right-sum g/square)
(us/seq-limit {:maxterms 16})))
"right-sum does not converge at 2^16 slices."))))
(deftest riemann-sum-tests
(is (ish? {:converged? true
:terms-checked 4
:result 333.3333333333333}
(let [f (fn [x] (* x x))]
(-> (map (@#'qr/left-sum f 0 10)
(us/powers 2))
(ir/richardson-sequence 2)
(us/seq-limit))))
"Richardson extrapolation speeds up convergence.")
(testing "incremental implementations"
;; left-sequence and right-sequence both internally rely on incremental
;; bumps for every even `n`.
(let [f g/square
n-seq (take 20 (iterate inc 1))]
(is (ish? (qr/left-sequence f 0 10 {:n n-seq})
(map (@#'qr/left-sum f 0 10) n-seq))
"Incremental implementation of left-sequence works.")
(is (ish? (qr/right-sequence f 0 10 {:n n-seq})
(map (@#'qr/right-sum f 0 10) n-seq))
"Incremental implementation of right-sequence works.")
(let [[counter1 f1] (u/counted g/square)
[counter2 f2] (u/counted g/square)]
;; run each sequence fully through, counting the function invocations
;; required by each.
(doall (qr/left-sequence f1 0 10 {:n n-seq}))
(doall (map (@#'qr/left-sum f2 0 10) n-seq))
(is (= 210
(int (ua/sum identity 1 21))
@counter2)
"The non-incremental version requires `n` evaluations for `n`
windows. 20 items requires 1 + 2 + ... + 20 = 210.")
(is (= 155
(int (- (ua/sum identity 1 21)
(ua/sum (map #(/ % 2) (range 2 21 2)))))
@counter1)
"every EVEN evaluation from 2 => n saves half of its function
evaluations. So the total is
(1 + 2 + ... 20) - (2/2 + 4/2 + ... 20/2) = 155")))))
(deftest interface-tests
(testing "left-integral"
(is (ish?
{:converged? true
:terms-checked 14
:result 2}
(qr/left-integral
g/sin 0 Math/PI {:accelerate? true
:tolerance v/machine-epsilon}))
"left-integral converges for sin over 0 => pi.")
(is (ish?
{:converged? false
:terms-checked 14
:result 10.333533164162947}
(qr/left-integral g/square 0 Math/PI {:maxterms 14}))
"left-integral does very poorly, non-accelerated."))
(testing "right-integral"
(is (ish?
{:converged? true
:terms-checked 14
:result 2}
(qr/right-integral
g/sin 0 Math/PI {:accelerate? true
:tolerance v/machine-epsilon}))
"right-integral converges for sin over 0 => pi.")
(is (ish?
{:converged? true
:terms-checked 15
:result 1.9999999938721431}
(qr/right-integral
g/sin 0 Math/PI {:maxterms 20}))
"right-integral does BETTER, converging to not quite the right
answer, with no acceleration."))
(testing "lower-integral"
(is (ish?
{:converged? true
:terms-checked 2
:result 0}
(qr/lower-integral g/sin 0 Math/PI))
"lower-integral breaks for this interval! BOTH of 1 and 2 have minimum
endpoints of 0, so the sequence converges after checking the minimum of
two terms.")
(is (ish?
{:converged? true
:terms-checked 14
:result 2}
(qr/lower-integral
g/sin 0 Math/PI {:accelerate? true
:minterms 3
:tolerance v/machine-epsilon}))
"lower-integral converges for sin over 0 => pi when you force it to
consider more than 3 terms."))
(testing "upper-integral"
(is (ish?
{:converged? true
:terms-checked #?(:cljs 15 :clj 13)
:result 2}
(qr/upper-integral
g/sin 0 Math/PI {:accelerate? true
:tolerance v/machine-epsilon}))
"upper-integral converges, with slightly different speeds on CLJS vs Clojure (at machine epsilon!).")))
|
[
{
"context": "ommon repo from github\"\n []\n (sh \"git\" \"clone\" \"git@github.com:exercism/x-common\"))\n\n(defn load-test-data\n \"Clo",
"end": 598,
"score": 0.9975396394729614,
"start": 584,
"tag": "EMAIL",
"value": "git@github.com"
},
{
"context": " github\"\n []\n (sh \"git\" \"clone\" \"git@github.com:exercism/x-common\"))\n\n(defn load-test-data\n \"Clones and l",
"end": 607,
"score": 0.9923667907714844,
"start": 599,
"tag": "USERNAME",
"value": "exercism"
}
] | _src/generator.clj | SaschaMann/clojure | 93 | (ns generator
(:require [cheshire.core :as json]
[clojure.java.shell :refer [sh]]
[clojure.java.io :refer [reader]]
[stencil.core :as stencil])
(:import (java.io File IOException)))
(defn file-exists?
"Helper function to determine if a given file exists."
[path]
(.exists (File. path)))
(defn warn-and-exit
"Wrapper function to warn with the given message and then exit with a non-zero return"
[message]
(println message)
(System/exit 1))
(defn clone-test-data
"Clone the x-common repo from github"
[]
(sh "git" "clone" "git@github.com:exercism/x-common"))
(defn load-test-data
"Clones and loads the test data for the given exercise"
[exercise-name]
(when-not (file-exists? "x-common")
(clone-test-data))
(let [test-data-filename (format "x-common/exercises/%s/canonical-data.json" exercise-name)]
(when-not (file-exists? test-data-filename)
(warn-and-exit
(format "Could not find test data for %s (looking in %s)"
exercise-name test-data-filename)))
(json/parse-stream (reader test-data-filename))))
(defn munge-test-data
"Loads the generator namespace for the exercise and calls the munge-data function on the given test-data."
[exercise-name test-data]
(let [exercise-ns (symbol (str exercise-name "-generator"))]
(try
(require [exercise-ns])
(if-let [munge-data-fn (ns-resolve exercise-ns (symbol "munge-data"))]
(munge-data-fn test-data)
(do
(println (format "No munge-data function defined in %s" exercise-ns))
(println (format "Skipping any munging of canonical-data for %s" exercise-name))
test-data))
(catch IOException e
(println (format "Could not require %s due to an exception:\n\t%s" exercise-ns (.getMessage e)))
(println (format "Skipping any munging of canonical-data for %s" exercise-name))
test-data))))
(defn generate-test-data
"Munges the test-data and renders the test for the exercise using the test template."
[exercise-name test-template-path test-data]
(let [munged-test-data (munge-test-data exercise-name test-data)
template (slurp test-template-path)]
(spit
(format "exercises/%s/test/%s_test.clj" exercise-name exercise-name)
(stencil/render-string template munged-test-data))))
(defn -main
"Uses the test template for the exercise and test data to generate test cases."
[exercise-name & args]
(let [test-template-path (format "exercises/%s/.meta/%s.mustache" exercise-name exercise-name)
test-data (load-test-data exercise-name)]
(if (file-exists? test-template-path)
(do
(generate-test-data exercise-name test-template-path test-data)
(println (format "Generated tests for %s exercise using template %s" exercise-name test-template-path)))
(warn-and-exit (format "No exercise test template found at '%s'" test-template-path))))
(shutdown-agents))
| 61146 | (ns generator
(:require [cheshire.core :as json]
[clojure.java.shell :refer [sh]]
[clojure.java.io :refer [reader]]
[stencil.core :as stencil])
(:import (java.io File IOException)))
(defn file-exists?
"Helper function to determine if a given file exists."
[path]
(.exists (File. path)))
(defn warn-and-exit
"Wrapper function to warn with the given message and then exit with a non-zero return"
[message]
(println message)
(System/exit 1))
(defn clone-test-data
"Clone the x-common repo from github"
[]
(sh "git" "clone" "<EMAIL>:exercism/x-common"))
(defn load-test-data
"Clones and loads the test data for the given exercise"
[exercise-name]
(when-not (file-exists? "x-common")
(clone-test-data))
(let [test-data-filename (format "x-common/exercises/%s/canonical-data.json" exercise-name)]
(when-not (file-exists? test-data-filename)
(warn-and-exit
(format "Could not find test data for %s (looking in %s)"
exercise-name test-data-filename)))
(json/parse-stream (reader test-data-filename))))
(defn munge-test-data
"Loads the generator namespace for the exercise and calls the munge-data function on the given test-data."
[exercise-name test-data]
(let [exercise-ns (symbol (str exercise-name "-generator"))]
(try
(require [exercise-ns])
(if-let [munge-data-fn (ns-resolve exercise-ns (symbol "munge-data"))]
(munge-data-fn test-data)
(do
(println (format "No munge-data function defined in %s" exercise-ns))
(println (format "Skipping any munging of canonical-data for %s" exercise-name))
test-data))
(catch IOException e
(println (format "Could not require %s due to an exception:\n\t%s" exercise-ns (.getMessage e)))
(println (format "Skipping any munging of canonical-data for %s" exercise-name))
test-data))))
(defn generate-test-data
"Munges the test-data and renders the test for the exercise using the test template."
[exercise-name test-template-path test-data]
(let [munged-test-data (munge-test-data exercise-name test-data)
template (slurp test-template-path)]
(spit
(format "exercises/%s/test/%s_test.clj" exercise-name exercise-name)
(stencil/render-string template munged-test-data))))
(defn -main
"Uses the test template for the exercise and test data to generate test cases."
[exercise-name & args]
(let [test-template-path (format "exercises/%s/.meta/%s.mustache" exercise-name exercise-name)
test-data (load-test-data exercise-name)]
(if (file-exists? test-template-path)
(do
(generate-test-data exercise-name test-template-path test-data)
(println (format "Generated tests for %s exercise using template %s" exercise-name test-template-path)))
(warn-and-exit (format "No exercise test template found at '%s'" test-template-path))))
(shutdown-agents))
| true | (ns generator
(:require [cheshire.core :as json]
[clojure.java.shell :refer [sh]]
[clojure.java.io :refer [reader]]
[stencil.core :as stencil])
(:import (java.io File IOException)))
(defn file-exists?
"Helper function to determine if a given file exists."
[path]
(.exists (File. path)))
(defn warn-and-exit
"Wrapper function to warn with the given message and then exit with a non-zero return"
[message]
(println message)
(System/exit 1))
(defn clone-test-data
"Clone the x-common repo from github"
[]
(sh "git" "clone" "PI:EMAIL:<EMAIL>END_PI:exercism/x-common"))
(defn load-test-data
"Clones and loads the test data for the given exercise"
[exercise-name]
(when-not (file-exists? "x-common")
(clone-test-data))
(let [test-data-filename (format "x-common/exercises/%s/canonical-data.json" exercise-name)]
(when-not (file-exists? test-data-filename)
(warn-and-exit
(format "Could not find test data for %s (looking in %s)"
exercise-name test-data-filename)))
(json/parse-stream (reader test-data-filename))))
(defn munge-test-data
"Loads the generator namespace for the exercise and calls the munge-data function on the given test-data."
[exercise-name test-data]
(let [exercise-ns (symbol (str exercise-name "-generator"))]
(try
(require [exercise-ns])
(if-let [munge-data-fn (ns-resolve exercise-ns (symbol "munge-data"))]
(munge-data-fn test-data)
(do
(println (format "No munge-data function defined in %s" exercise-ns))
(println (format "Skipping any munging of canonical-data for %s" exercise-name))
test-data))
(catch IOException e
(println (format "Could not require %s due to an exception:\n\t%s" exercise-ns (.getMessage e)))
(println (format "Skipping any munging of canonical-data for %s" exercise-name))
test-data))))
(defn generate-test-data
"Munges the test-data and renders the test for the exercise using the test template."
[exercise-name test-template-path test-data]
(let [munged-test-data (munge-test-data exercise-name test-data)
template (slurp test-template-path)]
(spit
(format "exercises/%s/test/%s_test.clj" exercise-name exercise-name)
(stencil/render-string template munged-test-data))))
(defn -main
"Uses the test template for the exercise and test data to generate test cases."
[exercise-name & args]
(let [test-template-path (format "exercises/%s/.meta/%s.mustache" exercise-name exercise-name)
test-data (load-test-data exercise-name)]
(if (file-exists? test-template-path)
(do
(generate-test-data exercise-name test-template-path test-data)
(println (format "Generated tests for %s exercise using template %s" exercise-name test-template-path)))
(warn-and-exit (format "No exercise test template found at '%s'" test-template-path))))
(shutdown-agents))
|
[
{
"context": "ext\n :name \"pass\"\n :placeholder \"password\"}]\n [:input\n {:type :submit\n :value ",
"end": 678,
"score": 0.9913879036903381,
"start": 670,
"tag": "PASSWORD",
"value": "password"
}
] | auth-example/src/auth_example/routes.cljs | macchiato-framework/examples | 33 | (ns auth-example.routes
(:require
[bidi.bidi :as bidi]
[hiccups.runtime]
[macchiato.middleware.anti-forgery :as af]
[macchiato.util.response :as r])
(:require-macros
[hiccups.core :refer [html]]))
(defn logged-in? [{:keys [identity]}]
(boolean identity))
(defn login-form []
[:div
[:h3 "Please login"]
[:form
{:method "POST"
:action "/login"}
[:input
{:type :hidden
:name "__anti-forgery-token"
:value af/*anti-forgery-token*}]
[:input
{:type :text
:name "name"
:placeholder "name"}]
[:input
{:type :text
:name "pass"
:placeholder "password"}]
[:input
{:type :submit
:value "login"}]]])
(defn logout-form [{:keys [identity]}]
[:div
[:h3 "Welcome " (:name identity)]
[:a {:href "/logout"} "logout"]])
(defn home [req res raise]
(-> (html
[:html
[:body
(if (logged-in? req)
(logout-form req)
(login-form))]])
(r/ok)
(r/content-type "text/html")
(res)))
(defn not-found [req res raise]
(-> (html
[:html
[:body
[:h2 (:uri req) " was not found"]]])
(r/not-found)
(r/content-type "text/html")
(res)))
(defn login [req res raise]
(println (:params req))
(-> (r/found "/")
(assoc-in [:session :identity :name] (-> req :params :name))
(res)))
(defn logout [req res raise]
(-> (r/found "/")
(update :session dissoc :identity)
(res)))
(def routes
["/" {"" {:get home}
"login" {:post login}
"logout" {:get logout}}])
(defn router [req res raise]
(if-let [{:keys [handler route-params]} (bidi/match-route* routes (:uri req) req)]
(handler (assoc req :route-params route-params) res raise)
(not-found req res raise)))
| 54016 | (ns auth-example.routes
(:require
[bidi.bidi :as bidi]
[hiccups.runtime]
[macchiato.middleware.anti-forgery :as af]
[macchiato.util.response :as r])
(:require-macros
[hiccups.core :refer [html]]))
(defn logged-in? [{:keys [identity]}]
(boolean identity))
(defn login-form []
[:div
[:h3 "Please login"]
[:form
{:method "POST"
:action "/login"}
[:input
{:type :hidden
:name "__anti-forgery-token"
:value af/*anti-forgery-token*}]
[:input
{:type :text
:name "name"
:placeholder "name"}]
[:input
{:type :text
:name "pass"
:placeholder "<PASSWORD>"}]
[:input
{:type :submit
:value "login"}]]])
(defn logout-form [{:keys [identity]}]
[:div
[:h3 "Welcome " (:name identity)]
[:a {:href "/logout"} "logout"]])
(defn home [req res raise]
(-> (html
[:html
[:body
(if (logged-in? req)
(logout-form req)
(login-form))]])
(r/ok)
(r/content-type "text/html")
(res)))
(defn not-found [req res raise]
(-> (html
[:html
[:body
[:h2 (:uri req) " was not found"]]])
(r/not-found)
(r/content-type "text/html")
(res)))
(defn login [req res raise]
(println (:params req))
(-> (r/found "/")
(assoc-in [:session :identity :name] (-> req :params :name))
(res)))
(defn logout [req res raise]
(-> (r/found "/")
(update :session dissoc :identity)
(res)))
(def routes
["/" {"" {:get home}
"login" {:post login}
"logout" {:get logout}}])
(defn router [req res raise]
(if-let [{:keys [handler route-params]} (bidi/match-route* routes (:uri req) req)]
(handler (assoc req :route-params route-params) res raise)
(not-found req res raise)))
| true | (ns auth-example.routes
(:require
[bidi.bidi :as bidi]
[hiccups.runtime]
[macchiato.middleware.anti-forgery :as af]
[macchiato.util.response :as r])
(:require-macros
[hiccups.core :refer [html]]))
(defn logged-in? [{:keys [identity]}]
(boolean identity))
(defn login-form []
[:div
[:h3 "Please login"]
[:form
{:method "POST"
:action "/login"}
[:input
{:type :hidden
:name "__anti-forgery-token"
:value af/*anti-forgery-token*}]
[:input
{:type :text
:name "name"
:placeholder "name"}]
[:input
{:type :text
:name "pass"
:placeholder "PI:PASSWORD:<PASSWORD>END_PI"}]
[:input
{:type :submit
:value "login"}]]])
(defn logout-form [{:keys [identity]}]
[:div
[:h3 "Welcome " (:name identity)]
[:a {:href "/logout"} "logout"]])
(defn home [req res raise]
(-> (html
[:html
[:body
(if (logged-in? req)
(logout-form req)
(login-form))]])
(r/ok)
(r/content-type "text/html")
(res)))
(defn not-found [req res raise]
(-> (html
[:html
[:body
[:h2 (:uri req) " was not found"]]])
(r/not-found)
(r/content-type "text/html")
(res)))
(defn login [req res raise]
(println (:params req))
(-> (r/found "/")
(assoc-in [:session :identity :name] (-> req :params :name))
(res)))
(defn logout [req res raise]
(-> (r/found "/")
(update :session dissoc :identity)
(res)))
(def routes
["/" {"" {:get home}
"login" {:post login}
"logout" {:get logout}}])
(defn router [req res raise]
(if-let [{:keys [handler route-params]} (bidi/match-route* routes (:uri req) req)]
(handler (assoc req :route-params route-params) res raise)
(not-found req res raise)))
|
[
{
"context": ":id :name] {:id 1})\n (where {:name \"John Doe\"})\n (where {:role \"admin\"})\n ",
"end": 1533,
"score": 0.9997612237930298,
"start": 1525,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "sers/person-id :people/id}) (where {:people/name \"John Doe\"}) str)))\n (is (= \"SELECT id AS \\\"id\\\", name",
"end": 3970,
"score": 0.9998430013656616,
"start": 3962,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "conn [\"INSERT INTO people (name, gender) VALUES ('John Doe', 'male')\"])\n (jdbc/execute! conn [\"INSERT",
"end": 5044,
"score": 0.9998209476470947,
"start": 5036,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " conn [\"INSERT INTO users (id, login) VALUES (1, 'john.doe')\"])\n (is (= 1 (fetch-count! query)))\n",
"end": 5134,
"score": 0.612389087677002,
"start": 5130,
"tag": "NAME",
"value": "john"
},
{
"context": "n [\"INSERT INTO users (id, login) VALUES (1, 'john.doe')\"])\n (is (= 1 (fetch-count! query)))\n ",
"end": 5138,
"score": 0.7767918109893799,
"start": 5135,
"tag": "USERNAME",
"value": "doe"
},
{
"context": "tch-count! query)))\n (is (= [{:id 1 :name \"John Doe\"}] (fetch! query)))\n (jdbc/execute! conn [",
"end": 5222,
"score": 0.9997625350952148,
"start": 5214,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "onn [\"INSERT INTO people (name, gender) VALUES ('Jane Doe', 'female')\"])\n (is (= 2 (fetch-count!",
"end": 5320,
"score": 0.9086396098136902,
"start": 5317,
"tag": "NAME",
"value": "ane"
},
{
"context": "1}) fetch-count!)))\n (is (= [{:id 1 :name \"John Doe\"} {:id 2 :name \"Jane Doe\"}] (-> query (where {:ge",
"end": 5477,
"score": 0.9997758865356445,
"start": 5469,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " (is (= [{:id 1 :name \"John Doe\"} {:id 2 :name \"Jane Doe\"}] (-> query (where {:gender [\"female\", \"male\"]})",
"end": 5502,
"score": 0.9997692108154297,
"start": 5494,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "\"male\"]}) fetch!)))\n (is (= [{:id 2 :name \"Jane Doe\" :gender \"female\"}] (-> query (where {:id 2}) (fe",
"end": 5601,
"score": 0.9997415542602539,
"start": 5593,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "]))))\n (is (= [{:person/id 1 :person/name \"John Doe\" :person/gender \"male\" :user/login \"john.doe\"}\n ",
"end": 5732,
"score": 0.999781608581543,
"start": 5724,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "ame \"John Doe\" :person/gender \"male\" :user/login \"john.doe\"}\n {:person/id 2 :person/name \"Jan",
"end": 5777,
"score": 0.9963516592979431,
"start": 5769,
"tag": "USERNAME",
"value": "john.doe"
},
{
"context": "doe\"}\n {:person/id 2 :person/name \"Jane Doe\" :person/gender \"female\" :user/login nil}]\n ",
"end": 5832,
"score": 0.9997899532318115,
"start": 5824,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": " fetch!)))\n (is (= [{:id 1 :name \"John Doe\"} {:id 2 :name \"Jane Doe\"}] (-> query (where {:or",
"end": 6105,
"score": 0.9997735023498535,
"start": 6097,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " (is (= [{:id 1 :name \"John Doe\"} {:id 2 :name \"Jane Doe\"}] (-> query (where {:or {:id 1 :gender \"female\"}",
"end": 6130,
"score": 0.9997586607933044,
"start": 6122,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "emale\"}}) fetch!)))\n (is (= [{:id 1 :name \"John Doe\"} {:id 2 :name \"Jane Doe\"}] (-> query (order [:id",
"end": 6231,
"score": 0.9997486472129822,
"start": 6223,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " (is (= [{:id 1 :name \"John Doe\"} {:id 2 :name \"Jane Doe\"}] (-> query (order [:id]) fetch!)))\n (is ",
"end": 6256,
"score": 0.9997535347938538,
"start": 6248,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "er [:id]) fetch!)))\n (is (= [{:id 2 :name \"Jane Doe\"} {:id 1 :name \"John Doe\"}] (-> query (order {:id",
"end": 6332,
"score": 0.9996424317359924,
"start": 6324,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": " (is (= [{:id 2 :name \"Jane Doe\"} {:id 1 :name \"John Doe\"}] (-> query (order {:id :desc}) fetch!)))\n ",
"end": 6357,
"score": 0.9997861385345459,
"start": 6349,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "y\"\n (is (= [{:person/id 1, :person/name \"John Doe\"}]\n (-> (select [:people :person]",
"end": 6490,
"score": 0.9997937679290771,
"start": 6482,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "id [:in (select :users [:users/id] {:users/login \"john.doe\"})]})\n fetch!))))))))\n\n(defte",
"end": 6634,
"score": 0.9940140247344971,
"start": 6626,
"tag": "USERNAME",
"value": "john.doe"
},
{
"context": "erate-sql-command (sql/insert nil :users {:login \"admin\" :role \"admin\"}))))\n (is\n (= \"INSERT INTO ",
"end": 6863,
"score": 0.9994017481803894,
"start": 6858,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "erate-sql-command (sql/update nil :users {:login \"admin\", :role \"admin\"} {:id 1})))))\n (testing \"Delete ",
"end": 7379,
"score": 0.999345064163208,
"start": 7374,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "s (= {:id 1} (-> (sql/insert conn :people {:name \"John Doe\"}) norm/execute!)))\n (is (= {:id 2} (-> (s",
"end": 8080,
"score": 0.999839186668396,
"start": 8072,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "} (-> (sql/insert conn :people [[:name :gender] [\"Jane Doe\" \"female\"] [\"Zoe Doe\" \"female\"]]) norm/execute!))",
"end": 8180,
"score": 0.9998273849487305,
"start": 8172,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": " :people [[:name :gender] [\"Jane Doe\" \"female\"] [\"Zoe Doe\" \"female\"]]) norm/execute!)))\n (is (= 3 (-",
"end": 8201,
"score": 0.9998171925544739,
"start": 8194,
"tag": "NAME",
"value": "Zoe Doe"
},
{
"context": "= [{:id 4} {:id 5} {:id 6} {:id 7} [{:id 4 :name \"Buzz Lightyear\"}]]\n (-> (sql/transaction conn\n ",
"end": 9162,
"score": 0.9963424801826477,
"start": 9148,
"tag": "NAME",
"value": "Buzz Lightyear"
},
{
"context": " (sql/insert nil :people {:name \"Buzz Lightyear\"})\n (sql/inser",
"end": 9290,
"score": 0.990608811378479,
"start": 9276,
"tag": "NAME",
"value": "Buzz Lightyear"
},
{
"context": " (sql/insert nil :people {:name \"Woody\"})\n (sql/inser",
"end": 9367,
"score": 0.9995229840278625,
"start": 9362,
"tag": "NAME",
"value": "Woody"
},
{
"context": " (sql/insert nil :people {:name \"Jessie\"})\n (sql/inser",
"end": 9445,
"score": 0.9995613098144531,
"start": 9439,
"tag": "NAME",
"value": "Jessie"
},
{
"context": " (sql/insert nil :people {:name \"Sid\"})\n (sql/selec",
"end": 9520,
"score": 0.999496340751648,
"start": 9517,
"tag": "NAME",
"value": "Sid"
},
{
"context": " (sql/select nil :people [:id :name] {:name \"Buzz Lightyear\"}))\n norm/execute!)))\n (",
"end": 9618,
"score": 0.9959914684295654,
"start": 9604,
"tag": "NAME",
"value": "Buzz Lightyear"
},
{
"context": " norm/execute!)))\n (is (= [{:id 4 :name \"Buzz Lightyear\"}\n {:id 5 :name \"Woody\"}\n ",
"end": 9703,
"score": 0.996865451335907,
"start": 9689,
"tag": "NAME",
"value": "Buzz Lightyear"
},
{
"context": "e \"Buzz Lightyear\"}\n {:id 5 :name \"Woody\"}\n {:id 6 :name \"Jessie\"}\n ",
"end": 9741,
"score": 0.9995853900909424,
"start": 9736,
"tag": "NAME",
"value": "Woody"
},
{
"context": "id 5 :name \"Woody\"}\n {:id 6 :name \"Jessie\"}\n {:id 7 :name \"Sid\"}]\n ",
"end": 9780,
"score": 0.9996325969696045,
"start": 9774,
"tag": "NAME",
"value": "Jessie"
},
{
"context": "d 6 :name \"Jessie\"}\n {:id 7 :name \"Sid\"}]\n (-> (sql/select conn :people [:",
"end": 9816,
"score": 0.9997232556343079,
"start": 9813,
"tag": "NAME",
"value": "Sid"
},
{
"context": " (sql/delete nil :people {:name \"Jane Doe\"})\n (sql",
"end": 10409,
"score": 0.999133288860321,
"start": 10401,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": " (sql/insert nil :people {:first-name \"John\" :last-name \"Doe\"})\n ",
"end": 10497,
"score": 0.9997755289077759,
"start": 10493,
"tag": "NAME",
"value": "John"
},
{
"context": "nsert nil :people {:first-name \"John\" :last-name \"Doe\"})\n (sql",
"end": 10514,
"score": 0.999713659286499,
"start": 10511,
"tag": "NAME",
"value": "Doe"
},
{
"context": " (sql/select nil :people [:id :name] {:name \"John Doe\"}))\n norm/execute!)))\n ",
"end": 10612,
"score": 0.99983811378479,
"start": 10604,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " norm/execute!)))\n (is (= [{:id 2 :name \"Jane Doe\"}]\n (-> (sql/select conn :people [:",
"end": 10697,
"score": 0.9997687935829163,
"start": 10689,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": " (-> (sql/select conn :people [:id :name] {:name \"Jane Doe\"}) norm/execute!))\n \"Record must be pr",
"end": 10773,
"score": 0.9998202919960022,
"start": 10765,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": " (is (= {:id 1} (-> (norm/create person {:name \"John Doe\" :gender \"male\"}) norm/execute!)))\n (is (=",
"end": 11506,
"score": 0.9998151659965515,
"start": 11498,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " (is (= {:id 2} (-> (norm/create person {:name \"Jane Doe\" :gender \"female\"}) norm/execute!)))\n (is ",
"end": 11605,
"score": 0.9997909665107727,
"start": 11597,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "s (= {:id 1} (-> (norm/create user {:id 1 :login \"john\" :role \"user\"}) norm/execute!))))\n (testing ",
"end": 11707,
"score": 0.8015251159667969,
"start": 11703,
"tag": "NAME",
"value": "john"
},
{
"context": " (testing \"fetching\"\n (is (= {:id 1 :name \"John Doe\" :gender \"male\"} (norm/fetch-by-id! person 1))\n ",
"end": 11805,
"score": 0.9998147487640381,
"start": 11797,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "ce to the entity.\")\n (is (= [{:id 1 :name \"John Doe\" :gender \"male\"}\n {:id 2 :name \"Ja",
"end": 12159,
"score": 0.9998157024383545,
"start": 12151,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "oe\" :gender \"male\"}\n {:id 2 :name \"Jane Doe\" :gender \"female\"}]\n (-> (norm/find",
"end": 12215,
"score": 0.9997963905334473,
"start": 12207,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "d person) fetch!)))\n (is (= [{:id 1 :name \"John Doe\" :gender \"male\"}] (-> (norm/find person {:id 1}) ",
"end": 12322,
"score": 0.9998048543930054,
"start": 12314,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " (testing \"order\"\n (is (= [{:id 2 :name \"Jane Doe\" :gender \"female\"}\n {:id 1 :name \"",
"end": 12444,
"score": 0.9997859001159668,
"start": 12436,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "\" :gender \"female\"}\n {:id 1 :name \"John Doe\" :gender \"male\"}]\n (-> (norm/find p",
"end": 12502,
"score": 0.9997804760932922,
"start": 12494,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " \"offset and limit\"\n (is (= [{:id 2 :name \"Jane Doe\" :gender \"female\"}]\n (-> (norm/find",
"end": 12678,
"score": 0.9998040795326233,
"start": 12670,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "(limit 1) fetch!)))\n (is (= [{:id 1 :name \"John Doe\" :gender \"male\"}]\n (-> (norm/find p",
"end": 12841,
"score": 0.9997506141662598,
"start": 12833,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "\n (is (= 1 (-> (norm/update person {:name \"Jane Love\"} {:id 2}) norm/execute!)))\n (is (= {:id 2",
"end": 13046,
"score": 0.99977707862854,
"start": 13037,
"tag": "NAME",
"value": "Jane Love"
},
{
"context": "2}) norm/execute!)))\n (is (= {:id 2 :name \"Jane Love\" :gender \"female\"} (norm/fetch-by-id! person 2)) ",
"end": 13113,
"score": 0.9997766017913818,
"start": 13104,
"tag": "NAME",
"value": "Jane Love"
},
{
"context": "conn [\"INSERT INTO people (name, gender) VALUES ('John Doe', 'male')\"])\n (jdbc/execute! conn [\"INSERT INT",
"end": 21008,
"score": 0.9997506141662598,
"start": 21000,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "conn [\"INSERT INTO people (name, gender) VALUES ('Jane Doe', 'female')\"])\n (jdbc/execute! conn [\"INSERT I",
"end": 21099,
"score": 0.9995444416999817,
"start": 21091,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "conn [\"INSERT INTO people (name, gender) VALUES ('Zoe Doe', 'female')\"])\n (jdbc/execute! conn [\"INSERT I",
"end": 21191,
"score": 0.9994678497314453,
"start": 21184,
"tag": "NAME",
"value": "Zoe Doe"
},
{
"context": "cts (person_id, type, value) VALUES (1, 'email', 'john.doe@mailinator.com')\"])\n (jdbc/execute! conn [\"INSERT INTO contac",
"end": 21323,
"score": 0.9981725811958313,
"start": 21300,
"tag": "EMAIL",
"value": "john.doe@mailinator.com"
},
{
"context": "cts (person_id, type, value) VALUES (2, 'email', 'jane.doe@mailinator.com')\"])\n (jdbc/execute! conn [\"INSERT INTO users ",
"end": 21560,
"score": 0.9999291300773621,
"start": 21537,
"tag": "EMAIL",
"value": "jane.doe@mailinator.com"
},
{
"context": " conn [\"INSERT INTO users (id, login) VALUES (1, 'john.doe')\"])\n (jdbc/execute! conn [\"INSERT INTO users ",
"end": 21642,
"score": 0.8712584972381592,
"start": 21634,
"tag": "NAME",
"value": "john.doe"
},
{
"context": "INSERT INTO users (id, login, active) VALUES (2, 'jane.doe', false)\"])\n (jdbc/execute! conn [\"INSERT INTO",
"end": 21732,
"score": 0.8486286997795105,
"start": 21724,
"tag": "NAME",
"value": "jane.doe"
},
{
"context": "INSERT INTO users (id, login, active) VALUES (3, 'zoe.doe', true)\"])\n (jdbc/execute! conn [\"INSERT INTO ",
"end": 21828,
"score": 0.8081527948379517,
"start": 21821,
"tag": "NAME",
"value": "zoe.doe"
},
{
"context": " (norm/find (:employee repository) {:person/name \"Jane Doe\"}) str)\n (-> (norm/find (:employee ",
"end": 26013,
"score": 0.9977321624755859,
"start": 26005,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "nd (:employee repository) {:employee.person/name \"Jane Doe\"}) str)\n (-> (norm/find (:employee ",
"end": 26107,
"score": 0.9971001744270325,
"start": 26099,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "loyee repository)) (where {:employee.person/name \"Jane Doe\"}) str)))\n (is (= \"SELECT \\\"user\\\".login A",
"end": 26209,
"score": 0.9981921315193176,
"start": 26201,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": " (norm/find {:user.person/name \"John Doe\"})\n str))\n \"Usage of",
"end": 27121,
"score": 0.9993247389793396,
"start": 27113,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "a256xxxx\"\n :user {:login \"buzz.lightyear\"\n :active false\n ",
"end": 30489,
"score": 0.999585747718811,
"start": 30475,
"tag": "USERNAME",
"value": "buzz.lightyear"
},
{
"context": "e\n :person {:name \"Buzz Lightyear\"}}})\n norm/execute!)))\n ",
"end": 30599,
"score": 0.998752236366272,
"start": 30585,
"tag": "NAME",
"value": "Buzz Lightyear"
},
{
"context": "epository) 4)))\n (is (= {:id 4 :login \"buzz.lightyear\" :active false :person {:id 4 :name \"Buzz Lightye",
"end": 30791,
"score": 0.9995887875556946,
"start": 30777,
"tag": "USERNAME",
"value": "buzz.lightyear"
},
{
"context": "zz.lightyear\" :active false :person {:id 4 :name \"Buzz Lightyear\"}}\n (norm/fetch-by-id! (:user r",
"end": 30843,
"score": 0.9986209273338318,
"start": 30829,
"tag": "NAME",
"value": "Buzz Lightyear"
},
{
"context": "= {:id 4 :salary 1000.0000M :person {:id 4 :name \"Buzz Lightyear\"} :active true}\n (norm/fetch-by",
"end": 32185,
"score": 0.9998129606246948,
"start": 32171,
"tag": "NAME",
"value": "Buzz Lightyear"
},
{
"context": " (is (= {:id 5} (norm/create! person {:name \"Sid\" :gender \"male\"})))\n (is (= {:id 5, :n",
"end": 33011,
"score": 0.9997930526733398,
"start": 33008,
"tag": "NAME",
"value": "Sid"
},
{
"context": "nder \"male\"})))\n (is (= {:id 5, :name \"SID\" :gender \"male\"} (norm/fetch-by-id! person 5))\n ",
"end": 33069,
"score": 0.9997839331626892,
"start": 33066,
"tag": "NAME",
"value": "SID"
},
{
"context": " (is (= {:id 1\n :login \"john.doe\"\n :active true\n ",
"end": 33340,
"score": 0.9976198077201843,
"start": 33332,
"tag": "USERNAME",
"value": "john.doe"
},
{
"context": " :person {:id 1\n :name \"John Doe\"\n :gender \"male\"}}\n ",
"end": 33448,
"score": 0.9997483491897583,
"start": 33440,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " :person {:id 2\n :name \"Jane Doe\"\n :gender \"female\"}}]\n ",
"end": 33996,
"score": 0.9998119473457336,
"start": 33988,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": " (where {:employee.person/name \"Jane Doe\"})\n fetch!))\n \"Claus",
"end": 34156,
"score": 0.9998211860656738,
"start": 34148,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "lds of related entities\"\n (is (= [{:login \"john.doe\", :person {:name \"John Doe\"}}] (norm/find! (:user",
"end": 34335,
"score": 0.999016284942627,
"start": 34327,
"tag": "USERNAME",
"value": "john.doe"
},
{
"context": " (is (= [{:login \"john.doe\", :person {:name \"John Doe\"}}] (norm/find! (:user repository) [:user/login :",
"end": 34362,
"score": 0.9998152852058411,
"start": 34354,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "g related entities\"\n (is (= [{:id 1 :name \"John Doe\" :gender \"male\"}]\n (-> (norm/find-r",
"end": 34518,
"score": 0.9998347759246826,
"start": 34510,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "related (:user repository) :person {:person/name \"John Doe\"}) fetch!)\n (-> (norm/find-related ",
"end": 34995,
"score": 0.9998477697372437,
"start": 34987,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "ed (:user repository) :person {:user.person/name \"John Doe\"}) fetch!)))\n (is (some? (-> (norm/find-re",
"end": 35100,
"score": 0.9998316764831543,
"start": 35092,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "(is (= [{:id 3 :person-id 2 :type \"email\" :value \"jane.doe@mailinator.com\" :owner {:id 2 :name \"Jane Doe\" :gender \"female\"}",
"end": 35820,
"score": 0.9999237060546875,
"start": 35797,
"tag": "EMAIL",
"value": "jane.doe@mailinator.com"
},
{
"context": "ue \"jane.doe@mailinator.com\" :owner {:id 2 :name \"Jane Doe\" :gender \"female\"}}]\n (-> (norm/fin",
"end": 35851,
"score": 0.9998719096183777,
"start": 35843,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "ted (:person repository) :contacts {:person/name \"Jane Doe\"}) fetch!)))\n (is (= 0 (-> (norm/find-rela",
"end": 35965,
"score": 0.9998748898506165,
"start": 35957,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "ary 1500.0000M :active true :person {:id 1 :name \"John Doe\" :gender \"male\"}}]\n (-> (norm/find-",
"end": 36563,
"score": 0.9998477697372437,
"start": 36555,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "ary 3000.0000M :active true :person {:id 2 :name \"Jane Doe\" :gender \"female\"}}]\n (-> (norm/fin",
"end": 36975,
"score": 0.9998731017112732,
"start": 36967,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "ary 1500.0000M :active true :person {:id 1 :name \"John Doe\" :gender \"male\"}}]\n (-> (norm/find-",
"end": 37176,
"score": 0.999840259552002,
"start": 37168,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " {:id 2}) fetch!)))\n (is (= [{:id 1 :name \"John Doe\" :gender \"male\"}]\n (-> (norm/find-r",
"end": 37326,
"score": 0.9998370409011841,
"start": 37318,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "ind-related (:contact repository) :owner {:value \"john.doe@mailinator.com\"}) fetch!))\n \"Filtering by a field of ",
"end": 37444,
"score": 0.9999232888221741,
"start": 37421,
"tag": "EMAIL",
"value": "john.doe@mailinator.com"
},
{
"context": "ity should work.\")\n (is (= [{:id 1 :login \"john.doe\" :active true :person {:id 1 :name \"John Doe\" :ge",
"end": 37564,
"score": 0.9644594788551331,
"start": 37556,
"tag": "USERNAME",
"value": "john.doe"
},
{
"context": "gin \"john.doe\" :active true :person {:id 1 :name \"John Doe\" :gender \"male\"}}]\n (-> (norm/find-",
"end": 37609,
"score": 0.9998413920402527,
"start": 37601,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "user-secret repository) :user {:user.person/name \"John Doe\"}) fetch!))\n \"Clause by a related enti",
"end": 37727,
"score": 0.9998129606246948,
"start": 37719,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "fetch with filter\"\n (is (= [{:id 1 :login \"john.doe\" :active true :person {:id 1, :name \"John Doe\", :",
"end": 37905,
"score": 0.9827885627746582,
"start": 37897,
"tag": "USERNAME",
"value": "john.doe"
},
{
"context": "in \"john.doe\" :active true :person {:id 1, :name \"John Doe\", :gender \"male\"}}\n {:id 3 :login ",
"end": 37951,
"score": 0.9998418092727661,
"start": 37943,
"tag": "NAME",
"value": "John Doe"
},
{
"context": ", :gender \"male\"}}\n {:id 3 :login \"zoe.doe\" :active true :person {:id 3, :name \"Zoe Doe\", :g",
"end": 38009,
"score": 0.9471696019172668,
"start": 38002,
"tag": "USERNAME",
"value": "zoe.doe"
},
{
"context": "gin \"zoe.doe\" :active true :person {:id 3, :name \"Zoe Doe\", :gender \"female\"}}]\n (-> (:user r",
"end": 38054,
"score": 0.9998367428779602,
"start": 38047,
"tag": "NAME",
"value": "Zoe Doe"
},
{
"context": "orm/find fetch!)))\n (is (= [{:id 3 :login \"zoe.doe\" :active true :person {:id 3, :name \"Zoe Doe\", :g",
"end": 38207,
"score": 0.951444685459137,
"start": 38200,
"tag": "USERNAME",
"value": "zoe.doe"
},
{
"context": "gin \"zoe.doe\" :active true :person {:id 3, :name \"Zoe Doe\", :gender \"female\"}}]\n (-> (:user r",
"end": 38252,
"score": 0.9998379349708557,
"start": 38245,
"tag": "NAME",
"value": "Zoe Doe"
},
{
"context": "norm/find (:user-secret repository) {:user/login \"john.doe\"}) fetch!))))\n (testing \"update\"\n (te",
"end": 38798,
"score": 0.9972241520881653,
"start": 38790,
"tag": "USERNAME",
"value": "john.doe"
},
{
"context": "zz\"}} {:id 4})))\n (is (= {:id 4 :name \"Buzz\"} (norm/fetch-by-id! (:person repository) 4))\n ",
"end": 39054,
"score": 0.9993314146995544,
"start": 39050,
"tag": "NAME",
"value": "Buzz"
},
{
"context": " (:user repository) {:role \"user\" :person {:name \"Buzz Lightyear\"}} {:id 4})))\n (is (= {:id 4 :login \"b",
"end": 39273,
"score": 0.9995635747909546,
"start": 39259,
"tag": "NAME",
"value": "Buzz Lightyear"
},
{
"context": "r\"}} {:id 4})))\n (is (= {:id 4 :login \"buzz.lightyear\" :role \"user\" :active false :person {:id 4, :name",
"end": 39336,
"score": 0.9992284774780273,
"start": 39322,
"tag": "USERNAME",
"value": "buzz.lightyear"
},
{
"context": ":role \"user\" :active false :person {:id 4, :name \"Buzz Lightyear\"}}\n (norm/fetch-by-id! (:user r",
"end": 39402,
"score": 0.9995986819267273,
"start": 39388,
"tag": "NAME",
"value": "Buzz Lightyear"
},
{
"context": "is (= 1 (norm/update! (:user repository) {:login \"buzz\"} {:person/name \"Buzz Lightyear\"})))\n (i",
"end": 40453,
"score": 0.9994351267814636,
"start": 40449,
"tag": "USERNAME",
"value": "buzz"
},
{
"context": "(:user repository) {:login \"buzz\"} {:person/name \"Buzz Lightyear\"})))\n (is (= {:id 4 :login \"buzz\" :role ",
"end": 40485,
"score": 0.9996683597564697,
"start": 40471,
"tag": "NAME",
"value": "Buzz Lightyear"
},
{
"context": "zz Lightyear\"})))\n (is (= {:id 4 :login \"buzz\" :role \"user\" :active false :person {:id 4, :name",
"end": 40527,
"score": 0.9994717240333557,
"start": 40523,
"tag": "USERNAME",
"value": "buzz"
},
{
"context": ":role \"user\" :active false :person {:id 4, :name \"Buzz Lightyear\"}}\n (norm/fetch-by-id! (:user rep",
"end": 40593,
"score": 0.9997256994247437,
"start": 40579,
"tag": "NAME",
"value": "Buzz Lightyear"
},
{
"context": " (is (= 1 (norm/update! person {:name \"Sid\"} {:id 5})))\n (is (= {:id 5, :name \"si",
"end": 40932,
"score": 0.9997111558914185,
"start": 40929,
"tag": "NAME",
"value": "Sid"
},
{
"context": "id\"} {:id 5})))\n (is (= {:id 5, :name \"sid\", :gender \"male\"} (norm/fetch-by-id! person 5))\n ",
"end": 40983,
"score": 0.9994931817054749,
"start": 40980,
"tag": "NAME",
"value": "sid"
},
{
"context": "1 (norm/delete! (:user repository) {:person/name \"Buzz Lightyear\"})))\n (is (nil? (norm/fetch-by-id! (:user ",
"end": 42006,
"score": 0.9970475435256958,
"start": 41992,
"tag": "NAME",
"value": "Buzz Lightyear"
}
] | test/norm/sql_test.clj | kurbatov/norm | 4 | (ns norm.sql-test
(:require [clojure.test :as t :refer [deftest testing is]]
[clojure.string :as str]
[next.jdbc :as jdbc]
[norm.core :as norm :refer [where order skip limit fetch! fetch-count!]]
[norm.sql :as sql]
[norm.sql.jdbc :refer [instance-meta]]
[norm.sql.specs :as sql.specs]))
(defn contains-all? [m & ks]
(= (clojure.set/intersection (set ks) (set (keys m))) (set ks)))
(deftest sql-query-test
(testing "Query building"
(is (= "SELECT * FROM users AS \"users\"" (str (sql/select nil :users))))
(is (= "SELECT * FROM users AS \"users\"" (str (sql/select nil :users [:*]))))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\"" (str (sql/select nil :users [:id :name]))))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".name AS \"user/name\" FROM users AS \"user\""
(str (sql/select nil [:users :user] [:user/id :user/name]))))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\""
(str (sql/select nil :users [:id :name] {})))
"Empty where clause should not apear in the query.")
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (id = ?)"
(str (sql/select nil :users [:id :name] {:id 1}))))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (((id = ?) AND (name = ?)) AND (role = ?))"
(-> (sql/select nil :users [:id :name] {:id 1})
(where {:name "John Doe"})
(where {:role "admin"})
str)))
(is (= "SELECT column_name AS \"column-name\" FROM information_schema.columns AS \"information_schema.columns\" WHERE (table_schema ILIKE ? AND table_name ILIKE ?)"
(-> (sql/select nil
:information-schema/columns
[:column-name]
{:table-schema [:ilike "public"]
:table-name [:ilike "table_name"]}) str)))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".name AS \"user/name\" FROM users AS \"user\" WHERE (\"user\".id = ?)"
(str (sql/select nil [:users :user] [:user/id :user/name] {:user/id 1}))))
(is (= "SELECT \"user\".id AS \"user/id\", \"person\".name AS \"person/name\" FROM (users AS \"user\" LEFT JOIN people AS \"person\" ON (\"user\".id = \"person\".id))"
(str (sql/select nil [[:users :user] :left-join [:people :person] {:user/id :person/id}] [:user/id :person/name]))))
(is (= "SELECT \"users\".*, \"people\".* FROM (users AS \"users\" LEFT JOIN people AS \"people\" ON (\"users\".id = \"people\".id))"
(str (sql/select nil [:users :left-join :people {:users/id :people/id}] [:users/* :people/*])))
"Wildcard should go without alias.")
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\" FROM users AS \"user\" WHERE (\"user\".id IN ((SELECT user_id AS \"user-id\" FROM employees AS \"employees\" WHERE (active IS true))))"
(str (sql/select nil [:users :user] [:user/id :user/login] {:user/id [:in (sql/select nil :employees [:user-id] {:active true})]}))))
(is (= "SELECT CURRENT_SCHEMA() AS \"current-schema\"" (str (sql/select nil nil [['(current-schema) :current-schema]]))))
(is (= "SELECT id AS \"id\" FROM tasks AS \"tasks\" WHERE (scheduled >= NOW())" (str (sql/select nil :tasks [:id] {:scheduled [:>= '(now)]})))))
(testing "Query parts amendment"
(let [query (sql/select nil :users [:id :name])]
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (id = ?)" (-> query (where {:id 1}) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM (users AS \"users\" LEFT JOIN people AS \"people\" ON (\"users\".person_id = \"people\".id)) WHERE (\"people\".name = ?)"
(-> query (sql/join :left-join :people {:users/person-id :people/id}) (where {:people/name "John Doe"}) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" OFFSET ?" (-> query (skip 2) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" LIMIT ?" (-> query (limit 10) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" LIMIT ? OFFSET ?" (-> query (skip 2) (limit 10) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (id = ?) LIMIT ? OFFSET ?"
(-> query (where {:id 1}) (skip 2) (limit 10) str)))))
(testing "Data fetching"
(with-open [conn (jdbc/get-connection {:dbtype "h2:mem"})]
(let [select (partial sql/select conn)
query (select :people [:id :name])]
(jdbc/execute! conn ["CREATE TABLE people (id BIGSERIAL, name VARCHAR(100), gender VARCHAR(10), birthday DATE)"])
(jdbc/execute! conn ["CREATE TABLE users (id BIGINT, login VARCHAR(100), role VARCHAR(50))"])
(is (zero? (fetch-count! query)))
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('John Doe', 'male')"])
(jdbc/execute! conn ["INSERT INTO users (id, login) VALUES (1, 'john.doe')"])
(is (= 1 (fetch-count! query)))
(is (= [{:id 1 :name "John Doe"}] (fetch! query)))
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('Jane Doe', 'female')"])
(is (= 2 (fetch-count! query)))
(is (= 1 (-> query (where {:id 1}) fetch-count!)))
(is (= [{:id 1 :name "John Doe"} {:id 2 :name "Jane Doe"}] (-> query (where {:gender ["female", "male"]}) fetch!)))
(is (= [{:id 2 :name "Jane Doe" :gender "female"}] (-> query (where {:id 2}) (fetch! [:id :name :gender]))))
(is (= [{:person/id 1 :person/name "John Doe" :person/gender "male" :user/login "john.doe"}
{:person/id 2 :person/name "Jane Doe" :person/gender "female" :user/login nil}]
(->
(select [[:people :person] :left-join [:users :user] {:person/id :user/id}] [:person/id :person/name :person/gender :user/login])
fetch!)))
(is (= [{:id 1 :name "John Doe"} {:id 2 :name "Jane Doe"}] (-> query (where {:or {:id 1 :gender "female"}}) fetch!)))
(is (= [{:id 1 :name "John Doe"} {:id 2 :name "Jane Doe"}] (-> query (order [:id]) fetch!)))
(is (= [{:id 2 :name "Jane Doe"} {:id 1 :name "John Doe"}] (-> query (order {:id :desc}) fetch!)))
(testing "with sub-query"
(is (= [{:person/id 1, :person/name "John Doe"}]
(-> (select [:people :person] [:person/id :person/name] {:person/id [:in (select :users [:users/id] {:users/login "john.doe"})]})
fetch!))))))))
(deftest sql-command-test
(testing "Insert command building"
(is (= "INSERT INTO users (login, role) VALUES (?, ?)" (sql/generate-sql-command (sql/insert nil :users {:login "admin" :role "admin"}))))
(is
(= "INSERT INTO users (login, role) VALUES (?, ?), (?, ?), (?, ?)"
(-> (sql/insert nil :users [[:login :role]
["admin" "admin"]
["foo" "user"]
["bar" "user"]])
sql/generate-sql-command))))
(testing "Update command building"
(is (= "UPDATE users SET login = ?, role = ? WHERE (id = ?)" (sql/generate-sql-command (sql/update nil :users {:login "admin", :role "admin"} {:id 1})))))
(testing "Delete command building"
(is (= "DELETE FROM users WHERE (id = ?)" (sql/generate-sql-command (sql/delete nil :users {:id 1})))))
(testing "Select command building"
(is (= "SELECT id AS \"id\", login AS \"login\" FROM users AS \"users\" WHERE (id = ?)"
(sql/generate-sql-command (sql/select nil :users [:id :login] {:id 1})))))
(testing "Execution"
(with-open [conn (jdbc/get-connection {:dbtype "h2:mem"})]
(jdbc/execute! conn ["CREATE TABLE people (id BIGSERIAL, name VARCHAR(100) NOT NULL, gender VARCHAR(10), birthday DATE)"])
(testing "of insert"
(is (= {:id 1} (-> (sql/insert conn :people {:name "John Doe"}) norm/execute!)))
(is (= {:id 2} (-> (sql/insert conn :people [[:name :gender] ["Jane Doe" "female"] ["Zoe Doe" "female"]]) norm/execute!)))
(is (= 3 (-> (sql/select conn :people) fetch-count!)) "Database must contain all the inserted records."))
(testing "of update"
(is (= 1 (-> (sql/update conn :people {:gender "male"} {:id 1}) norm/execute!)))
(is (= [{:id 1 :gender "male"}] (-> (sql/select conn :people [:id :gender] {:id 1}) fetch!)) "Row must change after update.")
(is (= 1 (-> (sql/update conn :people {:gender nil} {:id 1}) norm/execute!)))
(is (= [{:id 1 :gender nil}] (-> (sql/select conn :people [:id :gender] {:id 1}) fetch!)) "Property must change after update with nil."))
(testing "of delete"
(is (= 1 (-> (sql/delete conn :people {:id 1}) norm/execute!)))
(is (= [{:id 2} {:id 3}] (-> (sql/select conn :people [:id]) fetch!)) "Deleted row must be missing from the table."))
(testing "of transaction"
(is (= [{:id 4} {:id 5} {:id 6} {:id 7} [{:id 4 :name "Buzz Lightyear"}]]
(-> (sql/transaction conn
(sql/insert nil :people {:name "Buzz Lightyear"})
(sql/insert nil :people {:name "Woody"})
(sql/insert nil :people {:name "Jessie"})
(sql/insert nil :people {:name "Sid"})
(sql/select nil :people [:id :name] {:name "Buzz Lightyear"}))
norm/execute!)))
(is (= [{:id 4 :name "Buzz Lightyear"}
{:id 5 :name "Woody"}
{:id 6 :name "Jessie"}
{:id 7 :name "Sid"}]
(-> (sql/select conn :people [:id :name] {:id [:> 3]}) norm/execute!)))
(is (= (repeat 4 1)
(-> (sql/delete conn :people {:id 4})
(norm/then (sql/delete conn :people {:id 5}))
(norm/then (sql/delete conn :people {:id 6}))
(norm/then (sql/delete conn :people {:id 7}))
norm/execute!)))
(is (thrown? org.h2.jdbc.JdbcSQLSyntaxErrorException
(-> (sql/transaction conn
(sql/delete nil :people {:name "Jane Doe"})
(sql/insert nil :people {:first-name "John" :last-name "Doe"})
(sql/select nil :people [:id :name] {:name "John Doe"}))
norm/execute!)))
(is (= [{:id 2 :name "Jane Doe"}]
(-> (sql/select conn :people [:id :name] {:name "Jane Doe"}) norm/execute!))
"Record must be present after failed transaction")))))
(deftest relational-entity-test
(with-open [conn (jdbc/get-connection {:dbtype "h2:mem"})]
(jdbc/execute! conn ["CREATE TABLE people (id BIGSERIAL, name VARCHAR(100), gender VARCHAR(10), birthday DATE)"])
(jdbc/execute! conn ["CREATE TABLE users (id BIGINT, login VARCHAR(100), role VARCHAR(50), active BOOLEAN)"])
(let [person (sql/create-entity {:db conn} {:name :person, :table :people, :fields [:id :name :gender :birthday]})
user (sql/create-entity {:db conn} {:name :user, :table :users, :fields [:id :login :role :active]})]
(testing "creation"
(is (= {:id 1} (-> (norm/create person {:name "John Doe" :gender "male"}) norm/execute!)))
(is (= {:id 2} (-> (norm/create person {:name "Jane Doe" :gender "female"}) norm/execute!)))
(is (= {:id 1} (-> (norm/create user {:id 1 :login "john" :role "user"}) norm/execute!))))
(testing "fetching"
(is (= {:id 1 :name "John Doe" :gender "male"} (norm/fetch-by-id! person 1))
(str (norm/find person {:id 1})))
(is (= (merge instance-meta {:entity person}) (-> (norm/fetch-by-id! person 1) meta))
"Metadata of an instance must contain an implementation of the `Instance `protocol and a reference to the entity.")
(is (= [{:id 1 :name "John Doe" :gender "male"}
{:id 2 :name "Jane Doe" :gender "female"}]
(-> (norm/find person) fetch!)))
(is (= [{:id 1 :name "John Doe" :gender "male"}] (-> (norm/find person {:id 1}) fetch!))))
(testing "order"
(is (= [{:id 2 :name "Jane Doe" :gender "female"}
{:id 1 :name "John Doe" :gender "male"}]
(-> (norm/find person {:birthday nil}) (order {:id :desc}) fetch!))))
(testing "offset and limit"
(is (= [{:id 2 :name "Jane Doe" :gender "female"}]
(-> (norm/find person {:birthday nil}) (order {:id :desc}) (skip 0) (limit 1) fetch!)))
(is (= [{:id 1 :name "John Doe" :gender "male"}]
(-> (norm/find person {:birthday nil}) (order {:id :desc}) (skip 1) (limit 1) fetch!))))
(testing "update"
(is (= 1 (-> (norm/update person {:name "Jane Love"} {:id 2}) norm/execute!)))
(is (= {:id 2 :name "Jane Love" :gender "female"} (norm/fetch-by-id! person 2)) "Entity must change after update."))
(testing "delete"
(is (= 1 (-> (norm/delete person {:id 2}) norm/execute!)))
(is (nil? (norm/fetch-by-id! person 2)) "Entity must be missing after delete."))
(testing "with filter"
(let [active-user (norm/with-filter user {:active true})
active-admin (norm/with-filter active-user {:role "admin"})]
(is (= (merge user {:filter {:active true}})
active-user))
(is (= (merge user {:filter '(and {:active true} {:role "admin"})})
active-admin))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\" FROM users AS \"user\" WHERE (\"user\".active IS true)"
(-> active-user norm/find str)))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\" FROM users AS \"user\" WHERE ((\"user\".active IS true) AND (\"user\".id = ?))"
(-> active-user (norm/find {:id 1}) str)))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\" FROM users AS \"user\" WHERE ((\"user\".active IS true) AND (\"user\".role = ?))"
(-> active-admin norm/find str)))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\" FROM users AS \"user\" WHERE (((\"user\".active IS true) AND (\"user\".role = ?)) AND (\"user\".id = ?))"
(-> active-admin (norm/find {:id 1}) str)))))
(testing "mutating an entity"
(is (= (merge user {:rels {:secret {:entity :secret
:type :has-one
:fk :user-id}}})
(norm/with-rels user {:secret {:entity :secret
:type :has-one
:fk :user-id}})))
(is (= true
(-> user
(norm/with-rels {:secret {:entity :secret
:type :has-one
:fk :user-id}})
(norm/with-eager [:secret])
(get-in [:rels :secret :eager]))))))))
(def entities
{:person {:table :people
:rels {:contacts {:entity :contact
:type :has-many
:fk :person-id}}}
:contact {:table :contacts
:rels {:owner {:entity :person
:type :belongs-to
:fk :person-id
:eager true}}}
:user {:table :users
:rels {:person {:entity :person
:type :belongs-to
:fk :id
:eager true}}}
:user-secret {:table :secrets
:rels {:user {:entity :user
:type :belongs-to
:fk :id}}}
:employee {:table :employees
:rels {:person {:entity :person
:type :belongs-to
:fk :id
:eager true}
:supervisor {:entity :employee
:type :belongs-to
:fk :supervisor-id}
:subordinates {:entity :employee
:type :has-many
:fk :supervisor-id
:filter {:active true}}
:responsibilities {:entity :responsibility
:type :has-many
:fk :employee-id
:rfk :responsibility-id
:join-table :employees-responsibilities
:filter {:active true}}
:nonresponsibilities {:entity :responsibility
:type :has-many
:fk :employee-id
:rfk :responsibility-id
:join-table :employees-responsibilities-negative
:filter {:active true}}}}
:responsibility {:table :responsibilities
:rels {:employees {:entity :employee
:type :has-many
:fk :responsibility-id
:rfk :employee-id
:join-table :employees-responsibilities
:filter {:active true}}
:nonemployees {:entity :employee
:type :has-many
:fk :responsibility-id
:rfk :employee-id
:join-table :employees-responsibilities-negative
:filter {:active true}}}}
:document {:table :documents
:rels {:items {:entity :doc-item
:type :has-many
:fk :doc-id}}}
:doc-item {:table :doc-items
:rels {:document {:entity :document
:type :belongs-to
:fk :doc-id}}}})
(deftest create-repository-test
(sql.specs/instrument)
(with-open [conn (jdbc/get-connection {:dbtype "h2:mem"})]
(jdbc/execute! conn ["CREATE TYPE GENDER AS ENUM ('male', 'female')"])
(jdbc/execute! conn ["CREATE TABLE people (id BIGSERIAL PRIMARY KEY, name VARCHAR(100), gender GENDER, birthday DATE)"])
(jdbc/execute! conn ["CREATE TABLE contacts (id BIGSERIAL PRIMARY KEY, person_id BIGINT REFERENCES people (id), type VARCHAR(32), value VARCHAR(128))"])
(jdbc/execute! conn ["CREATE TABLE users (id BIGINT PRIMARY KEY REFERENCES people (id), login VARCHAR(100), role VARCHAR(50), active BOOLEAN DEFAULT true)"])
(jdbc/execute! conn ["CREATE TABLE secrets (id BIGINT PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE, secret VARCHAR(256))"])
(jdbc/execute! conn ["CREATE TABLE employees (id BIGSERIAL PRIMARY KEY REFERENCES people (id), supervisor_id BIGINT REFERENCES employees (id), salary NUMERIC(19, 4), active BOOLEAN DEFAULT true)"])
(jdbc/execute! conn ["CREATE TABLE responsibilities (id BIGSERIAL PRIMARY KEY, title VARCHAR(128), description TEXT, active BOOLEAN DEFAULT true)"])
(jdbc/execute! conn ["CREATE TABLE employees_responsibilities (employee_id BIGINT REFERENCES employees (id), responsibility_id BIGINT REFERENCES responsibilities (id), PRIMARY KEY (employee_id,responsibility_id))"])
(jdbc/execute! conn ["CREATE VIEW employees_responsibilities_negative AS
(SELECT e.id AS employee_id, r.id AS responsibility_id
FROM (employees AS e CROSS JOIN responsibilities AS r)
LEFT JOIN employees_responsibilities AS er
ON er.responsibility_id = r.id AND er.employee_id = e.id
WHERE er.employee_id IS NULL)"])
(jdbc/execute! conn ["CREATE TABLE documents (id BIGSERIAL PRIMARY KEY, type VARCHAR(100), status VARCHAR (100), sum NUMBER(19,4), created_at DATE)"])
(jdbc/execute! conn ["CREATE TABLE doc_items (id BIGSERIAL PRIMARY KEY, doc_id BIGINT REFERENCES documents (id), line_number INT, ordered INT, shipped INT)"])
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('John Doe', 'male')"])
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('Jane Doe', 'female')"])
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('Zoe Doe', 'female')"])
(jdbc/execute! conn ["INSERT INTO contacts (person_id, type, value) VALUES (1, 'email', 'john.doe@mailinator.com')"])
(jdbc/execute! conn ["INSERT INTO contacts (person_id, type, value) VALUES (1, 'phone', '+1(xxx)xxx-xx-xx')"])
(jdbc/execute! conn ["INSERT INTO contacts (person_id, type, value) VALUES (2, 'email', 'jane.doe@mailinator.com')"])
(jdbc/execute! conn ["INSERT INTO users (id, login) VALUES (1, 'john.doe')"])
(jdbc/execute! conn ["INSERT INTO users (id, login, active) VALUES (2, 'jane.doe', false)"])
(jdbc/execute! conn ["INSERT INTO users (id, login, active) VALUES (3, 'zoe.doe', true)"])
(jdbc/execute! conn ["INSERT INTO secrets (id, secret) VALUES (1, 'sha256(xxxxxxx)')"])
(jdbc/execute! conn ["INSERT INTO secrets (id, secret) VALUES (2, 'sha256(yyyyyyy)')"])
(jdbc/execute! conn ["INSERT INTO secrets (id, secret) VALUES (3, 'sha256(zzzzzzz)')"])
(jdbc/execute! conn ["INSERT INTO employees (id, salary) VALUES (1, 1500)"])
(jdbc/execute! conn ["INSERT INTO employees (id, supervisor_id, salary) VALUES (2, 1, 3000)"])
(jdbc/execute! conn ["INSERT INTO employees (id, supervisor_id, salary, active) VALUES (3, 1, 3100, false)"])
(jdbc/execute! conn ["INSERT INTO responsibilities (title) VALUES ('Cleaning')"])
(jdbc/execute! conn ["INSERT INTO responsibilities (title) VALUES ('Watering plants')"])
(jdbc/execute! conn ["INSERT INTO responsibilities (title) VALUES ('Gardening')"])
(jdbc/execute! conn ["INSERT INTO responsibilities (title, active) VALUES ('Deprecated activity', false)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (1, 1)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (1, 3)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (2, 2)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (3, 2)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (3, 4)"])
(let [repository (norm/create-repository :sql entities {:db conn})]
#_(is (instance? norm.sql.RelationalEntity (:person repository)))
(is (= repository @(:repository (meta (:person repository)))) "Entity must have repository in metadata.")
(is (= (keys entities) (keys repository)) "All the entities should be presented in the repository.")
(is (= [:person :contact] (keys (norm/only repository [:person :contact]))) "Only specified entities must be present.")
(is (= [:person :contact :user :document :doc-item] (keys (norm/except repository [:user-secret :employee :responsibility])))
"Specified entities must be absent.")
(testing "Fields population."
(is (= [:id :name :gender :birthday] (get-in repository [:person :fields])))
(is (= [:id :person-id :type :value] (get-in repository [:contact :fields])))
(is (= [:id :login :role :active] (get-in repository [:user :fields]))))
(testing "Transaction creation"
(is (= [] (norm/transaction repository))
"New transaction should be empty.")
#_(is (satisfies? norm/Command (norm/transaction repository))
"Transaction should be a command."); https://ask.clojure.org/index.php/4622/satisfies-doesnt-work-instance-based-protocol-polymorphism
(is (apply contains-all? (meta (norm/transaction repository)) (keys sql/sql-command-meta))
"Transaction should be a command."))
(testing "SQL generation"
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\", \"user.person\".id AS \"user.person/id\", \"user.person\".name AS \"user.person/name\", \"user.person\".gender AS \"user.person/gender\", \"user.person\".birthday AS \"user.person/birthday\" FROM (users AS \"user\" LEFT JOIN people AS \"user.person\" ON (\"user\".id = \"user.person\".id))"
(str (norm/find (:user repository)))))
(is (= "SELECT \"employee\".id AS \"employee/id\", \"employee\".supervisor_id AS \"employee/supervisor-id\", \"employee\".salary AS \"employee/salary\", \"employee\".active AS \"employee/active\", \"employee.person\".id AS \"employee.person/id\", \"employee.person\".name AS \"employee.person/name\", \"employee.person\".gender AS \"employee.person/gender\", \"employee.person\".birthday AS \"employee.person/birthday\" FROM (employees AS \"employee\" LEFT JOIN people AS \"employee.person\" ON (\"employee\".id = \"employee.person\".id)) WHERE (\"employee.person\".name = ?)"
(-> (norm/find (:employee repository) {:person/name "Jane Doe"}) str)
(-> (norm/find (:employee repository) {:employee.person/name "Jane Doe"}) str)
(-> (norm/find (:employee repository)) (where {:employee.person/name "Jane Doe"}) str)))
(is (= "SELECT \"user\".login AS \"user/login\", \"user.person\".name AS \"user.person/name\" FROM (users AS \"user\" LEFT JOIN people AS \"user.person\" ON (\"user\".id = \"user.person\".id)) WHERE (\"user\".id = ?)"
(str (norm/find (:user repository) [:user/login :person/name] {:id 1}))
(str (norm/find (:user repository) [:login :person/name] {:user/id 1}))))
(is (= "SELECT \"user_secret\".id AS \"user-secret/id\", \"user_secret\".secret AS \"user-secret/secret\" FROM (secrets AS \"user_secret\" LEFT JOIN (users AS \"user_secret.user\" LEFT JOIN people AS \"user_secret.user.person\" ON (\"user_secret.user\".id = \"user_secret.user.person\".id)) ON (\"user_secret\".id = \"user_secret.user\".id)) WHERE (\"user_secret.user.person\".name = ?)"
(-> (:user-secret repository)
(norm/find {:user.person/name "John Doe"})
str))
"Usage of a relation's relation in WHERE clause must join it in.")
(is (= "SELECT \"user.person\".id AS \"user.person/id\", \"user.person\".name AS \"user.person/name\", \"user.person\".gender AS \"user.person/gender\", \"user.person\".birthday AS \"user.person/birthday\" FROM (people AS \"user.person\" LEFT JOIN users AS \"user\" ON (\"user\".id = \"user.person\".id)) WHERE (\"user.person\".id = ?)"
(-> (:user repository)
(norm/find-related :person nil)
(norm/where {:id 1})
str))
"Field in WHERE clause must be prefixed with a selecting entity name.")
(is (= "SELECT \"user.person\".id AS \"user.person/id\", \"user.person\".name AS \"user.person/name\", \"user.person\".gender AS \"user.person/gender\", \"user.person\".birthday AS \"user.person/birthday\" FROM (people AS \"user.person\" LEFT JOIN users AS \"user\" ON (\"user\".id = \"user.person\".id)) WHERE (\"user\".id = ?)"
(-> (:user repository)
(norm/find-related :person nil)
(norm/where ^:exact {:user/id 1})
str))
"Field in WHERE clause must not be modified for exact clause.")
(is (= "SELECT \"person\".id AS \"person/id\", \"person\".name AS \"person/name\", \"person\".gender AS \"person/gender\", \"person\".birthday AS \"person/birthday\" FROM people AS \"person\" ORDER BY \"person\".id, \"person\".name"
(-> (norm/find (:person repository))
(norm/order [:id :name])
str))
"Fields in ORDER clause must be prefixed with an entity name.")
(is (= "SELECT \"person\".id AS \"person/id\", \"person\".name AS \"person/name\", \"person\".gender AS \"person/gender\", \"person\".birthday AS \"person/birthday\" FROM people AS \"person\" ORDER BY \"person\".name DESC, \"person\".id ASC"
(-> (norm/find (:person repository))
(norm/order {:name :desc :id :asc})
str))
"Fields in ORDER clause must be prefixed with an entity name.")
(is (= "SELECT \"person\".id AS \"person/id\", \"person\".name AS \"person/name\", \"person\".gender AS \"person/gender\", \"person\".birthday AS \"person/birthday\" FROM people AS \"person\" ORDER BY id, name"
(-> (norm/find (:person repository))
(norm/order ^:exact [:id :name])
str))
"Fields in ORDER clause must not be modified for exact values.")
(is (= "SELECT \"person\".id AS \"person/id\", \"person\".name AS \"person/name\", \"person\".gender AS \"person/gender\", \"person\".birthday AS \"person/birthday\" FROM people AS \"person\" ORDER BY name DESC, id ASC"
(-> (norm/find (:person repository))
(norm/order ^:exact {:name :desc :id :asc})
str))
"Fields in ORDER clause must not be modified for exact values."))
(testing "creation"
(testing "with embedded entities"
(testing "of belongs-to relationship"
(is (= {:id 4}
(-> (norm/create
(:user-secret repository)
{:secret "sha256xxxx"
:user {:login "buzz.lightyear"
:active false
:person {:name "Buzz Lightyear"}}})
norm/execute!)))
(is (= {:id 4 :secret "sha256xxxx"} (norm/fetch-by-id! (:user-secret repository) 4)))
(is (= {:id 4 :login "buzz.lightyear" :active false :person {:id 4 :name "Buzz Lightyear"}}
(norm/fetch-by-id! (:user repository) 4))))
(testing "of has-many relationship"
(is (= {:id 1}
(norm/create! (:document repository)
{:type "test"
:status "new"
:sum 1000
:items [{:line-number 1
:ordered 10}
{:line-number 2
:ordered 20}
{:line-number 3
:ordered 30}]})))
(is (= {:id 1 :type "test" :status "new" :sum 1000.0000M} (norm/fetch-by-id! (:document repository) 1)))
(is (= 3
(-> (:doc-item repository)
(norm/find! {:doc-id 1})
count))))
(testing "of many to many relationship"
(is (= {:id 4}
(norm/create! (:employee repository)
{:id 4
:salary 1000
:responsibilities [{:id 2} {:title "Saving the world"}]})))
(is (= {:id 4 :salary 1000.0000M :person {:id 4 :name "Buzz Lightyear"} :active true}
(norm/fetch-by-id! (:employee repository) 4))
"Aggregation root must be saved")
(is (= {:id 5 :title "Saving the world" :active true}
(norm/fetch-by-id! (:responsibility repository) 5))
"Related entity must be created.")
(is (= [{:id 2 :title "Watering plants" :active true}
{:id 5 :title "Saving the world" :active true}]
(norm/find-related! (:employee repository) :responsibilities {:id 4}))
"Pre-existed and created entities must be referenced.")
))
(testing "with prepare function"
(let [person (assoc (:person repository) :prepare #(update % :name str/upper-case))]
(is (= {:id 5} (norm/create! person {:name "Sid" :gender "male"})))
(is (= {:id 5, :name "SID" :gender "male"} (norm/fetch-by-id! person 5))
"Field must be preprocessed with `prepare` fn."))))
(testing "eager fetching"
(let [instance (norm/fetch-by-id! (:user repository) 1)]
(is (= {:id 1
:login "john.doe"
:active true
:person {:id 1
:name "John Doe"
:gender "male"}}
instance))
(is (= (merge instance-meta {:entity (:user repository)})
(meta instance)))
(is (= (merge instance-meta {:entity (:person repository)})
(meta (:person instance)))
"Related entity must have correct metadata."))
(is (= [{:id 2
:supervisor-id 1
:salary 3000.0000M
:active true
:person {:id 2
:name "Jane Doe"
:gender "female"}}]
(-> (norm/find (:employee repository))
(where {:employee.person/name "Jane Doe"})
fetch!))
"Clause by related entity's fields must work."))
(testing "fetching fields of related entities"
(is (= [{:login "john.doe", :person {:name "John Doe"}}] (norm/find! (:user repository) [:user/login :person/name] {:id 1}))))
(testing "fetching related entities"
(is (= [{:id 1 :name "John Doe" :gender "male"}]
(-> (norm/find-related (:user repository) :person {:id 1}) fetch!)
(-> (norm/find-related (:user repository) :person {:user/id 1}) fetch!)
(-> (norm/find-related (:user repository) :person nil) (where ^:exact {:user/id 1}) fetch!)
(-> (norm/find-related (:user repository) :person nil) (where {:id 1}) fetch!)
(-> (norm/find-related (:user repository) :person {:person/name "John Doe"}) fetch!)
(-> (norm/find-related (:user repository) :person {:user.person/name "John Doe"}) fetch!)))
(is (some? (-> (norm/find-related! (:user repository) :person {:id 1})
first
meta
:entity))
"Instance of related entity should have an entity in meta.")
(is (some? (-> (norm/find-related! (:user repository) :person {:id 1})
first
meta
((comp (partial partial =) :entity))
(filter (vals repository))
first))
"Instance of related entity should have a correct entity in metadata (found in repository).")
(is (= [{:id 3 :person-id 2 :type "email" :value "jane.doe@mailinator.com" :owner {:id 2 :name "Jane Doe" :gender "female"}}]
(-> (norm/find-related (:person repository) :contacts {:person/name "Jane Doe"}) fetch!)))
(is (= 0 (-> (norm/find-related (:person repository) :contacts {:id 3}) fetch-count!)))
(is (= 2 (-> (norm/find-related (:employee repository) :responsibilities {:id 1}) fetch-count!)))
(is (= [{:id 1, :title "Cleaning", :active true} {:id 3, :title "Gardening", :active true}]
(-> (norm/find-related (:employee repository) :responsibilities {:id 1}) fetch!)
(-> (norm/find-related (:employee repository) :nonresponsibilities {:id 4}) fetch!)))
(is (= [{:id 1 :salary 1500.0000M :active true :person {:id 1 :name "John Doe" :gender "male"}}]
(-> (norm/find-related (:responsibility repository) :employees {:id 1}) fetch!)
(-> (norm/find-related (:responsibility repository) :employees {:id 3}) fetch!)
(-> (norm/find-related (:responsibility repository) :nonemployees {:id 2}) fetch!)))
(is (= [{:id 2 :supervisor-id 1 :salary 3000.0000M :active true :person {:id 2 :name "Jane Doe" :gender "female"}}]
(-> (norm/find-related (:employee repository) :subordinates {:id 1}) fetch!)))
(is (= [{:id 1 :salary 1500.0000M :active true :person {:id 1 :name "John Doe" :gender "male"}}]
(-> (norm/find-related (:employee repository) :supervisor {:id 2}) fetch!)))
(is (= [{:id 1 :name "John Doe" :gender "male"}]
(-> (norm/find-related (:contact repository) :owner {:value "john.doe@mailinator.com"}) fetch!))
"Filtering by a field of the main entity should work.")
(is (= [{:id 1 :login "john.doe" :active true :person {:id 1 :name "John Doe" :gender "male"}}]
(-> (norm/find-related (:user-secret repository) :user {:user.person/name "John Doe"}) fetch!))
"Clause by a related entity's relation should join the source to the query."))
(testing "fetch with filter"
(is (= [{:id 1 :login "john.doe" :active true :person {:id 1, :name "John Doe", :gender "male"}}
{:id 3 :login "zoe.doe" :active true :person {:id 3, :name "Zoe Doe", :gender "female"}}]
(-> (:user repository) (norm/with-filter {:active true}) norm/find fetch!)))
(is (= [{:id 3 :login "zoe.doe" :active true :person {:id 3, :name "Zoe Doe", :gender "female"}}]
(-> (:user repository) (norm/with-filter {:active true}) (norm/find {:person/gender "female"}) fetch!))))
(testing "fetch with transform"
(let [person (assoc (:person repository) :transform #(update % :name str/lower-case))]
(is (= {:id 5, :name "sid", :gender "male"} (norm/fetch-by-id! person 5)))))
(testing "filter by related entities without eager fetching"
(is (= [{:id 1, :secret "sha256(xxxxxxx)"}] (-> (norm/find (:user-secret repository) {:user/login "john.doe"}) fetch!))))
(testing "update"
(testing "with embedded entities"
(testing "of belongs-to relationship"
(is (= 1 (norm/update! (:user repository) {:person {:name "Buzz"}} {:id 4})))
(is (= {:id 4 :name "Buzz"} (norm/fetch-by-id! (:person repository) 4))
"Updating of an embedded entity must change the entity.")
(is (= 2 (norm/update! (:user repository) {:role "user" :person {:name "Buzz Lightyear"}} {:id 4})))
(is (= {:id 4 :login "buzz.lightyear" :role "user" :active false :person {:id 4, :name "Buzz Lightyear"}}
(norm/fetch-by-id! (:user repository) 4))
"Updating with an embedded entity must change both the main and embedded entity."))
(testing "of has-many relationship"
(is (= 4 (norm/update! (:document repository)
{:status "shipped"
:items [{:id 1 :shipped 0}
{:id 2 :shipped 20}
{:id 3 :shipped 10}]}
{:id 1})))
(is (= "shipped" (-> (:document repository) (norm/fetch-by-id! 1) :status)) "Aggregation root must be updated.")
(is (= 0 (-> (:doc-item repository) (norm/fetch-by-id! 1) :shipped)) "Component of aggregation must be updated.")
(is (= 20 (-> (:doc-item repository) (norm/fetch-by-id! 2) :shipped)) "Component of aggregation must be updated.")))
(testing "filtered by relationship"
(is (= 1 (norm/update! (:user repository) {:login "buzz"} {:person/name "Buzz Lightyear"})))
(is (= {:id 4 :login "buzz" :role "user" :active false :person {:id 4, :name "Buzz Lightyear"}}
(norm/fetch-by-id! (:user repository) 4))
"Update with filtering by related entity must change the main entity."))
(testing "with prepare function"
(let [person (assoc (:person repository) :prepare #(update % :name str/lower-case))]
(is (= 1 (norm/update! person {:name "Sid"} {:id 5})))
(is (= {:id 5, :name "sid", :gender "male"} (norm/fetch-by-id! person 5))
"Field must be preprocessed with prepare fn."))))
(testing "changing relations"
(is (= {:employee-id 1, :responsibility-id 2}
(norm/create-relation! (:employee repository) 1 :responsibilities 2)))
(is (= [{:id 1, :title "Cleaning", :active true} {:id 3, :title "Gardening", :active true} {:id 2, :title "Watering plants", :active true}]
(norm/find-related! (:employee repository) :responsibilities {:id 1}))
"Created relation should be found.")
(is (= 1 (norm/delete-relation! (:employee repository) 1 :responsibilities 2)))
(is (= [{:id 1, :title "Cleaning", :active true} {:id 3, :title "Gardening", :active true}]
(norm/find-related! (:employee repository) :responsibilities {:id 1}))
"Deleted relation should not be found."))
(testing "delete by related entity"
(is (= 1 (norm/delete! (:user repository) {:person/name "Buzz Lightyear"})))
(is (nil? (norm/fetch-by-id! (:user repository) 4)) "Deleted entity must not be found."))))
(sql.specs/unstrument))
| 12326 | (ns norm.sql-test
(:require [clojure.test :as t :refer [deftest testing is]]
[clojure.string :as str]
[next.jdbc :as jdbc]
[norm.core :as norm :refer [where order skip limit fetch! fetch-count!]]
[norm.sql :as sql]
[norm.sql.jdbc :refer [instance-meta]]
[norm.sql.specs :as sql.specs]))
(defn contains-all? [m & ks]
(= (clojure.set/intersection (set ks) (set (keys m))) (set ks)))
(deftest sql-query-test
(testing "Query building"
(is (= "SELECT * FROM users AS \"users\"" (str (sql/select nil :users))))
(is (= "SELECT * FROM users AS \"users\"" (str (sql/select nil :users [:*]))))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\"" (str (sql/select nil :users [:id :name]))))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".name AS \"user/name\" FROM users AS \"user\""
(str (sql/select nil [:users :user] [:user/id :user/name]))))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\""
(str (sql/select nil :users [:id :name] {})))
"Empty where clause should not apear in the query.")
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (id = ?)"
(str (sql/select nil :users [:id :name] {:id 1}))))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (((id = ?) AND (name = ?)) AND (role = ?))"
(-> (sql/select nil :users [:id :name] {:id 1})
(where {:name "<NAME>"})
(where {:role "admin"})
str)))
(is (= "SELECT column_name AS \"column-name\" FROM information_schema.columns AS \"information_schema.columns\" WHERE (table_schema ILIKE ? AND table_name ILIKE ?)"
(-> (sql/select nil
:information-schema/columns
[:column-name]
{:table-schema [:ilike "public"]
:table-name [:ilike "table_name"]}) str)))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".name AS \"user/name\" FROM users AS \"user\" WHERE (\"user\".id = ?)"
(str (sql/select nil [:users :user] [:user/id :user/name] {:user/id 1}))))
(is (= "SELECT \"user\".id AS \"user/id\", \"person\".name AS \"person/name\" FROM (users AS \"user\" LEFT JOIN people AS \"person\" ON (\"user\".id = \"person\".id))"
(str (sql/select nil [[:users :user] :left-join [:people :person] {:user/id :person/id}] [:user/id :person/name]))))
(is (= "SELECT \"users\".*, \"people\".* FROM (users AS \"users\" LEFT JOIN people AS \"people\" ON (\"users\".id = \"people\".id))"
(str (sql/select nil [:users :left-join :people {:users/id :people/id}] [:users/* :people/*])))
"Wildcard should go without alias.")
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\" FROM users AS \"user\" WHERE (\"user\".id IN ((SELECT user_id AS \"user-id\" FROM employees AS \"employees\" WHERE (active IS true))))"
(str (sql/select nil [:users :user] [:user/id :user/login] {:user/id [:in (sql/select nil :employees [:user-id] {:active true})]}))))
(is (= "SELECT CURRENT_SCHEMA() AS \"current-schema\"" (str (sql/select nil nil [['(current-schema) :current-schema]]))))
(is (= "SELECT id AS \"id\" FROM tasks AS \"tasks\" WHERE (scheduled >= NOW())" (str (sql/select nil :tasks [:id] {:scheduled [:>= '(now)]})))))
(testing "Query parts amendment"
(let [query (sql/select nil :users [:id :name])]
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (id = ?)" (-> query (where {:id 1}) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM (users AS \"users\" LEFT JOIN people AS \"people\" ON (\"users\".person_id = \"people\".id)) WHERE (\"people\".name = ?)"
(-> query (sql/join :left-join :people {:users/person-id :people/id}) (where {:people/name "<NAME>"}) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" OFFSET ?" (-> query (skip 2) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" LIMIT ?" (-> query (limit 10) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" LIMIT ? OFFSET ?" (-> query (skip 2) (limit 10) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (id = ?) LIMIT ? OFFSET ?"
(-> query (where {:id 1}) (skip 2) (limit 10) str)))))
(testing "Data fetching"
(with-open [conn (jdbc/get-connection {:dbtype "h2:mem"})]
(let [select (partial sql/select conn)
query (select :people [:id :name])]
(jdbc/execute! conn ["CREATE TABLE people (id BIGSERIAL, name VARCHAR(100), gender VARCHAR(10), birthday DATE)"])
(jdbc/execute! conn ["CREATE TABLE users (id BIGINT, login VARCHAR(100), role VARCHAR(50))"])
(is (zero? (fetch-count! query)))
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('<NAME>', 'male')"])
(jdbc/execute! conn ["INSERT INTO users (id, login) VALUES (1, '<NAME>.doe')"])
(is (= 1 (fetch-count! query)))
(is (= [{:id 1 :name "<NAME>"}] (fetch! query)))
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('J<NAME> Doe', 'female')"])
(is (= 2 (fetch-count! query)))
(is (= 1 (-> query (where {:id 1}) fetch-count!)))
(is (= [{:id 1 :name "<NAME>"} {:id 2 :name "<NAME>"}] (-> query (where {:gender ["female", "male"]}) fetch!)))
(is (= [{:id 2 :name "<NAME>" :gender "female"}] (-> query (where {:id 2}) (fetch! [:id :name :gender]))))
(is (= [{:person/id 1 :person/name "<NAME>" :person/gender "male" :user/login "john.doe"}
{:person/id 2 :person/name "<NAME>" :person/gender "female" :user/login nil}]
(->
(select [[:people :person] :left-join [:users :user] {:person/id :user/id}] [:person/id :person/name :person/gender :user/login])
fetch!)))
(is (= [{:id 1 :name "<NAME>"} {:id 2 :name "<NAME>"}] (-> query (where {:or {:id 1 :gender "female"}}) fetch!)))
(is (= [{:id 1 :name "<NAME>"} {:id 2 :name "<NAME>"}] (-> query (order [:id]) fetch!)))
(is (= [{:id 2 :name "<NAME>"} {:id 1 :name "<NAME>"}] (-> query (order {:id :desc}) fetch!)))
(testing "with sub-query"
(is (= [{:person/id 1, :person/name "<NAME>"}]
(-> (select [:people :person] [:person/id :person/name] {:person/id [:in (select :users [:users/id] {:users/login "john.doe"})]})
fetch!))))))))
(deftest sql-command-test
(testing "Insert command building"
(is (= "INSERT INTO users (login, role) VALUES (?, ?)" (sql/generate-sql-command (sql/insert nil :users {:login "admin" :role "admin"}))))
(is
(= "INSERT INTO users (login, role) VALUES (?, ?), (?, ?), (?, ?)"
(-> (sql/insert nil :users [[:login :role]
["admin" "admin"]
["foo" "user"]
["bar" "user"]])
sql/generate-sql-command))))
(testing "Update command building"
(is (= "UPDATE users SET login = ?, role = ? WHERE (id = ?)" (sql/generate-sql-command (sql/update nil :users {:login "admin", :role "admin"} {:id 1})))))
(testing "Delete command building"
(is (= "DELETE FROM users WHERE (id = ?)" (sql/generate-sql-command (sql/delete nil :users {:id 1})))))
(testing "Select command building"
(is (= "SELECT id AS \"id\", login AS \"login\" FROM users AS \"users\" WHERE (id = ?)"
(sql/generate-sql-command (sql/select nil :users [:id :login] {:id 1})))))
(testing "Execution"
(with-open [conn (jdbc/get-connection {:dbtype "h2:mem"})]
(jdbc/execute! conn ["CREATE TABLE people (id BIGSERIAL, name VARCHAR(100) NOT NULL, gender VARCHAR(10), birthday DATE)"])
(testing "of insert"
(is (= {:id 1} (-> (sql/insert conn :people {:name "<NAME>"}) norm/execute!)))
(is (= {:id 2} (-> (sql/insert conn :people [[:name :gender] ["<NAME>" "female"] ["<NAME>" "female"]]) norm/execute!)))
(is (= 3 (-> (sql/select conn :people) fetch-count!)) "Database must contain all the inserted records."))
(testing "of update"
(is (= 1 (-> (sql/update conn :people {:gender "male"} {:id 1}) norm/execute!)))
(is (= [{:id 1 :gender "male"}] (-> (sql/select conn :people [:id :gender] {:id 1}) fetch!)) "Row must change after update.")
(is (= 1 (-> (sql/update conn :people {:gender nil} {:id 1}) norm/execute!)))
(is (= [{:id 1 :gender nil}] (-> (sql/select conn :people [:id :gender] {:id 1}) fetch!)) "Property must change after update with nil."))
(testing "of delete"
(is (= 1 (-> (sql/delete conn :people {:id 1}) norm/execute!)))
(is (= [{:id 2} {:id 3}] (-> (sql/select conn :people [:id]) fetch!)) "Deleted row must be missing from the table."))
(testing "of transaction"
(is (= [{:id 4} {:id 5} {:id 6} {:id 7} [{:id 4 :name "<NAME>"}]]
(-> (sql/transaction conn
(sql/insert nil :people {:name "<NAME>"})
(sql/insert nil :people {:name "<NAME>"})
(sql/insert nil :people {:name "<NAME>"})
(sql/insert nil :people {:name "<NAME>"})
(sql/select nil :people [:id :name] {:name "<NAME>"}))
norm/execute!)))
(is (= [{:id 4 :name "<NAME>"}
{:id 5 :name "<NAME>"}
{:id 6 :name "<NAME>"}
{:id 7 :name "<NAME>"}]
(-> (sql/select conn :people [:id :name] {:id [:> 3]}) norm/execute!)))
(is (= (repeat 4 1)
(-> (sql/delete conn :people {:id 4})
(norm/then (sql/delete conn :people {:id 5}))
(norm/then (sql/delete conn :people {:id 6}))
(norm/then (sql/delete conn :people {:id 7}))
norm/execute!)))
(is (thrown? org.h2.jdbc.JdbcSQLSyntaxErrorException
(-> (sql/transaction conn
(sql/delete nil :people {:name "<NAME>"})
(sql/insert nil :people {:first-name "<NAME>" :last-name "<NAME>"})
(sql/select nil :people [:id :name] {:name "<NAME>"}))
norm/execute!)))
(is (= [{:id 2 :name "<NAME>"}]
(-> (sql/select conn :people [:id :name] {:name "<NAME>"}) norm/execute!))
"Record must be present after failed transaction")))))
(deftest relational-entity-test
(with-open [conn (jdbc/get-connection {:dbtype "h2:mem"})]
(jdbc/execute! conn ["CREATE TABLE people (id BIGSERIAL, name VARCHAR(100), gender VARCHAR(10), birthday DATE)"])
(jdbc/execute! conn ["CREATE TABLE users (id BIGINT, login VARCHAR(100), role VARCHAR(50), active BOOLEAN)"])
(let [person (sql/create-entity {:db conn} {:name :person, :table :people, :fields [:id :name :gender :birthday]})
user (sql/create-entity {:db conn} {:name :user, :table :users, :fields [:id :login :role :active]})]
(testing "creation"
(is (= {:id 1} (-> (norm/create person {:name "<NAME>" :gender "male"}) norm/execute!)))
(is (= {:id 2} (-> (norm/create person {:name "<NAME>" :gender "female"}) norm/execute!)))
(is (= {:id 1} (-> (norm/create user {:id 1 :login "<NAME>" :role "user"}) norm/execute!))))
(testing "fetching"
(is (= {:id 1 :name "<NAME>" :gender "male"} (norm/fetch-by-id! person 1))
(str (norm/find person {:id 1})))
(is (= (merge instance-meta {:entity person}) (-> (norm/fetch-by-id! person 1) meta))
"Metadata of an instance must contain an implementation of the `Instance `protocol and a reference to the entity.")
(is (= [{:id 1 :name "<NAME>" :gender "male"}
{:id 2 :name "<NAME>" :gender "female"}]
(-> (norm/find person) fetch!)))
(is (= [{:id 1 :name "<NAME>" :gender "male"}] (-> (norm/find person {:id 1}) fetch!))))
(testing "order"
(is (= [{:id 2 :name "<NAME>" :gender "female"}
{:id 1 :name "<NAME>" :gender "male"}]
(-> (norm/find person {:birthday nil}) (order {:id :desc}) fetch!))))
(testing "offset and limit"
(is (= [{:id 2 :name "<NAME>" :gender "female"}]
(-> (norm/find person {:birthday nil}) (order {:id :desc}) (skip 0) (limit 1) fetch!)))
(is (= [{:id 1 :name "<NAME>" :gender "male"}]
(-> (norm/find person {:birthday nil}) (order {:id :desc}) (skip 1) (limit 1) fetch!))))
(testing "update"
(is (= 1 (-> (norm/update person {:name "<NAME>"} {:id 2}) norm/execute!)))
(is (= {:id 2 :name "<NAME>" :gender "female"} (norm/fetch-by-id! person 2)) "Entity must change after update."))
(testing "delete"
(is (= 1 (-> (norm/delete person {:id 2}) norm/execute!)))
(is (nil? (norm/fetch-by-id! person 2)) "Entity must be missing after delete."))
(testing "with filter"
(let [active-user (norm/with-filter user {:active true})
active-admin (norm/with-filter active-user {:role "admin"})]
(is (= (merge user {:filter {:active true}})
active-user))
(is (= (merge user {:filter '(and {:active true} {:role "admin"})})
active-admin))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\" FROM users AS \"user\" WHERE (\"user\".active IS true)"
(-> active-user norm/find str)))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\" FROM users AS \"user\" WHERE ((\"user\".active IS true) AND (\"user\".id = ?))"
(-> active-user (norm/find {:id 1}) str)))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\" FROM users AS \"user\" WHERE ((\"user\".active IS true) AND (\"user\".role = ?))"
(-> active-admin norm/find str)))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\" FROM users AS \"user\" WHERE (((\"user\".active IS true) AND (\"user\".role = ?)) AND (\"user\".id = ?))"
(-> active-admin (norm/find {:id 1}) str)))))
(testing "mutating an entity"
(is (= (merge user {:rels {:secret {:entity :secret
:type :has-one
:fk :user-id}}})
(norm/with-rels user {:secret {:entity :secret
:type :has-one
:fk :user-id}})))
(is (= true
(-> user
(norm/with-rels {:secret {:entity :secret
:type :has-one
:fk :user-id}})
(norm/with-eager [:secret])
(get-in [:rels :secret :eager]))))))))
(def entities
{:person {:table :people
:rels {:contacts {:entity :contact
:type :has-many
:fk :person-id}}}
:contact {:table :contacts
:rels {:owner {:entity :person
:type :belongs-to
:fk :person-id
:eager true}}}
:user {:table :users
:rels {:person {:entity :person
:type :belongs-to
:fk :id
:eager true}}}
:user-secret {:table :secrets
:rels {:user {:entity :user
:type :belongs-to
:fk :id}}}
:employee {:table :employees
:rels {:person {:entity :person
:type :belongs-to
:fk :id
:eager true}
:supervisor {:entity :employee
:type :belongs-to
:fk :supervisor-id}
:subordinates {:entity :employee
:type :has-many
:fk :supervisor-id
:filter {:active true}}
:responsibilities {:entity :responsibility
:type :has-many
:fk :employee-id
:rfk :responsibility-id
:join-table :employees-responsibilities
:filter {:active true}}
:nonresponsibilities {:entity :responsibility
:type :has-many
:fk :employee-id
:rfk :responsibility-id
:join-table :employees-responsibilities-negative
:filter {:active true}}}}
:responsibility {:table :responsibilities
:rels {:employees {:entity :employee
:type :has-many
:fk :responsibility-id
:rfk :employee-id
:join-table :employees-responsibilities
:filter {:active true}}
:nonemployees {:entity :employee
:type :has-many
:fk :responsibility-id
:rfk :employee-id
:join-table :employees-responsibilities-negative
:filter {:active true}}}}
:document {:table :documents
:rels {:items {:entity :doc-item
:type :has-many
:fk :doc-id}}}
:doc-item {:table :doc-items
:rels {:document {:entity :document
:type :belongs-to
:fk :doc-id}}}})
(deftest create-repository-test
(sql.specs/instrument)
(with-open [conn (jdbc/get-connection {:dbtype "h2:mem"})]
(jdbc/execute! conn ["CREATE TYPE GENDER AS ENUM ('male', 'female')"])
(jdbc/execute! conn ["CREATE TABLE people (id BIGSERIAL PRIMARY KEY, name VARCHAR(100), gender GENDER, birthday DATE)"])
(jdbc/execute! conn ["CREATE TABLE contacts (id BIGSERIAL PRIMARY KEY, person_id BIGINT REFERENCES people (id), type VARCHAR(32), value VARCHAR(128))"])
(jdbc/execute! conn ["CREATE TABLE users (id BIGINT PRIMARY KEY REFERENCES people (id), login VARCHAR(100), role VARCHAR(50), active BOOLEAN DEFAULT true)"])
(jdbc/execute! conn ["CREATE TABLE secrets (id BIGINT PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE, secret VARCHAR(256))"])
(jdbc/execute! conn ["CREATE TABLE employees (id BIGSERIAL PRIMARY KEY REFERENCES people (id), supervisor_id BIGINT REFERENCES employees (id), salary NUMERIC(19, 4), active BOOLEAN DEFAULT true)"])
(jdbc/execute! conn ["CREATE TABLE responsibilities (id BIGSERIAL PRIMARY KEY, title VARCHAR(128), description TEXT, active BOOLEAN DEFAULT true)"])
(jdbc/execute! conn ["CREATE TABLE employees_responsibilities (employee_id BIGINT REFERENCES employees (id), responsibility_id BIGINT REFERENCES responsibilities (id), PRIMARY KEY (employee_id,responsibility_id))"])
(jdbc/execute! conn ["CREATE VIEW employees_responsibilities_negative AS
(SELECT e.id AS employee_id, r.id AS responsibility_id
FROM (employees AS e CROSS JOIN responsibilities AS r)
LEFT JOIN employees_responsibilities AS er
ON er.responsibility_id = r.id AND er.employee_id = e.id
WHERE er.employee_id IS NULL)"])
(jdbc/execute! conn ["CREATE TABLE documents (id BIGSERIAL PRIMARY KEY, type VARCHAR(100), status VARCHAR (100), sum NUMBER(19,4), created_at DATE)"])
(jdbc/execute! conn ["CREATE TABLE doc_items (id BIGSERIAL PRIMARY KEY, doc_id BIGINT REFERENCES documents (id), line_number INT, ordered INT, shipped INT)"])
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('<NAME>', 'male')"])
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('<NAME>', 'female')"])
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('<NAME>', 'female')"])
(jdbc/execute! conn ["INSERT INTO contacts (person_id, type, value) VALUES (1, 'email', '<EMAIL>')"])
(jdbc/execute! conn ["INSERT INTO contacts (person_id, type, value) VALUES (1, 'phone', '+1(xxx)xxx-xx-xx')"])
(jdbc/execute! conn ["INSERT INTO contacts (person_id, type, value) VALUES (2, 'email', '<EMAIL>')"])
(jdbc/execute! conn ["INSERT INTO users (id, login) VALUES (1, '<NAME>')"])
(jdbc/execute! conn ["INSERT INTO users (id, login, active) VALUES (2, '<NAME>', false)"])
(jdbc/execute! conn ["INSERT INTO users (id, login, active) VALUES (3, '<NAME>', true)"])
(jdbc/execute! conn ["INSERT INTO secrets (id, secret) VALUES (1, 'sha256(xxxxxxx)')"])
(jdbc/execute! conn ["INSERT INTO secrets (id, secret) VALUES (2, 'sha256(yyyyyyy)')"])
(jdbc/execute! conn ["INSERT INTO secrets (id, secret) VALUES (3, 'sha256(zzzzzzz)')"])
(jdbc/execute! conn ["INSERT INTO employees (id, salary) VALUES (1, 1500)"])
(jdbc/execute! conn ["INSERT INTO employees (id, supervisor_id, salary) VALUES (2, 1, 3000)"])
(jdbc/execute! conn ["INSERT INTO employees (id, supervisor_id, salary, active) VALUES (3, 1, 3100, false)"])
(jdbc/execute! conn ["INSERT INTO responsibilities (title) VALUES ('Cleaning')"])
(jdbc/execute! conn ["INSERT INTO responsibilities (title) VALUES ('Watering plants')"])
(jdbc/execute! conn ["INSERT INTO responsibilities (title) VALUES ('Gardening')"])
(jdbc/execute! conn ["INSERT INTO responsibilities (title, active) VALUES ('Deprecated activity', false)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (1, 1)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (1, 3)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (2, 2)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (3, 2)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (3, 4)"])
(let [repository (norm/create-repository :sql entities {:db conn})]
#_(is (instance? norm.sql.RelationalEntity (:person repository)))
(is (= repository @(:repository (meta (:person repository)))) "Entity must have repository in metadata.")
(is (= (keys entities) (keys repository)) "All the entities should be presented in the repository.")
(is (= [:person :contact] (keys (norm/only repository [:person :contact]))) "Only specified entities must be present.")
(is (= [:person :contact :user :document :doc-item] (keys (norm/except repository [:user-secret :employee :responsibility])))
"Specified entities must be absent.")
(testing "Fields population."
(is (= [:id :name :gender :birthday] (get-in repository [:person :fields])))
(is (= [:id :person-id :type :value] (get-in repository [:contact :fields])))
(is (= [:id :login :role :active] (get-in repository [:user :fields]))))
(testing "Transaction creation"
(is (= [] (norm/transaction repository))
"New transaction should be empty.")
#_(is (satisfies? norm/Command (norm/transaction repository))
"Transaction should be a command."); https://ask.clojure.org/index.php/4622/satisfies-doesnt-work-instance-based-protocol-polymorphism
(is (apply contains-all? (meta (norm/transaction repository)) (keys sql/sql-command-meta))
"Transaction should be a command."))
(testing "SQL generation"
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\", \"user.person\".id AS \"user.person/id\", \"user.person\".name AS \"user.person/name\", \"user.person\".gender AS \"user.person/gender\", \"user.person\".birthday AS \"user.person/birthday\" FROM (users AS \"user\" LEFT JOIN people AS \"user.person\" ON (\"user\".id = \"user.person\".id))"
(str (norm/find (:user repository)))))
(is (= "SELECT \"employee\".id AS \"employee/id\", \"employee\".supervisor_id AS \"employee/supervisor-id\", \"employee\".salary AS \"employee/salary\", \"employee\".active AS \"employee/active\", \"employee.person\".id AS \"employee.person/id\", \"employee.person\".name AS \"employee.person/name\", \"employee.person\".gender AS \"employee.person/gender\", \"employee.person\".birthday AS \"employee.person/birthday\" FROM (employees AS \"employee\" LEFT JOIN people AS \"employee.person\" ON (\"employee\".id = \"employee.person\".id)) WHERE (\"employee.person\".name = ?)"
(-> (norm/find (:employee repository) {:person/name "<NAME>"}) str)
(-> (norm/find (:employee repository) {:employee.person/name "<NAME>"}) str)
(-> (norm/find (:employee repository)) (where {:employee.person/name "<NAME>"}) str)))
(is (= "SELECT \"user\".login AS \"user/login\", \"user.person\".name AS \"user.person/name\" FROM (users AS \"user\" LEFT JOIN people AS \"user.person\" ON (\"user\".id = \"user.person\".id)) WHERE (\"user\".id = ?)"
(str (norm/find (:user repository) [:user/login :person/name] {:id 1}))
(str (norm/find (:user repository) [:login :person/name] {:user/id 1}))))
(is (= "SELECT \"user_secret\".id AS \"user-secret/id\", \"user_secret\".secret AS \"user-secret/secret\" FROM (secrets AS \"user_secret\" LEFT JOIN (users AS \"user_secret.user\" LEFT JOIN people AS \"user_secret.user.person\" ON (\"user_secret.user\".id = \"user_secret.user.person\".id)) ON (\"user_secret\".id = \"user_secret.user\".id)) WHERE (\"user_secret.user.person\".name = ?)"
(-> (:user-secret repository)
(norm/find {:user.person/name "<NAME>"})
str))
"Usage of a relation's relation in WHERE clause must join it in.")
(is (= "SELECT \"user.person\".id AS \"user.person/id\", \"user.person\".name AS \"user.person/name\", \"user.person\".gender AS \"user.person/gender\", \"user.person\".birthday AS \"user.person/birthday\" FROM (people AS \"user.person\" LEFT JOIN users AS \"user\" ON (\"user\".id = \"user.person\".id)) WHERE (\"user.person\".id = ?)"
(-> (:user repository)
(norm/find-related :person nil)
(norm/where {:id 1})
str))
"Field in WHERE clause must be prefixed with a selecting entity name.")
(is (= "SELECT \"user.person\".id AS \"user.person/id\", \"user.person\".name AS \"user.person/name\", \"user.person\".gender AS \"user.person/gender\", \"user.person\".birthday AS \"user.person/birthday\" FROM (people AS \"user.person\" LEFT JOIN users AS \"user\" ON (\"user\".id = \"user.person\".id)) WHERE (\"user\".id = ?)"
(-> (:user repository)
(norm/find-related :person nil)
(norm/where ^:exact {:user/id 1})
str))
"Field in WHERE clause must not be modified for exact clause.")
(is (= "SELECT \"person\".id AS \"person/id\", \"person\".name AS \"person/name\", \"person\".gender AS \"person/gender\", \"person\".birthday AS \"person/birthday\" FROM people AS \"person\" ORDER BY \"person\".id, \"person\".name"
(-> (norm/find (:person repository))
(norm/order [:id :name])
str))
"Fields in ORDER clause must be prefixed with an entity name.")
(is (= "SELECT \"person\".id AS \"person/id\", \"person\".name AS \"person/name\", \"person\".gender AS \"person/gender\", \"person\".birthday AS \"person/birthday\" FROM people AS \"person\" ORDER BY \"person\".name DESC, \"person\".id ASC"
(-> (norm/find (:person repository))
(norm/order {:name :desc :id :asc})
str))
"Fields in ORDER clause must be prefixed with an entity name.")
(is (= "SELECT \"person\".id AS \"person/id\", \"person\".name AS \"person/name\", \"person\".gender AS \"person/gender\", \"person\".birthday AS \"person/birthday\" FROM people AS \"person\" ORDER BY id, name"
(-> (norm/find (:person repository))
(norm/order ^:exact [:id :name])
str))
"Fields in ORDER clause must not be modified for exact values.")
(is (= "SELECT \"person\".id AS \"person/id\", \"person\".name AS \"person/name\", \"person\".gender AS \"person/gender\", \"person\".birthday AS \"person/birthday\" FROM people AS \"person\" ORDER BY name DESC, id ASC"
(-> (norm/find (:person repository))
(norm/order ^:exact {:name :desc :id :asc})
str))
"Fields in ORDER clause must not be modified for exact values."))
(testing "creation"
(testing "with embedded entities"
(testing "of belongs-to relationship"
(is (= {:id 4}
(-> (norm/create
(:user-secret repository)
{:secret "sha256xxxx"
:user {:login "buzz.lightyear"
:active false
:person {:name "<NAME>"}}})
norm/execute!)))
(is (= {:id 4 :secret "sha256xxxx"} (norm/fetch-by-id! (:user-secret repository) 4)))
(is (= {:id 4 :login "buzz.lightyear" :active false :person {:id 4 :name "<NAME>"}}
(norm/fetch-by-id! (:user repository) 4))))
(testing "of has-many relationship"
(is (= {:id 1}
(norm/create! (:document repository)
{:type "test"
:status "new"
:sum 1000
:items [{:line-number 1
:ordered 10}
{:line-number 2
:ordered 20}
{:line-number 3
:ordered 30}]})))
(is (= {:id 1 :type "test" :status "new" :sum 1000.0000M} (norm/fetch-by-id! (:document repository) 1)))
(is (= 3
(-> (:doc-item repository)
(norm/find! {:doc-id 1})
count))))
(testing "of many to many relationship"
(is (= {:id 4}
(norm/create! (:employee repository)
{:id 4
:salary 1000
:responsibilities [{:id 2} {:title "Saving the world"}]})))
(is (= {:id 4 :salary 1000.0000M :person {:id 4 :name "<NAME>"} :active true}
(norm/fetch-by-id! (:employee repository) 4))
"Aggregation root must be saved")
(is (= {:id 5 :title "Saving the world" :active true}
(norm/fetch-by-id! (:responsibility repository) 5))
"Related entity must be created.")
(is (= [{:id 2 :title "Watering plants" :active true}
{:id 5 :title "Saving the world" :active true}]
(norm/find-related! (:employee repository) :responsibilities {:id 4}))
"Pre-existed and created entities must be referenced.")
))
(testing "with prepare function"
(let [person (assoc (:person repository) :prepare #(update % :name str/upper-case))]
(is (= {:id 5} (norm/create! person {:name "<NAME>" :gender "male"})))
(is (= {:id 5, :name "<NAME>" :gender "male"} (norm/fetch-by-id! person 5))
"Field must be preprocessed with `prepare` fn."))))
(testing "eager fetching"
(let [instance (norm/fetch-by-id! (:user repository) 1)]
(is (= {:id 1
:login "john.doe"
:active true
:person {:id 1
:name "<NAME>"
:gender "male"}}
instance))
(is (= (merge instance-meta {:entity (:user repository)})
(meta instance)))
(is (= (merge instance-meta {:entity (:person repository)})
(meta (:person instance)))
"Related entity must have correct metadata."))
(is (= [{:id 2
:supervisor-id 1
:salary 3000.0000M
:active true
:person {:id 2
:name "<NAME>"
:gender "female"}}]
(-> (norm/find (:employee repository))
(where {:employee.person/name "<NAME>"})
fetch!))
"Clause by related entity's fields must work."))
(testing "fetching fields of related entities"
(is (= [{:login "john.doe", :person {:name "<NAME>"}}] (norm/find! (:user repository) [:user/login :person/name] {:id 1}))))
(testing "fetching related entities"
(is (= [{:id 1 :name "<NAME>" :gender "male"}]
(-> (norm/find-related (:user repository) :person {:id 1}) fetch!)
(-> (norm/find-related (:user repository) :person {:user/id 1}) fetch!)
(-> (norm/find-related (:user repository) :person nil) (where ^:exact {:user/id 1}) fetch!)
(-> (norm/find-related (:user repository) :person nil) (where {:id 1}) fetch!)
(-> (norm/find-related (:user repository) :person {:person/name "<NAME>"}) fetch!)
(-> (norm/find-related (:user repository) :person {:user.person/name "<NAME>"}) fetch!)))
(is (some? (-> (norm/find-related! (:user repository) :person {:id 1})
first
meta
:entity))
"Instance of related entity should have an entity in meta.")
(is (some? (-> (norm/find-related! (:user repository) :person {:id 1})
first
meta
((comp (partial partial =) :entity))
(filter (vals repository))
first))
"Instance of related entity should have a correct entity in metadata (found in repository).")
(is (= [{:id 3 :person-id 2 :type "email" :value "<EMAIL>" :owner {:id 2 :name "<NAME>" :gender "female"}}]
(-> (norm/find-related (:person repository) :contacts {:person/name "<NAME>"}) fetch!)))
(is (= 0 (-> (norm/find-related (:person repository) :contacts {:id 3}) fetch-count!)))
(is (= 2 (-> (norm/find-related (:employee repository) :responsibilities {:id 1}) fetch-count!)))
(is (= [{:id 1, :title "Cleaning", :active true} {:id 3, :title "Gardening", :active true}]
(-> (norm/find-related (:employee repository) :responsibilities {:id 1}) fetch!)
(-> (norm/find-related (:employee repository) :nonresponsibilities {:id 4}) fetch!)))
(is (= [{:id 1 :salary 1500.0000M :active true :person {:id 1 :name "<NAME>" :gender "male"}}]
(-> (norm/find-related (:responsibility repository) :employees {:id 1}) fetch!)
(-> (norm/find-related (:responsibility repository) :employees {:id 3}) fetch!)
(-> (norm/find-related (:responsibility repository) :nonemployees {:id 2}) fetch!)))
(is (= [{:id 2 :supervisor-id 1 :salary 3000.0000M :active true :person {:id 2 :name "<NAME>" :gender "female"}}]
(-> (norm/find-related (:employee repository) :subordinates {:id 1}) fetch!)))
(is (= [{:id 1 :salary 1500.0000M :active true :person {:id 1 :name "<NAME>" :gender "male"}}]
(-> (norm/find-related (:employee repository) :supervisor {:id 2}) fetch!)))
(is (= [{:id 1 :name "<NAME>" :gender "male"}]
(-> (norm/find-related (:contact repository) :owner {:value "<EMAIL>"}) fetch!))
"Filtering by a field of the main entity should work.")
(is (= [{:id 1 :login "john.doe" :active true :person {:id 1 :name "<NAME>" :gender "male"}}]
(-> (norm/find-related (:user-secret repository) :user {:user.person/name "<NAME>"}) fetch!))
"Clause by a related entity's relation should join the source to the query."))
(testing "fetch with filter"
(is (= [{:id 1 :login "john.doe" :active true :person {:id 1, :name "<NAME>", :gender "male"}}
{:id 3 :login "zoe.doe" :active true :person {:id 3, :name "<NAME>", :gender "female"}}]
(-> (:user repository) (norm/with-filter {:active true}) norm/find fetch!)))
(is (= [{:id 3 :login "zoe.doe" :active true :person {:id 3, :name "<NAME>", :gender "female"}}]
(-> (:user repository) (norm/with-filter {:active true}) (norm/find {:person/gender "female"}) fetch!))))
(testing "fetch with transform"
(let [person (assoc (:person repository) :transform #(update % :name str/lower-case))]
(is (= {:id 5, :name "sid", :gender "male"} (norm/fetch-by-id! person 5)))))
(testing "filter by related entities without eager fetching"
(is (= [{:id 1, :secret "sha256(xxxxxxx)"}] (-> (norm/find (:user-secret repository) {:user/login "john.doe"}) fetch!))))
(testing "update"
(testing "with embedded entities"
(testing "of belongs-to relationship"
(is (= 1 (norm/update! (:user repository) {:person {:name "Buzz"}} {:id 4})))
(is (= {:id 4 :name "<NAME>"} (norm/fetch-by-id! (:person repository) 4))
"Updating of an embedded entity must change the entity.")
(is (= 2 (norm/update! (:user repository) {:role "user" :person {:name "<NAME>"}} {:id 4})))
(is (= {:id 4 :login "buzz.lightyear" :role "user" :active false :person {:id 4, :name "<NAME>"}}
(norm/fetch-by-id! (:user repository) 4))
"Updating with an embedded entity must change both the main and embedded entity."))
(testing "of has-many relationship"
(is (= 4 (norm/update! (:document repository)
{:status "shipped"
:items [{:id 1 :shipped 0}
{:id 2 :shipped 20}
{:id 3 :shipped 10}]}
{:id 1})))
(is (= "shipped" (-> (:document repository) (norm/fetch-by-id! 1) :status)) "Aggregation root must be updated.")
(is (= 0 (-> (:doc-item repository) (norm/fetch-by-id! 1) :shipped)) "Component of aggregation must be updated.")
(is (= 20 (-> (:doc-item repository) (norm/fetch-by-id! 2) :shipped)) "Component of aggregation must be updated.")))
(testing "filtered by relationship"
(is (= 1 (norm/update! (:user repository) {:login "buzz"} {:person/name "<NAME>"})))
(is (= {:id 4 :login "buzz" :role "user" :active false :person {:id 4, :name "<NAME>"}}
(norm/fetch-by-id! (:user repository) 4))
"Update with filtering by related entity must change the main entity."))
(testing "with prepare function"
(let [person (assoc (:person repository) :prepare #(update % :name str/lower-case))]
(is (= 1 (norm/update! person {:name "<NAME>"} {:id 5})))
(is (= {:id 5, :name "<NAME>", :gender "male"} (norm/fetch-by-id! person 5))
"Field must be preprocessed with prepare fn."))))
(testing "changing relations"
(is (= {:employee-id 1, :responsibility-id 2}
(norm/create-relation! (:employee repository) 1 :responsibilities 2)))
(is (= [{:id 1, :title "Cleaning", :active true} {:id 3, :title "Gardening", :active true} {:id 2, :title "Watering plants", :active true}]
(norm/find-related! (:employee repository) :responsibilities {:id 1}))
"Created relation should be found.")
(is (= 1 (norm/delete-relation! (:employee repository) 1 :responsibilities 2)))
(is (= [{:id 1, :title "Cleaning", :active true} {:id 3, :title "Gardening", :active true}]
(norm/find-related! (:employee repository) :responsibilities {:id 1}))
"Deleted relation should not be found."))
(testing "delete by related entity"
(is (= 1 (norm/delete! (:user repository) {:person/name "<NAME>"})))
(is (nil? (norm/fetch-by-id! (:user repository) 4)) "Deleted entity must not be found."))))
(sql.specs/unstrument))
| true | (ns norm.sql-test
(:require [clojure.test :as t :refer [deftest testing is]]
[clojure.string :as str]
[next.jdbc :as jdbc]
[norm.core :as norm :refer [where order skip limit fetch! fetch-count!]]
[norm.sql :as sql]
[norm.sql.jdbc :refer [instance-meta]]
[norm.sql.specs :as sql.specs]))
(defn contains-all? [m & ks]
(= (clojure.set/intersection (set ks) (set (keys m))) (set ks)))
(deftest sql-query-test
(testing "Query building"
(is (= "SELECT * FROM users AS \"users\"" (str (sql/select nil :users))))
(is (= "SELECT * FROM users AS \"users\"" (str (sql/select nil :users [:*]))))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\"" (str (sql/select nil :users [:id :name]))))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".name AS \"user/name\" FROM users AS \"user\""
(str (sql/select nil [:users :user] [:user/id :user/name]))))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\""
(str (sql/select nil :users [:id :name] {})))
"Empty where clause should not apear in the query.")
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (id = ?)"
(str (sql/select nil :users [:id :name] {:id 1}))))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (((id = ?) AND (name = ?)) AND (role = ?))"
(-> (sql/select nil :users [:id :name] {:id 1})
(where {:name "PI:NAME:<NAME>END_PI"})
(where {:role "admin"})
str)))
(is (= "SELECT column_name AS \"column-name\" FROM information_schema.columns AS \"information_schema.columns\" WHERE (table_schema ILIKE ? AND table_name ILIKE ?)"
(-> (sql/select nil
:information-schema/columns
[:column-name]
{:table-schema [:ilike "public"]
:table-name [:ilike "table_name"]}) str)))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".name AS \"user/name\" FROM users AS \"user\" WHERE (\"user\".id = ?)"
(str (sql/select nil [:users :user] [:user/id :user/name] {:user/id 1}))))
(is (= "SELECT \"user\".id AS \"user/id\", \"person\".name AS \"person/name\" FROM (users AS \"user\" LEFT JOIN people AS \"person\" ON (\"user\".id = \"person\".id))"
(str (sql/select nil [[:users :user] :left-join [:people :person] {:user/id :person/id}] [:user/id :person/name]))))
(is (= "SELECT \"users\".*, \"people\".* FROM (users AS \"users\" LEFT JOIN people AS \"people\" ON (\"users\".id = \"people\".id))"
(str (sql/select nil [:users :left-join :people {:users/id :people/id}] [:users/* :people/*])))
"Wildcard should go without alias.")
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\" FROM users AS \"user\" WHERE (\"user\".id IN ((SELECT user_id AS \"user-id\" FROM employees AS \"employees\" WHERE (active IS true))))"
(str (sql/select nil [:users :user] [:user/id :user/login] {:user/id [:in (sql/select nil :employees [:user-id] {:active true})]}))))
(is (= "SELECT CURRENT_SCHEMA() AS \"current-schema\"" (str (sql/select nil nil [['(current-schema) :current-schema]]))))
(is (= "SELECT id AS \"id\" FROM tasks AS \"tasks\" WHERE (scheduled >= NOW())" (str (sql/select nil :tasks [:id] {:scheduled [:>= '(now)]})))))
(testing "Query parts amendment"
(let [query (sql/select nil :users [:id :name])]
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (id = ?)" (-> query (where {:id 1}) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM (users AS \"users\" LEFT JOIN people AS \"people\" ON (\"users\".person_id = \"people\".id)) WHERE (\"people\".name = ?)"
(-> query (sql/join :left-join :people {:users/person-id :people/id}) (where {:people/name "PI:NAME:<NAME>END_PI"}) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" OFFSET ?" (-> query (skip 2) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" LIMIT ?" (-> query (limit 10) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" LIMIT ? OFFSET ?" (-> query (skip 2) (limit 10) str)))
(is (= "SELECT id AS \"id\", name AS \"name\" FROM users AS \"users\" WHERE (id = ?) LIMIT ? OFFSET ?"
(-> query (where {:id 1}) (skip 2) (limit 10) str)))))
(testing "Data fetching"
(with-open [conn (jdbc/get-connection {:dbtype "h2:mem"})]
(let [select (partial sql/select conn)
query (select :people [:id :name])]
(jdbc/execute! conn ["CREATE TABLE people (id BIGSERIAL, name VARCHAR(100), gender VARCHAR(10), birthday DATE)"])
(jdbc/execute! conn ["CREATE TABLE users (id BIGINT, login VARCHAR(100), role VARCHAR(50))"])
(is (zero? (fetch-count! query)))
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('PI:NAME:<NAME>END_PI', 'male')"])
(jdbc/execute! conn ["INSERT INTO users (id, login) VALUES (1, 'PI:NAME:<NAME>END_PI.doe')"])
(is (= 1 (fetch-count! query)))
(is (= [{:id 1 :name "PI:NAME:<NAME>END_PI"}] (fetch! query)))
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('JPI:NAME:<NAME>END_PI Doe', 'female')"])
(is (= 2 (fetch-count! query)))
(is (= 1 (-> query (where {:id 1}) fetch-count!)))
(is (= [{:id 1 :name "PI:NAME:<NAME>END_PI"} {:id 2 :name "PI:NAME:<NAME>END_PI"}] (-> query (where {:gender ["female", "male"]}) fetch!)))
(is (= [{:id 2 :name "PI:NAME:<NAME>END_PI" :gender "female"}] (-> query (where {:id 2}) (fetch! [:id :name :gender]))))
(is (= [{:person/id 1 :person/name "PI:NAME:<NAME>END_PI" :person/gender "male" :user/login "john.doe"}
{:person/id 2 :person/name "PI:NAME:<NAME>END_PI" :person/gender "female" :user/login nil}]
(->
(select [[:people :person] :left-join [:users :user] {:person/id :user/id}] [:person/id :person/name :person/gender :user/login])
fetch!)))
(is (= [{:id 1 :name "PI:NAME:<NAME>END_PI"} {:id 2 :name "PI:NAME:<NAME>END_PI"}] (-> query (where {:or {:id 1 :gender "female"}}) fetch!)))
(is (= [{:id 1 :name "PI:NAME:<NAME>END_PI"} {:id 2 :name "PI:NAME:<NAME>END_PI"}] (-> query (order [:id]) fetch!)))
(is (= [{:id 2 :name "PI:NAME:<NAME>END_PI"} {:id 1 :name "PI:NAME:<NAME>END_PI"}] (-> query (order {:id :desc}) fetch!)))
(testing "with sub-query"
(is (= [{:person/id 1, :person/name "PI:NAME:<NAME>END_PI"}]
(-> (select [:people :person] [:person/id :person/name] {:person/id [:in (select :users [:users/id] {:users/login "john.doe"})]})
fetch!))))))))
(deftest sql-command-test
(testing "Insert command building"
(is (= "INSERT INTO users (login, role) VALUES (?, ?)" (sql/generate-sql-command (sql/insert nil :users {:login "admin" :role "admin"}))))
(is
(= "INSERT INTO users (login, role) VALUES (?, ?), (?, ?), (?, ?)"
(-> (sql/insert nil :users [[:login :role]
["admin" "admin"]
["foo" "user"]
["bar" "user"]])
sql/generate-sql-command))))
(testing "Update command building"
(is (= "UPDATE users SET login = ?, role = ? WHERE (id = ?)" (sql/generate-sql-command (sql/update nil :users {:login "admin", :role "admin"} {:id 1})))))
(testing "Delete command building"
(is (= "DELETE FROM users WHERE (id = ?)" (sql/generate-sql-command (sql/delete nil :users {:id 1})))))
(testing "Select command building"
(is (= "SELECT id AS \"id\", login AS \"login\" FROM users AS \"users\" WHERE (id = ?)"
(sql/generate-sql-command (sql/select nil :users [:id :login] {:id 1})))))
(testing "Execution"
(with-open [conn (jdbc/get-connection {:dbtype "h2:mem"})]
(jdbc/execute! conn ["CREATE TABLE people (id BIGSERIAL, name VARCHAR(100) NOT NULL, gender VARCHAR(10), birthday DATE)"])
(testing "of insert"
(is (= {:id 1} (-> (sql/insert conn :people {:name "PI:NAME:<NAME>END_PI"}) norm/execute!)))
(is (= {:id 2} (-> (sql/insert conn :people [[:name :gender] ["PI:NAME:<NAME>END_PI" "female"] ["PI:NAME:<NAME>END_PI" "female"]]) norm/execute!)))
(is (= 3 (-> (sql/select conn :people) fetch-count!)) "Database must contain all the inserted records."))
(testing "of update"
(is (= 1 (-> (sql/update conn :people {:gender "male"} {:id 1}) norm/execute!)))
(is (= [{:id 1 :gender "male"}] (-> (sql/select conn :people [:id :gender] {:id 1}) fetch!)) "Row must change after update.")
(is (= 1 (-> (sql/update conn :people {:gender nil} {:id 1}) norm/execute!)))
(is (= [{:id 1 :gender nil}] (-> (sql/select conn :people [:id :gender] {:id 1}) fetch!)) "Property must change after update with nil."))
(testing "of delete"
(is (= 1 (-> (sql/delete conn :people {:id 1}) norm/execute!)))
(is (= [{:id 2} {:id 3}] (-> (sql/select conn :people [:id]) fetch!)) "Deleted row must be missing from the table."))
(testing "of transaction"
(is (= [{:id 4} {:id 5} {:id 6} {:id 7} [{:id 4 :name "PI:NAME:<NAME>END_PI"}]]
(-> (sql/transaction conn
(sql/insert nil :people {:name "PI:NAME:<NAME>END_PI"})
(sql/insert nil :people {:name "PI:NAME:<NAME>END_PI"})
(sql/insert nil :people {:name "PI:NAME:<NAME>END_PI"})
(sql/insert nil :people {:name "PI:NAME:<NAME>END_PI"})
(sql/select nil :people [:id :name] {:name "PI:NAME:<NAME>END_PI"}))
norm/execute!)))
(is (= [{:id 4 :name "PI:NAME:<NAME>END_PI"}
{:id 5 :name "PI:NAME:<NAME>END_PI"}
{:id 6 :name "PI:NAME:<NAME>END_PI"}
{:id 7 :name "PI:NAME:<NAME>END_PI"}]
(-> (sql/select conn :people [:id :name] {:id [:> 3]}) norm/execute!)))
(is (= (repeat 4 1)
(-> (sql/delete conn :people {:id 4})
(norm/then (sql/delete conn :people {:id 5}))
(norm/then (sql/delete conn :people {:id 6}))
(norm/then (sql/delete conn :people {:id 7}))
norm/execute!)))
(is (thrown? org.h2.jdbc.JdbcSQLSyntaxErrorException
(-> (sql/transaction conn
(sql/delete nil :people {:name "PI:NAME:<NAME>END_PI"})
(sql/insert nil :people {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"})
(sql/select nil :people [:id :name] {:name "PI:NAME:<NAME>END_PI"}))
norm/execute!)))
(is (= [{:id 2 :name "PI:NAME:<NAME>END_PI"}]
(-> (sql/select conn :people [:id :name] {:name "PI:NAME:<NAME>END_PI"}) norm/execute!))
"Record must be present after failed transaction")))))
(deftest relational-entity-test
(with-open [conn (jdbc/get-connection {:dbtype "h2:mem"})]
(jdbc/execute! conn ["CREATE TABLE people (id BIGSERIAL, name VARCHAR(100), gender VARCHAR(10), birthday DATE)"])
(jdbc/execute! conn ["CREATE TABLE users (id BIGINT, login VARCHAR(100), role VARCHAR(50), active BOOLEAN)"])
(let [person (sql/create-entity {:db conn} {:name :person, :table :people, :fields [:id :name :gender :birthday]})
user (sql/create-entity {:db conn} {:name :user, :table :users, :fields [:id :login :role :active]})]
(testing "creation"
(is (= {:id 1} (-> (norm/create person {:name "PI:NAME:<NAME>END_PI" :gender "male"}) norm/execute!)))
(is (= {:id 2} (-> (norm/create person {:name "PI:NAME:<NAME>END_PI" :gender "female"}) norm/execute!)))
(is (= {:id 1} (-> (norm/create user {:id 1 :login "PI:NAME:<NAME>END_PI" :role "user"}) norm/execute!))))
(testing "fetching"
(is (= {:id 1 :name "PI:NAME:<NAME>END_PI" :gender "male"} (norm/fetch-by-id! person 1))
(str (norm/find person {:id 1})))
(is (= (merge instance-meta {:entity person}) (-> (norm/fetch-by-id! person 1) meta))
"Metadata of an instance must contain an implementation of the `Instance `protocol and a reference to the entity.")
(is (= [{:id 1 :name "PI:NAME:<NAME>END_PI" :gender "male"}
{:id 2 :name "PI:NAME:<NAME>END_PI" :gender "female"}]
(-> (norm/find person) fetch!)))
(is (= [{:id 1 :name "PI:NAME:<NAME>END_PI" :gender "male"}] (-> (norm/find person {:id 1}) fetch!))))
(testing "order"
(is (= [{:id 2 :name "PI:NAME:<NAME>END_PI" :gender "female"}
{:id 1 :name "PI:NAME:<NAME>END_PI" :gender "male"}]
(-> (norm/find person {:birthday nil}) (order {:id :desc}) fetch!))))
(testing "offset and limit"
(is (= [{:id 2 :name "PI:NAME:<NAME>END_PI" :gender "female"}]
(-> (norm/find person {:birthday nil}) (order {:id :desc}) (skip 0) (limit 1) fetch!)))
(is (= [{:id 1 :name "PI:NAME:<NAME>END_PI" :gender "male"}]
(-> (norm/find person {:birthday nil}) (order {:id :desc}) (skip 1) (limit 1) fetch!))))
(testing "update"
(is (= 1 (-> (norm/update person {:name "PI:NAME:<NAME>END_PI"} {:id 2}) norm/execute!)))
(is (= {:id 2 :name "PI:NAME:<NAME>END_PI" :gender "female"} (norm/fetch-by-id! person 2)) "Entity must change after update."))
(testing "delete"
(is (= 1 (-> (norm/delete person {:id 2}) norm/execute!)))
(is (nil? (norm/fetch-by-id! person 2)) "Entity must be missing after delete."))
(testing "with filter"
(let [active-user (norm/with-filter user {:active true})
active-admin (norm/with-filter active-user {:role "admin"})]
(is (= (merge user {:filter {:active true}})
active-user))
(is (= (merge user {:filter '(and {:active true} {:role "admin"})})
active-admin))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\" FROM users AS \"user\" WHERE (\"user\".active IS true)"
(-> active-user norm/find str)))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\" FROM users AS \"user\" WHERE ((\"user\".active IS true) AND (\"user\".id = ?))"
(-> active-user (norm/find {:id 1}) str)))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\" FROM users AS \"user\" WHERE ((\"user\".active IS true) AND (\"user\".role = ?))"
(-> active-admin norm/find str)))
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\" FROM users AS \"user\" WHERE (((\"user\".active IS true) AND (\"user\".role = ?)) AND (\"user\".id = ?))"
(-> active-admin (norm/find {:id 1}) str)))))
(testing "mutating an entity"
(is (= (merge user {:rels {:secret {:entity :secret
:type :has-one
:fk :user-id}}})
(norm/with-rels user {:secret {:entity :secret
:type :has-one
:fk :user-id}})))
(is (= true
(-> user
(norm/with-rels {:secret {:entity :secret
:type :has-one
:fk :user-id}})
(norm/with-eager [:secret])
(get-in [:rels :secret :eager]))))))))
(def entities
{:person {:table :people
:rels {:contacts {:entity :contact
:type :has-many
:fk :person-id}}}
:contact {:table :contacts
:rels {:owner {:entity :person
:type :belongs-to
:fk :person-id
:eager true}}}
:user {:table :users
:rels {:person {:entity :person
:type :belongs-to
:fk :id
:eager true}}}
:user-secret {:table :secrets
:rels {:user {:entity :user
:type :belongs-to
:fk :id}}}
:employee {:table :employees
:rels {:person {:entity :person
:type :belongs-to
:fk :id
:eager true}
:supervisor {:entity :employee
:type :belongs-to
:fk :supervisor-id}
:subordinates {:entity :employee
:type :has-many
:fk :supervisor-id
:filter {:active true}}
:responsibilities {:entity :responsibility
:type :has-many
:fk :employee-id
:rfk :responsibility-id
:join-table :employees-responsibilities
:filter {:active true}}
:nonresponsibilities {:entity :responsibility
:type :has-many
:fk :employee-id
:rfk :responsibility-id
:join-table :employees-responsibilities-negative
:filter {:active true}}}}
:responsibility {:table :responsibilities
:rels {:employees {:entity :employee
:type :has-many
:fk :responsibility-id
:rfk :employee-id
:join-table :employees-responsibilities
:filter {:active true}}
:nonemployees {:entity :employee
:type :has-many
:fk :responsibility-id
:rfk :employee-id
:join-table :employees-responsibilities-negative
:filter {:active true}}}}
:document {:table :documents
:rels {:items {:entity :doc-item
:type :has-many
:fk :doc-id}}}
:doc-item {:table :doc-items
:rels {:document {:entity :document
:type :belongs-to
:fk :doc-id}}}})
(deftest create-repository-test
(sql.specs/instrument)
(with-open [conn (jdbc/get-connection {:dbtype "h2:mem"})]
(jdbc/execute! conn ["CREATE TYPE GENDER AS ENUM ('male', 'female')"])
(jdbc/execute! conn ["CREATE TABLE people (id BIGSERIAL PRIMARY KEY, name VARCHAR(100), gender GENDER, birthday DATE)"])
(jdbc/execute! conn ["CREATE TABLE contacts (id BIGSERIAL PRIMARY KEY, person_id BIGINT REFERENCES people (id), type VARCHAR(32), value VARCHAR(128))"])
(jdbc/execute! conn ["CREATE TABLE users (id BIGINT PRIMARY KEY REFERENCES people (id), login VARCHAR(100), role VARCHAR(50), active BOOLEAN DEFAULT true)"])
(jdbc/execute! conn ["CREATE TABLE secrets (id BIGINT PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE, secret VARCHAR(256))"])
(jdbc/execute! conn ["CREATE TABLE employees (id BIGSERIAL PRIMARY KEY REFERENCES people (id), supervisor_id BIGINT REFERENCES employees (id), salary NUMERIC(19, 4), active BOOLEAN DEFAULT true)"])
(jdbc/execute! conn ["CREATE TABLE responsibilities (id BIGSERIAL PRIMARY KEY, title VARCHAR(128), description TEXT, active BOOLEAN DEFAULT true)"])
(jdbc/execute! conn ["CREATE TABLE employees_responsibilities (employee_id BIGINT REFERENCES employees (id), responsibility_id BIGINT REFERENCES responsibilities (id), PRIMARY KEY (employee_id,responsibility_id))"])
(jdbc/execute! conn ["CREATE VIEW employees_responsibilities_negative AS
(SELECT e.id AS employee_id, r.id AS responsibility_id
FROM (employees AS e CROSS JOIN responsibilities AS r)
LEFT JOIN employees_responsibilities AS er
ON er.responsibility_id = r.id AND er.employee_id = e.id
WHERE er.employee_id IS NULL)"])
(jdbc/execute! conn ["CREATE TABLE documents (id BIGSERIAL PRIMARY KEY, type VARCHAR(100), status VARCHAR (100), sum NUMBER(19,4), created_at DATE)"])
(jdbc/execute! conn ["CREATE TABLE doc_items (id BIGSERIAL PRIMARY KEY, doc_id BIGINT REFERENCES documents (id), line_number INT, ordered INT, shipped INT)"])
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('PI:NAME:<NAME>END_PI', 'male')"])
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('PI:NAME:<NAME>END_PI', 'female')"])
(jdbc/execute! conn ["INSERT INTO people (name, gender) VALUES ('PI:NAME:<NAME>END_PI', 'female')"])
(jdbc/execute! conn ["INSERT INTO contacts (person_id, type, value) VALUES (1, 'email', 'PI:EMAIL:<EMAIL>END_PI')"])
(jdbc/execute! conn ["INSERT INTO contacts (person_id, type, value) VALUES (1, 'phone', '+1(xxx)xxx-xx-xx')"])
(jdbc/execute! conn ["INSERT INTO contacts (person_id, type, value) VALUES (2, 'email', 'PI:EMAIL:<EMAIL>END_PI')"])
(jdbc/execute! conn ["INSERT INTO users (id, login) VALUES (1, 'PI:NAME:<NAME>END_PI')"])
(jdbc/execute! conn ["INSERT INTO users (id, login, active) VALUES (2, 'PI:NAME:<NAME>END_PI', false)"])
(jdbc/execute! conn ["INSERT INTO users (id, login, active) VALUES (3, 'PI:NAME:<NAME>END_PI', true)"])
(jdbc/execute! conn ["INSERT INTO secrets (id, secret) VALUES (1, 'sha256(xxxxxxx)')"])
(jdbc/execute! conn ["INSERT INTO secrets (id, secret) VALUES (2, 'sha256(yyyyyyy)')"])
(jdbc/execute! conn ["INSERT INTO secrets (id, secret) VALUES (3, 'sha256(zzzzzzz)')"])
(jdbc/execute! conn ["INSERT INTO employees (id, salary) VALUES (1, 1500)"])
(jdbc/execute! conn ["INSERT INTO employees (id, supervisor_id, salary) VALUES (2, 1, 3000)"])
(jdbc/execute! conn ["INSERT INTO employees (id, supervisor_id, salary, active) VALUES (3, 1, 3100, false)"])
(jdbc/execute! conn ["INSERT INTO responsibilities (title) VALUES ('Cleaning')"])
(jdbc/execute! conn ["INSERT INTO responsibilities (title) VALUES ('Watering plants')"])
(jdbc/execute! conn ["INSERT INTO responsibilities (title) VALUES ('Gardening')"])
(jdbc/execute! conn ["INSERT INTO responsibilities (title, active) VALUES ('Deprecated activity', false)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (1, 1)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (1, 3)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (2, 2)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (3, 2)"])
(jdbc/execute! conn ["INSERT INTO employees_responsibilities (employee_id, responsibility_id) VALUES (3, 4)"])
(let [repository (norm/create-repository :sql entities {:db conn})]
#_(is (instance? norm.sql.RelationalEntity (:person repository)))
(is (= repository @(:repository (meta (:person repository)))) "Entity must have repository in metadata.")
(is (= (keys entities) (keys repository)) "All the entities should be presented in the repository.")
(is (= [:person :contact] (keys (norm/only repository [:person :contact]))) "Only specified entities must be present.")
(is (= [:person :contact :user :document :doc-item] (keys (norm/except repository [:user-secret :employee :responsibility])))
"Specified entities must be absent.")
(testing "Fields population."
(is (= [:id :name :gender :birthday] (get-in repository [:person :fields])))
(is (= [:id :person-id :type :value] (get-in repository [:contact :fields])))
(is (= [:id :login :role :active] (get-in repository [:user :fields]))))
(testing "Transaction creation"
(is (= [] (norm/transaction repository))
"New transaction should be empty.")
#_(is (satisfies? norm/Command (norm/transaction repository))
"Transaction should be a command."); https://ask.clojure.org/index.php/4622/satisfies-doesnt-work-instance-based-protocol-polymorphism
(is (apply contains-all? (meta (norm/transaction repository)) (keys sql/sql-command-meta))
"Transaction should be a command."))
(testing "SQL generation"
(is (= "SELECT \"user\".id AS \"user/id\", \"user\".login AS \"user/login\", \"user\".role AS \"user/role\", \"user\".active AS \"user/active\", \"user.person\".id AS \"user.person/id\", \"user.person\".name AS \"user.person/name\", \"user.person\".gender AS \"user.person/gender\", \"user.person\".birthday AS \"user.person/birthday\" FROM (users AS \"user\" LEFT JOIN people AS \"user.person\" ON (\"user\".id = \"user.person\".id))"
(str (norm/find (:user repository)))))
(is (= "SELECT \"employee\".id AS \"employee/id\", \"employee\".supervisor_id AS \"employee/supervisor-id\", \"employee\".salary AS \"employee/salary\", \"employee\".active AS \"employee/active\", \"employee.person\".id AS \"employee.person/id\", \"employee.person\".name AS \"employee.person/name\", \"employee.person\".gender AS \"employee.person/gender\", \"employee.person\".birthday AS \"employee.person/birthday\" FROM (employees AS \"employee\" LEFT JOIN people AS \"employee.person\" ON (\"employee\".id = \"employee.person\".id)) WHERE (\"employee.person\".name = ?)"
(-> (norm/find (:employee repository) {:person/name "PI:NAME:<NAME>END_PI"}) str)
(-> (norm/find (:employee repository) {:employee.person/name "PI:NAME:<NAME>END_PI"}) str)
(-> (norm/find (:employee repository)) (where {:employee.person/name "PI:NAME:<NAME>END_PI"}) str)))
(is (= "SELECT \"user\".login AS \"user/login\", \"user.person\".name AS \"user.person/name\" FROM (users AS \"user\" LEFT JOIN people AS \"user.person\" ON (\"user\".id = \"user.person\".id)) WHERE (\"user\".id = ?)"
(str (norm/find (:user repository) [:user/login :person/name] {:id 1}))
(str (norm/find (:user repository) [:login :person/name] {:user/id 1}))))
(is (= "SELECT \"user_secret\".id AS \"user-secret/id\", \"user_secret\".secret AS \"user-secret/secret\" FROM (secrets AS \"user_secret\" LEFT JOIN (users AS \"user_secret.user\" LEFT JOIN people AS \"user_secret.user.person\" ON (\"user_secret.user\".id = \"user_secret.user.person\".id)) ON (\"user_secret\".id = \"user_secret.user\".id)) WHERE (\"user_secret.user.person\".name = ?)"
(-> (:user-secret repository)
(norm/find {:user.person/name "PI:NAME:<NAME>END_PI"})
str))
"Usage of a relation's relation in WHERE clause must join it in.")
(is (= "SELECT \"user.person\".id AS \"user.person/id\", \"user.person\".name AS \"user.person/name\", \"user.person\".gender AS \"user.person/gender\", \"user.person\".birthday AS \"user.person/birthday\" FROM (people AS \"user.person\" LEFT JOIN users AS \"user\" ON (\"user\".id = \"user.person\".id)) WHERE (\"user.person\".id = ?)"
(-> (:user repository)
(norm/find-related :person nil)
(norm/where {:id 1})
str))
"Field in WHERE clause must be prefixed with a selecting entity name.")
(is (= "SELECT \"user.person\".id AS \"user.person/id\", \"user.person\".name AS \"user.person/name\", \"user.person\".gender AS \"user.person/gender\", \"user.person\".birthday AS \"user.person/birthday\" FROM (people AS \"user.person\" LEFT JOIN users AS \"user\" ON (\"user\".id = \"user.person\".id)) WHERE (\"user\".id = ?)"
(-> (:user repository)
(norm/find-related :person nil)
(norm/where ^:exact {:user/id 1})
str))
"Field in WHERE clause must not be modified for exact clause.")
(is (= "SELECT \"person\".id AS \"person/id\", \"person\".name AS \"person/name\", \"person\".gender AS \"person/gender\", \"person\".birthday AS \"person/birthday\" FROM people AS \"person\" ORDER BY \"person\".id, \"person\".name"
(-> (norm/find (:person repository))
(norm/order [:id :name])
str))
"Fields in ORDER clause must be prefixed with an entity name.")
(is (= "SELECT \"person\".id AS \"person/id\", \"person\".name AS \"person/name\", \"person\".gender AS \"person/gender\", \"person\".birthday AS \"person/birthday\" FROM people AS \"person\" ORDER BY \"person\".name DESC, \"person\".id ASC"
(-> (norm/find (:person repository))
(norm/order {:name :desc :id :asc})
str))
"Fields in ORDER clause must be prefixed with an entity name.")
(is (= "SELECT \"person\".id AS \"person/id\", \"person\".name AS \"person/name\", \"person\".gender AS \"person/gender\", \"person\".birthday AS \"person/birthday\" FROM people AS \"person\" ORDER BY id, name"
(-> (norm/find (:person repository))
(norm/order ^:exact [:id :name])
str))
"Fields in ORDER clause must not be modified for exact values.")
(is (= "SELECT \"person\".id AS \"person/id\", \"person\".name AS \"person/name\", \"person\".gender AS \"person/gender\", \"person\".birthday AS \"person/birthday\" FROM people AS \"person\" ORDER BY name DESC, id ASC"
(-> (norm/find (:person repository))
(norm/order ^:exact {:name :desc :id :asc})
str))
"Fields in ORDER clause must not be modified for exact values."))
(testing "creation"
(testing "with embedded entities"
(testing "of belongs-to relationship"
(is (= {:id 4}
(-> (norm/create
(:user-secret repository)
{:secret "sha256xxxx"
:user {:login "buzz.lightyear"
:active false
:person {:name "PI:NAME:<NAME>END_PI"}}})
norm/execute!)))
(is (= {:id 4 :secret "sha256xxxx"} (norm/fetch-by-id! (:user-secret repository) 4)))
(is (= {:id 4 :login "buzz.lightyear" :active false :person {:id 4 :name "PI:NAME:<NAME>END_PI"}}
(norm/fetch-by-id! (:user repository) 4))))
(testing "of has-many relationship"
(is (= {:id 1}
(norm/create! (:document repository)
{:type "test"
:status "new"
:sum 1000
:items [{:line-number 1
:ordered 10}
{:line-number 2
:ordered 20}
{:line-number 3
:ordered 30}]})))
(is (= {:id 1 :type "test" :status "new" :sum 1000.0000M} (norm/fetch-by-id! (:document repository) 1)))
(is (= 3
(-> (:doc-item repository)
(norm/find! {:doc-id 1})
count))))
(testing "of many to many relationship"
(is (= {:id 4}
(norm/create! (:employee repository)
{:id 4
:salary 1000
:responsibilities [{:id 2} {:title "Saving the world"}]})))
(is (= {:id 4 :salary 1000.0000M :person {:id 4 :name "PI:NAME:<NAME>END_PI"} :active true}
(norm/fetch-by-id! (:employee repository) 4))
"Aggregation root must be saved")
(is (= {:id 5 :title "Saving the world" :active true}
(norm/fetch-by-id! (:responsibility repository) 5))
"Related entity must be created.")
(is (= [{:id 2 :title "Watering plants" :active true}
{:id 5 :title "Saving the world" :active true}]
(norm/find-related! (:employee repository) :responsibilities {:id 4}))
"Pre-existed and created entities must be referenced.")
))
(testing "with prepare function"
(let [person (assoc (:person repository) :prepare #(update % :name str/upper-case))]
(is (= {:id 5} (norm/create! person {:name "PI:NAME:<NAME>END_PI" :gender "male"})))
(is (= {:id 5, :name "PI:NAME:<NAME>END_PI" :gender "male"} (norm/fetch-by-id! person 5))
"Field must be preprocessed with `prepare` fn."))))
(testing "eager fetching"
(let [instance (norm/fetch-by-id! (:user repository) 1)]
(is (= {:id 1
:login "john.doe"
:active true
:person {:id 1
:name "PI:NAME:<NAME>END_PI"
:gender "male"}}
instance))
(is (= (merge instance-meta {:entity (:user repository)})
(meta instance)))
(is (= (merge instance-meta {:entity (:person repository)})
(meta (:person instance)))
"Related entity must have correct metadata."))
(is (= [{:id 2
:supervisor-id 1
:salary 3000.0000M
:active true
:person {:id 2
:name "PI:NAME:<NAME>END_PI"
:gender "female"}}]
(-> (norm/find (:employee repository))
(where {:employee.person/name "PI:NAME:<NAME>END_PI"})
fetch!))
"Clause by related entity's fields must work."))
(testing "fetching fields of related entities"
(is (= [{:login "john.doe", :person {:name "PI:NAME:<NAME>END_PI"}}] (norm/find! (:user repository) [:user/login :person/name] {:id 1}))))
(testing "fetching related entities"
(is (= [{:id 1 :name "PI:NAME:<NAME>END_PI" :gender "male"}]
(-> (norm/find-related (:user repository) :person {:id 1}) fetch!)
(-> (norm/find-related (:user repository) :person {:user/id 1}) fetch!)
(-> (norm/find-related (:user repository) :person nil) (where ^:exact {:user/id 1}) fetch!)
(-> (norm/find-related (:user repository) :person nil) (where {:id 1}) fetch!)
(-> (norm/find-related (:user repository) :person {:person/name "PI:NAME:<NAME>END_PI"}) fetch!)
(-> (norm/find-related (:user repository) :person {:user.person/name "PI:NAME:<NAME>END_PI"}) fetch!)))
(is (some? (-> (norm/find-related! (:user repository) :person {:id 1})
first
meta
:entity))
"Instance of related entity should have an entity in meta.")
(is (some? (-> (norm/find-related! (:user repository) :person {:id 1})
first
meta
((comp (partial partial =) :entity))
(filter (vals repository))
first))
"Instance of related entity should have a correct entity in metadata (found in repository).")
(is (= [{:id 3 :person-id 2 :type "email" :value "PI:EMAIL:<EMAIL>END_PI" :owner {:id 2 :name "PI:NAME:<NAME>END_PI" :gender "female"}}]
(-> (norm/find-related (:person repository) :contacts {:person/name "PI:NAME:<NAME>END_PI"}) fetch!)))
(is (= 0 (-> (norm/find-related (:person repository) :contacts {:id 3}) fetch-count!)))
(is (= 2 (-> (norm/find-related (:employee repository) :responsibilities {:id 1}) fetch-count!)))
(is (= [{:id 1, :title "Cleaning", :active true} {:id 3, :title "Gardening", :active true}]
(-> (norm/find-related (:employee repository) :responsibilities {:id 1}) fetch!)
(-> (norm/find-related (:employee repository) :nonresponsibilities {:id 4}) fetch!)))
(is (= [{:id 1 :salary 1500.0000M :active true :person {:id 1 :name "PI:NAME:<NAME>END_PI" :gender "male"}}]
(-> (norm/find-related (:responsibility repository) :employees {:id 1}) fetch!)
(-> (norm/find-related (:responsibility repository) :employees {:id 3}) fetch!)
(-> (norm/find-related (:responsibility repository) :nonemployees {:id 2}) fetch!)))
(is (= [{:id 2 :supervisor-id 1 :salary 3000.0000M :active true :person {:id 2 :name "PI:NAME:<NAME>END_PI" :gender "female"}}]
(-> (norm/find-related (:employee repository) :subordinates {:id 1}) fetch!)))
(is (= [{:id 1 :salary 1500.0000M :active true :person {:id 1 :name "PI:NAME:<NAME>END_PI" :gender "male"}}]
(-> (norm/find-related (:employee repository) :supervisor {:id 2}) fetch!)))
(is (= [{:id 1 :name "PI:NAME:<NAME>END_PI" :gender "male"}]
(-> (norm/find-related (:contact repository) :owner {:value "PI:EMAIL:<EMAIL>END_PI"}) fetch!))
"Filtering by a field of the main entity should work.")
(is (= [{:id 1 :login "john.doe" :active true :person {:id 1 :name "PI:NAME:<NAME>END_PI" :gender "male"}}]
(-> (norm/find-related (:user-secret repository) :user {:user.person/name "PI:NAME:<NAME>END_PI"}) fetch!))
"Clause by a related entity's relation should join the source to the query."))
(testing "fetch with filter"
(is (= [{:id 1 :login "john.doe" :active true :person {:id 1, :name "PI:NAME:<NAME>END_PI", :gender "male"}}
{:id 3 :login "zoe.doe" :active true :person {:id 3, :name "PI:NAME:<NAME>END_PI", :gender "female"}}]
(-> (:user repository) (norm/with-filter {:active true}) norm/find fetch!)))
(is (= [{:id 3 :login "zoe.doe" :active true :person {:id 3, :name "PI:NAME:<NAME>END_PI", :gender "female"}}]
(-> (:user repository) (norm/with-filter {:active true}) (norm/find {:person/gender "female"}) fetch!))))
(testing "fetch with transform"
(let [person (assoc (:person repository) :transform #(update % :name str/lower-case))]
(is (= {:id 5, :name "sid", :gender "male"} (norm/fetch-by-id! person 5)))))
(testing "filter by related entities without eager fetching"
(is (= [{:id 1, :secret "sha256(xxxxxxx)"}] (-> (norm/find (:user-secret repository) {:user/login "john.doe"}) fetch!))))
(testing "update"
(testing "with embedded entities"
(testing "of belongs-to relationship"
(is (= 1 (norm/update! (:user repository) {:person {:name "Buzz"}} {:id 4})))
(is (= {:id 4 :name "PI:NAME:<NAME>END_PI"} (norm/fetch-by-id! (:person repository) 4))
"Updating of an embedded entity must change the entity.")
(is (= 2 (norm/update! (:user repository) {:role "user" :person {:name "PI:NAME:<NAME>END_PI"}} {:id 4})))
(is (= {:id 4 :login "buzz.lightyear" :role "user" :active false :person {:id 4, :name "PI:NAME:<NAME>END_PI"}}
(norm/fetch-by-id! (:user repository) 4))
"Updating with an embedded entity must change both the main and embedded entity."))
(testing "of has-many relationship"
(is (= 4 (norm/update! (:document repository)
{:status "shipped"
:items [{:id 1 :shipped 0}
{:id 2 :shipped 20}
{:id 3 :shipped 10}]}
{:id 1})))
(is (= "shipped" (-> (:document repository) (norm/fetch-by-id! 1) :status)) "Aggregation root must be updated.")
(is (= 0 (-> (:doc-item repository) (norm/fetch-by-id! 1) :shipped)) "Component of aggregation must be updated.")
(is (= 20 (-> (:doc-item repository) (norm/fetch-by-id! 2) :shipped)) "Component of aggregation must be updated.")))
(testing "filtered by relationship"
(is (= 1 (norm/update! (:user repository) {:login "buzz"} {:person/name "PI:NAME:<NAME>END_PI"})))
(is (= {:id 4 :login "buzz" :role "user" :active false :person {:id 4, :name "PI:NAME:<NAME>END_PI"}}
(norm/fetch-by-id! (:user repository) 4))
"Update with filtering by related entity must change the main entity."))
(testing "with prepare function"
(let [person (assoc (:person repository) :prepare #(update % :name str/lower-case))]
(is (= 1 (norm/update! person {:name "PI:NAME:<NAME>END_PI"} {:id 5})))
(is (= {:id 5, :name "PI:NAME:<NAME>END_PI", :gender "male"} (norm/fetch-by-id! person 5))
"Field must be preprocessed with prepare fn."))))
(testing "changing relations"
(is (= {:employee-id 1, :responsibility-id 2}
(norm/create-relation! (:employee repository) 1 :responsibilities 2)))
(is (= [{:id 1, :title "Cleaning", :active true} {:id 3, :title "Gardening", :active true} {:id 2, :title "Watering plants", :active true}]
(norm/find-related! (:employee repository) :responsibilities {:id 1}))
"Created relation should be found.")
(is (= 1 (norm/delete-relation! (:employee repository) 1 :responsibilities 2)))
(is (= [{:id 1, :title "Cleaning", :active true} {:id 3, :title "Gardening", :active true}]
(norm/find-related! (:employee repository) :responsibilities {:id 1}))
"Deleted relation should not be found."))
(testing "delete by related entity"
(is (= 1 (norm/delete! (:user repository) {:person/name "PI:NAME:<NAME>END_PI"})))
(is (nil? (norm/fetch-by-id! (:user repository) 4)) "Deleted entity must not be found."))))
(sql.specs/unstrument))
|
[
{
"context": "lose anything in processing.\n\n Partially based on Marin Atanasov Nikolov's tutorial at\n http://dnaeon.github.io/recursively",
"end": 802,
"score": 0.9986940622329712,
"start": 778,
"tag": "NAME",
"value": "Marin Atanasov Nikolov's"
}
] | api/test/wfl/unit/routes_test.clj | broadinstitute/wfl | 15 | (ns wfl.unit.routes-test
(:require [clojure.test :refer [deftest is testing]]
[wfl.api.routes :as routes]))
(def sample-endpoints
[["/some/unauth/endpoint"
{:get {:handler identity}}]
["/api/some/auth/endpoint"
{:get {:handler identity}}]
["/api/some/other/auth/endpoint"
{:get {:handler identity}}
{:post {:handler identity}}]
["/api/has/swagger/config"
{:get {:handler identity
:swagger {:foo "bar"}}}]])
(defn config-for-endpoint
"Return the config for the first endpoint matching the given route."
[endpoint-route endpoints]
(first (filter #(= endpoint-route (first %)) endpoints)))
(defn recursive-merge
"Deep merging of maps so we can test that we don't lose anything in processing.
Partially based on Marin Atanasov Nikolov's tutorial at
http://dnaeon.github.io/recursively-merging-maps-in-clojure/"
[& maps]
(letfn [(partial-merge [& to-merge]
(if (some #(map? %) to-merge)
(apply merge-with partial-merge to-merge)
(last to-merge)))]
(reduce partial-merge maps)))
(deftest test-route-processing
(testing "route processing"
(let [processed-sample-endpoints (routes/endpoint-swagger-auth-processor sample-endpoints)]
(testing "no extra insertions"
(is (not (contains?
(:get (second (config-for-endpoint "/some/unauth/endpoint" processed-sample-endpoints)))
:swagger))))
(testing "proper insertion"
(is (contains?
(:get (second (config-for-endpoint "/api/some/auth/endpoint" processed-sample-endpoints)))
:swagger))
(is (every? #(contains? (first (vals %)) :swagger)
(rest (config-for-endpoint "/api/some/other/auth/endpoint" processed-sample-endpoints)))))
(testing "proper contents"
(is (= "Authenticated" (-> (config-for-endpoint "/api/some/auth/endpoint" processed-sample-endpoints)
second
:get
:swagger
:tags
first)))
(is (contains? (-> (config-for-endpoint "/api/some/auth/endpoint" processed-sample-endpoints)
second
:get
:swagger
:security
first) :googleoauth)))
(testing "merges with existing"
(is (= "Authenticated" (-> (config-for-endpoint "/api/has/swagger/config" processed-sample-endpoints)
second
:get
:swagger
:tags
first)))
(is (= "bar" (-> (config-for-endpoint "/api/has/swagger/config" processed-sample-endpoints)
second
:get
:swagger
:foo))))
(testing "isn't lossy"
(is (every? identity
(map (fn [sample processed]
(and
(= (first sample) (first processed))
(every? identity
;; does processed not change when we
;; override it with the original?
;; (is processed a superset of original)
(map #(= %2 (recursive-merge %2 %1))
(rest sample) (rest processed)))))
sample-endpoints processed-sample-endpoints)))))))
| 14034 | (ns wfl.unit.routes-test
(:require [clojure.test :refer [deftest is testing]]
[wfl.api.routes :as routes]))
(def sample-endpoints
[["/some/unauth/endpoint"
{:get {:handler identity}}]
["/api/some/auth/endpoint"
{:get {:handler identity}}]
["/api/some/other/auth/endpoint"
{:get {:handler identity}}
{:post {:handler identity}}]
["/api/has/swagger/config"
{:get {:handler identity
:swagger {:foo "bar"}}}]])
(defn config-for-endpoint
"Return the config for the first endpoint matching the given route."
[endpoint-route endpoints]
(first (filter #(= endpoint-route (first %)) endpoints)))
(defn recursive-merge
"Deep merging of maps so we can test that we don't lose anything in processing.
Partially based on <NAME> tutorial at
http://dnaeon.github.io/recursively-merging-maps-in-clojure/"
[& maps]
(letfn [(partial-merge [& to-merge]
(if (some #(map? %) to-merge)
(apply merge-with partial-merge to-merge)
(last to-merge)))]
(reduce partial-merge maps)))
(deftest test-route-processing
(testing "route processing"
(let [processed-sample-endpoints (routes/endpoint-swagger-auth-processor sample-endpoints)]
(testing "no extra insertions"
(is (not (contains?
(:get (second (config-for-endpoint "/some/unauth/endpoint" processed-sample-endpoints)))
:swagger))))
(testing "proper insertion"
(is (contains?
(:get (second (config-for-endpoint "/api/some/auth/endpoint" processed-sample-endpoints)))
:swagger))
(is (every? #(contains? (first (vals %)) :swagger)
(rest (config-for-endpoint "/api/some/other/auth/endpoint" processed-sample-endpoints)))))
(testing "proper contents"
(is (= "Authenticated" (-> (config-for-endpoint "/api/some/auth/endpoint" processed-sample-endpoints)
second
:get
:swagger
:tags
first)))
(is (contains? (-> (config-for-endpoint "/api/some/auth/endpoint" processed-sample-endpoints)
second
:get
:swagger
:security
first) :googleoauth)))
(testing "merges with existing"
(is (= "Authenticated" (-> (config-for-endpoint "/api/has/swagger/config" processed-sample-endpoints)
second
:get
:swagger
:tags
first)))
(is (= "bar" (-> (config-for-endpoint "/api/has/swagger/config" processed-sample-endpoints)
second
:get
:swagger
:foo))))
(testing "isn't lossy"
(is (every? identity
(map (fn [sample processed]
(and
(= (first sample) (first processed))
(every? identity
;; does processed not change when we
;; override it with the original?
;; (is processed a superset of original)
(map #(= %2 (recursive-merge %2 %1))
(rest sample) (rest processed)))))
sample-endpoints processed-sample-endpoints)))))))
| true | (ns wfl.unit.routes-test
(:require [clojure.test :refer [deftest is testing]]
[wfl.api.routes :as routes]))
(def sample-endpoints
[["/some/unauth/endpoint"
{:get {:handler identity}}]
["/api/some/auth/endpoint"
{:get {:handler identity}}]
["/api/some/other/auth/endpoint"
{:get {:handler identity}}
{:post {:handler identity}}]
["/api/has/swagger/config"
{:get {:handler identity
:swagger {:foo "bar"}}}]])
(defn config-for-endpoint
"Return the config for the first endpoint matching the given route."
[endpoint-route endpoints]
(first (filter #(= endpoint-route (first %)) endpoints)))
(defn recursive-merge
"Deep merging of maps so we can test that we don't lose anything in processing.
Partially based on PI:NAME:<NAME>END_PI tutorial at
http://dnaeon.github.io/recursively-merging-maps-in-clojure/"
[& maps]
(letfn [(partial-merge [& to-merge]
(if (some #(map? %) to-merge)
(apply merge-with partial-merge to-merge)
(last to-merge)))]
(reduce partial-merge maps)))
(deftest test-route-processing
(testing "route processing"
(let [processed-sample-endpoints (routes/endpoint-swagger-auth-processor sample-endpoints)]
(testing "no extra insertions"
(is (not (contains?
(:get (second (config-for-endpoint "/some/unauth/endpoint" processed-sample-endpoints)))
:swagger))))
(testing "proper insertion"
(is (contains?
(:get (second (config-for-endpoint "/api/some/auth/endpoint" processed-sample-endpoints)))
:swagger))
(is (every? #(contains? (first (vals %)) :swagger)
(rest (config-for-endpoint "/api/some/other/auth/endpoint" processed-sample-endpoints)))))
(testing "proper contents"
(is (= "Authenticated" (-> (config-for-endpoint "/api/some/auth/endpoint" processed-sample-endpoints)
second
:get
:swagger
:tags
first)))
(is (contains? (-> (config-for-endpoint "/api/some/auth/endpoint" processed-sample-endpoints)
second
:get
:swagger
:security
first) :googleoauth)))
(testing "merges with existing"
(is (= "Authenticated" (-> (config-for-endpoint "/api/has/swagger/config" processed-sample-endpoints)
second
:get
:swagger
:tags
first)))
(is (= "bar" (-> (config-for-endpoint "/api/has/swagger/config" processed-sample-endpoints)
second
:get
:swagger
:foo))))
(testing "isn't lossy"
(is (every? identity
(map (fn [sample processed]
(and
(= (first sample) (first processed))
(every? identity
;; does processed not change when we
;; override it with the original?
;; (is processed a superset of original)
(map #(= %2 (recursive-merge %2 %1))
(rest sample) (rest processed)))))
sample-endpoints processed-sample-endpoints)))))))
|
[
{
"context": "zy relational algebra\"\n :url \"https://github.com/Workiva/lazy-tables\"\n :license {:name \"Apache License, V",
"end": 138,
"score": 0.9994897842407227,
"start": 131,
"tag": "USERNAME",
"value": "Workiva"
},
{
"context": "jars_username\n :password :env/clojars_password\n :sign-releases false}}\n\n",
"end": 708,
"score": 0.97054523229599,
"start": 688,
"tag": "PASSWORD",
"value": "env/clojars_password"
}
] | project.clj | Workiva/lazy-tables | 1 | (defproject com.workiva/lazy-tables "0.1.2"
:description "A set of tools for lazy relational algebra"
:url "https://github.com/Workiva/lazy-tables"
:license {:name "Apache License, Version 2.0"}
:plugins [[lein-shell "0.5.0"]
[lein-codox "0.10.6"]
[lein-cljfmt "0.6.4"]]
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/math.combinatorics "0.1.4"]
[org.clojure/test.check "0.10.0-alpha3"]
[potemkin "0.4.5"]]
:deploy-repositories {"clojars"
{:url "https://repo.clojars.org"
:username :env/clojars_username
:password :env/clojars_password
:sign-releases false}}
:source-paths ["src"]
:test-paths ["test"]
:aliases {"docs" ["do" "clean-docs," "with-profile" "docs" "codox"]
"clean-docs" ["shell" "rm" "-rf" "./documentation"]}
:codox {:metadata {:doc/format :markdown}
:themes [:rdash]
:html {:transforms [[:title]
[:substitute [:title "Lazy-Tables API Docs"]]
[:span.project-version]
[:substitute nil]
[:pre.deps]
[:substitute [:a {:href "https://clojars.org/com.workiva/lazy-tables"}
[:img {:src "https://img.shields.io/clojars/v/com.workiva/lazy-tables.svg"}]]]]}
:output-path "documentation"}
:cljfmt {:indentation? false}
:repl-options {:init-ns lazy-tables.core}
:profiles {:docs {:dependencies [[codox-theme-rdash "0.1.2"]]}})
| 120456 | (defproject com.workiva/lazy-tables "0.1.2"
:description "A set of tools for lazy relational algebra"
:url "https://github.com/Workiva/lazy-tables"
:license {:name "Apache License, Version 2.0"}
:plugins [[lein-shell "0.5.0"]
[lein-codox "0.10.6"]
[lein-cljfmt "0.6.4"]]
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/math.combinatorics "0.1.4"]
[org.clojure/test.check "0.10.0-alpha3"]
[potemkin "0.4.5"]]
:deploy-repositories {"clojars"
{:url "https://repo.clojars.org"
:username :env/clojars_username
:password :<PASSWORD>
:sign-releases false}}
:source-paths ["src"]
:test-paths ["test"]
:aliases {"docs" ["do" "clean-docs," "with-profile" "docs" "codox"]
"clean-docs" ["shell" "rm" "-rf" "./documentation"]}
:codox {:metadata {:doc/format :markdown}
:themes [:rdash]
:html {:transforms [[:title]
[:substitute [:title "Lazy-Tables API Docs"]]
[:span.project-version]
[:substitute nil]
[:pre.deps]
[:substitute [:a {:href "https://clojars.org/com.workiva/lazy-tables"}
[:img {:src "https://img.shields.io/clojars/v/com.workiva/lazy-tables.svg"}]]]]}
:output-path "documentation"}
:cljfmt {:indentation? false}
:repl-options {:init-ns lazy-tables.core}
:profiles {:docs {:dependencies [[codox-theme-rdash "0.1.2"]]}})
| true | (defproject com.workiva/lazy-tables "0.1.2"
:description "A set of tools for lazy relational algebra"
:url "https://github.com/Workiva/lazy-tables"
:license {:name "Apache License, Version 2.0"}
:plugins [[lein-shell "0.5.0"]
[lein-codox "0.10.6"]
[lein-cljfmt "0.6.4"]]
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/math.combinatorics "0.1.4"]
[org.clojure/test.check "0.10.0-alpha3"]
[potemkin "0.4.5"]]
:deploy-repositories {"clojars"
{:url "https://repo.clojars.org"
:username :env/clojars_username
:password :PI:PASSWORD:<PASSWORD>END_PI
:sign-releases false}}
:source-paths ["src"]
:test-paths ["test"]
:aliases {"docs" ["do" "clean-docs," "with-profile" "docs" "codox"]
"clean-docs" ["shell" "rm" "-rf" "./documentation"]}
:codox {:metadata {:doc/format :markdown}
:themes [:rdash]
:html {:transforms [[:title]
[:substitute [:title "Lazy-Tables API Docs"]]
[:span.project-version]
[:substitute nil]
[:pre.deps]
[:substitute [:a {:href "https://clojars.org/com.workiva/lazy-tables"}
[:img {:src "https://img.shields.io/clojars/v/com.workiva/lazy-tables.svg"}]]]]}
:output-path "documentation"}
:cljfmt {:indentation? false}
:repl-options {:init-ns lazy-tables.core}
:profiles {:docs {:dependencies [[codox-theme-rdash "0.1.2"]]}})
|
[
{
"context": "(fn [{db :db} [_ error]]\n ;; TODO: [2022-05-15, ilshat@sultanov.team] Show notification\n (log/info :news/rss-channe",
"end": 522,
"score": 0.9998663067817688,
"start": 502,
"tag": "EMAIL",
"value": "ilshat@sultanov.team"
}
] | src/main/clojure/metaverse/renderer/news/events.cljs | sultanov-team/metaverse | 1 | (ns metaverse.renderer.news.events
(:require
[metaverse.common.logger :as log :include-macros true]
[re-frame.core :as rf]))
(rf/reg-event-fx
:news/rss-channels->success
(fn [{db :db} [_ rss-channels]]
(log/info :news/rss-channels->success rss-channels)
{:db (assoc-in db [:news :rss-channels] @rss-channels)
:dispatch [:set-readiness :news/rss-channels :ready]}))
(rf/reg-event-fx
:news/rss-channels->failure
(fn [{db :db} [_ error]]
;; TODO: [2022-05-15, ilshat@sultanov.team] Show notification
(log/info :news/rss-channels->failure error)
{:db (update db :news dissoc :rss-channels)
:dispatch [:set-readiness :news/rss-channels :failed]}))
(rf/reg-event-fx
:news/rss-channels
(fn [{db :db} _]
{:db (update db :news dissoc :rss-channels)
:dispatch [:set-readiness :news/rss-channels :loading]
:api/invoke {:event [:news/rss-channels]
:on-success [:news/rss-channels->success]
:on-failure [:news/rss-channels->failure]}}))
| 41348 | (ns metaverse.renderer.news.events
(:require
[metaverse.common.logger :as log :include-macros true]
[re-frame.core :as rf]))
(rf/reg-event-fx
:news/rss-channels->success
(fn [{db :db} [_ rss-channels]]
(log/info :news/rss-channels->success rss-channels)
{:db (assoc-in db [:news :rss-channels] @rss-channels)
:dispatch [:set-readiness :news/rss-channels :ready]}))
(rf/reg-event-fx
:news/rss-channels->failure
(fn [{db :db} [_ error]]
;; TODO: [2022-05-15, <EMAIL>] Show notification
(log/info :news/rss-channels->failure error)
{:db (update db :news dissoc :rss-channels)
:dispatch [:set-readiness :news/rss-channels :failed]}))
(rf/reg-event-fx
:news/rss-channels
(fn [{db :db} _]
{:db (update db :news dissoc :rss-channels)
:dispatch [:set-readiness :news/rss-channels :loading]
:api/invoke {:event [:news/rss-channels]
:on-success [:news/rss-channels->success]
:on-failure [:news/rss-channels->failure]}}))
| true | (ns metaverse.renderer.news.events
(:require
[metaverse.common.logger :as log :include-macros true]
[re-frame.core :as rf]))
(rf/reg-event-fx
:news/rss-channels->success
(fn [{db :db} [_ rss-channels]]
(log/info :news/rss-channels->success rss-channels)
{:db (assoc-in db [:news :rss-channels] @rss-channels)
:dispatch [:set-readiness :news/rss-channels :ready]}))
(rf/reg-event-fx
:news/rss-channels->failure
(fn [{db :db} [_ error]]
;; TODO: [2022-05-15, PI:EMAIL:<EMAIL>END_PI] Show notification
(log/info :news/rss-channels->failure error)
{:db (update db :news dissoc :rss-channels)
:dispatch [:set-readiness :news/rss-channels :failed]}))
(rf/reg-event-fx
:news/rss-channels
(fn [{db :db} _]
{:db (update db :news dissoc :rss-channels)
:dispatch [:set-readiness :news/rss-channels :loading]
:api/invoke {:event [:news/rss-channels]
:on-success [:news/rss-channels->success]
:on-failure [:news/rss-channels->failure]}}))
|
[
{
"context": " :username \"must be present\" :password \"must be present\" \n :endpoint \"must be present\" :managm",
"end": 1002,
"score": 0.9991579055786133,
"start": 987,
"tag": "PASSWORD",
"value": "must be present"
}
] | test/re_core/test/config.clj | celestial-ops/core | 1 | (ns re-core.test.config
(:require
[re-core.fixtures.data :refer (local-prox)]
[flatland.useful.map :refer (dissoc-in*)]
[re-core.config :refer (validate-conf)])
(:use midje.sweet))
(defn validate-missing [& ks]
(validate-conf (dissoc-in* local-prox ks)))
(fact "legal configuration"
(validate-conf local-prox) => {})
(fact "missing re-core options detected"
(validate-missing :re-core :https-port) => {:re-core {:https-port "must be present"}}
(validate-missing :re-core :port) => {:re-core {:port "must be present"}})
(fact "missing aws options"
(validate-conf (assoc-in local-prox [:hypervisor :dev :aws] {})) =>
{:hypervisor {:dev {:aws {:access-key "must be present" :secret-key "must be present"}}}})
(fact "missing openstack options"
(validate-conf (assoc-in local-prox [:hypervisor :dev :openstack] {})) =>
{:hypervisor
{:dev
{:openstack {
:username "must be present" :password "must be present"
:endpoint "must be present" :managment-interface "must be present"}}}})
(fact "wrong central logging"
(validate-conf (assoc-in local-prox [:re-core :log :gelf :type] :foo)) =>
{:re-core {:log {:gelf
{:type "type must be either #{:kibana3 :graylog2 :logstash :kibana4}"}}}})
(fact "workers configuration"
(validate-conf (assoc-in local-prox [:re-core :job :workers :stage] "bar")) =>
{:re-core {:job {:workers {:stage "must be a integer"}}}})
| 75984 | (ns re-core.test.config
(:require
[re-core.fixtures.data :refer (local-prox)]
[flatland.useful.map :refer (dissoc-in*)]
[re-core.config :refer (validate-conf)])
(:use midje.sweet))
(defn validate-missing [& ks]
(validate-conf (dissoc-in* local-prox ks)))
(fact "legal configuration"
(validate-conf local-prox) => {})
(fact "missing re-core options detected"
(validate-missing :re-core :https-port) => {:re-core {:https-port "must be present"}}
(validate-missing :re-core :port) => {:re-core {:port "must be present"}})
(fact "missing aws options"
(validate-conf (assoc-in local-prox [:hypervisor :dev :aws] {})) =>
{:hypervisor {:dev {:aws {:access-key "must be present" :secret-key "must be present"}}}})
(fact "missing openstack options"
(validate-conf (assoc-in local-prox [:hypervisor :dev :openstack] {})) =>
{:hypervisor
{:dev
{:openstack {
:username "must be present" :password "<PASSWORD>"
:endpoint "must be present" :managment-interface "must be present"}}}})
(fact "wrong central logging"
(validate-conf (assoc-in local-prox [:re-core :log :gelf :type] :foo)) =>
{:re-core {:log {:gelf
{:type "type must be either #{:kibana3 :graylog2 :logstash :kibana4}"}}}})
(fact "workers configuration"
(validate-conf (assoc-in local-prox [:re-core :job :workers :stage] "bar")) =>
{:re-core {:job {:workers {:stage "must be a integer"}}}})
| true | (ns re-core.test.config
(:require
[re-core.fixtures.data :refer (local-prox)]
[flatland.useful.map :refer (dissoc-in*)]
[re-core.config :refer (validate-conf)])
(:use midje.sweet))
(defn validate-missing [& ks]
(validate-conf (dissoc-in* local-prox ks)))
(fact "legal configuration"
(validate-conf local-prox) => {})
(fact "missing re-core options detected"
(validate-missing :re-core :https-port) => {:re-core {:https-port "must be present"}}
(validate-missing :re-core :port) => {:re-core {:port "must be present"}})
(fact "missing aws options"
(validate-conf (assoc-in local-prox [:hypervisor :dev :aws] {})) =>
{:hypervisor {:dev {:aws {:access-key "must be present" :secret-key "must be present"}}}})
(fact "missing openstack options"
(validate-conf (assoc-in local-prox [:hypervisor :dev :openstack] {})) =>
{:hypervisor
{:dev
{:openstack {
:username "must be present" :password "PI:PASSWORD:<PASSWORD>END_PI"
:endpoint "must be present" :managment-interface "must be present"}}}})
(fact "wrong central logging"
(validate-conf (assoc-in local-prox [:re-core :log :gelf :type] :foo)) =>
{:re-core {:log {:gelf
{:type "type must be either #{:kibana3 :graylog2 :logstash :kibana4}"}}}})
(fact "workers configuration"
(validate-conf (assoc-in local-prox [:re-core :job :workers :stage] "bar")) =>
{:re-core {:job {:workers {:stage "must be a integer"}}}})
|
[
{
"context": "c License - Version 1.0\" :url \"https://github.com/nathanmarz/storm/blob/master/LICENSE.html\"}\n :mailing-list ",
"end": 398,
"score": 0.9934245347976685,
"start": 388,
"tag": "USERNAME",
"value": "nathanmarz"
},
{
"context": "gle.com/group/storm-user\"\n :post \"storm-user@googlegroups.com\"}\n :dependencies [~@DEPENDENCIES]\n :plugins [[~",
"end": 603,
"score": 0.9999195337295532,
"start": 576,
"tag": "EMAIL",
"value": "storm-user@googlegroups.com"
}
] | project.clj | raikon/SocialEyeser | 0 | (def VERSION (.trim (slurp "VERSION")))
(def MODULES (-> "MODULES" slurp (.split "\n")))
(def DEPENDENCIES (for [m MODULES] [(symbol (str "storm/" m)) VERSION]))
(eval `(defproject storm/storm ~VERSION
:url "http://storm-project.net"
:description "Distributed and fault-tolerant realtime computation"
:license {:name "Eclipse Public License - Version 1.0" :url "https://github.com/nathanmarz/storm/blob/master/LICENSE.html"}
:mailing-list {:name "Storm user mailing list"
:archive "https://groups.google.com/group/storm-user"
:post "storm-user@googlegroups.com"}
:dependencies [~@DEPENDENCIES]
:plugins [[~'lein-sub "0.2.1"]]
:min-lein-version "2.0.0"
:sub [~@MODULES]
))
| 71504 | (def VERSION (.trim (slurp "VERSION")))
(def MODULES (-> "MODULES" slurp (.split "\n")))
(def DEPENDENCIES (for [m MODULES] [(symbol (str "storm/" m)) VERSION]))
(eval `(defproject storm/storm ~VERSION
:url "http://storm-project.net"
:description "Distributed and fault-tolerant realtime computation"
:license {:name "Eclipse Public License - Version 1.0" :url "https://github.com/nathanmarz/storm/blob/master/LICENSE.html"}
:mailing-list {:name "Storm user mailing list"
:archive "https://groups.google.com/group/storm-user"
:post "<EMAIL>"}
:dependencies [~@DEPENDENCIES]
:plugins [[~'lein-sub "0.2.1"]]
:min-lein-version "2.0.0"
:sub [~@MODULES]
))
| true | (def VERSION (.trim (slurp "VERSION")))
(def MODULES (-> "MODULES" slurp (.split "\n")))
(def DEPENDENCIES (for [m MODULES] [(symbol (str "storm/" m)) VERSION]))
(eval `(defproject storm/storm ~VERSION
:url "http://storm-project.net"
:description "Distributed and fault-tolerant realtime computation"
:license {:name "Eclipse Public License - Version 1.0" :url "https://github.com/nathanmarz/storm/blob/master/LICENSE.html"}
:mailing-list {:name "Storm user mailing list"
:archive "https://groups.google.com/group/storm-user"
:post "PI:EMAIL:<EMAIL>END_PI"}
:dependencies [~@DEPENDENCIES]
:plugins [[~'lein-sub "0.2.1"]]
:min-lein-version "2.0.0"
:sub [~@MODULES]
))
|
[
{
"context": "factory fseq]]))\n\n(defseq :email [n] (str \"user\" n \"@test.com\"))\n(defseq :password [n] (str \"password\" n))\n(def",
"end": 136,
"score": 0.8916504979133606,
"start": 126,
"tag": "EMAIL",
"value": "\"@test.com"
},
{
"context": "user\" n \"@test.com\"))\n(defseq :password [n] (str \"password\" n))\n(defseq :nickname [n] (str \"nickname\" n))\n(d",
"end": 176,
"score": 0.9571772813796997,
"start": 168,
"tag": "PASSWORD",
"value": "password"
}
] | test/clj/villagebook/factory.clj | sathia27/villagebook | 0 | (ns villagebook.factory
(:use [clj-factory.core :only [deffactory defseq factory fseq]]))
(defseq :email [n] (str "user" n "@test.com"))
(defseq :password [n] (str "password" n))
(defseq :nickname [n] (str "nickname" n))
(defseq :name [n] (str "name" n))
(defseq :orgname [n] (str "organisation" n))
(defseq :orgcolor [n] (str "color" n))
(defseq :category-name [n] (str "Category " n))
(defseq :field-name [n] (str "Field " n))
(deffactory :user
{:email (fseq :email)
:password (fseq :password)
:nickname (fseq :password)
:name (fseq :name)})
(deffactory :organisation
{:name (fseq :orgname)
:color (fseq :orgcolor)})
(deffactory :field
{:name (fseq :field-name)})
(def user1 (factory :user))
(def user2 (assoc (factory :user) :name nil))
(def organisation (factory :organisation))
(def category1 (fseq :category-name))
(def field1 (factory :field))
(def field2 (factory :field))
| 122123 | (ns villagebook.factory
(:use [clj-factory.core :only [deffactory defseq factory fseq]]))
(defseq :email [n] (str "user" n <EMAIL>"))
(defseq :password [n] (str "<PASSWORD>" n))
(defseq :nickname [n] (str "nickname" n))
(defseq :name [n] (str "name" n))
(defseq :orgname [n] (str "organisation" n))
(defseq :orgcolor [n] (str "color" n))
(defseq :category-name [n] (str "Category " n))
(defseq :field-name [n] (str "Field " n))
(deffactory :user
{:email (fseq :email)
:password (fseq :password)
:nickname (fseq :password)
:name (fseq :name)})
(deffactory :organisation
{:name (fseq :orgname)
:color (fseq :orgcolor)})
(deffactory :field
{:name (fseq :field-name)})
(def user1 (factory :user))
(def user2 (assoc (factory :user) :name nil))
(def organisation (factory :organisation))
(def category1 (fseq :category-name))
(def field1 (factory :field))
(def field2 (factory :field))
| true | (ns villagebook.factory
(:use [clj-factory.core :only [deffactory defseq factory fseq]]))
(defseq :email [n] (str "user" n PI:EMAIL:<EMAIL>END_PI"))
(defseq :password [n] (str "PI:PASSWORD:<PASSWORD>END_PI" n))
(defseq :nickname [n] (str "nickname" n))
(defseq :name [n] (str "name" n))
(defseq :orgname [n] (str "organisation" n))
(defseq :orgcolor [n] (str "color" n))
(defseq :category-name [n] (str "Category " n))
(defseq :field-name [n] (str "Field " n))
(deffactory :user
{:email (fseq :email)
:password (fseq :password)
:nickname (fseq :password)
:name (fseq :name)})
(deffactory :organisation
{:name (fseq :orgname)
:color (fseq :orgcolor)})
(deffactory :field
{:name (fseq :field-name)})
(def user1 (factory :user))
(def user2 (assoc (factory :user) :name nil))
(def organisation (factory :organisation))
(def category1 (fseq :category-name))
(def field1 (factory :field))
(def field2 (factory :field))
|
[
{
"context": "the standby validators from privnet\n(def wifs\n [\"KxyjQ8eUa4FHt3Gvioyt1Wz29cTUrE4eTqX3yFSk1YFCsPL8uNsY\"\n \"KzfPUYDC9n2yf4fK5ro4C8KMcdeXtFuEnStycbZgX3Go",
"end": 668,
"score": 0.9963130354881287,
"start": 616,
"tag": "KEY",
"value": "KxyjQ8eUa4FHt3Gvioyt1Wz29cTUrE4eTqX3yFSk1YFCsPL8uNsY"
},
{
"context": "a4FHt3Gvioyt1Wz29cTUrE4eTqX3yFSk1YFCsPL8uNsY\"\n \"KzfPUYDC9n2yf4fK5ro4C8KMcdeXtFuEnStycbZgX3GomiUsvX6W\"\n \"L2oEXKRAAMiPEZukwR5ho2S6SMeQLhcK9mF71ZnF7GvT",
"end": 726,
"score": 0.9965967535972595,
"start": 674,
"tag": "KEY",
"value": "KzfPUYDC9n2yf4fK5ro4C8KMcdeXtFuEnStycbZgX3GomiUsvX6W"
},
{
"context": "9n2yf4fK5ro4C8KMcdeXtFuEnStycbZgX3GomiUsvX6W\"\n \"L2oEXKRAAMiPEZukwR5ho2S6SMeQLhcK9mF71ZnF7GvT8dU4Kkgz\"\n \"KzgWE3u3EDp13XPXXuTKZxeJ3Gi8Bsm8f9ijY3ZsCKKR",
"end": 784,
"score": 0.9934358596801758,
"start": 732,
"tag": "KEY",
"value": "L2oEXKRAAMiPEZukwR5ho2S6SMeQLhcK9mF71ZnF7GvT8dU4Kkgz"
},
{
"context": "AMiPEZukwR5ho2S6SMeQLhcK9mF71ZnF7GvT8dU4Kkgz\"\n \"KzgWE3u3EDp13XPXXuTKZxeJ3Gi8Bsm8f9ijY3ZsCKKRvZUo1Cdn\"])\n\n(defn create [path passw]\n (UserWallet/Creat",
"end": 842,
"score": 0.9967652559280396,
"start": 790,
"tag": "KEY",
"value": "KzgWE3u3EDp13XPXXuTKZxeJ3Gi8Bsm8f9ijY3ZsCKKRvZUo1Cdn"
}
] | src/neo_clj/wallet.clj | effectai/neo-clojure-clr | 5 | (ns neo-clj.wallet
(:require
[neo-clj.blockchain :as blockchain]
[neo-clj.crypto :as crypto]
[clojure.string :as str])
(:import
[System.IO File Directory]
[Neo Fixed8 Helper]
Neo.Implementations.Wallets.EntityFramework.UserWallet
[Neo.Core TransactionOutput ContractTransaction Blockchain
ClaimTransaction TransactionAttribute CoinReference CoinState]
[Neo.Cryptography.ECC ECCurve ECPoint]
[Neo.Wallets Wallet VerificationContract Coin]
[Neo.SmartContract ContractParametersContext Contract]))
;; The wallets corresponding to the standby validators from privnet
(def wifs
["KxyjQ8eUa4FHt3Gvioyt1Wz29cTUrE4eTqX3yFSk1YFCsPL8uNsY"
"KzfPUYDC9n2yf4fK5ro4C8KMcdeXtFuEnStycbZgX3GomiUsvX6W"
"L2oEXKRAAMiPEZukwR5ho2S6SMeQLhcK9mF71ZnF7GvT8dU4Kkgz"
"KzgWE3u3EDp13XPXXuTKZxeJ3Gi8Bsm8f9ijY3ZsCKKRvZUo1Cdn"])
(defn create [path passw]
(UserWallet/Create path passw))
(defn open [path passw]
(UserWallet/Open path passw))
(defn open-or-create
"Open a wallet or create it if it doesn't exist"
[path passw]
(let [path (if (str/starts-with? path "/")
path
(str (Directory/GetCurrentDirectory) "/" path))]
(if (File/Exists path)
(open path passw)
(create path passw))))
(defn neo-balance [wallet]
(->> (:neo blockchain/asset-ids) (.GetAvailable wallet)))
(defn gas-balance [wallet]
(->> (:gas blockchain/asset-ids) (.GetAvailable wallet)))
(defn balance-for-key [wallet script-hash]
(let [coins (->> wallet .GetCoins vec
(filter #(= (.. % Output ScriptHash) script-hash))
(filter #(.HasFlag (.State %) CoinState/Confirmed))
(filter #(not (.HasFlag (.State %) CoinState/Spent)))
(filter #(not (.HasFlag (.State %) CoinState/Frozen)))
(filter #(not (.HasFlag (.State %) CoinState/Locked)))
(filter #(not (.HasFlag (.State %) CoinState/WatchOnly))))
neo-coins (filter #(= (.. % Output AssetId) (:neo blockchain/asset-ids)) coins)
gas-coins (filter #(= (.. % Output AssetId) (:gas blockchain/asset-ids)) coins)]
{:neo (reduce #(+ %1 (int (str (.. %2 Output Value)))) 0 neo-coins)
:gas (reduce #(+ %1 (int (str (.. %2 Output Value)))) 0 gas-coins)}))
(defn get-a-public-key
"Generate new keypair for the wallet and return the public"
[wallet]
(-> wallet .CreateKey .PublicKey .ToString))
(defn match-key
"Get a KeyPair from wallet that matches a public key"
[key wallet]
(->> (.EncodePoint key true)
Neo.Core.Helper/ToScriptHash
(. wallet GetKey)))
(defn pub-hash-to-ecpoint
"Convert public-key hash to ECPoint"
[hash]
(->> hash
Helper/HexToBytes
(#(. ECPoint DecodePoint % ECCurve/Secp256r1))))
(defn add-multi-sig-contract [wallet public-keys]
(let [keys (map pub-hash-to-ecpoint public-keys)
key (->> (map #(match-key % wallet) keys)
(filter #(not (nil? %)))
first)
contract (VerificationContract/CreateMultiSigContract (.PublicKeyHash key) 3 (into-array keys))]
(.AddContract wallet contract)
contract))
(defn make-transaction
([wallet to-address amount] (make-transaction wallet to-address amount (:neo blockchain/asset-ids)))
([wallet to-address amount asset-id]
(let [scripthash-to (Wallet/ToScriptHash to-address)
f8-amount (Fixed8/Parse amount)
fee (Fixed8/Zero)
output (doto (TransactionOutput.)
(#(set! (.AssetId %) asset-id))
(#(set! (.Value %) f8-amount))
(#(set! (.ScriptHash %) scripthash-to)))
tx (doto (ContractTransaction.)
(#(set! (.Outputs %) (into-array [output]))))
txx (.MakeTransaction wallet tx nil fee)
ctx (ContractParametersContext. txx)]
{:tx tx
:ctx ctx})))
(defn sign
"Sign a context using the necessary keys from wallet. Returns
boolean wether all scripthashes could be signed."
[wallet ctx]
(doall
(map
(fn [script-hash]
(when-let [contract (.GetContract wallet script-hash)]
(when-let [key (.GetKeyByScriptHash wallet script-hash)]
(let [message (->> (.Verifiable ctx) (. Neo.Core.Helper GetHashData) crypto/hash256)
signature (crypto/sign message key)]
(.AddSignature ctx contract (.PublicKey key) signature)))))
(.ScriptHashes ctx)))
ctx)
(defn pub-key-to-address [pub-hash]
(-> pub-hash pub-hash-to-ecpoint
VerificationContract/CreateSignatureContract
(.Address)))
(defn get-keys
"Get clojure map of info about all the keys in wallet"
[wallet]
(letfn [(addr [k]
(let [address (-> k .PublicKey str pub-key-to-address)
script-hash (Wallet/ToScriptHash address)]
{:public-key (-> k .PublicKey str)
:private-key (-> k .PrivateKey Helper/ToHexString)
:wif (.Export k)
:balance (balance-for-key wallet script-hash)
:script-hash (str script-hash)
:address address}))]
(->> wallet .GetKeys vec (map addr))))
(defn claim-gas-tx
"Creates a transaction that claims GAS for wallet.
If `coins` is supplied should be a vec of `Coin` objects that are
used in the claim. If absent all unclaimed coins in the wallet are
used."
([wallet] (claim-gas-tx wallet (vec (.GetUnclaimedCoins wallet))))
([wallet coins]
(let [;; change-address (.GetChangeAddress wallet)
change-address (-> wallet get-keys first :address Wallet/ToScriptHash)]
(when (empty? coins)
(throw (Exception. "No claimable gas")))
(let [claims (map #(.Reference %) coins)
output (doto (TransactionOutput.)
(#(set! (.AssetId %) (:gas blockchain/asset-ids)))
(#(set! (.Value %) (. Blockchain CalculateBonus claims false)))
(#(set! (.ScriptHash %) change-address)))
tx (doto (ClaimTransaction.)
(#(set! (.Claims %) (into-array claims)))
(#(set! (.Attributes %) (make-array
TransactionAttribute 0)))
(#(set! (.Inputs %) (make-array CoinReference 0)))
(#(set! (.Outputs %) (into-array [output]))))
ctx (ContractParametersContext. tx)]
ctx))))
(defn claim-gas-for-address-tx
"Creates a transaction that claims GAS for an `address` in `wallet`.
The `address` should be a string. Only coins originating from this
address are included in the claim."
[wallet address]
(let [coins (->> wallet .GetUnclaimedCoins vec
(filter #(= (.Address %) address)))]
(claim-gas-tx wallet coins)))
| 82229 | (ns neo-clj.wallet
(:require
[neo-clj.blockchain :as blockchain]
[neo-clj.crypto :as crypto]
[clojure.string :as str])
(:import
[System.IO File Directory]
[Neo Fixed8 Helper]
Neo.Implementations.Wallets.EntityFramework.UserWallet
[Neo.Core TransactionOutput ContractTransaction Blockchain
ClaimTransaction TransactionAttribute CoinReference CoinState]
[Neo.Cryptography.ECC ECCurve ECPoint]
[Neo.Wallets Wallet VerificationContract Coin]
[Neo.SmartContract ContractParametersContext Contract]))
;; The wallets corresponding to the standby validators from privnet
(def wifs
["<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"])
(defn create [path passw]
(UserWallet/Create path passw))
(defn open [path passw]
(UserWallet/Open path passw))
(defn open-or-create
"Open a wallet or create it if it doesn't exist"
[path passw]
(let [path (if (str/starts-with? path "/")
path
(str (Directory/GetCurrentDirectory) "/" path))]
(if (File/Exists path)
(open path passw)
(create path passw))))
(defn neo-balance [wallet]
(->> (:neo blockchain/asset-ids) (.GetAvailable wallet)))
(defn gas-balance [wallet]
(->> (:gas blockchain/asset-ids) (.GetAvailable wallet)))
(defn balance-for-key [wallet script-hash]
(let [coins (->> wallet .GetCoins vec
(filter #(= (.. % Output ScriptHash) script-hash))
(filter #(.HasFlag (.State %) CoinState/Confirmed))
(filter #(not (.HasFlag (.State %) CoinState/Spent)))
(filter #(not (.HasFlag (.State %) CoinState/Frozen)))
(filter #(not (.HasFlag (.State %) CoinState/Locked)))
(filter #(not (.HasFlag (.State %) CoinState/WatchOnly))))
neo-coins (filter #(= (.. % Output AssetId) (:neo blockchain/asset-ids)) coins)
gas-coins (filter #(= (.. % Output AssetId) (:gas blockchain/asset-ids)) coins)]
{:neo (reduce #(+ %1 (int (str (.. %2 Output Value)))) 0 neo-coins)
:gas (reduce #(+ %1 (int (str (.. %2 Output Value)))) 0 gas-coins)}))
(defn get-a-public-key
"Generate new keypair for the wallet and return the public"
[wallet]
(-> wallet .CreateKey .PublicKey .ToString))
(defn match-key
"Get a KeyPair from wallet that matches a public key"
[key wallet]
(->> (.EncodePoint key true)
Neo.Core.Helper/ToScriptHash
(. wallet GetKey)))
(defn pub-hash-to-ecpoint
"Convert public-key hash to ECPoint"
[hash]
(->> hash
Helper/HexToBytes
(#(. ECPoint DecodePoint % ECCurve/Secp256r1))))
(defn add-multi-sig-contract [wallet public-keys]
(let [keys (map pub-hash-to-ecpoint public-keys)
key (->> (map #(match-key % wallet) keys)
(filter #(not (nil? %)))
first)
contract (VerificationContract/CreateMultiSigContract (.PublicKeyHash key) 3 (into-array keys))]
(.AddContract wallet contract)
contract))
(defn make-transaction
([wallet to-address amount] (make-transaction wallet to-address amount (:neo blockchain/asset-ids)))
([wallet to-address amount asset-id]
(let [scripthash-to (Wallet/ToScriptHash to-address)
f8-amount (Fixed8/Parse amount)
fee (Fixed8/Zero)
output (doto (TransactionOutput.)
(#(set! (.AssetId %) asset-id))
(#(set! (.Value %) f8-amount))
(#(set! (.ScriptHash %) scripthash-to)))
tx (doto (ContractTransaction.)
(#(set! (.Outputs %) (into-array [output]))))
txx (.MakeTransaction wallet tx nil fee)
ctx (ContractParametersContext. txx)]
{:tx tx
:ctx ctx})))
(defn sign
"Sign a context using the necessary keys from wallet. Returns
boolean wether all scripthashes could be signed."
[wallet ctx]
(doall
(map
(fn [script-hash]
(when-let [contract (.GetContract wallet script-hash)]
(when-let [key (.GetKeyByScriptHash wallet script-hash)]
(let [message (->> (.Verifiable ctx) (. Neo.Core.Helper GetHashData) crypto/hash256)
signature (crypto/sign message key)]
(.AddSignature ctx contract (.PublicKey key) signature)))))
(.ScriptHashes ctx)))
ctx)
(defn pub-key-to-address [pub-hash]
(-> pub-hash pub-hash-to-ecpoint
VerificationContract/CreateSignatureContract
(.Address)))
(defn get-keys
"Get clojure map of info about all the keys in wallet"
[wallet]
(letfn [(addr [k]
(let [address (-> k .PublicKey str pub-key-to-address)
script-hash (Wallet/ToScriptHash address)]
{:public-key (-> k .PublicKey str)
:private-key (-> k .PrivateKey Helper/ToHexString)
:wif (.Export k)
:balance (balance-for-key wallet script-hash)
:script-hash (str script-hash)
:address address}))]
(->> wallet .GetKeys vec (map addr))))
(defn claim-gas-tx
"Creates a transaction that claims GAS for wallet.
If `coins` is supplied should be a vec of `Coin` objects that are
used in the claim. If absent all unclaimed coins in the wallet are
used."
([wallet] (claim-gas-tx wallet (vec (.GetUnclaimedCoins wallet))))
([wallet coins]
(let [;; change-address (.GetChangeAddress wallet)
change-address (-> wallet get-keys first :address Wallet/ToScriptHash)]
(when (empty? coins)
(throw (Exception. "No claimable gas")))
(let [claims (map #(.Reference %) coins)
output (doto (TransactionOutput.)
(#(set! (.AssetId %) (:gas blockchain/asset-ids)))
(#(set! (.Value %) (. Blockchain CalculateBonus claims false)))
(#(set! (.ScriptHash %) change-address)))
tx (doto (ClaimTransaction.)
(#(set! (.Claims %) (into-array claims)))
(#(set! (.Attributes %) (make-array
TransactionAttribute 0)))
(#(set! (.Inputs %) (make-array CoinReference 0)))
(#(set! (.Outputs %) (into-array [output]))))
ctx (ContractParametersContext. tx)]
ctx))))
(defn claim-gas-for-address-tx
"Creates a transaction that claims GAS for an `address` in `wallet`.
The `address` should be a string. Only coins originating from this
address are included in the claim."
[wallet address]
(let [coins (->> wallet .GetUnclaimedCoins vec
(filter #(= (.Address %) address)))]
(claim-gas-tx wallet coins)))
| true | (ns neo-clj.wallet
(:require
[neo-clj.blockchain :as blockchain]
[neo-clj.crypto :as crypto]
[clojure.string :as str])
(:import
[System.IO File Directory]
[Neo Fixed8 Helper]
Neo.Implementations.Wallets.EntityFramework.UserWallet
[Neo.Core TransactionOutput ContractTransaction Blockchain
ClaimTransaction TransactionAttribute CoinReference CoinState]
[Neo.Cryptography.ECC ECCurve ECPoint]
[Neo.Wallets Wallet VerificationContract Coin]
[Neo.SmartContract ContractParametersContext Contract]))
;; The wallets corresponding to the standby validators from privnet
(def wifs
["PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"])
(defn create [path passw]
(UserWallet/Create path passw))
(defn open [path passw]
(UserWallet/Open path passw))
(defn open-or-create
"Open a wallet or create it if it doesn't exist"
[path passw]
(let [path (if (str/starts-with? path "/")
path
(str (Directory/GetCurrentDirectory) "/" path))]
(if (File/Exists path)
(open path passw)
(create path passw))))
(defn neo-balance [wallet]
(->> (:neo blockchain/asset-ids) (.GetAvailable wallet)))
(defn gas-balance [wallet]
(->> (:gas blockchain/asset-ids) (.GetAvailable wallet)))
(defn balance-for-key [wallet script-hash]
(let [coins (->> wallet .GetCoins vec
(filter #(= (.. % Output ScriptHash) script-hash))
(filter #(.HasFlag (.State %) CoinState/Confirmed))
(filter #(not (.HasFlag (.State %) CoinState/Spent)))
(filter #(not (.HasFlag (.State %) CoinState/Frozen)))
(filter #(not (.HasFlag (.State %) CoinState/Locked)))
(filter #(not (.HasFlag (.State %) CoinState/WatchOnly))))
neo-coins (filter #(= (.. % Output AssetId) (:neo blockchain/asset-ids)) coins)
gas-coins (filter #(= (.. % Output AssetId) (:gas blockchain/asset-ids)) coins)]
{:neo (reduce #(+ %1 (int (str (.. %2 Output Value)))) 0 neo-coins)
:gas (reduce #(+ %1 (int (str (.. %2 Output Value)))) 0 gas-coins)}))
(defn get-a-public-key
"Generate new keypair for the wallet and return the public"
[wallet]
(-> wallet .CreateKey .PublicKey .ToString))
(defn match-key
"Get a KeyPair from wallet that matches a public key"
[key wallet]
(->> (.EncodePoint key true)
Neo.Core.Helper/ToScriptHash
(. wallet GetKey)))
(defn pub-hash-to-ecpoint
"Convert public-key hash to ECPoint"
[hash]
(->> hash
Helper/HexToBytes
(#(. ECPoint DecodePoint % ECCurve/Secp256r1))))
(defn add-multi-sig-contract [wallet public-keys]
(let [keys (map pub-hash-to-ecpoint public-keys)
key (->> (map #(match-key % wallet) keys)
(filter #(not (nil? %)))
first)
contract (VerificationContract/CreateMultiSigContract (.PublicKeyHash key) 3 (into-array keys))]
(.AddContract wallet contract)
contract))
(defn make-transaction
([wallet to-address amount] (make-transaction wallet to-address amount (:neo blockchain/asset-ids)))
([wallet to-address amount asset-id]
(let [scripthash-to (Wallet/ToScriptHash to-address)
f8-amount (Fixed8/Parse amount)
fee (Fixed8/Zero)
output (doto (TransactionOutput.)
(#(set! (.AssetId %) asset-id))
(#(set! (.Value %) f8-amount))
(#(set! (.ScriptHash %) scripthash-to)))
tx (doto (ContractTransaction.)
(#(set! (.Outputs %) (into-array [output]))))
txx (.MakeTransaction wallet tx nil fee)
ctx (ContractParametersContext. txx)]
{:tx tx
:ctx ctx})))
(defn sign
"Sign a context using the necessary keys from wallet. Returns
boolean wether all scripthashes could be signed."
[wallet ctx]
(doall
(map
(fn [script-hash]
(when-let [contract (.GetContract wallet script-hash)]
(when-let [key (.GetKeyByScriptHash wallet script-hash)]
(let [message (->> (.Verifiable ctx) (. Neo.Core.Helper GetHashData) crypto/hash256)
signature (crypto/sign message key)]
(.AddSignature ctx contract (.PublicKey key) signature)))))
(.ScriptHashes ctx)))
ctx)
(defn pub-key-to-address [pub-hash]
(-> pub-hash pub-hash-to-ecpoint
VerificationContract/CreateSignatureContract
(.Address)))
(defn get-keys
"Get clojure map of info about all the keys in wallet"
[wallet]
(letfn [(addr [k]
(let [address (-> k .PublicKey str pub-key-to-address)
script-hash (Wallet/ToScriptHash address)]
{:public-key (-> k .PublicKey str)
:private-key (-> k .PrivateKey Helper/ToHexString)
:wif (.Export k)
:balance (balance-for-key wallet script-hash)
:script-hash (str script-hash)
:address address}))]
(->> wallet .GetKeys vec (map addr))))
(defn claim-gas-tx
"Creates a transaction that claims GAS for wallet.
If `coins` is supplied should be a vec of `Coin` objects that are
used in the claim. If absent all unclaimed coins in the wallet are
used."
([wallet] (claim-gas-tx wallet (vec (.GetUnclaimedCoins wallet))))
([wallet coins]
(let [;; change-address (.GetChangeAddress wallet)
change-address (-> wallet get-keys first :address Wallet/ToScriptHash)]
(when (empty? coins)
(throw (Exception. "No claimable gas")))
(let [claims (map #(.Reference %) coins)
output (doto (TransactionOutput.)
(#(set! (.AssetId %) (:gas blockchain/asset-ids)))
(#(set! (.Value %) (. Blockchain CalculateBonus claims false)))
(#(set! (.ScriptHash %) change-address)))
tx (doto (ClaimTransaction.)
(#(set! (.Claims %) (into-array claims)))
(#(set! (.Attributes %) (make-array
TransactionAttribute 0)))
(#(set! (.Inputs %) (make-array CoinReference 0)))
(#(set! (.Outputs %) (into-array [output]))))
ctx (ContractParametersContext. tx)]
ctx))))
(defn claim-gas-for-address-tx
"Creates a transaction that claims GAS for an `address` in `wallet`.
The `address` should be a string. Only coins originating from this
address are included in the claim."
[wallet address]
(let [coins (->> wallet .GetUnclaimedCoins vec
(filter #(= (.Address %) address)))]
(claim-gas-tx wallet coins)))
|
[
{
"context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;\n;; Copyright (c) 2008, J. Bester\n;; All rights reserved.\n;;\n;; Redistribution and ",
"end": 430,
"score": 0.9998810291290283,
"start": 421,
"tag": "NAME",
"value": "J. Bester"
}
] | src/cljext/str.clj | jbester/cljext | 9 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File : str.clj
;; Function : String library
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Send comments or questions to code at freshlime dot org
;; $Id: 951f79ebab7f8fd78373db72b3d031c7892369b8 $
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Copyright (c) 2008, J. Bester
;; 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.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``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 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns cljext.str
(:refer-clojure))
(defn chomp
"Remove \r\n \n or \r line endings from string and return it"
([#^String str]
(let [len (count str)]
(cond (.endsWith str "\r\n")
(.substring str 0 (- len 2))
(or (.endsWith str "\n") (.endsWith str "\r"))
(.substring str 0 (dec len))
true
str))))
(defn str-concat
"Concatenate strings together"
([& items]
(let [builder (StringBuilder.)]
(doseq [item items]
(.append builder #^String item))
(.toString builder))))
| 9352 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File : str.clj
;; Function : String library
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Send comments or questions to code at freshlime dot org
;; $Id: 951f79ebab7f8fd78373db72b3d031c7892369b8 $
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Copyright (c) 2008, <NAME>
;; 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.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``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 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns cljext.str
(:refer-clojure))
(defn chomp
"Remove \r\n \n or \r line endings from string and return it"
([#^String str]
(let [len (count str)]
(cond (.endsWith str "\r\n")
(.substring str 0 (- len 2))
(or (.endsWith str "\n") (.endsWith str "\r"))
(.substring str 0 (dec len))
true
str))))
(defn str-concat
"Concatenate strings together"
([& items]
(let [builder (StringBuilder.)]
(doseq [item items]
(.append builder #^String item))
(.toString builder))))
| true | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File : str.clj
;; Function : String library
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Send comments or questions to code at freshlime dot org
;; $Id: 951f79ebab7f8fd78373db72b3d031c7892369b8 $
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Copyright (c) 2008, PI:NAME:<NAME>END_PI
;; 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.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``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 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns cljext.str
(:refer-clojure))
(defn chomp
"Remove \r\n \n or \r line endings from string and return it"
([#^String str]
(let [len (count str)]
(cond (.endsWith str "\r\n")
(.substring str 0 (- len 2))
(or (.endsWith str "\n") (.endsWith str "\r"))
(.substring str 0 (dec len))
true
str))))
(defn str-concat
"Concatenate strings together"
([& items]
(let [builder (StringBuilder.)]
(doseq [item items]
(.append builder #^String item))
(.toString builder))))
|
[
{
"context": "n 16 9876)\n\n(println @n)\n\n(def data (atom {:name \"t-rav\" :email \"mtravis@ca.abc.com\"} :error-mode :contin",
"end": 162,
"score": 0.706855833530426,
"start": 157,
"tag": "USERNAME",
"value": "t-rav"
},
{
"context": "intln @n)\n\n(def data (atom {:name \"t-rav\" :email \"mtravis@ca.abc.com\"} :error-mode :continue))\n(set-validator! data :e",
"end": 190,
"score": 0.9999237060546875,
"start": 172,
"tag": "EMAIL",
"value": "mtravis@ca.abc.com"
}
] | state-management/validators.clj | travism26/random_clojure_stuff | 0 | (def eh 15)
(println eh)
(def n (atom 15 :validator pos?))
(println @n)
(swap! n inc)
(compare-and-set! n 16 9876)
(println @n)
(def data (atom {:name "t-rav" :email "mtravis@ca.abc.com"} :error-mode :continue))
(set-validator! data :email)
;(swap! data dissoc :email)
(println @data)
(def nums (atom [2 4 8] :validator #(every? even? %)))
(swap! nums conj 6)
(println @nums)
;(swap! nums conj 9)
(set-validator! nums #(every? pos? %))
;(swap! nums conj -10)
(set-validator! nums nil)
(swap! nums conj -9)
(println @nums)
| 71773 | (def eh 15)
(println eh)
(def n (atom 15 :validator pos?))
(println @n)
(swap! n inc)
(compare-and-set! n 16 9876)
(println @n)
(def data (atom {:name "t-rav" :email "<EMAIL>"} :error-mode :continue))
(set-validator! data :email)
;(swap! data dissoc :email)
(println @data)
(def nums (atom [2 4 8] :validator #(every? even? %)))
(swap! nums conj 6)
(println @nums)
;(swap! nums conj 9)
(set-validator! nums #(every? pos? %))
;(swap! nums conj -10)
(set-validator! nums nil)
(swap! nums conj -9)
(println @nums)
| true | (def eh 15)
(println eh)
(def n (atom 15 :validator pos?))
(println @n)
(swap! n inc)
(compare-and-set! n 16 9876)
(println @n)
(def data (atom {:name "t-rav" :email "PI:EMAIL:<EMAIL>END_PI"} :error-mode :continue))
(set-validator! data :email)
;(swap! data dissoc :email)
(println @data)
(def nums (atom [2 4 8] :validator #(every? even? %)))
(swap! nums conj 6)
(println @nums)
;(swap! nums conj 9)
(set-validator! nums #(every? pos? %))
;(swap! nums conj -10)
(set-validator! nums nil)
(swap! nums conj -9)
(println @nums)
|
[
{
"context": "\"password='' query='..'\")))\n (is (= \"password='******'\" (mask-password-in-string \"password='secret'\")))",
"end": 8018,
"score": 0.8913796544075012,
"start": 8018,
"tag": "PASSWORD",
"value": ""
},
{
"context": "ord='******'\" (mask-password-in-string \"password='secret'\")))\n (is (= \"password = '******'\" (mask-passw",
"end": 8069,
"score": 0.7962378859519958,
"start": 8063,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": "ng \"password='secret'\")))\n (is (= \"password = '******'\" (mask-password-in-string \"password = 'secret'\")",
"end": 8099,
"score": 0.6774251461029053,
"start": 8099,
"tag": "PASSWORD",
"value": ""
},
{
"context": "= '******'\" (mask-password-in-string \"password = 'secret'\")))\n (is (= \"password='******' | password='**",
"end": 8152,
"score": 0.7754605412483215,
"start": 8146,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": "ng \"password = 'secret'\")))\n (is (= \"password='******' | password='***'\" (mask-password-in-string \"pass",
"end": 8180,
"score": 0.583616316318512,
"start": 8180,
"tag": "PASSWORD",
"value": ""
},
{
"context": "ssword='***'\" (mask-password-in-string \"password='secret' | password='abc'\")))\n (is (= \"user='joe' pass",
"end": 8248,
"score": 0.6061581373214722,
"start": 8242,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": "password-in-string \"password='secret' | password='abc'\")))\n (is (= \"user='joe' password='***********",
"end": 8265,
"score": 0.5836213827133179,
"start": 8262,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": "ssword='abc'\")))\n (is (= \"user='joe' password='************'\" (mask-password-in-string \"user='joe' password='",
"end": 8304,
"score": 0.9300587177276611,
"start": 8304,
"tag": "PASSWORD",
"value": ""
},
{
"context": "'\" (mask-password-in-string \"user='joe' password='secret \\\\\\\"x\\\\\\\"'\"))))\n (testing \"with password in doub",
"end": 8372,
"score": 0.7910916805267334,
"start": 8366,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": "ssword-in-string \"user='joe' password='secret \\\\\\\"x\\\\\\\"'\"))))\n (testing \"with password in double quotes\"",
"end": 8378,
"score": 0.8780423402786255,
"start": 8377,
"tag": "PASSWORD",
"value": "x"
},
{
"context": "ring \"password=''''''\")))\n (is (= \"password='''******'''\" (mask-password-in-string \"password='''secret'",
"end": 9064,
"score": 0.597924530506134,
"start": 9064,
"tag": "PASSWORD",
"value": ""
},
{
"context": "'******'''\" (mask-password-in-string \"password='''secret'''\")))\n (is (= \"password = '''******'''\" (mask",
"end": 9119,
"score": 0.8104680776596069,
"start": 9113,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": "ssword = '''secret'''\")))\n (is (= \"password='''******''' | password='''***'''\" (mask-password-in-string",
"end": 9242,
"score": 0.8719916343688965,
"start": 9242,
"tag": "PASSWORD",
"value": ""
},
{
"context": ")\n (is (= \"password='''******''' | password='''***'''\" (mask-password-in-string \"password='''secret'",
"end": 9266,
"score": 0.5140518546104431,
"start": 9266,
"tag": "PASSWORD",
"value": ""
},
{
"context": "='''***'''\" (mask-password-in-string \"password='''secret''' | password='''abc'''\")))\n (is (= \"user='''j",
"end": 9318,
"score": 0.7229183316230774,
"start": 9312,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": "rd-in-string \"password='''secret''' | password='''abc'''\")))\n (is (= \"user='''joe''' password='''***",
"end": 9339,
"score": 0.8652276396751404,
"start": 9336,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": "abc'''\")))\n (is (= \"user='''joe''' password='''************'''\" (mask-password-in-string \"user='''joe''' ",
"end": 9386,
"score": 0.7960030436515808,
"start": 9386,
"tag": "PASSWORD",
"value": ""
},
{
"context": "-in-string \"user='''joe''' password='''secret \\\\\\\"x\\\\\\\"'''\"))))\n (testing \"with unquoted password\"\n ",
"end": 9468,
"score": 0.6428747177124023,
"start": 9467,
"tag": "PASSWORD",
"value": "x"
},
{
"context": "g \"password : 'secret'\")))\n (is (= \"password: '******' | password: '***'\" (mask-password-in-string \"pas",
"end": 10501,
"score": 0.5604041218757629,
"start": 10501,
"tag": "PASSWORD",
"value": ""
},
{
"context": "ssword-in-string \"password: 'secret' | password: 'abc'\")))\n (is (= \"'password': '******' | 'password",
"end": 10589,
"score": 0.853869616985321,
"start": 10586,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": "rd-in-string \"'password': 'secret' | 'password': 'abc'\"))))\n (testing \"with password in map in double ",
"end": 10714,
"score": 0.9644462466239929,
"start": 10711,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": "sword : '''secret'''\")))\n (is (= \"password: '''******''' | password: '''***'''\" (mask-password-in-strin",
"end": 11607,
"score": 0.606238067150116,
"start": 11607,
"tag": "PASSWORD",
"value": ""
},
{
"context": "-in-string \"password: '''secret''' | password: '''abc'''\")))\n (is (= \"'''password''': '''******''' |",
"end": 11707,
"score": 0.5909590721130371,
"start": 11704,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": "'''password''': '''secret''' | '''password''': '''abc'''\"))))\n )\n\n(deftest apply-default-http-options-",
"end": 11864,
"score": 0.6567615270614624,
"start": 11861,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": "z 3 } { :x 1 :y 2})))\n (is (= { :auth { :user \"dave\" :password \"secret123\" :preemptive true } }\n ",
"end": 12357,
"score": 0.9995959997177124,
"start": 12353,
"tag": "USERNAME",
"value": "dave"
},
{
"context": "})))\n (is (= { :auth { :user \"dave\" :password \"secret123\" :preemptive true } }\n (apply-default-h",
"end": 12379,
"score": 0.9994069933891296,
"start": 12370,
"tag": "PASSWORD",
"value": "secret123"
},
{
"context": "}\n (apply-default-http-options { :user \"dave\" :password \"secret123\"} {})))\n (is (= { :auth ",
"end": 12454,
"score": 0.9995946884155273,
"start": 12450,
"tag": "USERNAME",
"value": "dave"
},
{
"context": "ly-default-http-options { :user \"dave\" :password \"secret123\"} {})))\n (is (= { :auth { :user \"dave\" :passwo",
"end": 12476,
"score": 0.9994174242019653,
"start": 12467,
"tag": "PASSWORD",
"value": "secret123"
},
{
"context": "rd \"secret123\"} {})))\n (is (= { :auth { :user \"dave\" :password \"secret123\" :preemptive true } }\n ",
"end": 12517,
"score": 0.9994484782218933,
"start": 12513,
"tag": "USERNAME",
"value": "dave"
},
{
"context": "})))\n (is (= { :auth { :user \"dave\" :password \"secret123\" :preemptive true } }\n (apply-default-h",
"end": 12539,
"score": 0.9994304180145264,
"start": 12530,
"tag": "PASSWORD",
"value": "secret123"
},
{
"context": " (apply-default-http-options { :username \"dave\" :password \"secret123\"} {})))))\n\n(deftest urldeco",
"end": 12618,
"score": 0.9994385838508606,
"start": 12614,
"tag": "USERNAME",
"value": "dave"
},
{
"context": "efault-http-options { :username \"dave\" :password \"secret123\"} {})))))\n\n(deftest urldecode-test\n (testing \"wi",
"end": 12640,
"score": 0.9994136691093445,
"start": 12631,
"tag": "PASSWORD",
"value": "secret123"
}
] | test/parsec/helpers_test.clj | ExpediaGroup/parsec | 1 | (ns parsec.helpers-test
(:require [clojure.test :refer :all]
[parsec.helpers :refer :all]
[parsec.test-helpers :refer :all]))
(deftest always-predicate-test
(testing "with nil"
(is (true? (always-predicate nil nil)))))
(deftest any-pred?-test
(testing "with nils"
(is (false? (any-pred? true? nil))))
(testing "with vector of booleans"
(is (true? (any-pred? true? [false true false])))
(is (false? (any-pred? true? [false false false])))
(is (true? (any-pred? false? [false true false])))
(is (false? (any-pred? false? [true true true])))))
(deftest in?-test
(testing "with empty list"
(is (false? (in? '() 1)))
(is (false? (in? '() nil))))
(testing "with empty vector"
(is (false? (in? [] 1)))
(is (false? (in? [] nil))))
(testing "with nil list"
(is (false? (in? nil 1)))
(is (false? (in? nil nil))))
(testing "with lists"
(is (true? (in? '(nil) nil)))
(is (true? (in? '(nil nil) nil)))
(is (true? (in? '(1 2 nil 3) nil)))
(is (false? (in? '(1 2 3 4) nil)))
(is (false? (in? '(1 2 3 4) 5)))
(is (true? (in? '(1 2 3 4) 3)))
(is (false? (in? '("x" "y" "z") "w")))
(is (true? (in? '("x" "y" "z") "x"))))
(testing "with vectors"
(is (true? (in? [nil] nil)))
(is (true? (in? [nil nil] nil)))
(is (true? (in? [1 2 nil 3] nil)))
(is (false? (in? [1 2 3 4] nil)))
(is (false? (in? [1 2 3 4] 5)))
(is (true? (in? [1 2 3 4] 3)))
(is (false? (in? ["x" "y" "z"] "w")))
(is (true? (in? ["x" "y" "z"] "x"))))
(testing "with strings"
(is (false? (in? "hello world" nil)))
(is (true? (in? "hello world" "hello")))
(is (false? (in? "hello world" "Hello")))
(is (true? (in? "555-4445" 5)))
(is (false? (in? "555-1445" 9)))))
(deftest mapmapv-test
(testing "with nil map"
(is (nil? (mapmapv identity nil))))
(testing "with empty map"
(is (= {} (mapmapv identity {}))))
(testing "with identity"
(is (= { :a 1 } (mapmapv identity { :a 1 }))))
(testing "with fn"
(is (= { :a 2 :b 2 } (mapmapv #(+ 1 %) { :a 1 :b 1 })))
(is (= { :a 3 :b 5 } (mapmapv count { :a [1,2,3] :b [4,5,6,7,8] }))))
(testing "with nil function"
(is (thrown? NullPointerException (mapmapv nil { :a 1 }))))
(testing "with vector"
(is (thrown? UnsupportedOperationException (mapmapv identity [1 2 3])))))
(deftest mapply-test
(testing "with nil map"
(is (zero? (mapply + nil))))
(testing "with empty map"
(is (zero? (mapply + { }))))
(testing "with nil map"
(is (= ":x1:y2" (mapply #(str % %2 %3 %4) { :x 1 :y 2 }))))
(testing "with empty map"
(is (= 10 (mapply + { 1 2 3 4 })))))
(deftest mapcat2-test
(testing "with nil map"
(is (empty? (mapcat2 identity nil))))
(testing "with empty list"
(is (empty? (mapcat2 identity []))))
(testing "with single element"
(is (= [1] (mapcat2 identity [1]))))
(testing "with multiple elements"
(is (= [1 2 3] (mapcat2 identity [1 2 3]))))
(testing "with lists returned"
(is (= [1 2 2 4 3 6] (mapcat2 #(vector % (* 2 %)) [1 2 3])))))
(deftest xor-test
(testing "with nil"
(is (false? (xor nil nil))))
(testing "with booleans"
(is (false? (xor true true)))
(is (false? (xor false false)))
(is (true? (xor false true)))
(is (true? (xor true false)))))
(deftest eval-expression-test
(testing "nil"
(is (nil? (eval-expression nil {} {}))))
(testing "number"
(is (= 444 (eval-expression 444 {} {}))))
(testing "keyword"
(is (= 155 (eval-expression :col1 { :col1 155 } {}))))
(testing "variable"
(is (= 42 (eval-expression [:variable "@V1"] {} { :variables { "@V1" 42 }}))))
(testing "function"
(is (= 1 (eval-expression (fn [_ _] 1) {} { :variables { }})))))
(deftest eval-expression-without-row-test
(testing "nil"
(is (nil? (eval-expression-without-row nil {}))))
(testing "number"
(is (= 444 (eval-expression-without-row 444 {}))))
(testing "keyword"
(is (thrown? Exception (eval-expression-without-row :col1 {}))))
(testing "variable"
(is (= 42 (eval-expression-without-row [:variable "@V1"] { :variables { "@V1" 42 }}))))
(testing "function"
(is (= 1 (eval-expression-without-row (fn [_ _] 1) { :variables { }})))))
(deftest expr-to-string-test
(testing "with list"
(is (= "[1,2,3]" (expr-to-string [1,2,3]))))
(testing "with string"
(is (= "hello" (expr-to-string "hello"))))
(testing "with string expression"
(is (= "hello" (expr-to-string [:expression "hello"]))))
(testing "with wrapped string expression"
(is (= "(hello)" (expr-to-string [:expression "hello"] true))))
(testing "with numerical expression"
(is (= "-1" (expr-to-string [:expression -1]))))
(testing "with wrapped numerical expression"
(is (= "(-1)" (expr-to-string [:expression -1] true))))
(testing "with boolean expression"
(is (= "true" (expr-to-string [:expression true]))))
(testing "with function of one variable"
(is (= "fn(1)" (expr-to-string [:function :fn [:expression 1]]))))
(testing "with function of two variables"
(is (= "fn(x,y)" (expr-to-string [:function :fn [:expression :x] [:expression :y]]))))
(testing "with avg function"
(is (= "avg(x)" (expr-to-string [:function :avg [:expression :x]]))))
(testing "with stddev function"
(is (= "stddev(x)" (expr-to-string [:function :stddev [:expression :x]]))))
(testing "with percentile function"
(is (= "percentile(x,99)" (expr-to-string [:function :percentile [:expression :x] [:expression 99]]))))
(testing "with isexist function"
(is (= "isexist(x)" (expr-to-string [:isexist-function [:expression :x]]))))
(testing "with not expression"
(is (= "!x" (expr-to-string [:expression [:not-operation :x]]))))
(testing "with and expression"
(is (= "x and y" (expr-to-string [:expression [:and-operation :x :y]]))))
(testing "with or expression"
(is (= "x or y" (expr-to-string [:expression [:or-operation :x :y]]))))
(testing "with xor expression"
(is (= "x xor y" (expr-to-string [:expression [:xor-operation :x :y]]))))
(testing "with negation expression"
(is (= "-x" (expr-to-string [:expression [:negation-operation :x]]))))
(testing "with addition expression"
(is (= "x+y" (expr-to-string [:expression [:addition-operation :x :y]]))))
(testing "with subtraction expression"
(is (= "x-y" (expr-to-string [:expression [:subtraction-operation :x :y]]))))
(testing "with multiplication expression"
(is (= "x*y" (expr-to-string [:expression [:multiplication-operation :x :y]]))))
(testing "with division expression"
(is (= "x/y" (expr-to-string [:expression [:division-operation :x :y]]))))
(testing "with equals expression"
(is (= "x==y" (expr-to-string [:expression [:equals-expression :x :y]]))))
(testing "with not equals expression"
(is (= "x!=y" (expr-to-string [:expression [:not-equals-expression :x :y]]))))
(testing "with less than expression"
(is (= "x<y" (expr-to-string [:expression [:less-than-expression :x :y]]))))
(testing "with less or equals expression"
(is (= "x<=y" (expr-to-string [:expression [:less-or-equals-expression :x :y]]))))
(testing "with greater than expression"
(is (= "x>y" (expr-to-string [:expression [:greater-than-expression :x :y]]))))
(testing "with greater or equals expression"
(is (= "x>=y" (expr-to-string [:expression [:greater-or-equals-expression :x :y]])))))
(deftest mask-password-in-string-test
(testing "with no password"
(is (= "" (mask-password-in-string "")))
(is (= "input mock" (mask-password-in-string "input mock")))
(is (= "input mock | select password | sort name asc" (mask-password-in-string "input mock | select password | sort name asc"))))
(testing "with password in single quotes"
(is (= "password=''" (mask-password-in-string "password=''")))
(is (= "password='' query='..'" (mask-password-in-string "password='' query='..'")))
(is (= "password='******'" (mask-password-in-string "password='secret'")))
(is (= "password = '******'" (mask-password-in-string "password = 'secret'")))
(is (= "password='******' | password='***'" (mask-password-in-string "password='secret' | password='abc'")))
(is (= "user='joe' password='************'" (mask-password-in-string "user='joe' password='secret \\\"x\\\"'"))))
(testing "with password in double quotes"
(is (= "password=\"\"" (mask-password-in-string "password=\"\"")))
(is (= "password=\"******\"" (mask-password-in-string "password=\"secret\"")))
(is (= "password = \"******\"" (mask-password-in-string "password = \"secret\"")))
(is (= "password=\"******\" | password=\"***\"" (mask-password-in-string "password=\"secret\" | password=\"abc\"")))
(is (= "user=\"joe\" password=\"************\"" (mask-password-in-string "user=\"joe\" password=\"secret \\\"x\\\"\""))))
(testing "with password in triple quotes"
(is (= "password=''''''" (mask-password-in-string "password=''''''")))
(is (= "password='''******'''" (mask-password-in-string "password='''secret'''")))
(is (= "password = '''******'''" (mask-password-in-string "password = '''secret'''")))
(is (= "password='''******''' | password='''***'''" (mask-password-in-string "password='''secret''' | password='''abc'''")))
(is (= "user='''joe''' password='''************'''" (mask-password-in-string "user='''joe''' password='''secret \\\"x\\\"'''"))))
(testing "with unquoted password"
(is (= "\"password=****;\"" (mask-password-in-string "\"password=mask;\"")))
(is (= "\"password=****\"" (mask-password-in-string "\"password=mask\"")))
(is (= " uri=\"jdbc:...?user=bmx&password=****;\" | " (mask-password-in-string " uri=\"jdbc:...?user=bmx&password=mask;\" | ")))
(is (= " uri=\"jdbc:...?user=bmx&password=****\" | " (mask-password-in-string " uri=\"jdbc:...?user=bmx&password=mask\" | ")))
(is (= " uri='jdbc:...?user=bmx&password=****;' | " (mask-password-in-string " uri='jdbc:...?user=bmx&password=mask;' | ")))
(is (= " uri='jdbc:...?user=bmx&password=****' | " (mask-password-in-string " uri='jdbc:...?user=bmx&password=mask' | "))))
(testing "with password in map in single quotes"
(is (= "password:''" (mask-password-in-string "password:''")))
(is (= "password:'******'" (mask-password-in-string "password:'secret'")))
(is (= "password : '******'" (mask-password-in-string "password : 'secret'")))
(is (= "password: '******' | password: '***'" (mask-password-in-string "password: 'secret' | password: 'abc'")))
(is (= "'password': '******' | 'password': '***'" (mask-password-in-string "'password': 'secret' | 'password': 'abc'"))))
(testing "with password in map in double quotes"
(is (= "password:\"\"" (mask-password-in-string "password:\"\"")))
(is (= "password:\"******\"" (mask-password-in-string "password:\"secret\"")))
(is (= "password : \"******\"" (mask-password-in-string "password : \"secret\"")))
(is (= "password: \"******\" | password: \"***\"" (mask-password-in-string "password: \"secret\" | password: \"abc\"")))
(is (= "\"password\": \"******\", \"password\": \"***\"" (mask-password-in-string "\"password\": \"secret\", \"password\": \"abc\""))))
(testing "with password in map in triple quotes"
(is (= "password:''''''" (mask-password-in-string "password:''''''")))
(is (= "password:'''******'''" (mask-password-in-string "password:'''secret'''")))
(is (= "password : '''******'''" (mask-password-in-string "password : '''secret'''")))
(is (= "password: '''******''' | password: '''***'''" (mask-password-in-string "password: '''secret''' | password: '''abc'''")))
(is (= "'''password''': '''******''' | '''password''': '''***'''" (mask-password-in-string "'''password''': '''secret''' | '''password''': '''abc'''"))))
)
(deftest apply-default-http-options-test
(testing "with nil"
(is (nil? (apply-default-http-options nil nil))))
(testing "with maps"
(is (= { :x 1 :y 2 } (apply-default-http-options { } { :x 1 :y 2})))
(is (= { :x 1 :y 2 } (apply-default-http-options { :x 1 :y 2} { })))
(is (= { :x 0 :y 2 } (apply-default-http-options { :x 0 } { :x 1 :y 2})))
(is (= { :x 1 :y 2 :z 3 } (apply-default-http-options { :z 3 } { :x 1 :y 2})))
(is (= { :auth { :user "dave" :password "secret123" :preemptive true } }
(apply-default-http-options { :user "dave" :password "secret123"} {})))
(is (= { :auth { :user "dave" :password "secret123" :preemptive true } }
(apply-default-http-options { :username "dave" :password "secret123"} {})))))
(deftest urldecode-test
(testing "with string"
(is (= "hello world" (urldecode "hello+world")))))
(deftest urlencode-test
(testing "with string"
(is (= "hello+world" (urlencode "hello world")))))
| 81974 | (ns parsec.helpers-test
(:require [clojure.test :refer :all]
[parsec.helpers :refer :all]
[parsec.test-helpers :refer :all]))
(deftest always-predicate-test
(testing "with nil"
(is (true? (always-predicate nil nil)))))
(deftest any-pred?-test
(testing "with nils"
(is (false? (any-pred? true? nil))))
(testing "with vector of booleans"
(is (true? (any-pred? true? [false true false])))
(is (false? (any-pred? true? [false false false])))
(is (true? (any-pred? false? [false true false])))
(is (false? (any-pred? false? [true true true])))))
(deftest in?-test
(testing "with empty list"
(is (false? (in? '() 1)))
(is (false? (in? '() nil))))
(testing "with empty vector"
(is (false? (in? [] 1)))
(is (false? (in? [] nil))))
(testing "with nil list"
(is (false? (in? nil 1)))
(is (false? (in? nil nil))))
(testing "with lists"
(is (true? (in? '(nil) nil)))
(is (true? (in? '(nil nil) nil)))
(is (true? (in? '(1 2 nil 3) nil)))
(is (false? (in? '(1 2 3 4) nil)))
(is (false? (in? '(1 2 3 4) 5)))
(is (true? (in? '(1 2 3 4) 3)))
(is (false? (in? '("x" "y" "z") "w")))
(is (true? (in? '("x" "y" "z") "x"))))
(testing "with vectors"
(is (true? (in? [nil] nil)))
(is (true? (in? [nil nil] nil)))
(is (true? (in? [1 2 nil 3] nil)))
(is (false? (in? [1 2 3 4] nil)))
(is (false? (in? [1 2 3 4] 5)))
(is (true? (in? [1 2 3 4] 3)))
(is (false? (in? ["x" "y" "z"] "w")))
(is (true? (in? ["x" "y" "z"] "x"))))
(testing "with strings"
(is (false? (in? "hello world" nil)))
(is (true? (in? "hello world" "hello")))
(is (false? (in? "hello world" "Hello")))
(is (true? (in? "555-4445" 5)))
(is (false? (in? "555-1445" 9)))))
(deftest mapmapv-test
(testing "with nil map"
(is (nil? (mapmapv identity nil))))
(testing "with empty map"
(is (= {} (mapmapv identity {}))))
(testing "with identity"
(is (= { :a 1 } (mapmapv identity { :a 1 }))))
(testing "with fn"
(is (= { :a 2 :b 2 } (mapmapv #(+ 1 %) { :a 1 :b 1 })))
(is (= { :a 3 :b 5 } (mapmapv count { :a [1,2,3] :b [4,5,6,7,8] }))))
(testing "with nil function"
(is (thrown? NullPointerException (mapmapv nil { :a 1 }))))
(testing "with vector"
(is (thrown? UnsupportedOperationException (mapmapv identity [1 2 3])))))
(deftest mapply-test
(testing "with nil map"
(is (zero? (mapply + nil))))
(testing "with empty map"
(is (zero? (mapply + { }))))
(testing "with nil map"
(is (= ":x1:y2" (mapply #(str % %2 %3 %4) { :x 1 :y 2 }))))
(testing "with empty map"
(is (= 10 (mapply + { 1 2 3 4 })))))
(deftest mapcat2-test
(testing "with nil map"
(is (empty? (mapcat2 identity nil))))
(testing "with empty list"
(is (empty? (mapcat2 identity []))))
(testing "with single element"
(is (= [1] (mapcat2 identity [1]))))
(testing "with multiple elements"
(is (= [1 2 3] (mapcat2 identity [1 2 3]))))
(testing "with lists returned"
(is (= [1 2 2 4 3 6] (mapcat2 #(vector % (* 2 %)) [1 2 3])))))
(deftest xor-test
(testing "with nil"
(is (false? (xor nil nil))))
(testing "with booleans"
(is (false? (xor true true)))
(is (false? (xor false false)))
(is (true? (xor false true)))
(is (true? (xor true false)))))
(deftest eval-expression-test
(testing "nil"
(is (nil? (eval-expression nil {} {}))))
(testing "number"
(is (= 444 (eval-expression 444 {} {}))))
(testing "keyword"
(is (= 155 (eval-expression :col1 { :col1 155 } {}))))
(testing "variable"
(is (= 42 (eval-expression [:variable "@V1"] {} { :variables { "@V1" 42 }}))))
(testing "function"
(is (= 1 (eval-expression (fn [_ _] 1) {} { :variables { }})))))
(deftest eval-expression-without-row-test
(testing "nil"
(is (nil? (eval-expression-without-row nil {}))))
(testing "number"
(is (= 444 (eval-expression-without-row 444 {}))))
(testing "keyword"
(is (thrown? Exception (eval-expression-without-row :col1 {}))))
(testing "variable"
(is (= 42 (eval-expression-without-row [:variable "@V1"] { :variables { "@V1" 42 }}))))
(testing "function"
(is (= 1 (eval-expression-without-row (fn [_ _] 1) { :variables { }})))))
(deftest expr-to-string-test
(testing "with list"
(is (= "[1,2,3]" (expr-to-string [1,2,3]))))
(testing "with string"
(is (= "hello" (expr-to-string "hello"))))
(testing "with string expression"
(is (= "hello" (expr-to-string [:expression "hello"]))))
(testing "with wrapped string expression"
(is (= "(hello)" (expr-to-string [:expression "hello"] true))))
(testing "with numerical expression"
(is (= "-1" (expr-to-string [:expression -1]))))
(testing "with wrapped numerical expression"
(is (= "(-1)" (expr-to-string [:expression -1] true))))
(testing "with boolean expression"
(is (= "true" (expr-to-string [:expression true]))))
(testing "with function of one variable"
(is (= "fn(1)" (expr-to-string [:function :fn [:expression 1]]))))
(testing "with function of two variables"
(is (= "fn(x,y)" (expr-to-string [:function :fn [:expression :x] [:expression :y]]))))
(testing "with avg function"
(is (= "avg(x)" (expr-to-string [:function :avg [:expression :x]]))))
(testing "with stddev function"
(is (= "stddev(x)" (expr-to-string [:function :stddev [:expression :x]]))))
(testing "with percentile function"
(is (= "percentile(x,99)" (expr-to-string [:function :percentile [:expression :x] [:expression 99]]))))
(testing "with isexist function"
(is (= "isexist(x)" (expr-to-string [:isexist-function [:expression :x]]))))
(testing "with not expression"
(is (= "!x" (expr-to-string [:expression [:not-operation :x]]))))
(testing "with and expression"
(is (= "x and y" (expr-to-string [:expression [:and-operation :x :y]]))))
(testing "with or expression"
(is (= "x or y" (expr-to-string [:expression [:or-operation :x :y]]))))
(testing "with xor expression"
(is (= "x xor y" (expr-to-string [:expression [:xor-operation :x :y]]))))
(testing "with negation expression"
(is (= "-x" (expr-to-string [:expression [:negation-operation :x]]))))
(testing "with addition expression"
(is (= "x+y" (expr-to-string [:expression [:addition-operation :x :y]]))))
(testing "with subtraction expression"
(is (= "x-y" (expr-to-string [:expression [:subtraction-operation :x :y]]))))
(testing "with multiplication expression"
(is (= "x*y" (expr-to-string [:expression [:multiplication-operation :x :y]]))))
(testing "with division expression"
(is (= "x/y" (expr-to-string [:expression [:division-operation :x :y]]))))
(testing "with equals expression"
(is (= "x==y" (expr-to-string [:expression [:equals-expression :x :y]]))))
(testing "with not equals expression"
(is (= "x!=y" (expr-to-string [:expression [:not-equals-expression :x :y]]))))
(testing "with less than expression"
(is (= "x<y" (expr-to-string [:expression [:less-than-expression :x :y]]))))
(testing "with less or equals expression"
(is (= "x<=y" (expr-to-string [:expression [:less-or-equals-expression :x :y]]))))
(testing "with greater than expression"
(is (= "x>y" (expr-to-string [:expression [:greater-than-expression :x :y]]))))
(testing "with greater or equals expression"
(is (= "x>=y" (expr-to-string [:expression [:greater-or-equals-expression :x :y]])))))
(deftest mask-password-in-string-test
(testing "with no password"
(is (= "" (mask-password-in-string "")))
(is (= "input mock" (mask-password-in-string "input mock")))
(is (= "input mock | select password | sort name asc" (mask-password-in-string "input mock | select password | sort name asc"))))
(testing "with password in single quotes"
(is (= "password=''" (mask-password-in-string "password=''")))
(is (= "password='' query='..'" (mask-password-in-string "password='' query='..'")))
(is (= "password='<PASSWORD>******'" (mask-password-in-string "password='<PASSWORD>'")))
(is (= "password = '<PASSWORD>******'" (mask-password-in-string "password = '<PASSWORD>'")))
(is (= "password='<PASSWORD>******' | password='***'" (mask-password-in-string "password='<PASSWORD>' | password='<PASSWORD>'")))
(is (= "user='joe' password='<PASSWORD>************'" (mask-password-in-string "user='joe' password='<PASSWORD> \\\"<PASSWORD>\\\"'"))))
(testing "with password in double quotes"
(is (= "password=\"\"" (mask-password-in-string "password=\"\"")))
(is (= "password=\"******\"" (mask-password-in-string "password=\"secret\"")))
(is (= "password = \"******\"" (mask-password-in-string "password = \"secret\"")))
(is (= "password=\"******\" | password=\"***\"" (mask-password-in-string "password=\"secret\" | password=\"abc\"")))
(is (= "user=\"joe\" password=\"************\"" (mask-password-in-string "user=\"joe\" password=\"secret \\\"x\\\"\""))))
(testing "with password in triple quotes"
(is (= "password=''''''" (mask-password-in-string "password=''''''")))
(is (= "password='''<PASSWORD>******'''" (mask-password-in-string "password='''<PASSWORD>'''")))
(is (= "password = '''******'''" (mask-password-in-string "password = '''secret'''")))
(is (= "password='''<PASSWORD>******''' | password='''<PASSWORD>***'''" (mask-password-in-string "password='''<PASSWORD>''' | password='''<PASSWORD>'''")))
(is (= "user='''joe''' password='''<PASSWORD>************'''" (mask-password-in-string "user='''joe''' password='''secret \\\"<PASSWORD>\\\"'''"))))
(testing "with unquoted password"
(is (= "\"password=****;\"" (mask-password-in-string "\"password=mask;\"")))
(is (= "\"password=****\"" (mask-password-in-string "\"password=mask\"")))
(is (= " uri=\"jdbc:...?user=bmx&password=****;\" | " (mask-password-in-string " uri=\"jdbc:...?user=bmx&password=mask;\" | ")))
(is (= " uri=\"jdbc:...?user=bmx&password=****\" | " (mask-password-in-string " uri=\"jdbc:...?user=bmx&password=mask\" | ")))
(is (= " uri='jdbc:...?user=bmx&password=****;' | " (mask-password-in-string " uri='jdbc:...?user=bmx&password=mask;' | ")))
(is (= " uri='jdbc:...?user=bmx&password=****' | " (mask-password-in-string " uri='jdbc:...?user=bmx&password=mask' | "))))
(testing "with password in map in single quotes"
(is (= "password:''" (mask-password-in-string "password:''")))
(is (= "password:'******'" (mask-password-in-string "password:'secret'")))
(is (= "password : '******'" (mask-password-in-string "password : 'secret'")))
(is (= "password: '<PASSWORD>******' | password: '***'" (mask-password-in-string "password: 'secret' | password: '<PASSWORD>'")))
(is (= "'password': '******' | 'password': '***'" (mask-password-in-string "'password': 'secret' | 'password': '<PASSWORD>'"))))
(testing "with password in map in double quotes"
(is (= "password:\"\"" (mask-password-in-string "password:\"\"")))
(is (= "password:\"******\"" (mask-password-in-string "password:\"secret\"")))
(is (= "password : \"******\"" (mask-password-in-string "password : \"secret\"")))
(is (= "password: \"******\" | password: \"***\"" (mask-password-in-string "password: \"secret\" | password: \"abc\"")))
(is (= "\"password\": \"******\", \"password\": \"***\"" (mask-password-in-string "\"password\": \"secret\", \"password\": \"abc\""))))
(testing "with password in map in triple quotes"
(is (= "password:''''''" (mask-password-in-string "password:''''''")))
(is (= "password:'''******'''" (mask-password-in-string "password:'''secret'''")))
(is (= "password : '''******'''" (mask-password-in-string "password : '''secret'''")))
(is (= "password: '''<PASSWORD>******''' | password: '''***'''" (mask-password-in-string "password: '''secret''' | password: '''<PASSWORD>'''")))
(is (= "'''password''': '''******''' | '''password''': '''***'''" (mask-password-in-string "'''password''': '''secret''' | '''password''': '''<PASSWORD>'''"))))
)
(deftest apply-default-http-options-test
(testing "with nil"
(is (nil? (apply-default-http-options nil nil))))
(testing "with maps"
(is (= { :x 1 :y 2 } (apply-default-http-options { } { :x 1 :y 2})))
(is (= { :x 1 :y 2 } (apply-default-http-options { :x 1 :y 2} { })))
(is (= { :x 0 :y 2 } (apply-default-http-options { :x 0 } { :x 1 :y 2})))
(is (= { :x 1 :y 2 :z 3 } (apply-default-http-options { :z 3 } { :x 1 :y 2})))
(is (= { :auth { :user "dave" :password "<PASSWORD>" :preemptive true } }
(apply-default-http-options { :user "dave" :password "<PASSWORD>"} {})))
(is (= { :auth { :user "dave" :password "<PASSWORD>" :preemptive true } }
(apply-default-http-options { :username "dave" :password "<PASSWORD>"} {})))))
(deftest urldecode-test
(testing "with string"
(is (= "hello world" (urldecode "hello+world")))))
(deftest urlencode-test
(testing "with string"
(is (= "hello+world" (urlencode "hello world")))))
| true | (ns parsec.helpers-test
(:require [clojure.test :refer :all]
[parsec.helpers :refer :all]
[parsec.test-helpers :refer :all]))
(deftest always-predicate-test
(testing "with nil"
(is (true? (always-predicate nil nil)))))
(deftest any-pred?-test
(testing "with nils"
(is (false? (any-pred? true? nil))))
(testing "with vector of booleans"
(is (true? (any-pred? true? [false true false])))
(is (false? (any-pred? true? [false false false])))
(is (true? (any-pred? false? [false true false])))
(is (false? (any-pred? false? [true true true])))))
(deftest in?-test
(testing "with empty list"
(is (false? (in? '() 1)))
(is (false? (in? '() nil))))
(testing "with empty vector"
(is (false? (in? [] 1)))
(is (false? (in? [] nil))))
(testing "with nil list"
(is (false? (in? nil 1)))
(is (false? (in? nil nil))))
(testing "with lists"
(is (true? (in? '(nil) nil)))
(is (true? (in? '(nil nil) nil)))
(is (true? (in? '(1 2 nil 3) nil)))
(is (false? (in? '(1 2 3 4) nil)))
(is (false? (in? '(1 2 3 4) 5)))
(is (true? (in? '(1 2 3 4) 3)))
(is (false? (in? '("x" "y" "z") "w")))
(is (true? (in? '("x" "y" "z") "x"))))
(testing "with vectors"
(is (true? (in? [nil] nil)))
(is (true? (in? [nil nil] nil)))
(is (true? (in? [1 2 nil 3] nil)))
(is (false? (in? [1 2 3 4] nil)))
(is (false? (in? [1 2 3 4] 5)))
(is (true? (in? [1 2 3 4] 3)))
(is (false? (in? ["x" "y" "z"] "w")))
(is (true? (in? ["x" "y" "z"] "x"))))
(testing "with strings"
(is (false? (in? "hello world" nil)))
(is (true? (in? "hello world" "hello")))
(is (false? (in? "hello world" "Hello")))
(is (true? (in? "555-4445" 5)))
(is (false? (in? "555-1445" 9)))))
(deftest mapmapv-test
(testing "with nil map"
(is (nil? (mapmapv identity nil))))
(testing "with empty map"
(is (= {} (mapmapv identity {}))))
(testing "with identity"
(is (= { :a 1 } (mapmapv identity { :a 1 }))))
(testing "with fn"
(is (= { :a 2 :b 2 } (mapmapv #(+ 1 %) { :a 1 :b 1 })))
(is (= { :a 3 :b 5 } (mapmapv count { :a [1,2,3] :b [4,5,6,7,8] }))))
(testing "with nil function"
(is (thrown? NullPointerException (mapmapv nil { :a 1 }))))
(testing "with vector"
(is (thrown? UnsupportedOperationException (mapmapv identity [1 2 3])))))
(deftest mapply-test
(testing "with nil map"
(is (zero? (mapply + nil))))
(testing "with empty map"
(is (zero? (mapply + { }))))
(testing "with nil map"
(is (= ":x1:y2" (mapply #(str % %2 %3 %4) { :x 1 :y 2 }))))
(testing "with empty map"
(is (= 10 (mapply + { 1 2 3 4 })))))
(deftest mapcat2-test
(testing "with nil map"
(is (empty? (mapcat2 identity nil))))
(testing "with empty list"
(is (empty? (mapcat2 identity []))))
(testing "with single element"
(is (= [1] (mapcat2 identity [1]))))
(testing "with multiple elements"
(is (= [1 2 3] (mapcat2 identity [1 2 3]))))
(testing "with lists returned"
(is (= [1 2 2 4 3 6] (mapcat2 #(vector % (* 2 %)) [1 2 3])))))
(deftest xor-test
(testing "with nil"
(is (false? (xor nil nil))))
(testing "with booleans"
(is (false? (xor true true)))
(is (false? (xor false false)))
(is (true? (xor false true)))
(is (true? (xor true false)))))
(deftest eval-expression-test
(testing "nil"
(is (nil? (eval-expression nil {} {}))))
(testing "number"
(is (= 444 (eval-expression 444 {} {}))))
(testing "keyword"
(is (= 155 (eval-expression :col1 { :col1 155 } {}))))
(testing "variable"
(is (= 42 (eval-expression [:variable "@V1"] {} { :variables { "@V1" 42 }}))))
(testing "function"
(is (= 1 (eval-expression (fn [_ _] 1) {} { :variables { }})))))
(deftest eval-expression-without-row-test
(testing "nil"
(is (nil? (eval-expression-without-row nil {}))))
(testing "number"
(is (= 444 (eval-expression-without-row 444 {}))))
(testing "keyword"
(is (thrown? Exception (eval-expression-without-row :col1 {}))))
(testing "variable"
(is (= 42 (eval-expression-without-row [:variable "@V1"] { :variables { "@V1" 42 }}))))
(testing "function"
(is (= 1 (eval-expression-without-row (fn [_ _] 1) { :variables { }})))))
(deftest expr-to-string-test
(testing "with list"
(is (= "[1,2,3]" (expr-to-string [1,2,3]))))
(testing "with string"
(is (= "hello" (expr-to-string "hello"))))
(testing "with string expression"
(is (= "hello" (expr-to-string [:expression "hello"]))))
(testing "with wrapped string expression"
(is (= "(hello)" (expr-to-string [:expression "hello"] true))))
(testing "with numerical expression"
(is (= "-1" (expr-to-string [:expression -1]))))
(testing "with wrapped numerical expression"
(is (= "(-1)" (expr-to-string [:expression -1] true))))
(testing "with boolean expression"
(is (= "true" (expr-to-string [:expression true]))))
(testing "with function of one variable"
(is (= "fn(1)" (expr-to-string [:function :fn [:expression 1]]))))
(testing "with function of two variables"
(is (= "fn(x,y)" (expr-to-string [:function :fn [:expression :x] [:expression :y]]))))
(testing "with avg function"
(is (= "avg(x)" (expr-to-string [:function :avg [:expression :x]]))))
(testing "with stddev function"
(is (= "stddev(x)" (expr-to-string [:function :stddev [:expression :x]]))))
(testing "with percentile function"
(is (= "percentile(x,99)" (expr-to-string [:function :percentile [:expression :x] [:expression 99]]))))
(testing "with isexist function"
(is (= "isexist(x)" (expr-to-string [:isexist-function [:expression :x]]))))
(testing "with not expression"
(is (= "!x" (expr-to-string [:expression [:not-operation :x]]))))
(testing "with and expression"
(is (= "x and y" (expr-to-string [:expression [:and-operation :x :y]]))))
(testing "with or expression"
(is (= "x or y" (expr-to-string [:expression [:or-operation :x :y]]))))
(testing "with xor expression"
(is (= "x xor y" (expr-to-string [:expression [:xor-operation :x :y]]))))
(testing "with negation expression"
(is (= "-x" (expr-to-string [:expression [:negation-operation :x]]))))
(testing "with addition expression"
(is (= "x+y" (expr-to-string [:expression [:addition-operation :x :y]]))))
(testing "with subtraction expression"
(is (= "x-y" (expr-to-string [:expression [:subtraction-operation :x :y]]))))
(testing "with multiplication expression"
(is (= "x*y" (expr-to-string [:expression [:multiplication-operation :x :y]]))))
(testing "with division expression"
(is (= "x/y" (expr-to-string [:expression [:division-operation :x :y]]))))
(testing "with equals expression"
(is (= "x==y" (expr-to-string [:expression [:equals-expression :x :y]]))))
(testing "with not equals expression"
(is (= "x!=y" (expr-to-string [:expression [:not-equals-expression :x :y]]))))
(testing "with less than expression"
(is (= "x<y" (expr-to-string [:expression [:less-than-expression :x :y]]))))
(testing "with less or equals expression"
(is (= "x<=y" (expr-to-string [:expression [:less-or-equals-expression :x :y]]))))
(testing "with greater than expression"
(is (= "x>y" (expr-to-string [:expression [:greater-than-expression :x :y]]))))
(testing "with greater or equals expression"
(is (= "x>=y" (expr-to-string [:expression [:greater-or-equals-expression :x :y]])))))
(deftest mask-password-in-string-test
(testing "with no password"
(is (= "" (mask-password-in-string "")))
(is (= "input mock" (mask-password-in-string "input mock")))
(is (= "input mock | select password | sort name asc" (mask-password-in-string "input mock | select password | sort name asc"))))
(testing "with password in single quotes"
(is (= "password=''" (mask-password-in-string "password=''")))
(is (= "password='' query='..'" (mask-password-in-string "password='' query='..'")))
(is (= "password='PI:PASSWORD:<PASSWORD>END_PI******'" (mask-password-in-string "password='PI:PASSWORD:<PASSWORD>END_PI'")))
(is (= "password = 'PI:PASSWORD:<PASSWORD>END_PI******'" (mask-password-in-string "password = 'PI:PASSWORD:<PASSWORD>END_PI'")))
(is (= "password='PI:PASSWORD:<PASSWORD>END_PI******' | password='***'" (mask-password-in-string "password='PI:PASSWORD:<PASSWORD>END_PI' | password='PI:PASSWORD:<PASSWORD>END_PI'")))
(is (= "user='joe' password='PI:PASSWORD:<PASSWORD>END_PI************'" (mask-password-in-string "user='joe' password='PI:PASSWORD:<PASSWORD>END_PI \\\"PI:PASSWORD:<PASSWORD>END_PI\\\"'"))))
(testing "with password in double quotes"
(is (= "password=\"\"" (mask-password-in-string "password=\"\"")))
(is (= "password=\"******\"" (mask-password-in-string "password=\"secret\"")))
(is (= "password = \"******\"" (mask-password-in-string "password = \"secret\"")))
(is (= "password=\"******\" | password=\"***\"" (mask-password-in-string "password=\"secret\" | password=\"abc\"")))
(is (= "user=\"joe\" password=\"************\"" (mask-password-in-string "user=\"joe\" password=\"secret \\\"x\\\"\""))))
(testing "with password in triple quotes"
(is (= "password=''''''" (mask-password-in-string "password=''''''")))
(is (= "password='''PI:PASSWORD:<PASSWORD>END_PI******'''" (mask-password-in-string "password='''PI:PASSWORD:<PASSWORD>END_PI'''")))
(is (= "password = '''******'''" (mask-password-in-string "password = '''secret'''")))
(is (= "password='''PI:PASSWORD:<PASSWORD>END_PI******''' | password='''PI:PASSWORD:<PASSWORD>END_PI***'''" (mask-password-in-string "password='''PI:PASSWORD:<PASSWORD>END_PI''' | password='''PI:PASSWORD:<PASSWORD>END_PI'''")))
(is (= "user='''joe''' password='''PI:PASSWORD:<PASSWORD>END_PI************'''" (mask-password-in-string "user='''joe''' password='''secret \\\"PI:PASSWORD:<PASSWORD>END_PI\\\"'''"))))
(testing "with unquoted password"
(is (= "\"password=****;\"" (mask-password-in-string "\"password=mask;\"")))
(is (= "\"password=****\"" (mask-password-in-string "\"password=mask\"")))
(is (= " uri=\"jdbc:...?user=bmx&password=****;\" | " (mask-password-in-string " uri=\"jdbc:...?user=bmx&password=mask;\" | ")))
(is (= " uri=\"jdbc:...?user=bmx&password=****\" | " (mask-password-in-string " uri=\"jdbc:...?user=bmx&password=mask\" | ")))
(is (= " uri='jdbc:...?user=bmx&password=****;' | " (mask-password-in-string " uri='jdbc:...?user=bmx&password=mask;' | ")))
(is (= " uri='jdbc:...?user=bmx&password=****' | " (mask-password-in-string " uri='jdbc:...?user=bmx&password=mask' | "))))
(testing "with password in map in single quotes"
(is (= "password:''" (mask-password-in-string "password:''")))
(is (= "password:'******'" (mask-password-in-string "password:'secret'")))
(is (= "password : '******'" (mask-password-in-string "password : 'secret'")))
(is (= "password: 'PI:PASSWORD:<PASSWORD>END_PI******' | password: '***'" (mask-password-in-string "password: 'secret' | password: 'PI:PASSWORD:<PASSWORD>END_PI'")))
(is (= "'password': '******' | 'password': '***'" (mask-password-in-string "'password': 'secret' | 'password': 'PI:PASSWORD:<PASSWORD>END_PI'"))))
(testing "with password in map in double quotes"
(is (= "password:\"\"" (mask-password-in-string "password:\"\"")))
(is (= "password:\"******\"" (mask-password-in-string "password:\"secret\"")))
(is (= "password : \"******\"" (mask-password-in-string "password : \"secret\"")))
(is (= "password: \"******\" | password: \"***\"" (mask-password-in-string "password: \"secret\" | password: \"abc\"")))
(is (= "\"password\": \"******\", \"password\": \"***\"" (mask-password-in-string "\"password\": \"secret\", \"password\": \"abc\""))))
(testing "with password in map in triple quotes"
(is (= "password:''''''" (mask-password-in-string "password:''''''")))
(is (= "password:'''******'''" (mask-password-in-string "password:'''secret'''")))
(is (= "password : '''******'''" (mask-password-in-string "password : '''secret'''")))
(is (= "password: '''PI:PASSWORD:<PASSWORD>END_PI******''' | password: '''***'''" (mask-password-in-string "password: '''secret''' | password: '''PI:PASSWORD:<PASSWORD>END_PI'''")))
(is (= "'''password''': '''******''' | '''password''': '''***'''" (mask-password-in-string "'''password''': '''secret''' | '''password''': '''PI:PASSWORD:<PASSWORD>END_PI'''"))))
)
(deftest apply-default-http-options-test
(testing "with nil"
(is (nil? (apply-default-http-options nil nil))))
(testing "with maps"
(is (= { :x 1 :y 2 } (apply-default-http-options { } { :x 1 :y 2})))
(is (= { :x 1 :y 2 } (apply-default-http-options { :x 1 :y 2} { })))
(is (= { :x 0 :y 2 } (apply-default-http-options { :x 0 } { :x 1 :y 2})))
(is (= { :x 1 :y 2 :z 3 } (apply-default-http-options { :z 3 } { :x 1 :y 2})))
(is (= { :auth { :user "dave" :password "PI:PASSWORD:<PASSWORD>END_PI" :preemptive true } }
(apply-default-http-options { :user "dave" :password "PI:PASSWORD:<PASSWORD>END_PI"} {})))
(is (= { :auth { :user "dave" :password "PI:PASSWORD:<PASSWORD>END_PI" :preemptive true } }
(apply-default-http-options { :username "dave" :password "PI:PASSWORD:<PASSWORD>END_PI"} {})))))
(deftest urldecode-test
(testing "with string"
(is (= "hello world" (urldecode "hello+world")))))
(deftest urlencode-test
(testing "with string"
(is (= "hello+world" (urlencode "hello world")))))
|
[
{
"context": "th headers and status\"\n (is (= {:body {:email \"foo@bar.com\", :id 1}, :status 201, :headers {:content-type :a",
"end": 1077,
"score": 0.999914824962616,
"start": 1066,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": "on/json}}\n (try-to-create-user {:email \"FOO@BAR.COM\", :new-user nil}))))\n\n (testing \"Should return a",
"end": 1196,
"score": 0.999915599822998,
"start": 1185,
"tag": "EMAIL",
"value": "FOO@BAR.COM"
},
{
"context": "urn a success Ring's response\"\n (is (= {:body \"foo@bar.com\", :status 200, :headers {}}\n (rop/>>=* ",
"end": 1487,
"score": 0.9999159574508667,
"start": 1476,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": " (rop/>>=* :email\n {:email \"FOO@BAR.COM\"}\n (rop/switch format-email)\n",
"end": 1585,
"score": 0.9999176859855652,
"start": 1574,
"tag": "EMAIL",
"value": "FOO@BAR.COM"
},
{
"context": "user #{:id}]\n {:email \"FOO@BAR.COM\", :new-user nil}\n (rop",
"end": 1863,
"score": 0.9999208450317383,
"start": 1852,
"tag": "EMAIL",
"value": "FOO@BAR.COM"
},
{
"context": "sers #{:id}]\n {:email \"FOO@BAR.COM\", :new-user nil, :new-users nil}\n ",
"end": 2294,
"score": 0.9999204874038696,
"start": 2283,
"tag": "EMAIL",
"value": "FOO@BAR.COM"
},
{
"context": "ing \"Should return a success\"\n (is (= {:email \"foo@bar.com\", :new-user {:email \"foo@bar.com\", :id 1}}\n ",
"end": 2682,
"score": 0.9999204874038696,
"start": 2671,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": " (is (= {:email \"foo@bar.com\", :new-user {:email \"foo@bar.com\", :id 1}}\n (rop/>>= {:email \"FOO@BAR.CO",
"end": 2715,
"score": 0.9999202489852905,
"start": 2704,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": "oo@bar.com\", :id 1}}\n (rop/>>= {:email \"FOO@BAR.COM\", :new-user nil}\n (rop/switch ",
"end": 2766,
"score": 0.9999207258224487,
"start": 2755,
"tag": "EMAIL",
"value": "FOO@BAR.COM"
}
] | test/rop/core_test.clj | staifa/rop | 0 | (ns rop.core-test
(:require
[clojure.string :refer [blank? lower-case]]
[clojure.test :refer [deftest is testing]]
[cats.core :as m]
[struct.core :as st]
[rop.core :as rop]))
(defn- format-email
[input]
(update input :email lower-case))
(defn- validate-email
[input]
(if (-> input :email blank?)
(rop/fail {:status 400, :body {:errors {:email ["Invalid format"]}}})
(rop/succeed input)))
(defn- create-user
[input]
(-> input
(assoc :new-user {:email (:email input), :id 1})
(assoc-in [:response :status] 201)
(assoc-in [:response :headers] {:content-type :application/json})))
(defn- send-email!
[input]
;; send e-mail here
(println "Sending e-mail"))
(defn try-to-create-user
[input]
(rop/>>=* :new-user
input
(rop/switch format-email)
validate-email
(rop/switch create-user)
(rop/dead send-email!)))
(deftest rop-test
(testing "Should return a success Ring's response with headers and status"
(is (= {:body {:email "foo@bar.com", :id 1}, :status 201, :headers {:content-type :application/json}}
(try-to-create-user {:email "FOO@BAR.COM", :new-user nil}))))
(testing "Should return a failure Ring's response"
(is (= {:body {:errors {:email ["Invalid format"]}} :status 400}
(try-to-create-user {:email "", :new-user nil}))))
(testing "Should return a success Ring's response"
(is (= {:body "foo@bar.com", :status 200, :headers {}}
(rop/>>=* :email
{:email "FOO@BAR.COM"}
(rop/switch format-email)
validate-email))))
(testing "Should return a success Ring's response with limited output"
(is (= {:id 1}
(:body (rop/>>=* [:new-user #{:id}]
{:email "FOO@BAR.COM", :new-user nil}
(rop/switch format-email)
validate-email
(rop/switch create-user)
(rop/dead send-email!))))))
(testing "Should return a success Ring's response with limited output on a collection"
(is (= [{:id 1}]
(:body (rop/>>=* [:new-users #{:id}]
{:email "FOO@BAR.COM", :new-user nil, :new-users nil}
(rop/switch format-email)
validate-email
(rop/switch create-user)
(rop/switch #(assoc % :new-users [(:new-user %)]))
(rop/dead send-email!))))))
(testing "Should return a success"
(is (= {:email "foo@bar.com", :new-user {:email "foo@bar.com", :id 1}}
(rop/>>= {:email "FOO@BAR.COM", :new-user nil}
(rop/switch format-email)
validate-email
(rop/switch #(assoc % :new-user {:email (:email %), :id 1}))
(rop/dead send-email!))))))
(deftest validate-request-test
(testing "should assoc a validated input"
(is (= {:request {:params {:id 1}}}
(m/extract (rop/=validate-request= st/validate
{:id [st/number-str]}
{}
:params
{:request {:params {:id "1"}}})))))
(testing "should assoc errors"
(is (= {:status 400, :body {:errors {:id "must be a number"}}}
(m/extract (rop/=validate-request= st/validate
{:id [st/number-str]}
{}
:params
{:request {:params {:id ""}}})))))
(testing "default values"
(is (= {:request {:params {:id 0, :a 1}}}
(m/extract (rop/=validate-request= st/validate
{:id [st/number-str], :a [st/number-str], :b [st/number-str]}
{:a 1}
:params
{:request {:params {:id "0"}}}))))))
(deftest merge-params-test
(is (= {:request {:params {:id 1, :foo :bar}, :body-params {:foo :bar}}}
(m/extract (rop/=merge-params= :body-params
:params
{:request {:params {:id 1}, :body-params {:foo :bar}}})))))
| 18837 | (ns rop.core-test
(:require
[clojure.string :refer [blank? lower-case]]
[clojure.test :refer [deftest is testing]]
[cats.core :as m]
[struct.core :as st]
[rop.core :as rop]))
(defn- format-email
[input]
(update input :email lower-case))
(defn- validate-email
[input]
(if (-> input :email blank?)
(rop/fail {:status 400, :body {:errors {:email ["Invalid format"]}}})
(rop/succeed input)))
(defn- create-user
[input]
(-> input
(assoc :new-user {:email (:email input), :id 1})
(assoc-in [:response :status] 201)
(assoc-in [:response :headers] {:content-type :application/json})))
(defn- send-email!
[input]
;; send e-mail here
(println "Sending e-mail"))
(defn try-to-create-user
[input]
(rop/>>=* :new-user
input
(rop/switch format-email)
validate-email
(rop/switch create-user)
(rop/dead send-email!)))
(deftest rop-test
(testing "Should return a success Ring's response with headers and status"
(is (= {:body {:email "<EMAIL>", :id 1}, :status 201, :headers {:content-type :application/json}}
(try-to-create-user {:email "<EMAIL>", :new-user nil}))))
(testing "Should return a failure Ring's response"
(is (= {:body {:errors {:email ["Invalid format"]}} :status 400}
(try-to-create-user {:email "", :new-user nil}))))
(testing "Should return a success Ring's response"
(is (= {:body "<EMAIL>", :status 200, :headers {}}
(rop/>>=* :email
{:email "<EMAIL>"}
(rop/switch format-email)
validate-email))))
(testing "Should return a success Ring's response with limited output"
(is (= {:id 1}
(:body (rop/>>=* [:new-user #{:id}]
{:email "<EMAIL>", :new-user nil}
(rop/switch format-email)
validate-email
(rop/switch create-user)
(rop/dead send-email!))))))
(testing "Should return a success Ring's response with limited output on a collection"
(is (= [{:id 1}]
(:body (rop/>>=* [:new-users #{:id}]
{:email "<EMAIL>", :new-user nil, :new-users nil}
(rop/switch format-email)
validate-email
(rop/switch create-user)
(rop/switch #(assoc % :new-users [(:new-user %)]))
(rop/dead send-email!))))))
(testing "Should return a success"
(is (= {:email "<EMAIL>", :new-user {:email "<EMAIL>", :id 1}}
(rop/>>= {:email "<EMAIL>", :new-user nil}
(rop/switch format-email)
validate-email
(rop/switch #(assoc % :new-user {:email (:email %), :id 1}))
(rop/dead send-email!))))))
(deftest validate-request-test
(testing "should assoc a validated input"
(is (= {:request {:params {:id 1}}}
(m/extract (rop/=validate-request= st/validate
{:id [st/number-str]}
{}
:params
{:request {:params {:id "1"}}})))))
(testing "should assoc errors"
(is (= {:status 400, :body {:errors {:id "must be a number"}}}
(m/extract (rop/=validate-request= st/validate
{:id [st/number-str]}
{}
:params
{:request {:params {:id ""}}})))))
(testing "default values"
(is (= {:request {:params {:id 0, :a 1}}}
(m/extract (rop/=validate-request= st/validate
{:id [st/number-str], :a [st/number-str], :b [st/number-str]}
{:a 1}
:params
{:request {:params {:id "0"}}}))))))
(deftest merge-params-test
(is (= {:request {:params {:id 1, :foo :bar}, :body-params {:foo :bar}}}
(m/extract (rop/=merge-params= :body-params
:params
{:request {:params {:id 1}, :body-params {:foo :bar}}})))))
| true | (ns rop.core-test
(:require
[clojure.string :refer [blank? lower-case]]
[clojure.test :refer [deftest is testing]]
[cats.core :as m]
[struct.core :as st]
[rop.core :as rop]))
(defn- format-email
[input]
(update input :email lower-case))
(defn- validate-email
[input]
(if (-> input :email blank?)
(rop/fail {:status 400, :body {:errors {:email ["Invalid format"]}}})
(rop/succeed input)))
(defn- create-user
[input]
(-> input
(assoc :new-user {:email (:email input), :id 1})
(assoc-in [:response :status] 201)
(assoc-in [:response :headers] {:content-type :application/json})))
(defn- send-email!
[input]
;; send e-mail here
(println "Sending e-mail"))
(defn try-to-create-user
[input]
(rop/>>=* :new-user
input
(rop/switch format-email)
validate-email
(rop/switch create-user)
(rop/dead send-email!)))
(deftest rop-test
(testing "Should return a success Ring's response with headers and status"
(is (= {:body {:email "PI:EMAIL:<EMAIL>END_PI", :id 1}, :status 201, :headers {:content-type :application/json}}
(try-to-create-user {:email "PI:EMAIL:<EMAIL>END_PI", :new-user nil}))))
(testing "Should return a failure Ring's response"
(is (= {:body {:errors {:email ["Invalid format"]}} :status 400}
(try-to-create-user {:email "", :new-user nil}))))
(testing "Should return a success Ring's response"
(is (= {:body "PI:EMAIL:<EMAIL>END_PI", :status 200, :headers {}}
(rop/>>=* :email
{:email "PI:EMAIL:<EMAIL>END_PI"}
(rop/switch format-email)
validate-email))))
(testing "Should return a success Ring's response with limited output"
(is (= {:id 1}
(:body (rop/>>=* [:new-user #{:id}]
{:email "PI:EMAIL:<EMAIL>END_PI", :new-user nil}
(rop/switch format-email)
validate-email
(rop/switch create-user)
(rop/dead send-email!))))))
(testing "Should return a success Ring's response with limited output on a collection"
(is (= [{:id 1}]
(:body (rop/>>=* [:new-users #{:id}]
{:email "PI:EMAIL:<EMAIL>END_PI", :new-user nil, :new-users nil}
(rop/switch format-email)
validate-email
(rop/switch create-user)
(rop/switch #(assoc % :new-users [(:new-user %)]))
(rop/dead send-email!))))))
(testing "Should return a success"
(is (= {:email "PI:EMAIL:<EMAIL>END_PI", :new-user {:email "PI:EMAIL:<EMAIL>END_PI", :id 1}}
(rop/>>= {:email "PI:EMAIL:<EMAIL>END_PI", :new-user nil}
(rop/switch format-email)
validate-email
(rop/switch #(assoc % :new-user {:email (:email %), :id 1}))
(rop/dead send-email!))))))
(deftest validate-request-test
(testing "should assoc a validated input"
(is (= {:request {:params {:id 1}}}
(m/extract (rop/=validate-request= st/validate
{:id [st/number-str]}
{}
:params
{:request {:params {:id "1"}}})))))
(testing "should assoc errors"
(is (= {:status 400, :body {:errors {:id "must be a number"}}}
(m/extract (rop/=validate-request= st/validate
{:id [st/number-str]}
{}
:params
{:request {:params {:id ""}}})))))
(testing "default values"
(is (= {:request {:params {:id 0, :a 1}}}
(m/extract (rop/=validate-request= st/validate
{:id [st/number-str], :a [st/number-str], :b [st/number-str]}
{:a 1}
:params
{:request {:params {:id "0"}}}))))))
(deftest merge-params-test
(is (= {:request {:params {:id 1, :foo :bar}, :body-params {:foo :bar}}}
(m/extract (rop/=merge-params= :body-params
:params
{:request {:params {:id 1}, :body-params {:foo :bar}}})))))
|
[
{
"context": "-page-match\n :params {\"__token\" \"invalid-token-175424\" \"_count\" \"1\"\n \"__t\" \"1",
"end": 17506,
"score": 0.9286680221557617,
"start": 17486,
"tag": "KEY",
"value": "invalid-token-175424"
},
{
"context": "[:issue 0 :diagnostics] := \"Invalid token `invalid-token-175424`.\")))))\n\n (testing \"on missing token",
"end": 17849,
"score": 0.6220594048500061,
"start": 17849,
"tag": "PASSWORD",
"value": ""
},
{
"context": "e 0 :diagnostics] := \"Invalid token `invalid-token-175424`.\")))))\n\n (testing \"on missing token\"\n (testi",
"end": 17862,
"score": 0.7779595255851746,
"start": 17856,
"tag": "PASSWORD",
"value": "175424"
},
{
"context": "-page-match\n :params {\"__token\" (str/repeat \"A\" 32) \"_count\" \"1\" \"__t\" \"1\"\n ",
"end": 18132,
"score": 0.9068413376808167,
"start": 18122,
"tag": "KEY",
"value": "str/repeat"
},
{
"context": "-page-match\n :params {\"__token\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB\" \"_count\" \"1\" \"__t\" \"1\" \"__page-id\" \"2\"}})]\n\n ",
"end": 28052,
"score": 0.9874976873397827,
"start": 28020,
"tag": "KEY",
"value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB"
},
{
"context": " #fhir/uri\"base-url-113047/Patient/__page?__token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB&_count=1&__t=1&__page-id=2\"\n ",
"end": 30486,
"score": 0.9575688242912292,
"start": 30456,
"tag": "KEY",
"value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
},
{
"context": "age-match\n :params {\"__token\" \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB\" \"_count\" \"1\" \"__t\" \"1\" \"__page-id\" \"2\"}})]\n\n ",
"end": 30793,
"score": 0.9961894750595093,
"start": 30761,
"tag": "KEY",
"value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB"
},
{
"context": " #fhir/uri\"base-url-113047/Patient/__page?__token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB&_count=1&__t=1&__page-id=3\"\n ",
"end": 30975,
"score": 0.5130557417869568,
"start": 30959,
"tag": "KEY",
"value": "AAAAAAAAAAAAAAAA"
},
{
"context": "url-113047/Patient/__page?__token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB&_count=1&__t=1&__page-id=3\"\n ",
"end": 30991,
"score": 0.5691067576408386,
"start": 30975,
"tag": "PASSWORD",
"value": "AAAAAAAAAAAAAAAB"
}
] | modules/interaction/test/blaze/interaction/search_type_test.clj | samply/blaze | 50 | (ns blaze.interaction.search-type-test
"Specifications relevant for the FHIR search interaction:
https://www.hl7.org/fhir/http.html#search"
(:require
[blaze.db.api-stub :refer [mem-node-system with-system-data]]
[blaze.fhir.spec.type :as type]
[blaze.interaction.search-type]
[blaze.interaction.search.nav-spec]
[blaze.interaction.search.params-spec]
[blaze.interaction.search.util-spec]
[blaze.middleware.fhir.db :refer [wrap-db]]
[blaze.middleware.fhir.db-spec]
[blaze.middleware.fhir.error :refer [wrap-error]]
[blaze.page-store-spec]
[blaze.page-store.local]
[blaze.test-util :refer [given-thrown]]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as st]
[clojure.test :as test :refer [deftest is testing]]
[cuerdas.core :as str]
[integrant.core :as ig]
[java-time :as time]
[juxt.iota :refer [given]]
[reitit.core :as reitit]
[taoensso.timbre :as log])
(:import
[java.time Instant]))
(st/instrument)
(log/set-level! :trace)
(defn- fixture [f]
(st/instrument)
(f)
(st/unstrument))
(test/use-fixtures :each fixture)
(def base-url "base-url-113047")
(def router
(reitit/router
[["/Patient" {:name :Patient/type}]
["/Patient/__page" {:name :Patient/page}]
["/MeasureReport" {:name :MeasureReport/type}]
["/Library" {:name :Library/type}]
["/List" {:name :List/type}]
["/Condition" {:name :Condition/type}]
["/Observation" {:name :Observation/type}]
["/Observation/__page" {:name :Observation/page}]
["/MedicationStatement" {:name :MedicationStatement/type}]
["/Medication" {:name :Medication/type}]
["/Organization" {:name :Organization/type}]
["/Encounter" {:name :Encounter/type}]]
{:syntax :bracket}))
(def patient-match
(reitit/map->Match
{:data
{:fhir.resource/type "Patient"}
:path "/Patient"}))
(def patient-search-match
(reitit/map->Match
{:data
{:name :Patient/search
:fhir.resource/type "Patient"}
:path "/Patient"}))
(def patient-page-match
(reitit/map->Match
{:data
{:name :Patient/page
:fhir.resource/type "Patient"}
:path "/Patient"}))
(def measure-report-match
(reitit/map->Match
{:data
{:fhir.resource/type "MeasureReport"}
:path "/MeasureReport"}))
(def list-match
(reitit/map->Match
{:data
{:fhir.resource/type "List"}
:path "/List"}))
(def observation-match
(reitit/map->Match
{:data
{:fhir.resource/type "Observation"}
:path "/Observation"}))
(def condition-match
(reitit/map->Match
{:data
{:fhir.resource/type "Condition"}
:path "/Condition"}))
(def medication-statement-match
(reitit/map->Match
{:data
{:fhir.resource/type "MedicationStatement"}
:path "/MedicationStatement"}))
(defn- link-url [body link-relation]
(->> body :link (filter (comp #{link-relation} :relation)) first :url))
(deftest init-test
(testing "nil config"
(given-thrown (ig/init {:blaze.interaction/search-type nil})
:key := :blaze.interaction/search-type
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `map?))
(testing "missing config"
(given-thrown (ig/init {:blaze.interaction/search-type {}})
:key := :blaze.interaction/search-type
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :clock))
[:explain ::s/problems 1 :pred] := `(fn ~'[%] (contains? ~'% :rng-fn))
[:explain ::s/problems 2 :pred] := `(fn ~'[%] (contains? ~'% :page-store))))
(testing "invalid clock"
(given-thrown (ig/init {:blaze.interaction/search-type {:clock ::invalid}})
:key := :blaze.interaction/search-type
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :rng-fn))
[:explain ::s/problems 1 :pred] := `(fn ~'[%] (contains? ~'% :page-store))
[:explain ::s/problems 2 :pred] := `time/clock?
[:explain ::s/problems 2 :val] := ::invalid)))
(def system
(assoc mem-node-system
:blaze.interaction/search-type
{:clock (ig/ref :blaze.test/clock)
:rng-fn (ig/ref :blaze.test/fixed-rng-fn)
:page-store (ig/ref :blaze.page-store/local)}
:blaze.test/fixed-rng-fn {}
:blaze.page-store/local {:secure-rng (ig/ref :blaze.test/fixed-rng)}
:blaze.test/fixed-rng {}))
(defn wrap-defaults [handler]
(fn [request]
(handler
(assoc request
:blaze/base-url base-url
::reitit/router router))))
(defmacro with-handler [[handler-binding] txs & body]
`(with-system-data [{node# :blaze.db/node
handler# :blaze.interaction/search-type} system]
~txs
(let [~handler-binding (-> handler# wrap-defaults (wrap-db node#)
wrap-error)]
~@body)))
(deftest handler-test
(testing "on unknown search parameter"
(testing "with strict handling"
(testing "returns error"
(with-handler [handler]
[]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=strict"}
:params {"foo" "bar"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"not-found"
[:issue 0 :diagnostics] := "The search-param with code `foo` and type `Patient` was not found.")))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=strict"}
:params {"foo" "bar" "_summary" "count"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"not-found"
[:issue 0 :diagnostics] := "The search-param with code `foo` and type `Patient` was not found."))))))
(testing "with lenient handling"
(testing "returns results with a self link lacking the unknown search parameter"
(testing "where the unknown search parameter is the only one"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=lenient"}
:params {"foo" "bar"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=50&__t=1&__page-id=0"
(link-url body "self"))))))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=lenient"}
:params {"foo" "bar" "_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_summary=count&_count=50&__t=1"
(link-url body "self"))))))))
(testing "with another search parameter"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"
:active true}]]]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=lenient"}
:params {"foo" "bar" "active" "true"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=50&__t=1&__page-id=1"
(link-url body "self"))))))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=lenient"}
:params {"foo" "bar" "active" "true" "_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_summary=count&_count=50&__t=1"
(link-url body "self"))))))))))
(testing "with default handling"
(testing "returns results with a self link lacking the unknown search parameter"
(testing "where the unknown search parameter is the only one"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"foo" "bar"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=50&__t=1&__page-id=0"
(link-url body "self"))))))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"foo" "bar" "_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_summary=count&_count=50&__t=1"
(link-url body "self"))))))))
(testing "with another search parameter"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"
:active true}]]]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"foo" "bar" "active" "true"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=50&__t=1&__page-id=1"
(link-url body "self"))))))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"foo" "bar" "active" "true" "_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_summary=count&_count=50&__t=1"
(link-url body "self")))))))))))
(testing "on invalid date-time"
(testing "returns error"
(with-handler [handler]
[]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
;; the date is already URl decoded and so contains a space instead of a plus
:params {"date" "2021-12-09T00:00:00 01:00"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"invalid"
[:issue 0 :diagnostics] := "Invalid date-time value `2021-12-09T00:00:00 01:00` in search parameter `date`.")))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
;; the date is already URl decoded and so contains a space instead of a plus
:params {"date" "2021-12-09T00:00:00 01:00" "_summary" "count"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"invalid"
[:issue 0 :diagnostics] := "Invalid date-time value `2021-12-09T00:00:00 01:00` in search parameter `date`."))))))
(testing "on invalid token"
(testing "returns error"
(with-handler [handler]
[]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-page-match
:params {"__token" "invalid-token-175424" "_count" "1"
"__t" "1" "__page-id" "1"}})]
(is (= 422 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"invalid"
[:issue 0 :diagnostics] := "Invalid token `invalid-token-175424`.")))))
(testing "on missing token"
(testing "returns error"
(with-handler [handler]
[]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-page-match
:params {"__token" (str/repeat "A" 32) "_count" "1" "__t" "1"
"__page-id" "1"}})]
(is (= 422 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"not-found"
[:issue 0 :diagnostics] := (format "Clauses of token `%s` not found."
(str/repeat "A" 32)))))))
(testing "with one patient"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]]
(testing "Returns all existing resources of type"
(let [{:keys [status body]}
@(handler {::reitit/match patient-match})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=50&__t=1&__page-id=0"
(link-url body "self"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0"
[:meta :versionId] := #fhir/id"1"
[:meta :lastUpdated] := Instant/EPOCH))
(testing "the entry has the right search information"
(given (-> body :entry first :search)
type/type := :fhir.Bundle.entry/search
:mode := #fhir/code"match"))))
(testing "with param _summary equal to count"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_summary=count&_count=50&__t=1"
(link-url body "self"))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))))
(testing "with param _count equal to zero"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_count" "0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=0&__t=1"
(link-url body "self"))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))))))
(testing "with two patients"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]]]
(testing "search for all patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"_count" "1"}})]
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=1&__t=1&__page-id=0"
(link-url body "self"))))
(testing "has a next link"
(is (= #fhir/uri"base-url-113047/Patient/__page?_count=1&__t=1&__page-id=1"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "following the self link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"_count" "1" "__t" "1" "__page-id" "0"}})]
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=1&__t=1&__page-id=0"
(link-url body "self"))))
(testing "has a next link"
(is (= #fhir/uri"base-url-113047/Patient/__page?_count=1&__t=1&__page-id=1"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "following the next link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"_count" "1" "__t" "1" "__page-id" "1"}})]
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=1&__t=1&__page-id=1"
(link-url body "self"))))
(testing "has no next link"
(is (nil? (link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))))
(testing "with three patients"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1" :active true}]
[:put {:fhir/type :fhir/Patient :id "2" :active true}]]]
(testing "search for active patients with _summary=count"
(testing "with strict handling"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=strict"}
:params {"active" "true" "_summary" "count"}})]
(testing "their is a total count because we used _summary=count"
(is (= #fhir/unsignedInt 2 (:total body))))))
(testing "with default handling"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"active" "true" "_summary" "count"}})]
(testing "their is a total count because we used _summary=count"
(is (= #fhir/unsignedInt 2 (:total body)))))))
(testing "on normal request"
(testing "search for active patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"active" "true" "_count" "1"}})]
(testing "their is no total count because we have clauses and we have
more hits than page-size"
(is (nil? (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=1&__t=1&__page-id=1"
(link-url body "self"))))
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Patient/__page?active=true&_count=1&__t=1&__page-id=2"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body))))))))
(testing "on /_search request"
(testing "search for active patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-search-match
:params {"active" "true" "_count" "1"}})]
(testing "their is no total count because we have clauses and we have
more hits than page-size"
(is (nil? (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=1&__t=1&__page-id=1"
(link-url body "self"))))
(testing "has a next link with token"
(is (= #fhir/uri"base-url-113047/Patient/__page?__token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB&_count=1&__t=1&__page-id=2"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body))))))))
(testing "following the self link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"active" "true" "_count" "1" "__t" "1" "__page-id" "1"}})]
(testing "their is no total count because we have clauses and we have
more hits than page-size"
(is (nil? (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=1&__t=1&__page-id=1"
(link-url body "self"))))
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Patient/__page?active=true&_count=1&__t=1&__page-id=2"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "following the next link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-page-match
:params {"__token" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB" "_count" "1" "__t" "1" "__page-id" "2"}})]
(testing "their is no total count because we have clauses and we have
more hits than page-size"
(is (nil? (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=1&__t=1&__page-id=2"
(link-url body "self"))))
(testing "has no next link"
(is (nil? (link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))))
(testing "with four patients"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1" :active true}]
[:put {:fhir/type :fhir/Patient :id "2" :active true}]
[:put {:fhir/type :fhir/Patient :id "3" :active true}]]]
(testing "on normal request"
(testing "search for active patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"active" "true" "_count" "1"}})]
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Patient/__page?active=true&_count=1&__t=1&__page-id=2"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "following the next link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-page-match
:params {"active" "true" "_count" "1" "__t" "1" "__page-id" "2"}})]
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Patient/__page?active=true&_count=1&__t=1&__page-id=3"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body))))))))
(testing "on /_search request"
(testing "search for active patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-search-match
:params {"active" "true" "_count" "1"}})]
(testing "has a next link with token"
(is (= #fhir/uri"base-url-113047/Patient/__page?__token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB&_count=1&__t=1&__page-id=2"
(link-url body "next"))))))
(testing "following the next link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-page-match
:params {"__token" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB" "_count" "1" "__t" "1" "__page-id" "2"}})]
(testing "has a next link with token"
(is (= #fhir/uri"base-url-113047/Patient/__page?__token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB&_count=1&__t=1&__page-id=3"
(link-url body "next")))))))))
(testing "_id search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_id" "0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0"))))
(testing "multiple id's"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]
[:put {:fhir/type :fhir/Patient :id "2"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_id" "0,2"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "the bundle contains one entry"
(is (= 2 (count (:entry body)))))
(testing "the first entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the second entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/2"
(-> body :entry second :fullUrl))))
(testing "the first entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0"))
(testing "the second entry has the right resource"
(given (-> body :entry second :resource)
:fhir/type := :fhir/Patient
:id := "2"))))))
(testing "_lastUpdated search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]]
(testing "the resource is created at EPOCH"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_lastUpdated" "1970-01-01"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "no resource is created after EPOCH"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_lastUpdated" "gt1970-01-02"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 0"
(is (= #fhir/unsignedInt 0 (:total body))))
(testing "the bundle contains no entry"
(is (zero? (count (:entry body))))))))
(testing "deleted resources are not found"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]
[[:delete "Patient" "0"]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_lastUpdated" "1970-01-01"}})]
(is (= 200 status))
(testing "the total count is 0"
(is (= #fhir/unsignedInt 0 (:total body))))
(testing "the bundle contains one entry"
(is (= 0 (count (:entry body)))))))))
(testing "_profile search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put
{:fhir/type :fhir/Patient :id "1"
:meta
#fhir/Meta
{:profile [#fhir/canonical"profile-uri-151511"]}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_profile" "profile-uri-151511"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/1"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
[:meta :profile 0] := #fhir/canonical"profile-uri-151511"
:id := "1")))))
(testing "_list search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]
[:put {:fhir/type :fhir/List :id "0"
:entry
[{:fhir/type :fhir.List/entry
:item
#fhir/Reference
{:reference "Patient/0"}}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_list" "0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0")))))
(testing "_has search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]
[:put {:fhir/type :fhir/Observation :id "0"
:subject
#fhir/Reference
{:reference "Patient/0"}
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 130M
:code #fhir/code"mm[Hg]"
:system #fhir/uri"http://unitsofmeasure.org"}}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject
#fhir/Reference
{:reference "Patient/0"}
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 150M
:code #fhir/code"mm[Hg]"
:system #fhir/uri"http://unitsofmeasure.org"}}]
[:put {:fhir/type :fhir/Observation :id "2"
:subject
#fhir/Reference
{:reference "Patient/1"}
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 100M
:code #fhir/code"mm[Hg]"
:system #fhir/uri"http://unitsofmeasure.org"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_has:Observation:patient:code-value-quantity" "8480-6$ge130"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0")))))
(testing "Patient identifier search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"
:identifier [#fhir/Identifier{:value "0"}]}]
[:put {:fhir/type :fhir/Patient :id "1"
:identifier [#fhir/Identifier{:value "1"}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"identifier" "0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
[:identifier 0 :value] := "0")))))
(testing "Patient language search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"
:communication
[{:fhir/type :fhir.Patient/communication
:language
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"urn:ietf:bcp:47"
:code #fhir/code"de"}]}}
{:fhir/type :fhir.Patient/communication
:language
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"urn:ietf:bcp:47"
:code #fhir/code"en"}]}}]}]
[:put {:fhir/type :fhir/Patient :id "1"
:communication
[{:fhir/type :fhir.Patient/communication
:language
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"urn:ietf:bcp:47"
:code #fhir/code"de"}]}}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"language" ["de" "en"]}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(is (= "0" (-> body :entry first :resource :id)))))))
(testing "Library title search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Library :id "0" :title "ab"}]
[:put {:fhir/type :fhir/Library :id "1" :title "b"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match {:data {:fhir.resource/type "Library"}}
:params {"title" "A"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Library/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Library
:id := "0")))))
(testing "MeasureReport measure search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/MeasureReport :id "0"
:measure #fhir/canonical"http://server.com/Measure/0"}]]
[[:put {:fhir/type :fhir/MeasureReport :id "1"
:measure #fhir/canonical"http://server.com/Measure/1"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match measure-report-match
:params {"measure" "http://server.com/Measure/0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/MeasureReport/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:measure := #fhir/canonical"http://server.com/Measure/0")))))
(testing "List item search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/List :id "id-123058"
:entry
[{:fhir/type :fhir.List/entry
:item
#fhir/Reference
{:identifier
#fhir/Identifier
{:system #fhir/uri"system-122917"
:value "value-122931"}}}]}]
[:put {:fhir/type :fhir/List :id "id-143814"
:entry
[{:fhir/type :fhir.List/entry
:item
#fhir/Reference
{:identifier
#fhir/Identifier
{:system #fhir/uri"system-122917"
:value "value-143818"}}}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match list-match
:params {"item:identifier" "system-122917|value-143818"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/List/id-143814"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:id := "id-143814")))))
(testing "Observation combo-code-value-quantity search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Observation :id "id-121049"
:component
[{:fhir/type :fhir.Observation/component
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 140M
:system #fhir/uri"http://unitsofmeasure.org"
:code #fhir/code"mm[Hg]"}}
{:fhir/type :fhir.Observation/component
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8462-4"}]}
:value
#fhir/Quantity
{:value 90M
:system #fhir/uri"http://unitsofmeasure.org"
:code #fhir/code"mm[Hg]"}}]}]]
[[:put {:fhir/type :fhir/Observation :id "id-123130"
:component
[{:fhir/type :fhir.Observation/component
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 150M
:system #fhir/uri"http://unitsofmeasure.org"
:code #fhir/code"mm[Hg]"}}
{:fhir/type :fhir.Observation/component
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8462-4"}]}
:value
#fhir/Quantity
{:value 100M
:system #fhir/uri"http://unitsofmeasure.org"
:code #fhir/code"mm[Hg]"}}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params
{"combo-code-value-quantity"
["http://loinc.org|8480-6$ge140|mm[Hg]"
"http://loinc.org|8462-4$ge90|mm[Hg]"]
"_count" "1"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Observation/__page?combo-code-value-quantity=http%3A%2F%2Floinc.org%7C8480-6%24ge140%7Cmm%5BHg%5D&combo-code-value-quantity=http%3A%2F%2Floinc.org%7C8462-4%24ge90%7Cmm%5BHg%5D&_count=1&__t=2&__page-id=id-123130"
(link-url body "next")))))))
(testing "Duplicate OR Search Parameters have no Effect (#293)"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Condition :id "0"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://fhir.de/CodeSystem/dimdi/icd-10-gm"
:code #fhir/code"C71.4"}]}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match condition-match
:params {"code" "C71.4,C71.4"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Condition/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
[:code :coding 0 :code] := #fhir/code"C71.4")))))
(testing "Paging works with OR Search Parameters"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Condition :id "0"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:code #fhir/code"0"}]}}]
[:put {:fhir/type :fhir/Condition :id "2"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:code #fhir/code"0"}]}}]
[:put {:fhir/type :fhir/Condition :id "1"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:code #fhir/code"1"}]}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match condition-match
:params {"code" "0,1" "_count" "2"
"__t" "1" "__page-id" "1"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Condition/1"
(-> body :entry first :fullUrl)))))))
(testing "Include Resources"
(testing "direct include"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "0"
:subject #fhir/Reference{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Observation?_include=Observation%3Asubject&_count=50&__t=1&__page-id=0"
(link-url body "self"))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/0"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Patient"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include"))))
(testing "with non-matching target type"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "0"
:subject #fhir/Reference{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject:Group"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/0"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match")))))
(testing "includes don't appear twice"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject #fhir/Reference{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Observation :id "2"
:subject #fhir/Reference{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "the bundle contains three entries"
(is (= 3 (count (:entry body)))))
(testing "the first entry is the first matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/1"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the second matched Observation"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Observation/2"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the third entry is the included Patient"
(given (-> body :entry (nth 2))
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include")))))
(testing "two includes"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Encounter :id "1"
:subject #fhir/Reference{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Observation :id "2"
:subject #fhir/Reference{:reference "Patient/0"}
:encounter #fhir/Reference{:reference "Encounter/1"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params
{"_include" ["Observation:subject" "Observation:encounter"]}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains three entries"
(is (= 3 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/2"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Encounter"
(given (-> body :entry (nth 2))
:fullUrl := #fhir/uri"base-url-113047/Encounter/1"
[:resource :fhir/type] := :fhir/Encounter
[:search :mode] := #fhir/code"include"))
(testing "the third entry is the included Patient"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include")))))
(testing "with paging"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject
#fhir/Reference
{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Patient :id "2"}]
[:put {:fhir/type :fhir/Observation :id "3"
:subject
#fhir/Reference
{:reference "Patient/2"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject" "_count" "1"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a next link"
(is (= #fhir/uri"base-url-113047/Observation/__page?_include=Observation%3Asubject&_count=1&__t=1&__page-id=3"
(link-url body "next"))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/1"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Patient"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include"))
(testing "second page"
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject" "_count" "2"
"__t" "1" "__page-id" "3"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Observation?_include=Observation%3Asubject&_count=2&__t=1&__page-id=3"
(link-url body "self"))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/3"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Patient"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Patient/2"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include"))))))))
(testing "iterative include"
(with-handler [handler]
[[[:put {:fhir/type :fhir/MedicationStatement :id "0"
:medication
#fhir/Reference
{:reference "Medication/0"}}]
[:put {:fhir/type :fhir/Medication :id "0"
:manufacturer
#fhir/Reference
{:reference "Organization/0"}}]
[:put {:fhir/type :fhir/Organization :id "0"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match medication-statement-match
:params
{"_include" "MedicationStatement:medication"
"_include:iterate" "Medication:manufacturer"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains two entries"
(is (= 3 (count (:entry body)))))
(testing "the first entry is the matched MedicationStatement"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/MedicationStatement/0"
[:resource :fhir/type] := :fhir/MedicationStatement
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Organization"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Organization/0"
[:resource :fhir/type] := :fhir/Organization
[:search :mode] := #fhir/code"include"))
(testing "the third entry is the included Medication"
(given (-> body :entry (nth 2))
:fullUrl := #fhir/uri"base-url-113047/Medication/0"
[:resource :fhir/type] := :fhir/Medication
[:search :mode] := #fhir/code"include")))))
(testing "non-iterative include doesn't work iterative"
(with-handler [handler]
[[[:put {:fhir/type :fhir/MedicationStatement :id "0"
:medication
#fhir/Reference
{:reference "Medication/0"}}]
[:put {:fhir/type :fhir/Medication :id "0"
:manufacturer
#fhir/Reference
{:reference "Organization/0"}}]
[:put {:fhir/type :fhir/Organization :id "0"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match medication-statement-match
:params
{"_include"
["MedicationStatement:medication" "Medication:manufacturer"]}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched MedicationStatement"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/MedicationStatement/0"
[:resource :fhir/type] := :fhir/MedicationStatement
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Medication"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Medication/0"
[:resource :fhir/type] := :fhir/Medication
[:search :mode] := #fhir/code"include")))))
(testing "revinclude"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject
#fhir/Reference
{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_revinclude" "Observation:subject"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_revinclude=Observation%3Asubject&_count=50&__t=1&__page-id=0"
(link-url body "self"))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched Patient"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Observation"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Observation/1"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"include"))))
(testing "two revincludes"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject
#fhir/Reference
{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Condition :id "2"
:subject
#fhir/Reference
{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params
{"_revinclude" ["Observation:subject" "Condition:subject"]}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_revinclude=Observation%3Asubject&_revinclude=Condition%3Asubject&_count=50&__t=1&__page-id=0"
(link-url body "self"))))
(testing "the bundle contains two entries"
(is (= 3 (count (:entry body)))))
(testing "the first entry is the matched Patient"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Observation"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Observation/1"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"include"))
(testing "the third entry is the included Condition"
(given (-> body :entry (nth 2))
:fullUrl := #fhir/uri"base-url-113047/Condition/2"
[:resource :fhir/type] := :fhir/Condition
[:search :mode] := #fhir/code"include"))))))
(testing "invalid include parameter"
(with-handler [handler]
[]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=strict"}
:params {"_include" "Observation"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"invalid"
[:issue 0 :diagnostics] := "Missing search parameter code in _include search parameter with source type `Observation`."))))))
| 63184 | (ns blaze.interaction.search-type-test
"Specifications relevant for the FHIR search interaction:
https://www.hl7.org/fhir/http.html#search"
(:require
[blaze.db.api-stub :refer [mem-node-system with-system-data]]
[blaze.fhir.spec.type :as type]
[blaze.interaction.search-type]
[blaze.interaction.search.nav-spec]
[blaze.interaction.search.params-spec]
[blaze.interaction.search.util-spec]
[blaze.middleware.fhir.db :refer [wrap-db]]
[blaze.middleware.fhir.db-spec]
[blaze.middleware.fhir.error :refer [wrap-error]]
[blaze.page-store-spec]
[blaze.page-store.local]
[blaze.test-util :refer [given-thrown]]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as st]
[clojure.test :as test :refer [deftest is testing]]
[cuerdas.core :as str]
[integrant.core :as ig]
[java-time :as time]
[juxt.iota :refer [given]]
[reitit.core :as reitit]
[taoensso.timbre :as log])
(:import
[java.time Instant]))
(st/instrument)
(log/set-level! :trace)
(defn- fixture [f]
(st/instrument)
(f)
(st/unstrument))
(test/use-fixtures :each fixture)
(def base-url "base-url-113047")
(def router
(reitit/router
[["/Patient" {:name :Patient/type}]
["/Patient/__page" {:name :Patient/page}]
["/MeasureReport" {:name :MeasureReport/type}]
["/Library" {:name :Library/type}]
["/List" {:name :List/type}]
["/Condition" {:name :Condition/type}]
["/Observation" {:name :Observation/type}]
["/Observation/__page" {:name :Observation/page}]
["/MedicationStatement" {:name :MedicationStatement/type}]
["/Medication" {:name :Medication/type}]
["/Organization" {:name :Organization/type}]
["/Encounter" {:name :Encounter/type}]]
{:syntax :bracket}))
(def patient-match
(reitit/map->Match
{:data
{:fhir.resource/type "Patient"}
:path "/Patient"}))
(def patient-search-match
(reitit/map->Match
{:data
{:name :Patient/search
:fhir.resource/type "Patient"}
:path "/Patient"}))
(def patient-page-match
(reitit/map->Match
{:data
{:name :Patient/page
:fhir.resource/type "Patient"}
:path "/Patient"}))
(def measure-report-match
(reitit/map->Match
{:data
{:fhir.resource/type "MeasureReport"}
:path "/MeasureReport"}))
(def list-match
(reitit/map->Match
{:data
{:fhir.resource/type "List"}
:path "/List"}))
(def observation-match
(reitit/map->Match
{:data
{:fhir.resource/type "Observation"}
:path "/Observation"}))
(def condition-match
(reitit/map->Match
{:data
{:fhir.resource/type "Condition"}
:path "/Condition"}))
(def medication-statement-match
(reitit/map->Match
{:data
{:fhir.resource/type "MedicationStatement"}
:path "/MedicationStatement"}))
(defn- link-url [body link-relation]
(->> body :link (filter (comp #{link-relation} :relation)) first :url))
(deftest init-test
(testing "nil config"
(given-thrown (ig/init {:blaze.interaction/search-type nil})
:key := :blaze.interaction/search-type
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `map?))
(testing "missing config"
(given-thrown (ig/init {:blaze.interaction/search-type {}})
:key := :blaze.interaction/search-type
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :clock))
[:explain ::s/problems 1 :pred] := `(fn ~'[%] (contains? ~'% :rng-fn))
[:explain ::s/problems 2 :pred] := `(fn ~'[%] (contains? ~'% :page-store))))
(testing "invalid clock"
(given-thrown (ig/init {:blaze.interaction/search-type {:clock ::invalid}})
:key := :blaze.interaction/search-type
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :rng-fn))
[:explain ::s/problems 1 :pred] := `(fn ~'[%] (contains? ~'% :page-store))
[:explain ::s/problems 2 :pred] := `time/clock?
[:explain ::s/problems 2 :val] := ::invalid)))
(def system
(assoc mem-node-system
:blaze.interaction/search-type
{:clock (ig/ref :blaze.test/clock)
:rng-fn (ig/ref :blaze.test/fixed-rng-fn)
:page-store (ig/ref :blaze.page-store/local)}
:blaze.test/fixed-rng-fn {}
:blaze.page-store/local {:secure-rng (ig/ref :blaze.test/fixed-rng)}
:blaze.test/fixed-rng {}))
(defn wrap-defaults [handler]
(fn [request]
(handler
(assoc request
:blaze/base-url base-url
::reitit/router router))))
(defmacro with-handler [[handler-binding] txs & body]
`(with-system-data [{node# :blaze.db/node
handler# :blaze.interaction/search-type} system]
~txs
(let [~handler-binding (-> handler# wrap-defaults (wrap-db node#)
wrap-error)]
~@body)))
(deftest handler-test
(testing "on unknown search parameter"
(testing "with strict handling"
(testing "returns error"
(with-handler [handler]
[]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=strict"}
:params {"foo" "bar"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"not-found"
[:issue 0 :diagnostics] := "The search-param with code `foo` and type `Patient` was not found.")))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=strict"}
:params {"foo" "bar" "_summary" "count"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"not-found"
[:issue 0 :diagnostics] := "The search-param with code `foo` and type `Patient` was not found."))))))
(testing "with lenient handling"
(testing "returns results with a self link lacking the unknown search parameter"
(testing "where the unknown search parameter is the only one"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=lenient"}
:params {"foo" "bar"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=50&__t=1&__page-id=0"
(link-url body "self"))))))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=lenient"}
:params {"foo" "bar" "_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_summary=count&_count=50&__t=1"
(link-url body "self"))))))))
(testing "with another search parameter"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"
:active true}]]]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=lenient"}
:params {"foo" "bar" "active" "true"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=50&__t=1&__page-id=1"
(link-url body "self"))))))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=lenient"}
:params {"foo" "bar" "active" "true" "_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_summary=count&_count=50&__t=1"
(link-url body "self"))))))))))
(testing "with default handling"
(testing "returns results with a self link lacking the unknown search parameter"
(testing "where the unknown search parameter is the only one"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"foo" "bar"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=50&__t=1&__page-id=0"
(link-url body "self"))))))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"foo" "bar" "_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_summary=count&_count=50&__t=1"
(link-url body "self"))))))))
(testing "with another search parameter"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"
:active true}]]]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"foo" "bar" "active" "true"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=50&__t=1&__page-id=1"
(link-url body "self"))))))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"foo" "bar" "active" "true" "_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_summary=count&_count=50&__t=1"
(link-url body "self")))))))))))
(testing "on invalid date-time"
(testing "returns error"
(with-handler [handler]
[]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
;; the date is already URl decoded and so contains a space instead of a plus
:params {"date" "2021-12-09T00:00:00 01:00"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"invalid"
[:issue 0 :diagnostics] := "Invalid date-time value `2021-12-09T00:00:00 01:00` in search parameter `date`.")))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
;; the date is already URl decoded and so contains a space instead of a plus
:params {"date" "2021-12-09T00:00:00 01:00" "_summary" "count"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"invalid"
[:issue 0 :diagnostics] := "Invalid date-time value `2021-12-09T00:00:00 01:00` in search parameter `date`."))))))
(testing "on invalid token"
(testing "returns error"
(with-handler [handler]
[]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-page-match
:params {"__token" "<KEY>" "_count" "1"
"__t" "1" "__page-id" "1"}})]
(is (= 422 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"invalid"
[:issue 0 :diagnostics] := "Invalid token `invalid<PASSWORD>-token-<PASSWORD>`.")))))
(testing "on missing token"
(testing "returns error"
(with-handler [handler]
[]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-page-match
:params {"__token" (<KEY> "A" 32) "_count" "1" "__t" "1"
"__page-id" "1"}})]
(is (= 422 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"not-found"
[:issue 0 :diagnostics] := (format "Clauses of token `%s` not found."
(str/repeat "A" 32)))))))
(testing "with one patient"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]]
(testing "Returns all existing resources of type"
(let [{:keys [status body]}
@(handler {::reitit/match patient-match})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=50&__t=1&__page-id=0"
(link-url body "self"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0"
[:meta :versionId] := #fhir/id"1"
[:meta :lastUpdated] := Instant/EPOCH))
(testing "the entry has the right search information"
(given (-> body :entry first :search)
type/type := :fhir.Bundle.entry/search
:mode := #fhir/code"match"))))
(testing "with param _summary equal to count"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_summary=count&_count=50&__t=1"
(link-url body "self"))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))))
(testing "with param _count equal to zero"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_count" "0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=0&__t=1"
(link-url body "self"))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))))))
(testing "with two patients"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]]]
(testing "search for all patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"_count" "1"}})]
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=1&__t=1&__page-id=0"
(link-url body "self"))))
(testing "has a next link"
(is (= #fhir/uri"base-url-113047/Patient/__page?_count=1&__t=1&__page-id=1"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "following the self link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"_count" "1" "__t" "1" "__page-id" "0"}})]
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=1&__t=1&__page-id=0"
(link-url body "self"))))
(testing "has a next link"
(is (= #fhir/uri"base-url-113047/Patient/__page?_count=1&__t=1&__page-id=1"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "following the next link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"_count" "1" "__t" "1" "__page-id" "1"}})]
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=1&__t=1&__page-id=1"
(link-url body "self"))))
(testing "has no next link"
(is (nil? (link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))))
(testing "with three patients"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1" :active true}]
[:put {:fhir/type :fhir/Patient :id "2" :active true}]]]
(testing "search for active patients with _summary=count"
(testing "with strict handling"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=strict"}
:params {"active" "true" "_summary" "count"}})]
(testing "their is a total count because we used _summary=count"
(is (= #fhir/unsignedInt 2 (:total body))))))
(testing "with default handling"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"active" "true" "_summary" "count"}})]
(testing "their is a total count because we used _summary=count"
(is (= #fhir/unsignedInt 2 (:total body)))))))
(testing "on normal request"
(testing "search for active patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"active" "true" "_count" "1"}})]
(testing "their is no total count because we have clauses and we have
more hits than page-size"
(is (nil? (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=1&__t=1&__page-id=1"
(link-url body "self"))))
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Patient/__page?active=true&_count=1&__t=1&__page-id=2"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body))))))))
(testing "on /_search request"
(testing "search for active patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-search-match
:params {"active" "true" "_count" "1"}})]
(testing "their is no total count because we have clauses and we have
more hits than page-size"
(is (nil? (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=1&__t=1&__page-id=1"
(link-url body "self"))))
(testing "has a next link with token"
(is (= #fhir/uri"base-url-113047/Patient/__page?__token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB&_count=1&__t=1&__page-id=2"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body))))))))
(testing "following the self link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"active" "true" "_count" "1" "__t" "1" "__page-id" "1"}})]
(testing "their is no total count because we have clauses and we have
more hits than page-size"
(is (nil? (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=1&__t=1&__page-id=1"
(link-url body "self"))))
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Patient/__page?active=true&_count=1&__t=1&__page-id=2"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "following the next link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-page-match
:params {"__token" "<KEY>" "_count" "1" "__t" "1" "__page-id" "2"}})]
(testing "their is no total count because we have clauses and we have
more hits than page-size"
(is (nil? (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=1&__t=1&__page-id=2"
(link-url body "self"))))
(testing "has no next link"
(is (nil? (link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))))
(testing "with four patients"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1" :active true}]
[:put {:fhir/type :fhir/Patient :id "2" :active true}]
[:put {:fhir/type :fhir/Patient :id "3" :active true}]]]
(testing "on normal request"
(testing "search for active patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"active" "true" "_count" "1"}})]
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Patient/__page?active=true&_count=1&__t=1&__page-id=2"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "following the next link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-page-match
:params {"active" "true" "_count" "1" "__t" "1" "__page-id" "2"}})]
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Patient/__page?active=true&_count=1&__t=1&__page-id=3"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body))))))))
(testing "on /_search request"
(testing "search for active patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-search-match
:params {"active" "true" "_count" "1"}})]
(testing "has a next link with token"
(is (= #fhir/uri"base-url-113047/Patient/__page?__token=<KEY>AB&_count=1&__t=1&__page-id=2"
(link-url body "next"))))))
(testing "following the next link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-page-match
:params {"__token" "<KEY>" "_count" "1" "__t" "1" "__page-id" "2"}})]
(testing "has a next link with token"
(is (= #fhir/uri"base-url-113047/Patient/__page?__token=<KEY> <PASSWORD>&_count=1&__t=1&__page-id=3"
(link-url body "next")))))))))
(testing "_id search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_id" "0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0"))))
(testing "multiple id's"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]
[:put {:fhir/type :fhir/Patient :id "2"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_id" "0,2"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "the bundle contains one entry"
(is (= 2 (count (:entry body)))))
(testing "the first entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the second entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/2"
(-> body :entry second :fullUrl))))
(testing "the first entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0"))
(testing "the second entry has the right resource"
(given (-> body :entry second :resource)
:fhir/type := :fhir/Patient
:id := "2"))))))
(testing "_lastUpdated search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]]
(testing "the resource is created at EPOCH"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_lastUpdated" "1970-01-01"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "no resource is created after EPOCH"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_lastUpdated" "gt1970-01-02"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 0"
(is (= #fhir/unsignedInt 0 (:total body))))
(testing "the bundle contains no entry"
(is (zero? (count (:entry body))))))))
(testing "deleted resources are not found"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]
[[:delete "Patient" "0"]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_lastUpdated" "1970-01-01"}})]
(is (= 200 status))
(testing "the total count is 0"
(is (= #fhir/unsignedInt 0 (:total body))))
(testing "the bundle contains one entry"
(is (= 0 (count (:entry body)))))))))
(testing "_profile search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put
{:fhir/type :fhir/Patient :id "1"
:meta
#fhir/Meta
{:profile [#fhir/canonical"profile-uri-151511"]}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_profile" "profile-uri-151511"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/1"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
[:meta :profile 0] := #fhir/canonical"profile-uri-151511"
:id := "1")))))
(testing "_list search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]
[:put {:fhir/type :fhir/List :id "0"
:entry
[{:fhir/type :fhir.List/entry
:item
#fhir/Reference
{:reference "Patient/0"}}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_list" "0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0")))))
(testing "_has search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]
[:put {:fhir/type :fhir/Observation :id "0"
:subject
#fhir/Reference
{:reference "Patient/0"}
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 130M
:code #fhir/code"mm[Hg]"
:system #fhir/uri"http://unitsofmeasure.org"}}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject
#fhir/Reference
{:reference "Patient/0"}
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 150M
:code #fhir/code"mm[Hg]"
:system #fhir/uri"http://unitsofmeasure.org"}}]
[:put {:fhir/type :fhir/Observation :id "2"
:subject
#fhir/Reference
{:reference "Patient/1"}
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 100M
:code #fhir/code"mm[Hg]"
:system #fhir/uri"http://unitsofmeasure.org"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_has:Observation:patient:code-value-quantity" "8480-6$ge130"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0")))))
(testing "Patient identifier search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"
:identifier [#fhir/Identifier{:value "0"}]}]
[:put {:fhir/type :fhir/Patient :id "1"
:identifier [#fhir/Identifier{:value "1"}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"identifier" "0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
[:identifier 0 :value] := "0")))))
(testing "Patient language search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"
:communication
[{:fhir/type :fhir.Patient/communication
:language
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"urn:ietf:bcp:47"
:code #fhir/code"de"}]}}
{:fhir/type :fhir.Patient/communication
:language
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"urn:ietf:bcp:47"
:code #fhir/code"en"}]}}]}]
[:put {:fhir/type :fhir/Patient :id "1"
:communication
[{:fhir/type :fhir.Patient/communication
:language
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"urn:ietf:bcp:47"
:code #fhir/code"de"}]}}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"language" ["de" "en"]}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(is (= "0" (-> body :entry first :resource :id)))))))
(testing "Library title search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Library :id "0" :title "ab"}]
[:put {:fhir/type :fhir/Library :id "1" :title "b"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match {:data {:fhir.resource/type "Library"}}
:params {"title" "A"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Library/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Library
:id := "0")))))
(testing "MeasureReport measure search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/MeasureReport :id "0"
:measure #fhir/canonical"http://server.com/Measure/0"}]]
[[:put {:fhir/type :fhir/MeasureReport :id "1"
:measure #fhir/canonical"http://server.com/Measure/1"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match measure-report-match
:params {"measure" "http://server.com/Measure/0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/MeasureReport/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:measure := #fhir/canonical"http://server.com/Measure/0")))))
(testing "List item search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/List :id "id-123058"
:entry
[{:fhir/type :fhir.List/entry
:item
#fhir/Reference
{:identifier
#fhir/Identifier
{:system #fhir/uri"system-122917"
:value "value-122931"}}}]}]
[:put {:fhir/type :fhir/List :id "id-143814"
:entry
[{:fhir/type :fhir.List/entry
:item
#fhir/Reference
{:identifier
#fhir/Identifier
{:system #fhir/uri"system-122917"
:value "value-143818"}}}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match list-match
:params {"item:identifier" "system-122917|value-143818"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/List/id-143814"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:id := "id-143814")))))
(testing "Observation combo-code-value-quantity search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Observation :id "id-121049"
:component
[{:fhir/type :fhir.Observation/component
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 140M
:system #fhir/uri"http://unitsofmeasure.org"
:code #fhir/code"mm[Hg]"}}
{:fhir/type :fhir.Observation/component
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8462-4"}]}
:value
#fhir/Quantity
{:value 90M
:system #fhir/uri"http://unitsofmeasure.org"
:code #fhir/code"mm[Hg]"}}]}]]
[[:put {:fhir/type :fhir/Observation :id "id-123130"
:component
[{:fhir/type :fhir.Observation/component
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 150M
:system #fhir/uri"http://unitsofmeasure.org"
:code #fhir/code"mm[Hg]"}}
{:fhir/type :fhir.Observation/component
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8462-4"}]}
:value
#fhir/Quantity
{:value 100M
:system #fhir/uri"http://unitsofmeasure.org"
:code #fhir/code"mm[Hg]"}}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params
{"combo-code-value-quantity"
["http://loinc.org|8480-6$ge140|mm[Hg]"
"http://loinc.org|8462-4$ge90|mm[Hg]"]
"_count" "1"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Observation/__page?combo-code-value-quantity=http%3A%2F%2Floinc.org%7C8480-6%24ge140%7Cmm%5BHg%5D&combo-code-value-quantity=http%3A%2F%2Floinc.org%7C8462-4%24ge90%7Cmm%5BHg%5D&_count=1&__t=2&__page-id=id-123130"
(link-url body "next")))))))
(testing "Duplicate OR Search Parameters have no Effect (#293)"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Condition :id "0"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://fhir.de/CodeSystem/dimdi/icd-10-gm"
:code #fhir/code"C71.4"}]}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match condition-match
:params {"code" "C71.4,C71.4"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Condition/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
[:code :coding 0 :code] := #fhir/code"C71.4")))))
(testing "Paging works with OR Search Parameters"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Condition :id "0"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:code #fhir/code"0"}]}}]
[:put {:fhir/type :fhir/Condition :id "2"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:code #fhir/code"0"}]}}]
[:put {:fhir/type :fhir/Condition :id "1"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:code #fhir/code"1"}]}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match condition-match
:params {"code" "0,1" "_count" "2"
"__t" "1" "__page-id" "1"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Condition/1"
(-> body :entry first :fullUrl)))))))
(testing "Include Resources"
(testing "direct include"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "0"
:subject #fhir/Reference{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Observation?_include=Observation%3Asubject&_count=50&__t=1&__page-id=0"
(link-url body "self"))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/0"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Patient"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include"))))
(testing "with non-matching target type"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "0"
:subject #fhir/Reference{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject:Group"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/0"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match")))))
(testing "includes don't appear twice"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject #fhir/Reference{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Observation :id "2"
:subject #fhir/Reference{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "the bundle contains three entries"
(is (= 3 (count (:entry body)))))
(testing "the first entry is the first matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/1"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the second matched Observation"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Observation/2"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the third entry is the included Patient"
(given (-> body :entry (nth 2))
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include")))))
(testing "two includes"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Encounter :id "1"
:subject #fhir/Reference{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Observation :id "2"
:subject #fhir/Reference{:reference "Patient/0"}
:encounter #fhir/Reference{:reference "Encounter/1"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params
{"_include" ["Observation:subject" "Observation:encounter"]}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains three entries"
(is (= 3 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/2"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Encounter"
(given (-> body :entry (nth 2))
:fullUrl := #fhir/uri"base-url-113047/Encounter/1"
[:resource :fhir/type] := :fhir/Encounter
[:search :mode] := #fhir/code"include"))
(testing "the third entry is the included Patient"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include")))))
(testing "with paging"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject
#fhir/Reference
{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Patient :id "2"}]
[:put {:fhir/type :fhir/Observation :id "3"
:subject
#fhir/Reference
{:reference "Patient/2"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject" "_count" "1"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a next link"
(is (= #fhir/uri"base-url-113047/Observation/__page?_include=Observation%3Asubject&_count=1&__t=1&__page-id=3"
(link-url body "next"))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/1"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Patient"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include"))
(testing "second page"
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject" "_count" "2"
"__t" "1" "__page-id" "3"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Observation?_include=Observation%3Asubject&_count=2&__t=1&__page-id=3"
(link-url body "self"))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/3"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Patient"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Patient/2"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include"))))))))
(testing "iterative include"
(with-handler [handler]
[[[:put {:fhir/type :fhir/MedicationStatement :id "0"
:medication
#fhir/Reference
{:reference "Medication/0"}}]
[:put {:fhir/type :fhir/Medication :id "0"
:manufacturer
#fhir/Reference
{:reference "Organization/0"}}]
[:put {:fhir/type :fhir/Organization :id "0"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match medication-statement-match
:params
{"_include" "MedicationStatement:medication"
"_include:iterate" "Medication:manufacturer"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains two entries"
(is (= 3 (count (:entry body)))))
(testing "the first entry is the matched MedicationStatement"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/MedicationStatement/0"
[:resource :fhir/type] := :fhir/MedicationStatement
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Organization"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Organization/0"
[:resource :fhir/type] := :fhir/Organization
[:search :mode] := #fhir/code"include"))
(testing "the third entry is the included Medication"
(given (-> body :entry (nth 2))
:fullUrl := #fhir/uri"base-url-113047/Medication/0"
[:resource :fhir/type] := :fhir/Medication
[:search :mode] := #fhir/code"include")))))
(testing "non-iterative include doesn't work iterative"
(with-handler [handler]
[[[:put {:fhir/type :fhir/MedicationStatement :id "0"
:medication
#fhir/Reference
{:reference "Medication/0"}}]
[:put {:fhir/type :fhir/Medication :id "0"
:manufacturer
#fhir/Reference
{:reference "Organization/0"}}]
[:put {:fhir/type :fhir/Organization :id "0"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match medication-statement-match
:params
{"_include"
["MedicationStatement:medication" "Medication:manufacturer"]}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched MedicationStatement"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/MedicationStatement/0"
[:resource :fhir/type] := :fhir/MedicationStatement
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Medication"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Medication/0"
[:resource :fhir/type] := :fhir/Medication
[:search :mode] := #fhir/code"include")))))
(testing "revinclude"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject
#fhir/Reference
{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_revinclude" "Observation:subject"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_revinclude=Observation%3Asubject&_count=50&__t=1&__page-id=0"
(link-url body "self"))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched Patient"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Observation"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Observation/1"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"include"))))
(testing "two revincludes"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject
#fhir/Reference
{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Condition :id "2"
:subject
#fhir/Reference
{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params
{"_revinclude" ["Observation:subject" "Condition:subject"]}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_revinclude=Observation%3Asubject&_revinclude=Condition%3Asubject&_count=50&__t=1&__page-id=0"
(link-url body "self"))))
(testing "the bundle contains two entries"
(is (= 3 (count (:entry body)))))
(testing "the first entry is the matched Patient"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Observation"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Observation/1"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"include"))
(testing "the third entry is the included Condition"
(given (-> body :entry (nth 2))
:fullUrl := #fhir/uri"base-url-113047/Condition/2"
[:resource :fhir/type] := :fhir/Condition
[:search :mode] := #fhir/code"include"))))))
(testing "invalid include parameter"
(with-handler [handler]
[]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=strict"}
:params {"_include" "Observation"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"invalid"
[:issue 0 :diagnostics] := "Missing search parameter code in _include search parameter with source type `Observation`."))))))
| true | (ns blaze.interaction.search-type-test
"Specifications relevant for the FHIR search interaction:
https://www.hl7.org/fhir/http.html#search"
(:require
[blaze.db.api-stub :refer [mem-node-system with-system-data]]
[blaze.fhir.spec.type :as type]
[blaze.interaction.search-type]
[blaze.interaction.search.nav-spec]
[blaze.interaction.search.params-spec]
[blaze.interaction.search.util-spec]
[blaze.middleware.fhir.db :refer [wrap-db]]
[blaze.middleware.fhir.db-spec]
[blaze.middleware.fhir.error :refer [wrap-error]]
[blaze.page-store-spec]
[blaze.page-store.local]
[blaze.test-util :refer [given-thrown]]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as st]
[clojure.test :as test :refer [deftest is testing]]
[cuerdas.core :as str]
[integrant.core :as ig]
[java-time :as time]
[juxt.iota :refer [given]]
[reitit.core :as reitit]
[taoensso.timbre :as log])
(:import
[java.time Instant]))
(st/instrument)
(log/set-level! :trace)
(defn- fixture [f]
(st/instrument)
(f)
(st/unstrument))
(test/use-fixtures :each fixture)
(def base-url "base-url-113047")
(def router
(reitit/router
[["/Patient" {:name :Patient/type}]
["/Patient/__page" {:name :Patient/page}]
["/MeasureReport" {:name :MeasureReport/type}]
["/Library" {:name :Library/type}]
["/List" {:name :List/type}]
["/Condition" {:name :Condition/type}]
["/Observation" {:name :Observation/type}]
["/Observation/__page" {:name :Observation/page}]
["/MedicationStatement" {:name :MedicationStatement/type}]
["/Medication" {:name :Medication/type}]
["/Organization" {:name :Organization/type}]
["/Encounter" {:name :Encounter/type}]]
{:syntax :bracket}))
(def patient-match
(reitit/map->Match
{:data
{:fhir.resource/type "Patient"}
:path "/Patient"}))
(def patient-search-match
(reitit/map->Match
{:data
{:name :Patient/search
:fhir.resource/type "Patient"}
:path "/Patient"}))
(def patient-page-match
(reitit/map->Match
{:data
{:name :Patient/page
:fhir.resource/type "Patient"}
:path "/Patient"}))
(def measure-report-match
(reitit/map->Match
{:data
{:fhir.resource/type "MeasureReport"}
:path "/MeasureReport"}))
(def list-match
(reitit/map->Match
{:data
{:fhir.resource/type "List"}
:path "/List"}))
(def observation-match
(reitit/map->Match
{:data
{:fhir.resource/type "Observation"}
:path "/Observation"}))
(def condition-match
(reitit/map->Match
{:data
{:fhir.resource/type "Condition"}
:path "/Condition"}))
(def medication-statement-match
(reitit/map->Match
{:data
{:fhir.resource/type "MedicationStatement"}
:path "/MedicationStatement"}))
(defn- link-url [body link-relation]
(->> body :link (filter (comp #{link-relation} :relation)) first :url))
(deftest init-test
(testing "nil config"
(given-thrown (ig/init {:blaze.interaction/search-type nil})
:key := :blaze.interaction/search-type
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `map?))
(testing "missing config"
(given-thrown (ig/init {:blaze.interaction/search-type {}})
:key := :blaze.interaction/search-type
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :clock))
[:explain ::s/problems 1 :pred] := `(fn ~'[%] (contains? ~'% :rng-fn))
[:explain ::s/problems 2 :pred] := `(fn ~'[%] (contains? ~'% :page-store))))
(testing "invalid clock"
(given-thrown (ig/init {:blaze.interaction/search-type {:clock ::invalid}})
:key := :blaze.interaction/search-type
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :rng-fn))
[:explain ::s/problems 1 :pred] := `(fn ~'[%] (contains? ~'% :page-store))
[:explain ::s/problems 2 :pred] := `time/clock?
[:explain ::s/problems 2 :val] := ::invalid)))
(def system
(assoc mem-node-system
:blaze.interaction/search-type
{:clock (ig/ref :blaze.test/clock)
:rng-fn (ig/ref :blaze.test/fixed-rng-fn)
:page-store (ig/ref :blaze.page-store/local)}
:blaze.test/fixed-rng-fn {}
:blaze.page-store/local {:secure-rng (ig/ref :blaze.test/fixed-rng)}
:blaze.test/fixed-rng {}))
(defn wrap-defaults [handler]
(fn [request]
(handler
(assoc request
:blaze/base-url base-url
::reitit/router router))))
(defmacro with-handler [[handler-binding] txs & body]
`(with-system-data [{node# :blaze.db/node
handler# :blaze.interaction/search-type} system]
~txs
(let [~handler-binding (-> handler# wrap-defaults (wrap-db node#)
wrap-error)]
~@body)))
(deftest handler-test
(testing "on unknown search parameter"
(testing "with strict handling"
(testing "returns error"
(with-handler [handler]
[]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=strict"}
:params {"foo" "bar"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"not-found"
[:issue 0 :diagnostics] := "The search-param with code `foo` and type `Patient` was not found.")))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=strict"}
:params {"foo" "bar" "_summary" "count"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"not-found"
[:issue 0 :diagnostics] := "The search-param with code `foo` and type `Patient` was not found."))))))
(testing "with lenient handling"
(testing "returns results with a self link lacking the unknown search parameter"
(testing "where the unknown search parameter is the only one"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=lenient"}
:params {"foo" "bar"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=50&__t=1&__page-id=0"
(link-url body "self"))))))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=lenient"}
:params {"foo" "bar" "_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_summary=count&_count=50&__t=1"
(link-url body "self"))))))))
(testing "with another search parameter"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"
:active true}]]]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=lenient"}
:params {"foo" "bar" "active" "true"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=50&__t=1&__page-id=1"
(link-url body "self"))))))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=lenient"}
:params {"foo" "bar" "active" "true" "_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_summary=count&_count=50&__t=1"
(link-url body "self"))))))))))
(testing "with default handling"
(testing "returns results with a self link lacking the unknown search parameter"
(testing "where the unknown search parameter is the only one"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"foo" "bar"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=50&__t=1&__page-id=0"
(link-url body "self"))))))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"foo" "bar" "_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_summary=count&_count=50&__t=1"
(link-url body "self"))))))))
(testing "with another search parameter"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"
:active true}]]]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"foo" "bar" "active" "true"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=50&__t=1&__page-id=1"
(link-url body "self"))))))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"foo" "bar" "active" "true" "_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle id is an LUID"
(is (= "AAAAAAAAAAAAAAAA" (:id body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_summary=count&_count=50&__t=1"
(link-url body "self")))))))))))
(testing "on invalid date-time"
(testing "returns error"
(with-handler [handler]
[]
(testing "normal result"
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
;; the date is already URl decoded and so contains a space instead of a plus
:params {"date" "2021-12-09T00:00:00 01:00"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"invalid"
[:issue 0 :diagnostics] := "Invalid date-time value `2021-12-09T00:00:00 01:00` in search parameter `date`.")))
(testing "summary result"
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
;; the date is already URl decoded and so contains a space instead of a plus
:params {"date" "2021-12-09T00:00:00 01:00" "_summary" "count"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"invalid"
[:issue 0 :diagnostics] := "Invalid date-time value `2021-12-09T00:00:00 01:00` in search parameter `date`."))))))
(testing "on invalid token"
(testing "returns error"
(with-handler [handler]
[]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-page-match
:params {"__token" "PI:KEY:<KEY>END_PI" "_count" "1"
"__t" "1" "__page-id" "1"}})]
(is (= 422 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"invalid"
[:issue 0 :diagnostics] := "Invalid token `invalidPI:PASSWORD:<PASSWORD>END_PI-token-PI:PASSWORD:<PASSWORD>END_PI`.")))))
(testing "on missing token"
(testing "returns error"
(with-handler [handler]
[]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-page-match
:params {"__token" (PI:KEY:<KEY>END_PI "A" 32) "_count" "1" "__t" "1"
"__page-id" "1"}})]
(is (= 422 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"not-found"
[:issue 0 :diagnostics] := (format "Clauses of token `%s` not found."
(str/repeat "A" 32)))))))
(testing "with one patient"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]]
(testing "Returns all existing resources of type"
(let [{:keys [status body]}
@(handler {::reitit/match patient-match})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=50&__t=1&__page-id=0"
(link-url body "self"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0"
[:meta :versionId] := #fhir/id"1"
[:meta :lastUpdated] := Instant/EPOCH))
(testing "the entry has the right search information"
(given (-> body :entry first :search)
type/type := :fhir.Bundle.entry/search
:mode := #fhir/code"match"))))
(testing "with param _summary equal to count"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_summary" "count"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_summary=count&_count=50&__t=1"
(link-url body "self"))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))))
(testing "with param _count equal to zero"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_count" "0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=0&__t=1"
(link-url body "self"))))
(testing "the bundle contains no entries"
(is (empty? (:entry body))))))))
(testing "with two patients"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]]]
(testing "search for all patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"_count" "1"}})]
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=1&__t=1&__page-id=0"
(link-url body "self"))))
(testing "has a next link"
(is (= #fhir/uri"base-url-113047/Patient/__page?_count=1&__t=1&__page-id=1"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "following the self link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"_count" "1" "__t" "1" "__page-id" "0"}})]
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=1&__t=1&__page-id=0"
(link-url body "self"))))
(testing "has a next link"
(is (= #fhir/uri"base-url-113047/Patient/__page?_count=1&__t=1&__page-id=1"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "following the next link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"_count" "1" "__t" "1" "__page-id" "1"}})]
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_count=1&__t=1&__page-id=1"
(link-url body "self"))))
(testing "has no next link"
(is (nil? (link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))))
(testing "with three patients"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1" :active true}]
[:put {:fhir/type :fhir/Patient :id "2" :active true}]]]
(testing "search for active patients with _summary=count"
(testing "with strict handling"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=strict"}
:params {"active" "true" "_summary" "count"}})]
(testing "their is a total count because we used _summary=count"
(is (= #fhir/unsignedInt 2 (:total body))))))
(testing "with default handling"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"active" "true" "_summary" "count"}})]
(testing "their is a total count because we used _summary=count"
(is (= #fhir/unsignedInt 2 (:total body)))))))
(testing "on normal request"
(testing "search for active patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"active" "true" "_count" "1"}})]
(testing "their is no total count because we have clauses and we have
more hits than page-size"
(is (nil? (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=1&__t=1&__page-id=1"
(link-url body "self"))))
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Patient/__page?active=true&_count=1&__t=1&__page-id=2"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body))))))))
(testing "on /_search request"
(testing "search for active patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-search-match
:params {"active" "true" "_count" "1"}})]
(testing "their is no total count because we have clauses and we have
more hits than page-size"
(is (nil? (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=1&__t=1&__page-id=1"
(link-url body "self"))))
(testing "has a next link with token"
(is (= #fhir/uri"base-url-113047/Patient/__page?__token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB&_count=1&__t=1&__page-id=2"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body))))))))
(testing "following the self link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"active" "true" "_count" "1" "__t" "1" "__page-id" "1"}})]
(testing "their is no total count because we have clauses and we have
more hits than page-size"
(is (nil? (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=1&__t=1&__page-id=1"
(link-url body "self"))))
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Patient/__page?active=true&_count=1&__t=1&__page-id=2"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "following the next link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-page-match
:params {"__token" "PI:KEY:<KEY>END_PI" "_count" "1" "__t" "1" "__page-id" "2"}})]
(testing "their is no total count because we have clauses and we have
more hits than page-size"
(is (nil? (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?active=true&_count=1&__t=1&__page-id=2"
(link-url body "self"))))
(testing "has no next link"
(is (nil? (link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))))
(testing "with four patients"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1" :active true}]
[:put {:fhir/type :fhir/Patient :id "2" :active true}]
[:put {:fhir/type :fhir/Patient :id "3" :active true}]]]
(testing "on normal request"
(testing "search for active patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-match
:params {"active" "true" "_count" "1"}})]
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Patient/__page?active=true&_count=1&__t=1&__page-id=2"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "following the next link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-page-match
:params {"active" "true" "_count" "1" "__t" "1" "__page-id" "2"}})]
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Patient/__page?active=true&_count=1&__t=1&__page-id=3"
(link-url body "next"))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body))))))))
(testing "on /_search request"
(testing "search for active patients with _count=1"
(let [{:keys [body]}
@(handler
{::reitit/match patient-search-match
:params {"active" "true" "_count" "1"}})]
(testing "has a next link with token"
(is (= #fhir/uri"base-url-113047/Patient/__page?__token=PI:KEY:<KEY>END_PIAB&_count=1&__t=1&__page-id=2"
(link-url body "next"))))))
(testing "following the next link"
(let [{:keys [body]}
@(handler
{::reitit/match patient-page-match
:params {"__token" "PI:KEY:<KEY>END_PI" "_count" "1" "__t" "1" "__page-id" "2"}})]
(testing "has a next link with token"
(is (= #fhir/uri"base-url-113047/Patient/__page?__token=PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI&_count=1&__t=1&__page-id=3"
(link-url body "next")))))))))
(testing "_id search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_id" "0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0"))))
(testing "multiple id's"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]
[:put {:fhir/type :fhir/Patient :id "2"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_id" "0,2"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "the bundle contains one entry"
(is (= 2 (count (:entry body)))))
(testing "the first entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the second entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/2"
(-> body :entry second :fullUrl))))
(testing "the first entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0"))
(testing "the second entry has the right resource"
(given (-> body :entry second :resource)
:fhir/type := :fhir/Patient
:id := "2"))))))
(testing "_lastUpdated search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]]
(testing "the resource is created at EPOCH"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_lastUpdated" "1970-01-01"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))))
(testing "no resource is created after EPOCH"
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_lastUpdated" "gt1970-01-02"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 0"
(is (= #fhir/unsignedInt 0 (:total body))))
(testing "the bundle contains no entry"
(is (zero? (count (:entry body))))))))
(testing "deleted resources are not found"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]]
[[:delete "Patient" "0"]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_lastUpdated" "1970-01-01"}})]
(is (= 200 status))
(testing "the total count is 0"
(is (= #fhir/unsignedInt 0 (:total body))))
(testing "the bundle contains one entry"
(is (= 0 (count (:entry body)))))))))
(testing "_profile search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put
{:fhir/type :fhir/Patient :id "1"
:meta
#fhir/Meta
{:profile [#fhir/canonical"profile-uri-151511"]}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_profile" "profile-uri-151511"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/1"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
[:meta :profile 0] := #fhir/canonical"profile-uri-151511"
:id := "1")))))
(testing "_list search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]
[:put {:fhir/type :fhir/List :id "0"
:entry
[{:fhir/type :fhir.List/entry
:item
#fhir/Reference
{:reference "Patient/0"}}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_list" "0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0")))))
(testing "_has search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Patient :id "1"}]
[:put {:fhir/type :fhir/Observation :id "0"
:subject
#fhir/Reference
{:reference "Patient/0"}
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 130M
:code #fhir/code"mm[Hg]"
:system #fhir/uri"http://unitsofmeasure.org"}}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject
#fhir/Reference
{:reference "Patient/0"}
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 150M
:code #fhir/code"mm[Hg]"
:system #fhir/uri"http://unitsofmeasure.org"}}]
[:put {:fhir/type :fhir/Observation :id "2"
:subject
#fhir/Reference
{:reference "Patient/1"}
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 100M
:code #fhir/code"mm[Hg]"
:system #fhir/uri"http://unitsofmeasure.org"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_has:Observation:patient:code-value-quantity" "8480-6$ge130"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Patient
:id := "0")))))
(testing "Patient identifier search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"
:identifier [#fhir/Identifier{:value "0"}]}]
[:put {:fhir/type :fhir/Patient :id "1"
:identifier [#fhir/Identifier{:value "1"}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"identifier" "0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
[:identifier 0 :value] := "0")))))
(testing "Patient language search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"
:communication
[{:fhir/type :fhir.Patient/communication
:language
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"urn:ietf:bcp:47"
:code #fhir/code"de"}]}}
{:fhir/type :fhir.Patient/communication
:language
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"urn:ietf:bcp:47"
:code #fhir/code"en"}]}}]}]
[:put {:fhir/type :fhir/Patient :id "1"
:communication
[{:fhir/type :fhir.Patient/communication
:language
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"urn:ietf:bcp:47"
:code #fhir/code"de"}]}}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"language" ["de" "en"]}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Patient/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(is (= "0" (-> body :entry first :resource :id)))))))
(testing "Library title search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Library :id "0" :title "ab"}]
[:put {:fhir/type :fhir/Library :id "1" :title "b"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match {:data {:fhir.resource/type "Library"}}
:params {"title" "A"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Library/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:fhir/type := :fhir/Library
:id := "0")))))
(testing "MeasureReport measure search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/MeasureReport :id "0"
:measure #fhir/canonical"http://server.com/Measure/0"}]]
[[:put {:fhir/type :fhir/MeasureReport :id "1"
:measure #fhir/canonical"http://server.com/Measure/1"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match measure-report-match
:params {"measure" "http://server.com/Measure/0"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/MeasureReport/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:measure := #fhir/canonical"http://server.com/Measure/0")))))
(testing "List item search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/List :id "id-123058"
:entry
[{:fhir/type :fhir.List/entry
:item
#fhir/Reference
{:identifier
#fhir/Identifier
{:system #fhir/uri"system-122917"
:value "value-122931"}}}]}]
[:put {:fhir/type :fhir/List :id "id-143814"
:entry
[{:fhir/type :fhir.List/entry
:item
#fhir/Reference
{:identifier
#fhir/Identifier
{:system #fhir/uri"system-122917"
:value "value-143818"}}}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match list-match
:params {"item:identifier" "system-122917|value-143818"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/List/id-143814"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
:id := "id-143814")))))
(testing "Observation combo-code-value-quantity search"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Observation :id "id-121049"
:component
[{:fhir/type :fhir.Observation/component
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 140M
:system #fhir/uri"http://unitsofmeasure.org"
:code #fhir/code"mm[Hg]"}}
{:fhir/type :fhir.Observation/component
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8462-4"}]}
:value
#fhir/Quantity
{:value 90M
:system #fhir/uri"http://unitsofmeasure.org"
:code #fhir/code"mm[Hg]"}}]}]]
[[:put {:fhir/type :fhir/Observation :id "id-123130"
:component
[{:fhir/type :fhir.Observation/component
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8480-6"}]}
:value
#fhir/Quantity
{:value 150M
:system #fhir/uri"http://unitsofmeasure.org"
:code #fhir/code"mm[Hg]"}}
{:fhir/type :fhir.Observation/component
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://loinc.org"
:code #fhir/code"8462-4"}]}
:value
#fhir/Quantity
{:value 100M
:system #fhir/uri"http://unitsofmeasure.org"
:code #fhir/code"mm[Hg]"}}]}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params
{"combo-code-value-quantity"
["http://loinc.org|8480-6$ge140|mm[Hg]"
"http://loinc.org|8462-4$ge90|mm[Hg]"]
"_count" "1"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "has a next link with search params"
(is (= #fhir/uri"base-url-113047/Observation/__page?combo-code-value-quantity=http%3A%2F%2Floinc.org%7C8480-6%24ge140%7Cmm%5BHg%5D&combo-code-value-quantity=http%3A%2F%2Floinc.org%7C8462-4%24ge90%7Cmm%5BHg%5D&_count=1&__t=2&__page-id=id-123130"
(link-url body "next")))))))
(testing "Duplicate OR Search Parameters have no Effect (#293)"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Condition :id "0"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri"http://fhir.de/CodeSystem/dimdi/icd-10-gm"
:code #fhir/code"C71.4"}]}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match condition-match
:params {"code" "C71.4,C71.4"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Condition/0"
(-> body :entry first :fullUrl))))
(testing "the entry has the right resource"
(given (-> body :entry first :resource)
[:code :coding 0 :code] := #fhir/code"C71.4")))))
(testing "Paging works with OR Search Parameters"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Condition :id "0"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:code #fhir/code"0"}]}}]
[:put {:fhir/type :fhir/Condition :id "2"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:code #fhir/code"0"}]}}]
[:put {:fhir/type :fhir/Condition :id "1"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:code #fhir/code"1"}]}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match condition-match
:params {"code" "0,1" "_count" "2"
"__t" "1" "__page-id" "1"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the entry has the right fullUrl"
(is (= #fhir/uri"base-url-113047/Condition/1"
(-> body :entry first :fullUrl)))))))
(testing "Include Resources"
(testing "direct include"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "0"
:subject #fhir/Reference{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Observation?_include=Observation%3Asubject&_count=50&__t=1&__page-id=0"
(link-url body "self"))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/0"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Patient"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include"))))
(testing "with non-matching target type"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "0"
:subject #fhir/Reference{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject:Group"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains one entry"
(is (= 1 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/0"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match")))))
(testing "includes don't appear twice"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject #fhir/Reference{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Observation :id "2"
:subject #fhir/Reference{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "the bundle contains three entries"
(is (= 3 (count (:entry body)))))
(testing "the first entry is the first matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/1"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the second matched Observation"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Observation/2"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the third entry is the included Patient"
(given (-> body :entry (nth 2))
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include")))))
(testing "two includes"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Encounter :id "1"
:subject #fhir/Reference{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Observation :id "2"
:subject #fhir/Reference{:reference "Patient/0"}
:encounter #fhir/Reference{:reference "Encounter/1"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params
{"_include" ["Observation:subject" "Observation:encounter"]}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains three entries"
(is (= 3 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/2"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Encounter"
(given (-> body :entry (nth 2))
:fullUrl := #fhir/uri"base-url-113047/Encounter/1"
[:resource :fhir/type] := :fhir/Encounter
[:search :mode] := #fhir/code"include"))
(testing "the third entry is the included Patient"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include")))))
(testing "with paging"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject
#fhir/Reference
{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Patient :id "2"}]
[:put {:fhir/type :fhir/Observation :id "3"
:subject
#fhir/Reference
{:reference "Patient/2"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject" "_count" "1"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a next link"
(is (= #fhir/uri"base-url-113047/Observation/__page?_include=Observation%3Asubject&_count=1&__t=1&__page-id=3"
(link-url body "next"))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/1"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Patient"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include"))
(testing "second page"
(let [{:keys [status body]}
@(handler
{::reitit/match observation-match
:params {"_include" "Observation:subject" "_count" "2"
"__t" "1" "__page-id" "3"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 2"
(is (= #fhir/unsignedInt 2 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Observation?_include=Observation%3Asubject&_count=2&__t=1&__page-id=3"
(link-url body "self"))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched Observation"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Observation/3"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Patient"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Patient/2"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"include"))))))))
(testing "iterative include"
(with-handler [handler]
[[[:put {:fhir/type :fhir/MedicationStatement :id "0"
:medication
#fhir/Reference
{:reference "Medication/0"}}]
[:put {:fhir/type :fhir/Medication :id "0"
:manufacturer
#fhir/Reference
{:reference "Organization/0"}}]
[:put {:fhir/type :fhir/Organization :id "0"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match medication-statement-match
:params
{"_include" "MedicationStatement:medication"
"_include:iterate" "Medication:manufacturer"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains two entries"
(is (= 3 (count (:entry body)))))
(testing "the first entry is the matched MedicationStatement"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/MedicationStatement/0"
[:resource :fhir/type] := :fhir/MedicationStatement
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Organization"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Organization/0"
[:resource :fhir/type] := :fhir/Organization
[:search :mode] := #fhir/code"include"))
(testing "the third entry is the included Medication"
(given (-> body :entry (nth 2))
:fullUrl := #fhir/uri"base-url-113047/Medication/0"
[:resource :fhir/type] := :fhir/Medication
[:search :mode] := #fhir/code"include")))))
(testing "non-iterative include doesn't work iterative"
(with-handler [handler]
[[[:put {:fhir/type :fhir/MedicationStatement :id "0"
:medication
#fhir/Reference
{:reference "Medication/0"}}]
[:put {:fhir/type :fhir/Medication :id "0"
:manufacturer
#fhir/Reference
{:reference "Organization/0"}}]
[:put {:fhir/type :fhir/Organization :id "0"}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match medication-statement-match
:params
{"_include"
["MedicationStatement:medication" "Medication:manufacturer"]}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched MedicationStatement"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/MedicationStatement/0"
[:resource :fhir/type] := :fhir/MedicationStatement
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Medication"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Medication/0"
[:resource :fhir/type] := :fhir/Medication
[:search :mode] := #fhir/code"include")))))
(testing "revinclude"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject
#fhir/Reference
{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params {"_revinclude" "Observation:subject"}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_revinclude=Observation%3Asubject&_count=50&__t=1&__page-id=0"
(link-url body "self"))))
(testing "the bundle contains two entries"
(is (= 2 (count (:entry body)))))
(testing "the first entry is the matched Patient"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Observation"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Observation/1"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"include"))))
(testing "two revincludes"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "1"
:subject
#fhir/Reference
{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Condition :id "2"
:subject
#fhir/Reference
{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:params
{"_revinclude" ["Observation:subject" "Condition:subject"]}})]
(is (= 200 status))
(testing "the body contains a bundle"
(is (= :fhir/Bundle (:fhir/type body))))
(testing "the bundle type is searchset"
(is (= #fhir/code"searchset" (:type body))))
(testing "the total count is 1"
(is (= #fhir/unsignedInt 1 (:total body))))
(testing "has a self link"
(is (= #fhir/uri"base-url-113047/Patient?_revinclude=Observation%3Asubject&_revinclude=Condition%3Asubject&_count=50&__t=1&__page-id=0"
(link-url body "self"))))
(testing "the bundle contains two entries"
(is (= 3 (count (:entry body)))))
(testing "the first entry is the matched Patient"
(given (-> body :entry first)
:fullUrl := #fhir/uri"base-url-113047/Patient/0"
[:resource :fhir/type] := :fhir/Patient
[:search :mode] := #fhir/code"match"))
(testing "the second entry is the included Observation"
(given (-> body :entry second)
:fullUrl := #fhir/uri"base-url-113047/Observation/1"
[:resource :fhir/type] := :fhir/Observation
[:search :mode] := #fhir/code"include"))
(testing "the third entry is the included Condition"
(given (-> body :entry (nth 2))
:fullUrl := #fhir/uri"base-url-113047/Condition/2"
[:resource :fhir/type] := :fhir/Condition
[:search :mode] := #fhir/code"include"))))))
(testing "invalid include parameter"
(with-handler [handler]
[]
(let [{:keys [status body]}
@(handler
{::reitit/match patient-match
:headers {"prefer" "handling=strict"}
:params {"_include" "Observation"}})]
(is (= 400 status))
(given body
:fhir/type := :fhir/OperationOutcome
[:issue 0 :severity] := #fhir/code"error"
[:issue 0 :code] := #fhir/code"invalid"
[:issue 0 :diagnostics] := "Missing search parameter code in _include search parameter with source type `Observation`."))))))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9998610615730286,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "es.clj: unit tests for fixtures in test.clj\n\n;; by Stuart Sierra\n;; March 28, 2009\n\n(ns clojure.test-clojure.test-",
"end": 544,
"score": 0.9998652338981628,
"start": 531,
"tag": "NAME",
"value": "Stuart Sierra"
}
] | Clojure/clojure/test_clojure/test_fixtures.clj | AydarLukmanov/ArcadiaGodot | 328 | ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;
;;; test_fixtures.clj: unit tests for fixtures in test.clj
;; by Stuart Sierra
;; March 28, 2009
(ns clojure.test-clojure.test-fixtures
(:use clojure.test))
(declare ^:dynamic *a* ^:dynamic *b* ^:dynamic *c* ^:dynamic *d*)
(def ^:dynamic *n* 0)
(defn fixture-a [f]
(binding [*a* 3] (f)))
(defn fixture-b [f]
(binding [*b* 5] (f)))
(defn fixture-c [f]
(binding [*c* 7] (f)))
(defn fixture-d [f]
(binding [*d* 11] (f)))
(defn inc-n-fixture [f]
(binding [*n* (inc *n*)] (f)))
(def side-effects (atom 0))
(defn side-effecting-fixture [f]
(swap! side-effects inc)
(f))
(use-fixtures :once fixture-a fixture-b)
(use-fixtures :each fixture-c fixture-d inc-n-fixture side-effecting-fixture)
(use-fixtures :each fixture-c fixture-d inc-n-fixture side-effecting-fixture)
(deftest can-use-once-fixtures
(is (= 3 *a*))
(is (= 5 *b*)))
(deftest can-use-each-fixtures
(is (= 7 *c*))
(is (= 11 *d*)))
(deftest use-fixtures-replaces
(is (= *n* 1)))
(deftest can-run-a-single-test-with-fixtures
;; We have to use a side-effecting fixture to test that the fixtures are
;; running, in order to distinguish fixtures run because of our call to
;; test-vars below from the same fixtures running prior to this test
(let [side-effects-so-far @side-effects
reported (atom [])]
(binding [report (fn [m] (swap! reported conj (:type m)))]
(test-vars [#'can-use-each-fixtures]))
(is (= [:begin-test-var :pass :pass :end-test-var] @reported))
(is (= (inc side-effects-so-far) @side-effects))))
(defn should-not-trigger-fixtures [])
(deftest a-var-lacking-test-meta-should-not-trigger-fixtures
(let [side-effects-so-far @side-effects]
(test-vars [#'should-not-trigger-fixtures])
(is (= side-effects-so-far @side-effects)))) | 92016 | ; Copyright (c) <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;
;;; test_fixtures.clj: unit tests for fixtures in test.clj
;; by <NAME>
;; March 28, 2009
(ns clojure.test-clojure.test-fixtures
(:use clojure.test))
(declare ^:dynamic *a* ^:dynamic *b* ^:dynamic *c* ^:dynamic *d*)
(def ^:dynamic *n* 0)
(defn fixture-a [f]
(binding [*a* 3] (f)))
(defn fixture-b [f]
(binding [*b* 5] (f)))
(defn fixture-c [f]
(binding [*c* 7] (f)))
(defn fixture-d [f]
(binding [*d* 11] (f)))
(defn inc-n-fixture [f]
(binding [*n* (inc *n*)] (f)))
(def side-effects (atom 0))
(defn side-effecting-fixture [f]
(swap! side-effects inc)
(f))
(use-fixtures :once fixture-a fixture-b)
(use-fixtures :each fixture-c fixture-d inc-n-fixture side-effecting-fixture)
(use-fixtures :each fixture-c fixture-d inc-n-fixture side-effecting-fixture)
(deftest can-use-once-fixtures
(is (= 3 *a*))
(is (= 5 *b*)))
(deftest can-use-each-fixtures
(is (= 7 *c*))
(is (= 11 *d*)))
(deftest use-fixtures-replaces
(is (= *n* 1)))
(deftest can-run-a-single-test-with-fixtures
;; We have to use a side-effecting fixture to test that the fixtures are
;; running, in order to distinguish fixtures run because of our call to
;; test-vars below from the same fixtures running prior to this test
(let [side-effects-so-far @side-effects
reported (atom [])]
(binding [report (fn [m] (swap! reported conj (:type m)))]
(test-vars [#'can-use-each-fixtures]))
(is (= [:begin-test-var :pass :pass :end-test-var] @reported))
(is (= (inc side-effects-so-far) @side-effects))))
(defn should-not-trigger-fixtures [])
(deftest a-var-lacking-test-meta-should-not-trigger-fixtures
(let [side-effects-so-far @side-effects]
(test-vars [#'should-not-trigger-fixtures])
(is (= side-effects-so-far @side-effects)))) | true | ; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;
;;; test_fixtures.clj: unit tests for fixtures in test.clj
;; by PI:NAME:<NAME>END_PI
;; March 28, 2009
(ns clojure.test-clojure.test-fixtures
(:use clojure.test))
(declare ^:dynamic *a* ^:dynamic *b* ^:dynamic *c* ^:dynamic *d*)
(def ^:dynamic *n* 0)
(defn fixture-a [f]
(binding [*a* 3] (f)))
(defn fixture-b [f]
(binding [*b* 5] (f)))
(defn fixture-c [f]
(binding [*c* 7] (f)))
(defn fixture-d [f]
(binding [*d* 11] (f)))
(defn inc-n-fixture [f]
(binding [*n* (inc *n*)] (f)))
(def side-effects (atom 0))
(defn side-effecting-fixture [f]
(swap! side-effects inc)
(f))
(use-fixtures :once fixture-a fixture-b)
(use-fixtures :each fixture-c fixture-d inc-n-fixture side-effecting-fixture)
(use-fixtures :each fixture-c fixture-d inc-n-fixture side-effecting-fixture)
(deftest can-use-once-fixtures
(is (= 3 *a*))
(is (= 5 *b*)))
(deftest can-use-each-fixtures
(is (= 7 *c*))
(is (= 11 *d*)))
(deftest use-fixtures-replaces
(is (= *n* 1)))
(deftest can-run-a-single-test-with-fixtures
;; We have to use a side-effecting fixture to test that the fixtures are
;; running, in order to distinguish fixtures run because of our call to
;; test-vars below from the same fixtures running prior to this test
(let [side-effects-so-far @side-effects
reported (atom [])]
(binding [report (fn [m] (swap! reported conj (:type m)))]
(test-vars [#'can-use-each-fixtures]))
(is (= [:begin-test-var :pass :pass :end-test-var] @reported))
(is (= (inc side-effects-so-far) @side-effects))))
(defn should-not-trigger-fixtures [])
(deftest a-var-lacking-test-meta-should-not-trigger-fixtures
(let [side-effects-so-far @side-effects]
(test-vars [#'should-not-trigger-fixtures])
(is (= side-effects-so-far @side-effects)))) |
[
{
"context": "09/04/understanding-y-combinator.html\n;; Thanks to Jeff Foster\n\n;; The mysterious and brain-shattering Y combina",
"end": 102,
"score": 0.9998906850814819,
"start": 91,
"tag": "NAME",
"value": "Jeff Foster"
}
] | func-prog/fp-oo/old-code/sources/Y.clj | tannerwelsh/code-training | 0 | ;; Taken from http://www.fatvat.co.uk/2009/04/understanding-y-combinator.html
;; Thanks to Jeff Foster
;; The mysterious and brain-shattering Y combinator!
(defn Y [r]
((fn [f] (f f))
(fn [f]
(r (fn [x] ((f f) x))))))
;; Defining factorial with Y
(Y (fn [factorial]
(fn [n]
(if (or (= 0 n) (= 1 n))
n
(* n (factorial (dec n)))))))
| 8626 | ;; Taken from http://www.fatvat.co.uk/2009/04/understanding-y-combinator.html
;; Thanks to <NAME>
;; The mysterious and brain-shattering Y combinator!
(defn Y [r]
((fn [f] (f f))
(fn [f]
(r (fn [x] ((f f) x))))))
;; Defining factorial with Y
(Y (fn [factorial]
(fn [n]
(if (or (= 0 n) (= 1 n))
n
(* n (factorial (dec n)))))))
| true | ;; Taken from http://www.fatvat.co.uk/2009/04/understanding-y-combinator.html
;; Thanks to PI:NAME:<NAME>END_PI
;; The mysterious and brain-shattering Y combinator!
(defn Y [r]
((fn [f] (f f))
(fn [f]
(r (fn [x] ((f f) x))))))
;; Defining factorial with Y
(Y (fn [factorial]
(fn [n]
(if (or (= 0 n) (= 1 n))
n
(* n (factorial (dec n)))))))
|
[
{
"context": "s event-data-percolator.consts)\n\n(def user-agent \"CrossrefEventDataBot (eventdata@crossref.org)\")\n(def user-agent-for-ro",
"end": 72,
"score": 0.952051043510437,
"start": 52,
"tag": "USERNAME",
"value": "CrossrefEventDataBot"
},
{
"context": "r.consts)\n\n(def user-agent \"CrossrefEventDataBot (eventdata@crossref.org)\")\n(def user-agent-for-robots \"CrossrefEventDataB",
"end": 96,
"score": 0.9999065399169922,
"start": 74,
"tag": "EMAIL",
"value": "eventdata@crossref.org"
}
] | src/event_data_percolator/consts.clj | CrossRef/event-data-percolator | 2 | (ns event-data-percolator.consts)
(def user-agent "CrossrefEventDataBot (eventdata@crossref.org)")
(def user-agent-for-robots "CrossrefEventDataBot") | 105319 | (ns event-data-percolator.consts)
(def user-agent "CrossrefEventDataBot (<EMAIL>)")
(def user-agent-for-robots "CrossrefEventDataBot") | true | (ns event-data-percolator.consts)
(def user-agent "CrossrefEventDataBot (PI:EMAIL:<EMAIL>END_PI)")
(def user-agent-for-robots "CrossrefEventDataBot") |
[
{
"context": "(ns ^{:author \"Adam Berger\"} ulvm.flows\n \"Flow operations\"\n (:require [clo",
"end": 26,
"score": 0.9998617172241211,
"start": 15,
"tag": "NAME",
"value": "Adam Berger"
}
] | src/ulvm/flows.clj | abrgr/ulvm | 0 | (ns ^{:author "Adam Berger"} ulvm.flows
"Flow operations"
(:require [clojure.spec :as s]
[ulvm.core :as ucore]
[ulvm.utils :as u]
[ulvm.project :as uprj]
[clojure.set :as cset]
[cats.monad.either :as e]))
(defn module-for-invocation
"The module that the given invocation references.
A scope-name is used to disambiguate references to
local modules."
[mods scope-name inv]
(let [inv-mod (->> [(:invocation-module inv)]
(into {}))
scope-mod (:scope-module inv-mod)
local-mod (:local-module inv-mod)
; we have to do some gymnastics to handle local and
; scope modules
mod-scope-name (-> (or (:scope scope-mod)
scope-name)
keyword)
module-name (-> (or (:module-name scope-mod)
local-mod)
keyword)
module (get-in mods [mod-scope-name module-name])]
{:mod module
:mod-name module-name
:scope mod-scope-name}))
(s/fdef module-for-invocation
:args (s/cat :mods (s/map-of keyword?
(s/map-of keyword?
::ucore/module))
:scope-name (s/nilable keyword?)
:inv ::uprj/inv)
:ret (s/keys :req-un [::uprj/mod ::uprj/mod-name ::uprj/scope]))
(defn- default-invocation-name
[invocation]
(-> (get invocation :invocation-module)
(#(or (get-in % [:scope-module :module-name])
(get % :local-module)))
(str "_")
(gensym)))
(defn- invocation-name
"Returns the name for the result of an invocation"
[invocation]
(get-in
invocation
[:name :name]
(default-invocation-name invocation)))
(defn named-invocations
"Returns a map from result names to invocations"
[invocations]
(reduce
(fn [named inv]
(conj named [(invocation-name inv) inv]))
{}
invocations))
(s/fdef named-invocations
:args (s/cat :invocations (s/coll-of ::uprj/inv))
:ret (s/map-of symbol? ::uprj/inv))
(defn- relevant-transformers
[prj bindings transformers]
(reduce
(fn [relevant [transform-name transform]]
(let [phase (u/get-in transform [:when :phase])
pred (u/get-in transform [:when :if])]
(if (uprj/eval-in-ctx prj [] bindings pred)
(assoc-in relevant [phase] (u/get-in transform [:do])) ; TODO: do we really want to allow multiple transformers with the same phase?
relevant)))
{}
transformers))
(s/def ::client-pre ::ucore/flow-invocations)
(s/def ::client-post ::ucore/flow-invocations)
(s/def ::server-pre ::ucore/flow-invocations)
(s/def ::server-post ::ucore/flow-invocations)
(s/def ::transformer-bindings map?)
(s/def ::transformers (s/map-of ::ucore/name ::ucore/transformer))
(s/fdef relevant-transformers
:args (s/cat :prj ::uprj/project
:bindings ::transformer-bindings
:transformers (s/nilable ::transformers))
:ret (s/keys :req-un [::client-pre
::client-post
::server-pre
::server-post]))
(defn- invocation-deps
[invocation]
(cset/union
(->>
(get-in invocation [:after :names])
second
flatten
(filter identity)
(into #{}))
(->> (:args invocation)
(filter
(fn [[_ [arg-type arg]]]
(= :ref arg-type)))
(map
(fn [[_ [_ [ref-arg-type arg]]]]
(if (= :default-ref-arg ref-arg-type)
arg
(:result arg))))
(into #{}))))
(defn invocation-dependency-graph
"Returns a map from invocation name to a set of names of the invocations it depends on."
[invocations]
(reduce
(fn [deps [name invocation]]
(merge-with cset/union deps {name (invocation-deps invocation)}))
{}
invocations))
(defn ordered-invocations
"Returns a seq of topologically ordered invocation names"
[invs deps params]
(let [sorted (u/topo-sort deps (keys invs) (into #{} params))]
(if (empty? (:unsat sorted))
(e/right (:items sorted))
(e/left {:msg "Failed to satisfy call graph dependencies"
:unsat-deps (:unsat sorted)}))))
(defn flow-params
"Returns the parameters of the flow."
[flow]
(get (meta flow) ::ucore/args))
(defn- home-scope
"Every flow has a \"home scope,\" which is the scope in which the flow
originates and from which all invocations initiate."
[flow]
(u/get-in flow [:config ::ucore/home-scope]))
(defn- inv-with-default-scope
"If inv refers to a local module, return an inv for that module on scope."
[scope inv]
(if-let [local-mod (u/get-in inv [:invocation-module :local-module])]
(assoc
inv
:invocation-module
{:scope-module (list (keyword local-mod) (symbol (str scope)))})
inv))
(defn- invs-with-default-scope
[scope invs]
(->> invs
(map
(fn [[k inv]]
[k (inv-with-default-scope scope inv)]))
(into {})))
(defn- sym-in-ns
[ns sym]
(symbol (str "*" ns "*" sym)))
(defn- inv-in-ns
[ns invs inv]
(update
inv
:args
#(->> %
(map
(fn [[arg-name arg]]
(let [def-ref (u/get-in arg [:ref :default-ref-arg])
named-ref (u/get-in arg [:ref :named-ref-arg])]
(cond
(and (some? def-ref) (contains? invs def-ref))
[arg-name [:ref [:default-ref-arg (sym-in-ns ns def-ref)]]]
(and (some? named-ref) (contains? invs (get named-ref :result)))
[arg-name [:ref [:named-ref-arg (assoc named-ref :result (sym-in-ns ns (get named-ref :result)))]]]
:else
[arg-name arg]))))
(into {}))))
(defn- invs-in-ns
[ns invs]
(reduce
(fn [ns-invs [n inv]]
(assoc
ns-invs
(sym-in-ns ns n)
(inv-in-ns ns invs inv)))
{}
invs))
(defn- transformers-for-rel-scope
[transformers rel-scope client-scope-name server-scope-name]
(let [def-scope-by-phase {:client-pre client-scope-name
:client-post client-scope-name
:server-pre server-scope-name
:server-post server-scope-name}
phases (if (= :client rel-scope)
[:client-pre :client-post]
[:server-pre :server-post])]
(map
#(some->> (get transformers %)
(s/conform ::ucore/flow-invocations)
named-invocations
(invs-with-default-scope (get def-scope-by-phase %)))
phases)))
(defn- get-transformer-mods
[mod transformers]
(let [transformer-mods (->> transformers
(apply concat)
vals
(map #(first (u/get-in % [:invocation-module :scope-module])))
set)]
(->> (get mod ::ucore/transformer-modules)
(filter
(fn [[mod-name mod]]
(transformer-mods mod-name)))
(into {}))))
(defn invs-in-scope
"Place invs in the provided scope"
[scope-name invs]
(map
(fn [[mod-ref & rest-of-inv]]
(if (symbol? mod-ref)
(concat [(list (-> mod-ref name keyword) (-> scope-name name symbol))] rest-of-inv)
(concat [mod-ref] rest-of-inv))) ; TODO: can check that mod-ref refers to scope
invs))
(s/fdef invs-in-scope
:args (s/cat :scope-name keyword?
:invs (s/nilable (s/coll-of ::ucore/flow-invocation)))
:ret (s/coll-of ::ucore/flow-invocation))
(defn expand-transformers
"Inlines applicable transformers for any module invocations in the flow."
([prj mods named-scope-cfgs canonical-flow]
(expand-transformers prj mods named-scope-cfgs nil canonical-flow))
([prj mods named-scope-cfgs scope canonical-flow]
(let [client-scope-name (home-scope canonical-flow)
client-scope-cfg (get named-scope-cfgs client-scope-name)]
(->> canonical-flow
:invocations
named-invocations
(reduce
(fn [acc [inv-name inv]]
(let [{mod :mod
server-scope-name :scope} (module-for-invocation mods scope inv) ; TODO: if scope is not nil and server-scope-name != scope, we have a problem (this is the case for scope initializers)
server-scope-cfg (get named-scope-cfgs server-scope-name)
param-bindings (->> (u/get-in inv [:args])
(map
(fn [[k arg]]
[k (s/unform ::ucore/flow-arg arg)]))
(into {}))
transformer-bindings {'*client-scope* client-scope-name
'*client-scope-cfg* client-scope-cfg
'*server-scope* server-scope-name
'*server-scope-cfg* server-scope-cfg
'*inv* (u/get-in inv [:invocation-module])}
; TODO: only allow some bindings in some phases
transformers (->> (get mod ::ucore/transformers)
(relevant-transformers prj (merge transformer-bindings param-bindings)))
client-transformers (transformers-for-rel-scope
transformers
:client
client-scope-name
server-scope-name)
server-transformers (transformers-for-rel-scope
transformers
:server
client-scope-name
server-scope-name)
client-mods (get-transformer-mods
mod
client-transformers)
server-mods (get-transformer-mods
mod
server-transformers)
all-transformers (->> (concat client-transformers server-transformers)
(apply merge)
(invs-in-ns inv-name))
new-invs (if (empty? all-transformers)
(list inv)
(vals all-transformers))
extra-mods-by-scope (->> (merge
{server-scope-name server-mods}
{client-scope-name client-mods})
(filter #(some? (key %)))
(into {}))]
(-> acc
(update
:extra-mods-by-scope
#(merge-with merge % extra-mods-by-scope))
(update-in
[:canonical-flow :invocations]
#(concat % new-invs)))))
{:extra-mods-by-scope {}
:canonical-flow (assoc canonical-flow :invocations [])})))))
| 1063 | (ns ^{:author "<NAME>"} ulvm.flows
"Flow operations"
(:require [clojure.spec :as s]
[ulvm.core :as ucore]
[ulvm.utils :as u]
[ulvm.project :as uprj]
[clojure.set :as cset]
[cats.monad.either :as e]))
(defn module-for-invocation
"The module that the given invocation references.
A scope-name is used to disambiguate references to
local modules."
[mods scope-name inv]
(let [inv-mod (->> [(:invocation-module inv)]
(into {}))
scope-mod (:scope-module inv-mod)
local-mod (:local-module inv-mod)
; we have to do some gymnastics to handle local and
; scope modules
mod-scope-name (-> (or (:scope scope-mod)
scope-name)
keyword)
module-name (-> (or (:module-name scope-mod)
local-mod)
keyword)
module (get-in mods [mod-scope-name module-name])]
{:mod module
:mod-name module-name
:scope mod-scope-name}))
(s/fdef module-for-invocation
:args (s/cat :mods (s/map-of keyword?
(s/map-of keyword?
::ucore/module))
:scope-name (s/nilable keyword?)
:inv ::uprj/inv)
:ret (s/keys :req-un [::uprj/mod ::uprj/mod-name ::uprj/scope]))
(defn- default-invocation-name
[invocation]
(-> (get invocation :invocation-module)
(#(or (get-in % [:scope-module :module-name])
(get % :local-module)))
(str "_")
(gensym)))
(defn- invocation-name
"Returns the name for the result of an invocation"
[invocation]
(get-in
invocation
[:name :name]
(default-invocation-name invocation)))
(defn named-invocations
"Returns a map from result names to invocations"
[invocations]
(reduce
(fn [named inv]
(conj named [(invocation-name inv) inv]))
{}
invocations))
(s/fdef named-invocations
:args (s/cat :invocations (s/coll-of ::uprj/inv))
:ret (s/map-of symbol? ::uprj/inv))
(defn- relevant-transformers
[prj bindings transformers]
(reduce
(fn [relevant [transform-name transform]]
(let [phase (u/get-in transform [:when :phase])
pred (u/get-in transform [:when :if])]
(if (uprj/eval-in-ctx prj [] bindings pred)
(assoc-in relevant [phase] (u/get-in transform [:do])) ; TODO: do we really want to allow multiple transformers with the same phase?
relevant)))
{}
transformers))
(s/def ::client-pre ::ucore/flow-invocations)
(s/def ::client-post ::ucore/flow-invocations)
(s/def ::server-pre ::ucore/flow-invocations)
(s/def ::server-post ::ucore/flow-invocations)
(s/def ::transformer-bindings map?)
(s/def ::transformers (s/map-of ::ucore/name ::ucore/transformer))
(s/fdef relevant-transformers
:args (s/cat :prj ::uprj/project
:bindings ::transformer-bindings
:transformers (s/nilable ::transformers))
:ret (s/keys :req-un [::client-pre
::client-post
::server-pre
::server-post]))
(defn- invocation-deps
[invocation]
(cset/union
(->>
(get-in invocation [:after :names])
second
flatten
(filter identity)
(into #{}))
(->> (:args invocation)
(filter
(fn [[_ [arg-type arg]]]
(= :ref arg-type)))
(map
(fn [[_ [_ [ref-arg-type arg]]]]
(if (= :default-ref-arg ref-arg-type)
arg
(:result arg))))
(into #{}))))
(defn invocation-dependency-graph
"Returns a map from invocation name to a set of names of the invocations it depends on."
[invocations]
(reduce
(fn [deps [name invocation]]
(merge-with cset/union deps {name (invocation-deps invocation)}))
{}
invocations))
(defn ordered-invocations
"Returns a seq of topologically ordered invocation names"
[invs deps params]
(let [sorted (u/topo-sort deps (keys invs) (into #{} params))]
(if (empty? (:unsat sorted))
(e/right (:items sorted))
(e/left {:msg "Failed to satisfy call graph dependencies"
:unsat-deps (:unsat sorted)}))))
(defn flow-params
"Returns the parameters of the flow."
[flow]
(get (meta flow) ::ucore/args))
(defn- home-scope
"Every flow has a \"home scope,\" which is the scope in which the flow
originates and from which all invocations initiate."
[flow]
(u/get-in flow [:config ::ucore/home-scope]))
(defn- inv-with-default-scope
"If inv refers to a local module, return an inv for that module on scope."
[scope inv]
(if-let [local-mod (u/get-in inv [:invocation-module :local-module])]
(assoc
inv
:invocation-module
{:scope-module (list (keyword local-mod) (symbol (str scope)))})
inv))
(defn- invs-with-default-scope
[scope invs]
(->> invs
(map
(fn [[k inv]]
[k (inv-with-default-scope scope inv)]))
(into {})))
(defn- sym-in-ns
[ns sym]
(symbol (str "*" ns "*" sym)))
(defn- inv-in-ns
[ns invs inv]
(update
inv
:args
#(->> %
(map
(fn [[arg-name arg]]
(let [def-ref (u/get-in arg [:ref :default-ref-arg])
named-ref (u/get-in arg [:ref :named-ref-arg])]
(cond
(and (some? def-ref) (contains? invs def-ref))
[arg-name [:ref [:default-ref-arg (sym-in-ns ns def-ref)]]]
(and (some? named-ref) (contains? invs (get named-ref :result)))
[arg-name [:ref [:named-ref-arg (assoc named-ref :result (sym-in-ns ns (get named-ref :result)))]]]
:else
[arg-name arg]))))
(into {}))))
(defn- invs-in-ns
[ns invs]
(reduce
(fn [ns-invs [n inv]]
(assoc
ns-invs
(sym-in-ns ns n)
(inv-in-ns ns invs inv)))
{}
invs))
(defn- transformers-for-rel-scope
[transformers rel-scope client-scope-name server-scope-name]
(let [def-scope-by-phase {:client-pre client-scope-name
:client-post client-scope-name
:server-pre server-scope-name
:server-post server-scope-name}
phases (if (= :client rel-scope)
[:client-pre :client-post]
[:server-pre :server-post])]
(map
#(some->> (get transformers %)
(s/conform ::ucore/flow-invocations)
named-invocations
(invs-with-default-scope (get def-scope-by-phase %)))
phases)))
(defn- get-transformer-mods
[mod transformers]
(let [transformer-mods (->> transformers
(apply concat)
vals
(map #(first (u/get-in % [:invocation-module :scope-module])))
set)]
(->> (get mod ::ucore/transformer-modules)
(filter
(fn [[mod-name mod]]
(transformer-mods mod-name)))
(into {}))))
(defn invs-in-scope
"Place invs in the provided scope"
[scope-name invs]
(map
(fn [[mod-ref & rest-of-inv]]
(if (symbol? mod-ref)
(concat [(list (-> mod-ref name keyword) (-> scope-name name symbol))] rest-of-inv)
(concat [mod-ref] rest-of-inv))) ; TODO: can check that mod-ref refers to scope
invs))
(s/fdef invs-in-scope
:args (s/cat :scope-name keyword?
:invs (s/nilable (s/coll-of ::ucore/flow-invocation)))
:ret (s/coll-of ::ucore/flow-invocation))
(defn expand-transformers
"Inlines applicable transformers for any module invocations in the flow."
([prj mods named-scope-cfgs canonical-flow]
(expand-transformers prj mods named-scope-cfgs nil canonical-flow))
([prj mods named-scope-cfgs scope canonical-flow]
(let [client-scope-name (home-scope canonical-flow)
client-scope-cfg (get named-scope-cfgs client-scope-name)]
(->> canonical-flow
:invocations
named-invocations
(reduce
(fn [acc [inv-name inv]]
(let [{mod :mod
server-scope-name :scope} (module-for-invocation mods scope inv) ; TODO: if scope is not nil and server-scope-name != scope, we have a problem (this is the case for scope initializers)
server-scope-cfg (get named-scope-cfgs server-scope-name)
param-bindings (->> (u/get-in inv [:args])
(map
(fn [[k arg]]
[k (s/unform ::ucore/flow-arg arg)]))
(into {}))
transformer-bindings {'*client-scope* client-scope-name
'*client-scope-cfg* client-scope-cfg
'*server-scope* server-scope-name
'*server-scope-cfg* server-scope-cfg
'*inv* (u/get-in inv [:invocation-module])}
; TODO: only allow some bindings in some phases
transformers (->> (get mod ::ucore/transformers)
(relevant-transformers prj (merge transformer-bindings param-bindings)))
client-transformers (transformers-for-rel-scope
transformers
:client
client-scope-name
server-scope-name)
server-transformers (transformers-for-rel-scope
transformers
:server
client-scope-name
server-scope-name)
client-mods (get-transformer-mods
mod
client-transformers)
server-mods (get-transformer-mods
mod
server-transformers)
all-transformers (->> (concat client-transformers server-transformers)
(apply merge)
(invs-in-ns inv-name))
new-invs (if (empty? all-transformers)
(list inv)
(vals all-transformers))
extra-mods-by-scope (->> (merge
{server-scope-name server-mods}
{client-scope-name client-mods})
(filter #(some? (key %)))
(into {}))]
(-> acc
(update
:extra-mods-by-scope
#(merge-with merge % extra-mods-by-scope))
(update-in
[:canonical-flow :invocations]
#(concat % new-invs)))))
{:extra-mods-by-scope {}
:canonical-flow (assoc canonical-flow :invocations [])})))))
| true | (ns ^{:author "PI:NAME:<NAME>END_PI"} ulvm.flows
"Flow operations"
(:require [clojure.spec :as s]
[ulvm.core :as ucore]
[ulvm.utils :as u]
[ulvm.project :as uprj]
[clojure.set :as cset]
[cats.monad.either :as e]))
(defn module-for-invocation
"The module that the given invocation references.
A scope-name is used to disambiguate references to
local modules."
[mods scope-name inv]
(let [inv-mod (->> [(:invocation-module inv)]
(into {}))
scope-mod (:scope-module inv-mod)
local-mod (:local-module inv-mod)
; we have to do some gymnastics to handle local and
; scope modules
mod-scope-name (-> (or (:scope scope-mod)
scope-name)
keyword)
module-name (-> (or (:module-name scope-mod)
local-mod)
keyword)
module (get-in mods [mod-scope-name module-name])]
{:mod module
:mod-name module-name
:scope mod-scope-name}))
(s/fdef module-for-invocation
:args (s/cat :mods (s/map-of keyword?
(s/map-of keyword?
::ucore/module))
:scope-name (s/nilable keyword?)
:inv ::uprj/inv)
:ret (s/keys :req-un [::uprj/mod ::uprj/mod-name ::uprj/scope]))
(defn- default-invocation-name
[invocation]
(-> (get invocation :invocation-module)
(#(or (get-in % [:scope-module :module-name])
(get % :local-module)))
(str "_")
(gensym)))
(defn- invocation-name
"Returns the name for the result of an invocation"
[invocation]
(get-in
invocation
[:name :name]
(default-invocation-name invocation)))
(defn named-invocations
"Returns a map from result names to invocations"
[invocations]
(reduce
(fn [named inv]
(conj named [(invocation-name inv) inv]))
{}
invocations))
(s/fdef named-invocations
:args (s/cat :invocations (s/coll-of ::uprj/inv))
:ret (s/map-of symbol? ::uprj/inv))
(defn- relevant-transformers
[prj bindings transformers]
(reduce
(fn [relevant [transform-name transform]]
(let [phase (u/get-in transform [:when :phase])
pred (u/get-in transform [:when :if])]
(if (uprj/eval-in-ctx prj [] bindings pred)
(assoc-in relevant [phase] (u/get-in transform [:do])) ; TODO: do we really want to allow multiple transformers with the same phase?
relevant)))
{}
transformers))
(s/def ::client-pre ::ucore/flow-invocations)
(s/def ::client-post ::ucore/flow-invocations)
(s/def ::server-pre ::ucore/flow-invocations)
(s/def ::server-post ::ucore/flow-invocations)
(s/def ::transformer-bindings map?)
(s/def ::transformers (s/map-of ::ucore/name ::ucore/transformer))
(s/fdef relevant-transformers
:args (s/cat :prj ::uprj/project
:bindings ::transformer-bindings
:transformers (s/nilable ::transformers))
:ret (s/keys :req-un [::client-pre
::client-post
::server-pre
::server-post]))
(defn- invocation-deps
[invocation]
(cset/union
(->>
(get-in invocation [:after :names])
second
flatten
(filter identity)
(into #{}))
(->> (:args invocation)
(filter
(fn [[_ [arg-type arg]]]
(= :ref arg-type)))
(map
(fn [[_ [_ [ref-arg-type arg]]]]
(if (= :default-ref-arg ref-arg-type)
arg
(:result arg))))
(into #{}))))
(defn invocation-dependency-graph
"Returns a map from invocation name to a set of names of the invocations it depends on."
[invocations]
(reduce
(fn [deps [name invocation]]
(merge-with cset/union deps {name (invocation-deps invocation)}))
{}
invocations))
(defn ordered-invocations
"Returns a seq of topologically ordered invocation names"
[invs deps params]
(let [sorted (u/topo-sort deps (keys invs) (into #{} params))]
(if (empty? (:unsat sorted))
(e/right (:items sorted))
(e/left {:msg "Failed to satisfy call graph dependencies"
:unsat-deps (:unsat sorted)}))))
(defn flow-params
"Returns the parameters of the flow."
[flow]
(get (meta flow) ::ucore/args))
(defn- home-scope
"Every flow has a \"home scope,\" which is the scope in which the flow
originates and from which all invocations initiate."
[flow]
(u/get-in flow [:config ::ucore/home-scope]))
(defn- inv-with-default-scope
"If inv refers to a local module, return an inv for that module on scope."
[scope inv]
(if-let [local-mod (u/get-in inv [:invocation-module :local-module])]
(assoc
inv
:invocation-module
{:scope-module (list (keyword local-mod) (symbol (str scope)))})
inv))
(defn- invs-with-default-scope
[scope invs]
(->> invs
(map
(fn [[k inv]]
[k (inv-with-default-scope scope inv)]))
(into {})))
(defn- sym-in-ns
[ns sym]
(symbol (str "*" ns "*" sym)))
(defn- inv-in-ns
[ns invs inv]
(update
inv
:args
#(->> %
(map
(fn [[arg-name arg]]
(let [def-ref (u/get-in arg [:ref :default-ref-arg])
named-ref (u/get-in arg [:ref :named-ref-arg])]
(cond
(and (some? def-ref) (contains? invs def-ref))
[arg-name [:ref [:default-ref-arg (sym-in-ns ns def-ref)]]]
(and (some? named-ref) (contains? invs (get named-ref :result)))
[arg-name [:ref [:named-ref-arg (assoc named-ref :result (sym-in-ns ns (get named-ref :result)))]]]
:else
[arg-name arg]))))
(into {}))))
(defn- invs-in-ns
[ns invs]
(reduce
(fn [ns-invs [n inv]]
(assoc
ns-invs
(sym-in-ns ns n)
(inv-in-ns ns invs inv)))
{}
invs))
(defn- transformers-for-rel-scope
[transformers rel-scope client-scope-name server-scope-name]
(let [def-scope-by-phase {:client-pre client-scope-name
:client-post client-scope-name
:server-pre server-scope-name
:server-post server-scope-name}
phases (if (= :client rel-scope)
[:client-pre :client-post]
[:server-pre :server-post])]
(map
#(some->> (get transformers %)
(s/conform ::ucore/flow-invocations)
named-invocations
(invs-with-default-scope (get def-scope-by-phase %)))
phases)))
(defn- get-transformer-mods
[mod transformers]
(let [transformer-mods (->> transformers
(apply concat)
vals
(map #(first (u/get-in % [:invocation-module :scope-module])))
set)]
(->> (get mod ::ucore/transformer-modules)
(filter
(fn [[mod-name mod]]
(transformer-mods mod-name)))
(into {}))))
(defn invs-in-scope
"Place invs in the provided scope"
[scope-name invs]
(map
(fn [[mod-ref & rest-of-inv]]
(if (symbol? mod-ref)
(concat [(list (-> mod-ref name keyword) (-> scope-name name symbol))] rest-of-inv)
(concat [mod-ref] rest-of-inv))) ; TODO: can check that mod-ref refers to scope
invs))
(s/fdef invs-in-scope
:args (s/cat :scope-name keyword?
:invs (s/nilable (s/coll-of ::ucore/flow-invocation)))
:ret (s/coll-of ::ucore/flow-invocation))
(defn expand-transformers
"Inlines applicable transformers for any module invocations in the flow."
([prj mods named-scope-cfgs canonical-flow]
(expand-transformers prj mods named-scope-cfgs nil canonical-flow))
([prj mods named-scope-cfgs scope canonical-flow]
(let [client-scope-name (home-scope canonical-flow)
client-scope-cfg (get named-scope-cfgs client-scope-name)]
(->> canonical-flow
:invocations
named-invocations
(reduce
(fn [acc [inv-name inv]]
(let [{mod :mod
server-scope-name :scope} (module-for-invocation mods scope inv) ; TODO: if scope is not nil and server-scope-name != scope, we have a problem (this is the case for scope initializers)
server-scope-cfg (get named-scope-cfgs server-scope-name)
param-bindings (->> (u/get-in inv [:args])
(map
(fn [[k arg]]
[k (s/unform ::ucore/flow-arg arg)]))
(into {}))
transformer-bindings {'*client-scope* client-scope-name
'*client-scope-cfg* client-scope-cfg
'*server-scope* server-scope-name
'*server-scope-cfg* server-scope-cfg
'*inv* (u/get-in inv [:invocation-module])}
; TODO: only allow some bindings in some phases
transformers (->> (get mod ::ucore/transformers)
(relevant-transformers prj (merge transformer-bindings param-bindings)))
client-transformers (transformers-for-rel-scope
transformers
:client
client-scope-name
server-scope-name)
server-transformers (transformers-for-rel-scope
transformers
:server
client-scope-name
server-scope-name)
client-mods (get-transformer-mods
mod
client-transformers)
server-mods (get-transformer-mods
mod
server-transformers)
all-transformers (->> (concat client-transformers server-transformers)
(apply merge)
(invs-in-ns inv-name))
new-invs (if (empty? all-transformers)
(list inv)
(vals all-transformers))
extra-mods-by-scope (->> (merge
{server-scope-name server-mods}
{client-scope-name client-mods})
(filter #(some? (key %)))
(into {}))]
(-> acc
(update
:extra-mods-by-scope
#(merge-with merge % extra-mods-by-scope))
(update-in
[:canonical-flow :invocations]
#(concat % new-invs)))))
{:extra-mods-by-scope {}
:canonical-flow (assoc canonical-flow :invocations [])})))))
|
[
{
"context": " (edn-set \\\"/tmp/secrets.edn\\\" [:lxc :pass] \\\"password\\\")\n \"\n [dest ks v]\n (let [data (clojure.edn/re",
"end": 8340,
"score": 0.878866970539093,
"start": 8332,
"tag": "PASSWORD",
"value": "password"
}
] | src/re_cog/resources/file.clj | re-ops/re-cog | 5 | (ns re-cog.resources.file
"File resources"
(:require
[clojure.core.strint :refer (<<)]
[re-cog.common.resources :refer (run-)]
[re-cog.common.functions :refer (require-functions)]
[re-cog.common.defs :refer (def-serial)]))
(require-functions)
(def-serial directory
"Directory resource:
(directory \"/tmp/bla\" :present) ; create
(directory \"/tmp/bla\" :absent) ; remove"
[dest state]
(letfn [(lazy-mkdir []
(if (fs/exists? dest) true (fs/mkdir dest)))
(lazy-rm []
(if (fs/exists? dest) (fs/delete-dir dest) true))]
(assert (#{:present :absent} state))
(let [states {:present lazy-mkdir :absent lazy-rm}]
(coherce ((states state))))))
(def-serial file
"A file resource:
; touch a file
(file \"/tmp/1\" :present)
; delete a file
(file \"/tmp/1\" :absent)
"
[path state]
(letfn [(touch [f]
(if (fs/exists? f) true (fs/touch f)))
(delete [f]
(if (fs/exists? f) (fs/delete f) true))]
(assert (#{:present :absent} state))
(let [states {:present touch :absent delete}]
(coherce ((states state) path)))))
(def-serial symlink
"Symlink a file:
; create a new symlink
(symlink \"/home/re-ops/.minimal-zsh/.zshrc\" \"/home/re-ops/.zshrc\") "
[path target]
(letfn [(symlink-target [t]
(let [f (java.nio.file.Paths/get (java.net.URI. (<< "file://~{t}")))]
(str (java.nio.file.Files/readSymbolicLink f))))]
(if (fs/exists? path)
(let [existing (symlink-target path)]
(if-not (= target existing)
(failure (<< "~{path} alreay points to ~{existing} and not to ~{target}"))
(success "symlink exists")))
(let [actual (.getPath (fs/sym-link path target))]
(if (= path actual)
(success (<< "symlink from ~{path} to ~{target} created"))
(failure (<< "failed to create symlink ~{actual} is not ~{path}")))))))
(def-serial template
"Template resource:
; apply a template and create a file:
(template \"/tmp/resources/templates/lxd/preseed.mustache\" \"/tmp/preseed.yaml\" {})
"
[tmpl dest args]
(let [source (slurp tmpl)
out (render source args)
parent (fs/parent dest)]
(if (not (fs/exists? parent))
(failure (<< "~{parent} missing, cannot spit template into ~{dest}"))
(do
(spit dest out)
(success (<< "created file from template under ~{dest}"))))))
(def-serial copy
"Copy a local file:
(copy \"/tmp/foo\" \"/tmp/bla\")
"
[src dest]
(try
(coherce (= (fs/copy src dest) dest))
(catch Exception e
(failure (.getMessage e)))))
(def-serial rename
"Move a local file:
(rename \"/tmp/foo\" \"/tmp/bla\")
"
[src dest]
(try
(coherce (fs/rename src dest))
(catch Exception e
(failure (.getMessage e)))))
(def-serial chmod
"Change file/directory mode resource:
(chmod \"/home\"/re-ops/.ssh\" \"0777\")
(chmod \"/home\"/re-ops/.ssh\" \"0777\" :recursive true)
"
[dest mode opts]
(letfn [(chmod-script []
(let [options (if (opts :recursive) "-R" "")]
(script
(set! ID @("id" "-u"))
(if (= "0" $ID)
("sudo" "/usr/bin/chmod" ~mode ~dest ~options)
("/usr/bin/chmod" ~mode ~dest ~options)))))]
(run- chmod-script)))
(def-serial chown
"Change file/directory owner using uid & gid resource:
; change file/folder ownership using user/group
(chown \"/home\"/re-ops/.ssh\" \"foo\" \"bar\")
; change file/folder ownership recursively
(chown \"/home\"/re-ops/.ssh\" \"foo\" \"bar\" {:recursive true})"
[dest user group opts]
(letfn [(chown-script []
(let [u-g (<< "~{user}:~{group}")
options (if (opts :recursive) "-R" "")]
(script
(set! ID @("id" "-u"))
(if (= "0" $ID)
("sudo" "/usr/bin/chown" ~u-g ~dest ~options)
("/usr/bin/chown" ~u-g ~dest ~options)))))]
(run- chown-script)))
(def-serial line
"File line resource either append or remove lines:
(line \"/tmp/foo\" \"bar\" :present); append line
(line \"/tmp/foo\" (line-eq \"bar\") :absent); remove all lines equal to bar from the file
(line \"/tmp/foo\" (fn [_ curr] (> 5 (.length curr))) :absent); remove lines using a function
(line \"/tmp/foo\" \"bar\" :replace :with \"foo\"); replace lines equal to bar with foo
(line \"/tmp/foo\" (fn [i _] (= i 2)) :replace :with \"foo\"); replace line in position 2 with value
(line \"/tmp/foo\" (fn [i _] (= i 2)) :comment :with \"#\"); comment line in position 2
"
[file v state & {:keys [with]}]
(letfn [(line-eq [line] (fn [_ curr] (not (= curr line))))
(add-line [line]
(let [contents (slurp file)]
(if (clojure.string/includes? contents line)
(success "file already contains line")
(do
(spit file (str line "\n") :append true)
(success "line added to file")))))
(replace-line [target]
(let [pred (if (string? target) (comp not (line-eq target)) target)
contents (slurp file)
replace-with (fn [i line] (if (pred i line) with line))
filtered (map-indexed replace-with
(clojure.string/split-lines contents))
output (clojure.string/join "\n" filtered)]
(if-not (= contents output)
(do
(spit file output)
(success "line replaced in file"))
(success "line not present in file"))))
(rm-line [target]
(let [pred (if (string? target) (line-eq target) target)
contents (slurp file)
filtered (keep-indexed pred (clojure.string/split-lines contents))
output (clojure.string/join "\n" filtered)]
(if-not (= contents output)
(do
(spit file output)
(success "line removed from file"))
(success "line not present in file"))))]
(let [states {:present add-line :absent rm-line :replace replace-line}]
(assert (into #{} (keys states)) state)
((states state) v))))
(def-serial uncomment
"Uncomment a line with separator value:
(uncomment \"/etc/ssh/sshd_config\" \"PermitRootLogin\" \"#\")
"
[dest k sep]
(if-not (fs/exists? dest)
(error (<< "~{dest} not found"))
(let [lines (slurp dest)
edited (clojure.string/replace-first lines (str sep k) k)]
(spit dest edited)
(success "line was uncommented"))))
(def-serial uncomment-nth
"Uncomment a line number nth with separator:
(uncomment-nth \"/etc/ssh/sshd_config\" \"#\" 1)
"
[dest sep n]
(if-not (fs/exists? dest)
(error (<< "~{dest} not found"))
(let [lines (clojure.string/split-lines (slurp dest))
edited (map-indexed
(fn [i line]
(if-not (= i n)
line
(clojure.string/replace-first line sep ""))) lines)]
(spit dest (clojure.string/join "\n" edited))
(success "line was uncommented at position"))))
(def-serial line-set
"Set an existing line value:
(line-set \"/etc/ssh/sshd_config\" \"PermitRootLogin\" \"no\" \" \")
"
[dest k v sep]
(letfn [(set-key [k v sep]
(fn [line]
(let [[f & _] (clojure.string/split line (re-pattern sep))]
(if (= f k)
(str k sep v)
line))))]
(if-not (fs/exists? dest)
(error (<< "~{dest} not found"))
(let [lines (slurp dest)
edited (map (set-key k v sep) (clojure.string/split-lines lines))]
(spit dest (clojure.string/join "\n" edited))
(success "value in file line was set")))))
(def-serial edn-set
"Set a value in an edn file:
(edn-set \"/tmp/secrets.edn\" [:lxc :pass] \"password\")
"
[dest ks v]
(let [data (clojure.edn/read-string (slurp dest))]
(if (= (get-in data ks) v)
(success "value is already set")
(do
(spit dest (with-out-str (pr (assoc-in data ks v))))
(success "value was set in file")))))
(def-serial yaml-set
"Set a value in a yaml file:
(yaml-set \"/tmp/test.yaml\" [:parent :key] \"value\")
"
[dest ks v]
(let [data (yaml/parse-string (slurp dest))]
(if (= (get-in data ks) v)
(success "value is already set")
(do
(spit dest
(yaml/generate-string
(assoc-in data ks v) :dumper-options {:flow-style :block}))
(success "value was set in file")))))
(def-serial replace-all
"Replace all occurrences of a Regex match in a file
(replace-all \"/etc/apt/sources.list\" \"us.\" \"local.\")
"
[dest match with]
(letfn [(edit [line]
(let [post (clojure.string/replace line (re-pattern match) with)]
{:updated? (not (= post line)) :line post}))]
(if-not (fs/exists? dest)
(error (<< "~{dest} not found"))
(let [lines (slurp dest)
edited (map edit (clojure.string/split-lines lines))
updated (count (filter :updated? edited))]
(spit dest (clojure.string/join "\n" (map :line edited)))
(success (<< "~{updated} lines were updated in ~{dest}"))))))
| 83906 | (ns re-cog.resources.file
"File resources"
(:require
[clojure.core.strint :refer (<<)]
[re-cog.common.resources :refer (run-)]
[re-cog.common.functions :refer (require-functions)]
[re-cog.common.defs :refer (def-serial)]))
(require-functions)
(def-serial directory
"Directory resource:
(directory \"/tmp/bla\" :present) ; create
(directory \"/tmp/bla\" :absent) ; remove"
[dest state]
(letfn [(lazy-mkdir []
(if (fs/exists? dest) true (fs/mkdir dest)))
(lazy-rm []
(if (fs/exists? dest) (fs/delete-dir dest) true))]
(assert (#{:present :absent} state))
(let [states {:present lazy-mkdir :absent lazy-rm}]
(coherce ((states state))))))
(def-serial file
"A file resource:
; touch a file
(file \"/tmp/1\" :present)
; delete a file
(file \"/tmp/1\" :absent)
"
[path state]
(letfn [(touch [f]
(if (fs/exists? f) true (fs/touch f)))
(delete [f]
(if (fs/exists? f) (fs/delete f) true))]
(assert (#{:present :absent} state))
(let [states {:present touch :absent delete}]
(coherce ((states state) path)))))
(def-serial symlink
"Symlink a file:
; create a new symlink
(symlink \"/home/re-ops/.minimal-zsh/.zshrc\" \"/home/re-ops/.zshrc\") "
[path target]
(letfn [(symlink-target [t]
(let [f (java.nio.file.Paths/get (java.net.URI. (<< "file://~{t}")))]
(str (java.nio.file.Files/readSymbolicLink f))))]
(if (fs/exists? path)
(let [existing (symlink-target path)]
(if-not (= target existing)
(failure (<< "~{path} alreay points to ~{existing} and not to ~{target}"))
(success "symlink exists")))
(let [actual (.getPath (fs/sym-link path target))]
(if (= path actual)
(success (<< "symlink from ~{path} to ~{target} created"))
(failure (<< "failed to create symlink ~{actual} is not ~{path}")))))))
(def-serial template
"Template resource:
; apply a template and create a file:
(template \"/tmp/resources/templates/lxd/preseed.mustache\" \"/tmp/preseed.yaml\" {})
"
[tmpl dest args]
(let [source (slurp tmpl)
out (render source args)
parent (fs/parent dest)]
(if (not (fs/exists? parent))
(failure (<< "~{parent} missing, cannot spit template into ~{dest}"))
(do
(spit dest out)
(success (<< "created file from template under ~{dest}"))))))
(def-serial copy
"Copy a local file:
(copy \"/tmp/foo\" \"/tmp/bla\")
"
[src dest]
(try
(coherce (= (fs/copy src dest) dest))
(catch Exception e
(failure (.getMessage e)))))
(def-serial rename
"Move a local file:
(rename \"/tmp/foo\" \"/tmp/bla\")
"
[src dest]
(try
(coherce (fs/rename src dest))
(catch Exception e
(failure (.getMessage e)))))
(def-serial chmod
"Change file/directory mode resource:
(chmod \"/home\"/re-ops/.ssh\" \"0777\")
(chmod \"/home\"/re-ops/.ssh\" \"0777\" :recursive true)
"
[dest mode opts]
(letfn [(chmod-script []
(let [options (if (opts :recursive) "-R" "")]
(script
(set! ID @("id" "-u"))
(if (= "0" $ID)
("sudo" "/usr/bin/chmod" ~mode ~dest ~options)
("/usr/bin/chmod" ~mode ~dest ~options)))))]
(run- chmod-script)))
(def-serial chown
"Change file/directory owner using uid & gid resource:
; change file/folder ownership using user/group
(chown \"/home\"/re-ops/.ssh\" \"foo\" \"bar\")
; change file/folder ownership recursively
(chown \"/home\"/re-ops/.ssh\" \"foo\" \"bar\" {:recursive true})"
[dest user group opts]
(letfn [(chown-script []
(let [u-g (<< "~{user}:~{group}")
options (if (opts :recursive) "-R" "")]
(script
(set! ID @("id" "-u"))
(if (= "0" $ID)
("sudo" "/usr/bin/chown" ~u-g ~dest ~options)
("/usr/bin/chown" ~u-g ~dest ~options)))))]
(run- chown-script)))
(def-serial line
"File line resource either append or remove lines:
(line \"/tmp/foo\" \"bar\" :present); append line
(line \"/tmp/foo\" (line-eq \"bar\") :absent); remove all lines equal to bar from the file
(line \"/tmp/foo\" (fn [_ curr] (> 5 (.length curr))) :absent); remove lines using a function
(line \"/tmp/foo\" \"bar\" :replace :with \"foo\"); replace lines equal to bar with foo
(line \"/tmp/foo\" (fn [i _] (= i 2)) :replace :with \"foo\"); replace line in position 2 with value
(line \"/tmp/foo\" (fn [i _] (= i 2)) :comment :with \"#\"); comment line in position 2
"
[file v state & {:keys [with]}]
(letfn [(line-eq [line] (fn [_ curr] (not (= curr line))))
(add-line [line]
(let [contents (slurp file)]
(if (clojure.string/includes? contents line)
(success "file already contains line")
(do
(spit file (str line "\n") :append true)
(success "line added to file")))))
(replace-line [target]
(let [pred (if (string? target) (comp not (line-eq target)) target)
contents (slurp file)
replace-with (fn [i line] (if (pred i line) with line))
filtered (map-indexed replace-with
(clojure.string/split-lines contents))
output (clojure.string/join "\n" filtered)]
(if-not (= contents output)
(do
(spit file output)
(success "line replaced in file"))
(success "line not present in file"))))
(rm-line [target]
(let [pred (if (string? target) (line-eq target) target)
contents (slurp file)
filtered (keep-indexed pred (clojure.string/split-lines contents))
output (clojure.string/join "\n" filtered)]
(if-not (= contents output)
(do
(spit file output)
(success "line removed from file"))
(success "line not present in file"))))]
(let [states {:present add-line :absent rm-line :replace replace-line}]
(assert (into #{} (keys states)) state)
((states state) v))))
(def-serial uncomment
"Uncomment a line with separator value:
(uncomment \"/etc/ssh/sshd_config\" \"PermitRootLogin\" \"#\")
"
[dest k sep]
(if-not (fs/exists? dest)
(error (<< "~{dest} not found"))
(let [lines (slurp dest)
edited (clojure.string/replace-first lines (str sep k) k)]
(spit dest edited)
(success "line was uncommented"))))
(def-serial uncomment-nth
"Uncomment a line number nth with separator:
(uncomment-nth \"/etc/ssh/sshd_config\" \"#\" 1)
"
[dest sep n]
(if-not (fs/exists? dest)
(error (<< "~{dest} not found"))
(let [lines (clojure.string/split-lines (slurp dest))
edited (map-indexed
(fn [i line]
(if-not (= i n)
line
(clojure.string/replace-first line sep ""))) lines)]
(spit dest (clojure.string/join "\n" edited))
(success "line was uncommented at position"))))
(def-serial line-set
"Set an existing line value:
(line-set \"/etc/ssh/sshd_config\" \"PermitRootLogin\" \"no\" \" \")
"
[dest k v sep]
(letfn [(set-key [k v sep]
(fn [line]
(let [[f & _] (clojure.string/split line (re-pattern sep))]
(if (= f k)
(str k sep v)
line))))]
(if-not (fs/exists? dest)
(error (<< "~{dest} not found"))
(let [lines (slurp dest)
edited (map (set-key k v sep) (clojure.string/split-lines lines))]
(spit dest (clojure.string/join "\n" edited))
(success "value in file line was set")))))
(def-serial edn-set
"Set a value in an edn file:
(edn-set \"/tmp/secrets.edn\" [:lxc :pass] \"<PASSWORD>\")
"
[dest ks v]
(let [data (clojure.edn/read-string (slurp dest))]
(if (= (get-in data ks) v)
(success "value is already set")
(do
(spit dest (with-out-str (pr (assoc-in data ks v))))
(success "value was set in file")))))
(def-serial yaml-set
"Set a value in a yaml file:
(yaml-set \"/tmp/test.yaml\" [:parent :key] \"value\")
"
[dest ks v]
(let [data (yaml/parse-string (slurp dest))]
(if (= (get-in data ks) v)
(success "value is already set")
(do
(spit dest
(yaml/generate-string
(assoc-in data ks v) :dumper-options {:flow-style :block}))
(success "value was set in file")))))
(def-serial replace-all
"Replace all occurrences of a Regex match in a file
(replace-all \"/etc/apt/sources.list\" \"us.\" \"local.\")
"
[dest match with]
(letfn [(edit [line]
(let [post (clojure.string/replace line (re-pattern match) with)]
{:updated? (not (= post line)) :line post}))]
(if-not (fs/exists? dest)
(error (<< "~{dest} not found"))
(let [lines (slurp dest)
edited (map edit (clojure.string/split-lines lines))
updated (count (filter :updated? edited))]
(spit dest (clojure.string/join "\n" (map :line edited)))
(success (<< "~{updated} lines were updated in ~{dest}"))))))
| true | (ns re-cog.resources.file
"File resources"
(:require
[clojure.core.strint :refer (<<)]
[re-cog.common.resources :refer (run-)]
[re-cog.common.functions :refer (require-functions)]
[re-cog.common.defs :refer (def-serial)]))
(require-functions)
(def-serial directory
"Directory resource:
(directory \"/tmp/bla\" :present) ; create
(directory \"/tmp/bla\" :absent) ; remove"
[dest state]
(letfn [(lazy-mkdir []
(if (fs/exists? dest) true (fs/mkdir dest)))
(lazy-rm []
(if (fs/exists? dest) (fs/delete-dir dest) true))]
(assert (#{:present :absent} state))
(let [states {:present lazy-mkdir :absent lazy-rm}]
(coherce ((states state))))))
(def-serial file
"A file resource:
; touch a file
(file \"/tmp/1\" :present)
; delete a file
(file \"/tmp/1\" :absent)
"
[path state]
(letfn [(touch [f]
(if (fs/exists? f) true (fs/touch f)))
(delete [f]
(if (fs/exists? f) (fs/delete f) true))]
(assert (#{:present :absent} state))
(let [states {:present touch :absent delete}]
(coherce ((states state) path)))))
(def-serial symlink
"Symlink a file:
; create a new symlink
(symlink \"/home/re-ops/.minimal-zsh/.zshrc\" \"/home/re-ops/.zshrc\") "
[path target]
(letfn [(symlink-target [t]
(let [f (java.nio.file.Paths/get (java.net.URI. (<< "file://~{t}")))]
(str (java.nio.file.Files/readSymbolicLink f))))]
(if (fs/exists? path)
(let [existing (symlink-target path)]
(if-not (= target existing)
(failure (<< "~{path} alreay points to ~{existing} and not to ~{target}"))
(success "symlink exists")))
(let [actual (.getPath (fs/sym-link path target))]
(if (= path actual)
(success (<< "symlink from ~{path} to ~{target} created"))
(failure (<< "failed to create symlink ~{actual} is not ~{path}")))))))
(def-serial template
"Template resource:
; apply a template and create a file:
(template \"/tmp/resources/templates/lxd/preseed.mustache\" \"/tmp/preseed.yaml\" {})
"
[tmpl dest args]
(let [source (slurp tmpl)
out (render source args)
parent (fs/parent dest)]
(if (not (fs/exists? parent))
(failure (<< "~{parent} missing, cannot spit template into ~{dest}"))
(do
(spit dest out)
(success (<< "created file from template under ~{dest}"))))))
(def-serial copy
"Copy a local file:
(copy \"/tmp/foo\" \"/tmp/bla\")
"
[src dest]
(try
(coherce (= (fs/copy src dest) dest))
(catch Exception e
(failure (.getMessage e)))))
(def-serial rename
"Move a local file:
(rename \"/tmp/foo\" \"/tmp/bla\")
"
[src dest]
(try
(coherce (fs/rename src dest))
(catch Exception e
(failure (.getMessage e)))))
(def-serial chmod
"Change file/directory mode resource:
(chmod \"/home\"/re-ops/.ssh\" \"0777\")
(chmod \"/home\"/re-ops/.ssh\" \"0777\" :recursive true)
"
[dest mode opts]
(letfn [(chmod-script []
(let [options (if (opts :recursive) "-R" "")]
(script
(set! ID @("id" "-u"))
(if (= "0" $ID)
("sudo" "/usr/bin/chmod" ~mode ~dest ~options)
("/usr/bin/chmod" ~mode ~dest ~options)))))]
(run- chmod-script)))
(def-serial chown
"Change file/directory owner using uid & gid resource:
; change file/folder ownership using user/group
(chown \"/home\"/re-ops/.ssh\" \"foo\" \"bar\")
; change file/folder ownership recursively
(chown \"/home\"/re-ops/.ssh\" \"foo\" \"bar\" {:recursive true})"
[dest user group opts]
(letfn [(chown-script []
(let [u-g (<< "~{user}:~{group}")
options (if (opts :recursive) "-R" "")]
(script
(set! ID @("id" "-u"))
(if (= "0" $ID)
("sudo" "/usr/bin/chown" ~u-g ~dest ~options)
("/usr/bin/chown" ~u-g ~dest ~options)))))]
(run- chown-script)))
(def-serial line
"File line resource either append or remove lines:
(line \"/tmp/foo\" \"bar\" :present); append line
(line \"/tmp/foo\" (line-eq \"bar\") :absent); remove all lines equal to bar from the file
(line \"/tmp/foo\" (fn [_ curr] (> 5 (.length curr))) :absent); remove lines using a function
(line \"/tmp/foo\" \"bar\" :replace :with \"foo\"); replace lines equal to bar with foo
(line \"/tmp/foo\" (fn [i _] (= i 2)) :replace :with \"foo\"); replace line in position 2 with value
(line \"/tmp/foo\" (fn [i _] (= i 2)) :comment :with \"#\"); comment line in position 2
"
[file v state & {:keys [with]}]
(letfn [(line-eq [line] (fn [_ curr] (not (= curr line))))
(add-line [line]
(let [contents (slurp file)]
(if (clojure.string/includes? contents line)
(success "file already contains line")
(do
(spit file (str line "\n") :append true)
(success "line added to file")))))
(replace-line [target]
(let [pred (if (string? target) (comp not (line-eq target)) target)
contents (slurp file)
replace-with (fn [i line] (if (pred i line) with line))
filtered (map-indexed replace-with
(clojure.string/split-lines contents))
output (clojure.string/join "\n" filtered)]
(if-not (= contents output)
(do
(spit file output)
(success "line replaced in file"))
(success "line not present in file"))))
(rm-line [target]
(let [pred (if (string? target) (line-eq target) target)
contents (slurp file)
filtered (keep-indexed pred (clojure.string/split-lines contents))
output (clojure.string/join "\n" filtered)]
(if-not (= contents output)
(do
(spit file output)
(success "line removed from file"))
(success "line not present in file"))))]
(let [states {:present add-line :absent rm-line :replace replace-line}]
(assert (into #{} (keys states)) state)
((states state) v))))
(def-serial uncomment
"Uncomment a line with separator value:
(uncomment \"/etc/ssh/sshd_config\" \"PermitRootLogin\" \"#\")
"
[dest k sep]
(if-not (fs/exists? dest)
(error (<< "~{dest} not found"))
(let [lines (slurp dest)
edited (clojure.string/replace-first lines (str sep k) k)]
(spit dest edited)
(success "line was uncommented"))))
(def-serial uncomment-nth
"Uncomment a line number nth with separator:
(uncomment-nth \"/etc/ssh/sshd_config\" \"#\" 1)
"
[dest sep n]
(if-not (fs/exists? dest)
(error (<< "~{dest} not found"))
(let [lines (clojure.string/split-lines (slurp dest))
edited (map-indexed
(fn [i line]
(if-not (= i n)
line
(clojure.string/replace-first line sep ""))) lines)]
(spit dest (clojure.string/join "\n" edited))
(success "line was uncommented at position"))))
(def-serial line-set
"Set an existing line value:
(line-set \"/etc/ssh/sshd_config\" \"PermitRootLogin\" \"no\" \" \")
"
[dest k v sep]
(letfn [(set-key [k v sep]
(fn [line]
(let [[f & _] (clojure.string/split line (re-pattern sep))]
(if (= f k)
(str k sep v)
line))))]
(if-not (fs/exists? dest)
(error (<< "~{dest} not found"))
(let [lines (slurp dest)
edited (map (set-key k v sep) (clojure.string/split-lines lines))]
(spit dest (clojure.string/join "\n" edited))
(success "value in file line was set")))))
(def-serial edn-set
"Set a value in an edn file:
(edn-set \"/tmp/secrets.edn\" [:lxc :pass] \"PI:PASSWORD:<PASSWORD>END_PI\")
"
[dest ks v]
(let [data (clojure.edn/read-string (slurp dest))]
(if (= (get-in data ks) v)
(success "value is already set")
(do
(spit dest (with-out-str (pr (assoc-in data ks v))))
(success "value was set in file")))))
(def-serial yaml-set
"Set a value in a yaml file:
(yaml-set \"/tmp/test.yaml\" [:parent :key] \"value\")
"
[dest ks v]
(let [data (yaml/parse-string (slurp dest))]
(if (= (get-in data ks) v)
(success "value is already set")
(do
(spit dest
(yaml/generate-string
(assoc-in data ks v) :dumper-options {:flow-style :block}))
(success "value was set in file")))))
(def-serial replace-all
"Replace all occurrences of a Regex match in a file
(replace-all \"/etc/apt/sources.list\" \"us.\" \"local.\")
"
[dest match with]
(letfn [(edit [line]
(let [post (clojure.string/replace line (re-pattern match) with)]
{:updated? (not (= post line)) :line post}))]
(if-not (fs/exists? dest)
(error (<< "~{dest} not found"))
(let [lines (slurp dest)
edited (map edit (clojure.string/split-lines lines))
updated (count (filter :updated? edited))]
(spit dest (clojure.string/join "\n" (map :line edited)))
(success (<< "~{updated} lines were updated in ~{dest}"))))))
|
[
{
"context": "; Copyright (C) 2014 Joseph Fosco. All Rights Reserved\n;\n; This program is free ",
"end": 37,
"score": 0.999840259552002,
"start": 25,
"tag": "NAME",
"value": "Joseph Fosco"
}
] | data/test/clojure/318eb273721045b435e8d5b41186ea279c53377acore_test.clj | harshp8l/deep-learning-lang-detection | 84 | ; Copyright (C) 2014 Joseph Fosco. All Rights Reserved
;
; This program is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with this program. If not, see <http://www.gnu.org/licenses/>.
;; To run tests:
;; 1. Load REPL with transport
;; 2. Load core_test.clj in REPL
;; 3. (ns transport.core-test)
;; 4. (run-tests)
(ns transport.core-test
(:require
[clojure.test :refer :all]
[overtone.live :refer [metronome]]
[transport.behavior :refer :all]
[transport.core :refer :all]
[transport.ensemble :refer [play-melody]]
[transport.instrument :refer [select-random-instrument]]
[transport.melodychar :refer :all]
[transport.players :refer :all]
[transport.schedule :refer [clear-scheduler]]
[transport.settings :refer :all]
)
(:import
transport.melodychar.MelodyChar
transport.behavior.Behavior
)
)
(comment
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
)
(deftest follow-test-1
(testing "Player 0 follows player 1 first time"
(let [tst-players
{
0
{
:behavior (Behavior. 0.2966165302092916, FOLLOW-PLAYER, 1)
:change-follow-info-note 0
:cur-note-beat 0
:function transport.ensemble/play-melody
:instrument-info (select-random-instrument)
:key 0
:melody {}
:melody-char (MelodyChar. 9, 4, 2, 0)
:metronome (metronome 64)
:mm 64
:player-id 0
:prev-note-beat 0
:scale :ionian
:seg-len 19726
:seg-num 1
:seg-start 0
}
1
{
:behavior (Behavior. 0.4798252752058973, IGNORE, nil)
:change-follow-info-note nil
:cur-note-beat 0
:function transport.ensemble/play-melody
:instrument-info(select-random-instrument)
:key 8
:melody {}
:melody-char (MelodyChar. 1, 7, 2, 6)
:metronome (metronome 94)
:mm 94
:player-id 1
:prev-note-beat 0
:scale :hindu
:seg-len 10565
:seg-num 1
:seg-start 0
}
}
]
(reset-players)
(send PLAYERS conj tst-players)
(await PLAYERS)
(is (= true
(try
(play-melody 0 0)
(transport-clear)
(println "PASS - Initial Follow test - PASS")
true
(catch Exception e
(println "ERROR - Exception in Initial Follow test - ERROR")
(println e)
(transport-clear)
false
)
)
))
)
))
| 106819 | ; Copyright (C) 2014 <NAME>. All Rights Reserved
;
; This program is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with this program. If not, see <http://www.gnu.org/licenses/>.
;; To run tests:
;; 1. Load REPL with transport
;; 2. Load core_test.clj in REPL
;; 3. (ns transport.core-test)
;; 4. (run-tests)
(ns transport.core-test
(:require
[clojure.test :refer :all]
[overtone.live :refer [metronome]]
[transport.behavior :refer :all]
[transport.core :refer :all]
[transport.ensemble :refer [play-melody]]
[transport.instrument :refer [select-random-instrument]]
[transport.melodychar :refer :all]
[transport.players :refer :all]
[transport.schedule :refer [clear-scheduler]]
[transport.settings :refer :all]
)
(:import
transport.melodychar.MelodyChar
transport.behavior.Behavior
)
)
(comment
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
)
(deftest follow-test-1
(testing "Player 0 follows player 1 first time"
(let [tst-players
{
0
{
:behavior (Behavior. 0.2966165302092916, FOLLOW-PLAYER, 1)
:change-follow-info-note 0
:cur-note-beat 0
:function transport.ensemble/play-melody
:instrument-info (select-random-instrument)
:key 0
:melody {}
:melody-char (MelodyChar. 9, 4, 2, 0)
:metronome (metronome 64)
:mm 64
:player-id 0
:prev-note-beat 0
:scale :ionian
:seg-len 19726
:seg-num 1
:seg-start 0
}
1
{
:behavior (Behavior. 0.4798252752058973, IGNORE, nil)
:change-follow-info-note nil
:cur-note-beat 0
:function transport.ensemble/play-melody
:instrument-info(select-random-instrument)
:key 8
:melody {}
:melody-char (MelodyChar. 1, 7, 2, 6)
:metronome (metronome 94)
:mm 94
:player-id 1
:prev-note-beat 0
:scale :hindu
:seg-len 10565
:seg-num 1
:seg-start 0
}
}
]
(reset-players)
(send PLAYERS conj tst-players)
(await PLAYERS)
(is (= true
(try
(play-melody 0 0)
(transport-clear)
(println "PASS - Initial Follow test - PASS")
true
(catch Exception e
(println "ERROR - Exception in Initial Follow test - ERROR")
(println e)
(transport-clear)
false
)
)
))
)
))
| true | ; Copyright (C) 2014 PI:NAME:<NAME>END_PI. All Rights Reserved
;
; This program is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with this program. If not, see <http://www.gnu.org/licenses/>.
;; To run tests:
;; 1. Load REPL with transport
;; 2. Load core_test.clj in REPL
;; 3. (ns transport.core-test)
;; 4. (run-tests)
(ns transport.core-test
(:require
[clojure.test :refer :all]
[overtone.live :refer [metronome]]
[transport.behavior :refer :all]
[transport.core :refer :all]
[transport.ensemble :refer [play-melody]]
[transport.instrument :refer [select-random-instrument]]
[transport.melodychar :refer :all]
[transport.players :refer :all]
[transport.schedule :refer [clear-scheduler]]
[transport.settings :refer :all]
)
(:import
transport.melodychar.MelodyChar
transport.behavior.Behavior
)
)
(comment
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
)
(deftest follow-test-1
(testing "Player 0 follows player 1 first time"
(let [tst-players
{
0
{
:behavior (Behavior. 0.2966165302092916, FOLLOW-PLAYER, 1)
:change-follow-info-note 0
:cur-note-beat 0
:function transport.ensemble/play-melody
:instrument-info (select-random-instrument)
:key 0
:melody {}
:melody-char (MelodyChar. 9, 4, 2, 0)
:metronome (metronome 64)
:mm 64
:player-id 0
:prev-note-beat 0
:scale :ionian
:seg-len 19726
:seg-num 1
:seg-start 0
}
1
{
:behavior (Behavior. 0.4798252752058973, IGNORE, nil)
:change-follow-info-note nil
:cur-note-beat 0
:function transport.ensemble/play-melody
:instrument-info(select-random-instrument)
:key 8
:melody {}
:melody-char (MelodyChar. 1, 7, 2, 6)
:metronome (metronome 94)
:mm 94
:player-id 1
:prev-note-beat 0
:scale :hindu
:seg-len 10565
:seg-num 1
:seg-start 0
}
}
]
(reset-players)
(send PLAYERS conj tst-players)
(await PLAYERS)
(is (= true
(try
(play-melody 0 0)
(transport-clear)
(println "PASS - Initial Follow test - PASS")
true
(catch Exception e
(println "ERROR - Exception in Initial Follow test - ERROR")
(println e)
(transport-clear)
false
)
)
))
)
))
|
[
{
"context": "me]\n :initial-state {:person/id 1 :person/name \"Tony\"}\n :extra-data 42}\n (dom/div \"TODO\"))\n\n(def",
"end": 548,
"score": 0.9995893836021423,
"start": 544,
"tag": "NAME",
"value": "Tony"
},
{
"context": "e (fn [{:keys [id]}] {:person/id id :person/name \"Tony\"})\n :extra-data 42}\n (dom/div \"TODO\"))\n\n(de",
"end": 759,
"score": 0.9996888637542725,
"start": 755,
"tag": "NAME",
"value": "Tony"
},
{
"context": " (comp/get-initial-state A) => {:person/name \"Tony\" :person/id 1}\n (comp/get-initial-state B {:",
"end": 1599,
"score": 0.9996060132980347,
"start": 1595,
"tag": "NAME",
"value": "Tony"
},
{
"context": "p/get-initial-state B {:id 22}) => {:person/name \"Tony\" :person/id 22}\n \"The class is available in ",
"end": 1679,
"score": 0.9997375011444092,
"start": 1675,
"tag": "NAME",
"value": "Tony"
}
] | src/test/com/fulcrologic/fulcro/components_spec.cljc | mruzekw/fulcro | 43 | (ns com.fulcrologic.fulcro.components-spec
(:require
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.algorithms.denormalize :as fdn]
#?(:clj [com.fulcrologic.fulcro.dom-server :as dom]
:cljs [com.fulcrologic.fulcro.dom :as dom])
#?(:cljs [goog.object :as gobj])
[fulcro-spec.core :refer [specification assertions behavior component]]))
(defsc A [this props]
{:ident :person/id
:query [:person/id :person/name]
:initial-state {:person/id 1 :person/name "Tony"}
:extra-data 42}
(dom/div "TODO"))
(defsc B [this props]
{:ident :person/id
:query [:person/id :person/name]
:initial-state (fn [{:keys [id]}] {:person/id id :person/name "Tony"})
:extra-data 42}
(dom/div "TODO"))
(def ui-a (comp/factory A))
(specification "Component basics"
(let [ui-a (comp/factory A)]
(assertions
"Supports arbitrary option data"
(-> A comp/component-options :extra-data) => 42
"Component class can be detected"
(comp/component-class? A) => true
(comp/component-class? (ui-a {})) => false
"The component name is available from the class"
(comp/component-name A) => (str `A)
"The registry key is available from the class"
(comp/class->registry-key A) => ::A
"Can be used to obtain the ident"
(comp/get-ident A {:person/id 4}) => [:person/id 4]
"Can be used to obtain the query"
(comp/get-query A) => [:person/id :person/name]
"Initial state"
(comp/get-initial-state A) => {:person/name "Tony" :person/id 1}
(comp/get-initial-state B {:id 22}) => {:person/name "Tony" :person/id 22}
"The class is available in the registry using a symbol or keyword"
(comp/registry-key->class ::A) => A
(comp/registry-key->class `A) => A)))
(specification "computed props"
(assertions
"Can be added and extracted on map-based props"
(comp/get-computed (comp/computed {} {:x 1})) => {:x 1}
"Can be added and extracted on vector props"
(comp/get-computed (comp/computed [] {:x 1})) => {:x 1}))
(specification "newer-props"
(assertions
"Returns the first props if neither are timestamped"
(comp/newer-props {:a 1} {:a 2}) => {:a 1}
"Returns the second props if the first are nil"
(comp/newer-props nil {:a 2}) => {:a 2}
"Returns the newer props if both have times"
(comp/newer-props (fdn/with-time {:a 1} 1) (fdn/with-time {:a 2} 2)) => {:a 2}
(comp/newer-props (fdn/with-time {:a 1} 2) (fdn/with-time {:a 2} 1)) => {:a 1}
"Returns the second props if the times are the same"
(comp/newer-props (fdn/with-time {:a 1} 1) (fdn/with-time {:a 2} 1)) => {:a 2}))
(specification "classname->class"
(assertions
"Returns from registry under fq keyword"
(nil? (comp/registry-key->class ::A)) => false
"Returns from registry under fq symbol"
(nil? (comp/registry-key->class `A)) => false))
(specification "react-type"
(assertions
"Returns the class when passed an instance"
#?(:clj (comp/react-type (ui-a {}))
:cljs (comp/react-type (A.))) => A))
(specification "wrap-update-extra-props"
(let [wrapper (comp/wrap-update-extra-props (fn [_ p] (assoc p :X 1)))
updated-props (wrapper A #js {})]
(assertions
"Places extra props in raw props at :fulcro$extra_props"
(comp/isoget updated-props :fulcro$extra_props) => {:X 1})))
| 40159 | (ns com.fulcrologic.fulcro.components-spec
(:require
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.algorithms.denormalize :as fdn]
#?(:clj [com.fulcrologic.fulcro.dom-server :as dom]
:cljs [com.fulcrologic.fulcro.dom :as dom])
#?(:cljs [goog.object :as gobj])
[fulcro-spec.core :refer [specification assertions behavior component]]))
(defsc A [this props]
{:ident :person/id
:query [:person/id :person/name]
:initial-state {:person/id 1 :person/name "<NAME>"}
:extra-data 42}
(dom/div "TODO"))
(defsc B [this props]
{:ident :person/id
:query [:person/id :person/name]
:initial-state (fn [{:keys [id]}] {:person/id id :person/name "<NAME>"})
:extra-data 42}
(dom/div "TODO"))
(def ui-a (comp/factory A))
(specification "Component basics"
(let [ui-a (comp/factory A)]
(assertions
"Supports arbitrary option data"
(-> A comp/component-options :extra-data) => 42
"Component class can be detected"
(comp/component-class? A) => true
(comp/component-class? (ui-a {})) => false
"The component name is available from the class"
(comp/component-name A) => (str `A)
"The registry key is available from the class"
(comp/class->registry-key A) => ::A
"Can be used to obtain the ident"
(comp/get-ident A {:person/id 4}) => [:person/id 4]
"Can be used to obtain the query"
(comp/get-query A) => [:person/id :person/name]
"Initial state"
(comp/get-initial-state A) => {:person/name "<NAME>" :person/id 1}
(comp/get-initial-state B {:id 22}) => {:person/name "<NAME>" :person/id 22}
"The class is available in the registry using a symbol or keyword"
(comp/registry-key->class ::A) => A
(comp/registry-key->class `A) => A)))
(specification "computed props"
(assertions
"Can be added and extracted on map-based props"
(comp/get-computed (comp/computed {} {:x 1})) => {:x 1}
"Can be added and extracted on vector props"
(comp/get-computed (comp/computed [] {:x 1})) => {:x 1}))
(specification "newer-props"
(assertions
"Returns the first props if neither are timestamped"
(comp/newer-props {:a 1} {:a 2}) => {:a 1}
"Returns the second props if the first are nil"
(comp/newer-props nil {:a 2}) => {:a 2}
"Returns the newer props if both have times"
(comp/newer-props (fdn/with-time {:a 1} 1) (fdn/with-time {:a 2} 2)) => {:a 2}
(comp/newer-props (fdn/with-time {:a 1} 2) (fdn/with-time {:a 2} 1)) => {:a 1}
"Returns the second props if the times are the same"
(comp/newer-props (fdn/with-time {:a 1} 1) (fdn/with-time {:a 2} 1)) => {:a 2}))
(specification "classname->class"
(assertions
"Returns from registry under fq keyword"
(nil? (comp/registry-key->class ::A)) => false
"Returns from registry under fq symbol"
(nil? (comp/registry-key->class `A)) => false))
(specification "react-type"
(assertions
"Returns the class when passed an instance"
#?(:clj (comp/react-type (ui-a {}))
:cljs (comp/react-type (A.))) => A))
(specification "wrap-update-extra-props"
(let [wrapper (comp/wrap-update-extra-props (fn [_ p] (assoc p :X 1)))
updated-props (wrapper A #js {})]
(assertions
"Places extra props in raw props at :fulcro$extra_props"
(comp/isoget updated-props :fulcro$extra_props) => {:X 1})))
| true | (ns com.fulcrologic.fulcro.components-spec
(:require
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.algorithms.denormalize :as fdn]
#?(:clj [com.fulcrologic.fulcro.dom-server :as dom]
:cljs [com.fulcrologic.fulcro.dom :as dom])
#?(:cljs [goog.object :as gobj])
[fulcro-spec.core :refer [specification assertions behavior component]]))
(defsc A [this props]
{:ident :person/id
:query [:person/id :person/name]
:initial-state {:person/id 1 :person/name "PI:NAME:<NAME>END_PI"}
:extra-data 42}
(dom/div "TODO"))
(defsc B [this props]
{:ident :person/id
:query [:person/id :person/name]
:initial-state (fn [{:keys [id]}] {:person/id id :person/name "PI:NAME:<NAME>END_PI"})
:extra-data 42}
(dom/div "TODO"))
(def ui-a (comp/factory A))
(specification "Component basics"
(let [ui-a (comp/factory A)]
(assertions
"Supports arbitrary option data"
(-> A comp/component-options :extra-data) => 42
"Component class can be detected"
(comp/component-class? A) => true
(comp/component-class? (ui-a {})) => false
"The component name is available from the class"
(comp/component-name A) => (str `A)
"The registry key is available from the class"
(comp/class->registry-key A) => ::A
"Can be used to obtain the ident"
(comp/get-ident A {:person/id 4}) => [:person/id 4]
"Can be used to obtain the query"
(comp/get-query A) => [:person/id :person/name]
"Initial state"
(comp/get-initial-state A) => {:person/name "PI:NAME:<NAME>END_PI" :person/id 1}
(comp/get-initial-state B {:id 22}) => {:person/name "PI:NAME:<NAME>END_PI" :person/id 22}
"The class is available in the registry using a symbol or keyword"
(comp/registry-key->class ::A) => A
(comp/registry-key->class `A) => A)))
(specification "computed props"
(assertions
"Can be added and extracted on map-based props"
(comp/get-computed (comp/computed {} {:x 1})) => {:x 1}
"Can be added and extracted on vector props"
(comp/get-computed (comp/computed [] {:x 1})) => {:x 1}))
(specification "newer-props"
(assertions
"Returns the first props if neither are timestamped"
(comp/newer-props {:a 1} {:a 2}) => {:a 1}
"Returns the second props if the first are nil"
(comp/newer-props nil {:a 2}) => {:a 2}
"Returns the newer props if both have times"
(comp/newer-props (fdn/with-time {:a 1} 1) (fdn/with-time {:a 2} 2)) => {:a 2}
(comp/newer-props (fdn/with-time {:a 1} 2) (fdn/with-time {:a 2} 1)) => {:a 1}
"Returns the second props if the times are the same"
(comp/newer-props (fdn/with-time {:a 1} 1) (fdn/with-time {:a 2} 1)) => {:a 2}))
(specification "classname->class"
(assertions
"Returns from registry under fq keyword"
(nil? (comp/registry-key->class ::A)) => false
"Returns from registry under fq symbol"
(nil? (comp/registry-key->class `A)) => false))
(specification "react-type"
(assertions
"Returns the class when passed an instance"
#?(:clj (comp/react-type (ui-a {}))
:cljs (comp/react-type (A.))) => A))
(specification "wrap-update-extra-props"
(let [wrapper (comp/wrap-update-extra-props (fn [_ p] (assoc p :X 1)))
updated-props (wrapper A #js {})]
(assertions
"Places extra props in raw props at :fulcro$extra_props"
(comp/isoget updated-props :fulcro$extra_props) => {:X 1})))
|
[
{
"context": " ;; un-specified keys\n (is (match? {:name/first \"Alfredo\"}\n {:name/first \"Alfredo\"\n ",
"end": 1734,
"score": 0.999748170375824,
"start": 1727,
"tag": "NAME",
"value": "Alfredo"
},
{
"context": "ame/first \"Alfredo\"}\n {:name/first \"Alfredo\"\n :name/last \"da Rocha Viana\"\n ",
"end": 1773,
"score": 0.9998006820678711,
"start": 1766,
"tag": "NAME",
"value": "Alfredo"
},
{
"context": "ame/first \"Alfredo\"\n :name/last \"da Rocha Viana\"\n :name/suffix \"Jr.\"})))\n\n(deftest ",
"end": 1818,
"score": 0.9998181462287903,
"start": 1804,
"tag": "NAME",
"value": "da Rocha Viana"
},
{
"context": "ture.\n (is (match? {:band/members [{:name/first \"Alfredo\"}\n {:name/first \"Ben",
"end": 2072,
"score": 0.9997439384460449,
"start": 2065,
"tag": "NAME",
"value": "Alfredo"
},
{
"context": "edo\"}\n {:name/first \"Benedito\"}]}\n {:band/members [{:name/first \"",
"end": 2127,
"score": 0.9997925758361816,
"start": 2119,
"tag": "NAME",
"value": "Benedito"
},
{
"context": "\"}]}\n {:band/members [{:name/first \"Alfredo\"\n :name/last \"da ",
"end": 2184,
"score": 0.999774158000946,
"start": 2177,
"tag": "NAME",
"value": "Alfredo"
},
{
"context": "edo\"\n :name/last \"da Rocha Viana\"\n :name/suffix \"Jr.",
"end": 2245,
"score": 0.9997967481613159,
"start": 2231,
"tag": "NAME",
"value": "da Rocha Viana"
},
{
"context": "Jr.\"}\n {:name/first \"Benedito\"\n :name/last \"Lace",
"end": 2350,
"score": 0.9998106956481934,
"start": 2342,
"tag": "NAME",
"value": "Benedito"
},
{
"context": "dito\"\n :name/last \"Lacerda\"}]\n :band/recordings []})))\n\n(defte",
"end": 2403,
"score": 0.9997310042381287,
"start": 2396,
"tag": "NAME",
"value": "Lacerda"
}
] | dev/matcher_combinators/readme_examples.clj | clojure-land/matcher-combinators | 284 | (ns matcher-combinators.readme-examples)
(require '[clojure.test :refer [deftest is]]
'[matcher-combinators.test] ;; adds support for `match?` and `thrown-match?` in `is` expressions
'[matcher-combinators.matchers :as m])
(deftest test-matching-with-explict-matchers
(is (match? (m/equals 37) (+ 29 8)))
(is (match? (m/regex #"fox") "The quick brown fox jumps over the lazy dog")))
(deftest test-matching-scalars
;; most scalar values are interpreted as an `equals` matcher
(is (match? 37 (+ 29 8)))
(is (match? "this string" (str "this" " " "string")))
(is (match? :this/keyword (keyword "this" "keyword")))
;; regular expressions are handled specially
(is (match? #"fox" "The quick brown fox jumps over the lazy dog")))
(deftest test-matching-sequences
;; A sequence is interpreted as an `equals` matcher, which specifies
;; count and order of matching elements. The elements, themselves,
;; are matched based on their types.
(is (match? [1 3] [1 3]))
(is (match? [1 odd?] [1 3]))
(is (match? [#"red" #"violet"] ["Roses are red" "Violets are ... violet"]))
;; use m/prefix when you only care about the first n items
(is (match? (m/prefix [odd? 3]) [1 3 5]))
;; use m/in-any-order when order doesn't matter
(is (match? (m/in-any-order [odd? odd? even?]) [1 2 3])))
(deftest test-matching-sets
;; A set is also interpreted as an `equals` matcher.
(is (match? #{1 2 3} #{3 2 1}))
(is (match? #{odd? even?} #{1 2}))
;; use m/set-equals to repeat predicates
(is (match? (m/set-equals [odd? odd? even?]) #{1 2 3})))
(deftest test-matching-maps
;; A map is interpreted as an `embeds` matcher, which ignores
;; un-specified keys
(is (match? {:name/first "Alfredo"}
{:name/first "Alfredo"
:name/last "da Rocha Viana"
:name/suffix "Jr."})))
(deftest test-matching-nested-datastructures
;; Maps, sequences, and sets follow the same semantics whether at
;; the top level or nested within a structure.
(is (match? {:band/members [{:name/first "Alfredo"}
{:name/first "Benedito"}]}
{:band/members [{:name/first "Alfredo"
:name/last "da Rocha Viana"
:name/suffix "Jr."}
{:name/first "Benedito"
:name/last "Lacerda"}]
:band/recordings []})))
(deftest exception-matching
(is (thrown-match? clojure.lang.ExceptionInfo
{:foo 1}
(throw (ex-info "Boom!" {:foo 1 :bar 2})))))
| 114898 | (ns matcher-combinators.readme-examples)
(require '[clojure.test :refer [deftest is]]
'[matcher-combinators.test] ;; adds support for `match?` and `thrown-match?` in `is` expressions
'[matcher-combinators.matchers :as m])
(deftest test-matching-with-explict-matchers
(is (match? (m/equals 37) (+ 29 8)))
(is (match? (m/regex #"fox") "The quick brown fox jumps over the lazy dog")))
(deftest test-matching-scalars
;; most scalar values are interpreted as an `equals` matcher
(is (match? 37 (+ 29 8)))
(is (match? "this string" (str "this" " " "string")))
(is (match? :this/keyword (keyword "this" "keyword")))
;; regular expressions are handled specially
(is (match? #"fox" "The quick brown fox jumps over the lazy dog")))
(deftest test-matching-sequences
;; A sequence is interpreted as an `equals` matcher, which specifies
;; count and order of matching elements. The elements, themselves,
;; are matched based on their types.
(is (match? [1 3] [1 3]))
(is (match? [1 odd?] [1 3]))
(is (match? [#"red" #"violet"] ["Roses are red" "Violets are ... violet"]))
;; use m/prefix when you only care about the first n items
(is (match? (m/prefix [odd? 3]) [1 3 5]))
;; use m/in-any-order when order doesn't matter
(is (match? (m/in-any-order [odd? odd? even?]) [1 2 3])))
(deftest test-matching-sets
;; A set is also interpreted as an `equals` matcher.
(is (match? #{1 2 3} #{3 2 1}))
(is (match? #{odd? even?} #{1 2}))
;; use m/set-equals to repeat predicates
(is (match? (m/set-equals [odd? odd? even?]) #{1 2 3})))
(deftest test-matching-maps
;; A map is interpreted as an `embeds` matcher, which ignores
;; un-specified keys
(is (match? {:name/first "<NAME>"}
{:name/first "<NAME>"
:name/last "<NAME>"
:name/suffix "Jr."})))
(deftest test-matching-nested-datastructures
;; Maps, sequences, and sets follow the same semantics whether at
;; the top level or nested within a structure.
(is (match? {:band/members [{:name/first "<NAME>"}
{:name/first "<NAME>"}]}
{:band/members [{:name/first "<NAME>"
:name/last "<NAME>"
:name/suffix "Jr."}
{:name/first "<NAME>"
:name/last "<NAME>"}]
:band/recordings []})))
(deftest exception-matching
(is (thrown-match? clojure.lang.ExceptionInfo
{:foo 1}
(throw (ex-info "Boom!" {:foo 1 :bar 2})))))
| true | (ns matcher-combinators.readme-examples)
(require '[clojure.test :refer [deftest is]]
'[matcher-combinators.test] ;; adds support for `match?` and `thrown-match?` in `is` expressions
'[matcher-combinators.matchers :as m])
(deftest test-matching-with-explict-matchers
(is (match? (m/equals 37) (+ 29 8)))
(is (match? (m/regex #"fox") "The quick brown fox jumps over the lazy dog")))
(deftest test-matching-scalars
;; most scalar values are interpreted as an `equals` matcher
(is (match? 37 (+ 29 8)))
(is (match? "this string" (str "this" " " "string")))
(is (match? :this/keyword (keyword "this" "keyword")))
;; regular expressions are handled specially
(is (match? #"fox" "The quick brown fox jumps over the lazy dog")))
(deftest test-matching-sequences
;; A sequence is interpreted as an `equals` matcher, which specifies
;; count and order of matching elements. The elements, themselves,
;; are matched based on their types.
(is (match? [1 3] [1 3]))
(is (match? [1 odd?] [1 3]))
(is (match? [#"red" #"violet"] ["Roses are red" "Violets are ... violet"]))
;; use m/prefix when you only care about the first n items
(is (match? (m/prefix [odd? 3]) [1 3 5]))
;; use m/in-any-order when order doesn't matter
(is (match? (m/in-any-order [odd? odd? even?]) [1 2 3])))
(deftest test-matching-sets
;; A set is also interpreted as an `equals` matcher.
(is (match? #{1 2 3} #{3 2 1}))
(is (match? #{odd? even?} #{1 2}))
;; use m/set-equals to repeat predicates
(is (match? (m/set-equals [odd? odd? even?]) #{1 2 3})))
(deftest test-matching-maps
;; A map is interpreted as an `embeds` matcher, which ignores
;; un-specified keys
(is (match? {:name/first "PI:NAME:<NAME>END_PI"}
{:name/first "PI:NAME:<NAME>END_PI"
:name/last "PI:NAME:<NAME>END_PI"
:name/suffix "Jr."})))
(deftest test-matching-nested-datastructures
;; Maps, sequences, and sets follow the same semantics whether at
;; the top level or nested within a structure.
(is (match? {:band/members [{:name/first "PI:NAME:<NAME>END_PI"}
{:name/first "PI:NAME:<NAME>END_PI"}]}
{:band/members [{:name/first "PI:NAME:<NAME>END_PI"
:name/last "PI:NAME:<NAME>END_PI"
:name/suffix "Jr."}
{:name/first "PI:NAME:<NAME>END_PI"
:name/last "PI:NAME:<NAME>END_PI"}]
:band/recordings []})))
(deftest exception-matching
(is (thrown-match? clojure.lang.ExceptionInfo
{:foo 1}
(throw (ex-info "Boom!" {:foo 1 :bar 2})))))
|
[
{
"context": "; Copyright (c) 2017-present Walmart, Inc.\n;\n; Licensed under the Apache License, Vers",
"end": 36,
"score": 0.8312142491340637,
"start": 29,
"tag": "NAME",
"value": "Walmart"
}
] | src/com/walmartlabs/lacinia/parser/docs.clj | hagenek/lacinia | 1,762 | ; Copyright (c) 2017-present Walmart, Inc.
;
; 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.
(ns com.walmartlabs.lacinia.parser.docs
"Parsing of a Markdown file for purposes of attaching documentation to a schema."
{:added "0.27.0"}
(:require
[clojure.string :as str]
[com.walmartlabs.lacinia.internal-utils :refer [cond-let]]))
(def ^:private header-re
;; Don't really care how deep the heading is
#"\#+\s+(.*?)\s*$")
(defn ^:private combine-block
[lines]
(->> lines
(str/join "\n")
str/trim))
(defn parse-docs
"Parses an input document. Returns a map who keys are the keyword versions of headers, and whose values
are the (trimmed) content immediately beneath that header.
The result is a documentation map that can be provided to [[inject-descriptions]]."
[input]
(loop [lines (str/split-lines input)
result {}
header nil
block []]
(cond-let
(nil? lines)
(if header
(assoc result header (combine-block block))
result)
:let [line (first lines)
more-lines (next lines)
[_ new-header] (re-matches header-re line)]
(some? new-header)
(recur more-lines
(if header
(assoc result header (combine-block block))
result)
(keyword new-header)
[])
(some? header)
(recur more-lines result header (conj block line))
:else
;; In the preamble, if any, before first header.
(recur more-lines result header block))))
| 21977 | ; Copyright (c) 2017-present <NAME>, Inc.
;
; 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.
(ns com.walmartlabs.lacinia.parser.docs
"Parsing of a Markdown file for purposes of attaching documentation to a schema."
{:added "0.27.0"}
(:require
[clojure.string :as str]
[com.walmartlabs.lacinia.internal-utils :refer [cond-let]]))
(def ^:private header-re
;; Don't really care how deep the heading is
#"\#+\s+(.*?)\s*$")
(defn ^:private combine-block
[lines]
(->> lines
(str/join "\n")
str/trim))
(defn parse-docs
"Parses an input document. Returns a map who keys are the keyword versions of headers, and whose values
are the (trimmed) content immediately beneath that header.
The result is a documentation map that can be provided to [[inject-descriptions]]."
[input]
(loop [lines (str/split-lines input)
result {}
header nil
block []]
(cond-let
(nil? lines)
(if header
(assoc result header (combine-block block))
result)
:let [line (first lines)
more-lines (next lines)
[_ new-header] (re-matches header-re line)]
(some? new-header)
(recur more-lines
(if header
(assoc result header (combine-block block))
result)
(keyword new-header)
[])
(some? header)
(recur more-lines result header (conj block line))
:else
;; In the preamble, if any, before first header.
(recur more-lines result header block))))
| true | ; Copyright (c) 2017-present PI:NAME:<NAME>END_PI, Inc.
;
; 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.
(ns com.walmartlabs.lacinia.parser.docs
"Parsing of a Markdown file for purposes of attaching documentation to a schema."
{:added "0.27.0"}
(:require
[clojure.string :as str]
[com.walmartlabs.lacinia.internal-utils :refer [cond-let]]))
(def ^:private header-re
;; Don't really care how deep the heading is
#"\#+\s+(.*?)\s*$")
(defn ^:private combine-block
[lines]
(->> lines
(str/join "\n")
str/trim))
(defn parse-docs
"Parses an input document. Returns a map who keys are the keyword versions of headers, and whose values
are the (trimmed) content immediately beneath that header.
The result is a documentation map that can be provided to [[inject-descriptions]]."
[input]
(loop [lines (str/split-lines input)
result {}
header nil
block []]
(cond-let
(nil? lines)
(if header
(assoc result header (combine-block block))
result)
:let [line (first lines)
more-lines (next lines)
[_ new-header] (re-matches header-re line)]
(some? new-header)
(recur more-lines
(if header
(assoc result header (combine-block block))
result)
(keyword new-header)
[])
(some? header)
(recur more-lines result header (conj block line))
:else
;; In the preamble, if any, before first header.
(recur more-lines result header block))))
|
[
{
"context": " file and\n returns a component map.\"\n {:author \"Sameer Rahmani (@lxsameer)\"}\n (:require\n [clojure.spec.alpha ",
"end": 365,
"score": 0.9998664259910583,
"start": 351,
"tag": "NAME",
"value": "Sameer Rahmani"
},
{
"context": "turns a component map.\"\n {:author \"Sameer Rahmani (@lxsameer)\"}\n (:require\n [clojure.spec.alpha :as s]\n ",
"end": 376,
"score": 0.9995840191841125,
"start": 366,
"tag": "USERNAME",
"value": "(@lxsameer"
}
] | http/src/clj/hellhound/components/webserver.clj | Codamic/hell-hound | 34 | (ns hellhound.components.webserver
"The default web/websocket server component of **HellHound**.
This component provides a webserver based on [aleph](//aleph.io).
In order this use this component simply call the `factory` function.
It's going to get the configuration from the environment edn file and
returns a component map."
{:author "Sameer Rahmani (@lxsameer)"}
(:require
[clojure.spec.alpha :as s]
[aleph.http :as aleph]
[hellhound.logger :as log]
[hellhound.core :as hellhound]
[hellhound.specs :as spec]
[hellhound.component :as hcomp]
[hellhound.http :as http]
[hellhound.streams :as streams]
[hellhound.http.handlers :as handlers]
[hellhound.http.response :as response]
[hellhound.http.route :as router]))
;; TODO: Extract the spec check into a predicate function called map-with
(s/def ::aleph-config
(s/and map?
#(and (contains? % :host)
(string? (:host %)))
#(and (contains? % :port)
(int? (:port %)))))
(def CONFIG_ERR_MSG
"Aleph configuration is invalid. Probably forgot to add the configuration to your system.")
(defn start!
"Returns a start function for the webserver component.
The return function starts the webserver using the given `routes`
and `config` map.
NOTE: This function RETURNS a start function."
[config]
(fn [this context]
(let [new-context (assoc context
:input (hcomp/input this)
:output (hcomp/output this))
config (merge (:config new-context) config)]
(spec/validate ::aleph-config config CONFIG_ERR_MSG)
(assoc this
:instance (aleph/start-server (handlers/req-to-stream new-context)
config)
:config config))))
(defn stop!
"Stops the running webserver server."
[this]
(when-let [server (:instance this)]
(.close server))
(dissoc this :instance))
(defn factory
"Returns a new webserver component by the given `routes` and an
optional `config` map.
The `routes` argument should be a valid **HellHound** route collection,
compatible with Pedestal library. **Hellhound**
provides a helper namespace for dealing with routes. Checkout
[[hellhound.http]] and [[hellhound.http.route]] namespaces for more info."
([]
(factory {}))
([config]
{:hellhound.component/name ::webserver
:hellhound.component/start-fn (start! config)
:hellhound.component/stop-fn stop!
:hellhound.component/fn
(fn [component]
(streams/consume response/resolver
(hcomp/input component)))}))
| 34770 | (ns hellhound.components.webserver
"The default web/websocket server component of **HellHound**.
This component provides a webserver based on [aleph](//aleph.io).
In order this use this component simply call the `factory` function.
It's going to get the configuration from the environment edn file and
returns a component map."
{:author "<NAME> (@lxsameer)"}
(:require
[clojure.spec.alpha :as s]
[aleph.http :as aleph]
[hellhound.logger :as log]
[hellhound.core :as hellhound]
[hellhound.specs :as spec]
[hellhound.component :as hcomp]
[hellhound.http :as http]
[hellhound.streams :as streams]
[hellhound.http.handlers :as handlers]
[hellhound.http.response :as response]
[hellhound.http.route :as router]))
;; TODO: Extract the spec check into a predicate function called map-with
(s/def ::aleph-config
(s/and map?
#(and (contains? % :host)
(string? (:host %)))
#(and (contains? % :port)
(int? (:port %)))))
(def CONFIG_ERR_MSG
"Aleph configuration is invalid. Probably forgot to add the configuration to your system.")
(defn start!
"Returns a start function for the webserver component.
The return function starts the webserver using the given `routes`
and `config` map.
NOTE: This function RETURNS a start function."
[config]
(fn [this context]
(let [new-context (assoc context
:input (hcomp/input this)
:output (hcomp/output this))
config (merge (:config new-context) config)]
(spec/validate ::aleph-config config CONFIG_ERR_MSG)
(assoc this
:instance (aleph/start-server (handlers/req-to-stream new-context)
config)
:config config))))
(defn stop!
"Stops the running webserver server."
[this]
(when-let [server (:instance this)]
(.close server))
(dissoc this :instance))
(defn factory
"Returns a new webserver component by the given `routes` and an
optional `config` map.
The `routes` argument should be a valid **HellHound** route collection,
compatible with Pedestal library. **Hellhound**
provides a helper namespace for dealing with routes. Checkout
[[hellhound.http]] and [[hellhound.http.route]] namespaces for more info."
([]
(factory {}))
([config]
{:hellhound.component/name ::webserver
:hellhound.component/start-fn (start! config)
:hellhound.component/stop-fn stop!
:hellhound.component/fn
(fn [component]
(streams/consume response/resolver
(hcomp/input component)))}))
| true | (ns hellhound.components.webserver
"The default web/websocket server component of **HellHound**.
This component provides a webserver based on [aleph](//aleph.io).
In order this use this component simply call the `factory` function.
It's going to get the configuration from the environment edn file and
returns a component map."
{:author "PI:NAME:<NAME>END_PI (@lxsameer)"}
(:require
[clojure.spec.alpha :as s]
[aleph.http :as aleph]
[hellhound.logger :as log]
[hellhound.core :as hellhound]
[hellhound.specs :as spec]
[hellhound.component :as hcomp]
[hellhound.http :as http]
[hellhound.streams :as streams]
[hellhound.http.handlers :as handlers]
[hellhound.http.response :as response]
[hellhound.http.route :as router]))
;; TODO: Extract the spec check into a predicate function called map-with
(s/def ::aleph-config
(s/and map?
#(and (contains? % :host)
(string? (:host %)))
#(and (contains? % :port)
(int? (:port %)))))
(def CONFIG_ERR_MSG
"Aleph configuration is invalid. Probably forgot to add the configuration to your system.")
(defn start!
"Returns a start function for the webserver component.
The return function starts the webserver using the given `routes`
and `config` map.
NOTE: This function RETURNS a start function."
[config]
(fn [this context]
(let [new-context (assoc context
:input (hcomp/input this)
:output (hcomp/output this))
config (merge (:config new-context) config)]
(spec/validate ::aleph-config config CONFIG_ERR_MSG)
(assoc this
:instance (aleph/start-server (handlers/req-to-stream new-context)
config)
:config config))))
(defn stop!
"Stops the running webserver server."
[this]
(when-let [server (:instance this)]
(.close server))
(dissoc this :instance))
(defn factory
"Returns a new webserver component by the given `routes` and an
optional `config` map.
The `routes` argument should be a valid **HellHound** route collection,
compatible with Pedestal library. **Hellhound**
provides a helper namespace for dealing with routes. Checkout
[[hellhound.http]] and [[hellhound.http.route]] namespaces for more info."
([]
(factory {}))
([config]
{:hellhound.component/name ::webserver
:hellhound.component/start-fn (start! config)
:hellhound.component/stop-fn stop!
:hellhound.component/fn
(fn [component]
(streams/consume response/resolver
(hcomp/input component)))}))
|
[
{
"context": "rname=\" user)\n (str \"--password=\" password)\n \"update\"]))]\n (when-not (ze",
"end": 556,
"score": 0.9989917874336243,
"start": 548,
"tag": "PASSWORD",
"value": "password"
}
] | api/test/wfl/tools/liquibase.clj | broadinstitute/wfl | 15 | (ns wfl.tools.liquibase
(:require [wfl.service.postgres :as postgres])
(:import [liquibase.integration.commandline Main]
[clojure.lang ExceptionInfo]))
(defn run-liquibase
"Migrate the database schema using Liquibase."
[changelog {:keys [user password connection-uri]}]
(let [status (Main/run
(into-array
String
[(str "--url=" connection-uri)
(str "--changeLogFile=" changelog)
(str "--username=" user)
(str "--password=" password)
"update"]))]
(when-not (zero? status)
(throw (ex-info "Liquibase migration failed" {:status status})))))
(defn -main
"Migrate the local database schema using Liquibase."
[]
(try
(run-liquibase "../database/changelog.xml" (postgres/wfl-db-config))
(System/exit 0)
(catch ExceptionInfo e
(binding [*out* *err*]
(-> e .getMessage println)
(-> e .getData :status System/exit)))))
| 110587 | (ns wfl.tools.liquibase
(:require [wfl.service.postgres :as postgres])
(:import [liquibase.integration.commandline Main]
[clojure.lang ExceptionInfo]))
(defn run-liquibase
"Migrate the database schema using Liquibase."
[changelog {:keys [user password connection-uri]}]
(let [status (Main/run
(into-array
String
[(str "--url=" connection-uri)
(str "--changeLogFile=" changelog)
(str "--username=" user)
(str "--password=" <PASSWORD>)
"update"]))]
(when-not (zero? status)
(throw (ex-info "Liquibase migration failed" {:status status})))))
(defn -main
"Migrate the local database schema using Liquibase."
[]
(try
(run-liquibase "../database/changelog.xml" (postgres/wfl-db-config))
(System/exit 0)
(catch ExceptionInfo e
(binding [*out* *err*]
(-> e .getMessage println)
(-> e .getData :status System/exit)))))
| true | (ns wfl.tools.liquibase
(:require [wfl.service.postgres :as postgres])
(:import [liquibase.integration.commandline Main]
[clojure.lang ExceptionInfo]))
(defn run-liquibase
"Migrate the database schema using Liquibase."
[changelog {:keys [user password connection-uri]}]
(let [status (Main/run
(into-array
String
[(str "--url=" connection-uri)
(str "--changeLogFile=" changelog)
(str "--username=" user)
(str "--password=" PI:PASSWORD:<PASSWORD>END_PI)
"update"]))]
(when-not (zero? status)
(throw (ex-info "Liquibase migration failed" {:status status})))))
(defn -main
"Migrate the local database schema using Liquibase."
[]
(try
(run-liquibase "../database/changelog.xml" (postgres/wfl-db-config))
(System/exit 0)
(catch ExceptionInfo e
(binding [*out* *err*]
(-> e .getMessage println)
(-> e .getData :status System/exit)))))
|
[
{
"context": " (mock/json-body {:name \"Renan\" :job \"SW\"})))]\n (is (= (:status response) 2",
"end": 491,
"score": 0.9998421669006348,
"start": 486,
"tag": "NAME",
"value": "Renan"
},
{
"context": " (is (= (:body response) \"{\\\"id\\\":1,\\\"name\\\":\\\"Renan\\\",\\\"job\\\":\\\"SW\\\"}\"))))\n\n (testing \"not-found rou",
"end": 603,
"score": 0.9998377561569214,
"start": 598,
"tag": "NAME",
"value": "Renan"
}
] | simple-api/test/simple_api/employers_api_test.clj | renanmarcos/clj-examples | 0 | (ns simple-api.employers-api-test
(:require [clojure.test :refer :all]
[ring.mock.request :as mock]
[simple-api.handler :refer :all]))
(deftest app-test
(testing "GET Employers"
(let [response (app (mock/request :get "/employers"))]
(is (= (:status response) 200))
(is (= (:body response) "[]"))))
(testing "POST Employers"
(let [response (app (-> (mock/request :post "/employers")
(mock/json-body {:name "Renan" :job "SW"})))]
(is (= (:status response) 201))
(is (= (:body response) "{\"id\":1,\"name\":\"Renan\",\"job\":\"SW\"}"))))
(testing "not-found route"
(let [response (app (mock/request :get "/invalid"))]
(is (= (:status response) 404))
(is (= (:body response) "Not Found"))))) | 68948 | (ns simple-api.employers-api-test
(:require [clojure.test :refer :all]
[ring.mock.request :as mock]
[simple-api.handler :refer :all]))
(deftest app-test
(testing "GET Employers"
(let [response (app (mock/request :get "/employers"))]
(is (= (:status response) 200))
(is (= (:body response) "[]"))))
(testing "POST Employers"
(let [response (app (-> (mock/request :post "/employers")
(mock/json-body {:name "<NAME>" :job "SW"})))]
(is (= (:status response) 201))
(is (= (:body response) "{\"id\":1,\"name\":\"<NAME>\",\"job\":\"SW\"}"))))
(testing "not-found route"
(let [response (app (mock/request :get "/invalid"))]
(is (= (:status response) 404))
(is (= (:body response) "Not Found"))))) | true | (ns simple-api.employers-api-test
(:require [clojure.test :refer :all]
[ring.mock.request :as mock]
[simple-api.handler :refer :all]))
(deftest app-test
(testing "GET Employers"
(let [response (app (mock/request :get "/employers"))]
(is (= (:status response) 200))
(is (= (:body response) "[]"))))
(testing "POST Employers"
(let [response (app (-> (mock/request :post "/employers")
(mock/json-body {:name "PI:NAME:<NAME>END_PI" :job "SW"})))]
(is (= (:status response) 201))
(is (= (:body response) "{\"id\":1,\"name\":\"PI:NAME:<NAME>END_PI\",\"job\":\"SW\"}"))))
(testing "not-found route"
(let [response (app (mock/request :get "/invalid"))]
(is (= (:status response) 404))
(is (= (:body response) "Not Found"))))) |
[
{
"context": " is testing]]))\n\n(def matches \n [{:winner-name \"Kvitova P.\",\n :loser-name \"Ostapenko J.\",\n :tournament \"",
"end": 156,
"score": 0.9993794560432434,
"start": 147,
"tag": "NAME",
"value": "Kvitova P"
},
{
"context": " \n [{:winner-name \"Kvitova P.\",\n :loser-name \"Ostapenko J.\",\n :tournament \"US Open\",\n :location \"New Yor",
"end": 188,
"score": 0.9994912147521973,
"start": 177,
"tag": "NAME",
"value": "Ostapenko J"
},
{
"context": " York\",\n :date \"2016-08-29\"}\n {:winner-name \"Kvitova P.\",\n :loser-name \"Buyukakcay C.\",\n :tournament ",
"end": 296,
"score": 0.9991922378540039,
"start": 287,
"tag": "NAME",
"value": "Kvitova P"
},
{
"context": "}\n {:winner-name \"Kvitova P.\",\n :loser-name \"Buyukakcay C.\",\n :tournament \"US Open\",\n :location \"New Yor",
"end": 329,
"score": 0.999518871307373,
"start": 317,
"tag": "NAME",
"value": "Buyukakcay C"
},
{
"context": " York\",\n :date \"2016-08-31\"}\n {:winner-name \"Kvitova P.\",\n :loser-name \"Svitolina E.\",\n :tournament \"",
"end": 437,
"score": 0.9993041157722473,
"start": 428,
"tag": "NAME",
"value": "Kvitova P"
},
{
"context": "}\n {:winner-name \"Kvitova P.\",\n :loser-name \"Svitolina E.\",\n :tournament \"US Open\",\n :location \"New Yor",
"end": 469,
"score": 0.9995810389518738,
"start": 458,
"tag": "NAME",
"value": "Svitolina E"
},
{
"context": " York\",\n :date \"2016-09-02\"}\n {:winner-name \"Kerber A.\",\n :loser-name \"Kvitova P.\",\n :tournament \"US",
"end": 576,
"score": 0.999382495880127,
"start": 568,
"tag": "NAME",
"value": "Kerber A"
},
{
"context": "\"}\n {:winner-name \"Kerber A.\",\n :loser-name \"Kvitova P.\",\n :tournament \"US Open\",\n :location \"New Yor",
"end": 606,
"score": 0.9995626211166382,
"start": 597,
"tag": "NAME",
"value": "Kvitova P"
},
{
"context": " York\",\n :date \"2016-09-05\"}\n {:winner-name \"Kvitova P.\",\n :loser-name \"Brengle M.\",\n :tournament \"To",
"end": 714,
"score": 0.9991523623466492,
"start": 705,
"tag": "NAME",
"value": "Kvitova P"
},
{
"context": "}\n {:winner-name \"Kvitova P.\",\n :loser-name \"Brengle M.\",\n :tournament \"Toray Pan Pacific Open\",\n :lo",
"end": 744,
"score": 0.9996581077575684,
"start": 735,
"tag": "NAME",
"value": "Brengle M"
},
{
"context": "Tokyo\",\n :date \"2016-09-20\"}\n {:winner-name \"Puig M.\",\n :loser-name \"Kvitova P.\",\n :tournament \"To",
"end": 861,
"score": 0.9989036321640015,
"start": 855,
"tag": "NAME",
"value": "Puig M"
},
{
"context": "20\"}\n {:winner-name \"Puig M.\",\n :loser-name \"Kvitova P.\",\n :tournament \"Toray Pan Pacific Open\",\n :lo",
"end": 891,
"score": 0.9994819760322571,
"start": 882,
"tag": "NAME",
"value": "Kvitova P"
},
{
"context": "date matches) matches)]\n (is (= {:winner-name \"Kvitova P.\",\n :loser-name \"Buyukakcay C.\",\n ",
"end": 1101,
"score": 0.9993045926094055,
"start": 1092,
"tag": "NAME",
"value": "Kvitova P"
},
{
"context": "inner-name \"Kvitova P.\",\n :loser-name \"Buyukakcay C.\",\n :tournament \"US Open\",\n :l",
"end": 1142,
"score": 0.9995756149291992,
"start": 1130,
"tag": "NAME",
"value": "Buyukakcay C"
},
{
"context": " lookup \"2016-08-31\")))\n (is (= {:winner-name \"Kvitova P.\",\n :loser-name \"Brengle M.\",\n ",
"end": 1321,
"score": 0.9991730451583862,
"start": 1312,
"tag": "NAME",
"value": "Kvitova P"
},
{
"context": "inner-name \"Kvitova P.\",\n :loser-name \"Brengle M.\",\n :tournament \"Toray Pan Pacific Open\",",
"end": 1359,
"score": 0.9996706247329712,
"start": 1350,
"tag": "NAME",
"value": "Brengle M"
}
] | Chapter05/tests/packt-clj.chapter-5-tests/test/packt_clj/chapter_5_tests/exercise_5_04_test.clj | transducer/The-Clojure-Workshop | 55 | (ns packt-clj.chapter-5-tests.exercise-5-04-test
(:require [clojure.test :as t :refer [deftest is testing]]))
(def matches
[{:winner-name "Kvitova P.",
:loser-name "Ostapenko J.",
:tournament "US Open",
:location "New York",
:date "2016-08-29"}
{:winner-name "Kvitova P.",
:loser-name "Buyukakcay C.",
:tournament "US Open",
:location "New York",
:date "2016-08-31"}
{:winner-name "Kvitova P.",
:loser-name "Svitolina E.",
:tournament "US Open",
:location "New York",
:date "2016-09-02"}
{:winner-name "Kerber A.",
:loser-name "Kvitova P.",
:tournament "US Open",
:location "New York",
:date "2016-09-05"}
{:winner-name "Kvitova P.",
:loser-name "Brengle M.",
:tournament "Toray Pan Pacific Open",
:location "Tokyo",
:date "2016-09-20"}
{:winner-name "Puig M.",
:loser-name "Kvitova P.",
:tournament "Toray Pan Pacific Open",
:location "Tokyo",
:date "2016-09-21"}])
(deftest matches-by-date
(let [lookup (zipmap (map :date matches) matches)]
(is (= {:winner-name "Kvitova P.",
:loser-name "Buyukakcay C.",
:tournament "US Open",
:location "New York",
:date "2016-08-31"}
(get lookup "2016-08-31")))
(is (= {:winner-name "Kvitova P.",
:loser-name "Brengle M.",
:tournament "Toray Pan Pacific Open",
:location "Tokyo",
:date "2016-09-20"}
(get lookup "2016-09-20")))))
| 44352 | (ns packt-clj.chapter-5-tests.exercise-5-04-test
(:require [clojure.test :as t :refer [deftest is testing]]))
(def matches
[{:winner-name "<NAME>.",
:loser-name "<NAME>.",
:tournament "US Open",
:location "New York",
:date "2016-08-29"}
{:winner-name "<NAME>.",
:loser-name "<NAME>.",
:tournament "US Open",
:location "New York",
:date "2016-08-31"}
{:winner-name "<NAME>.",
:loser-name "<NAME>.",
:tournament "US Open",
:location "New York",
:date "2016-09-02"}
{:winner-name "<NAME>.",
:loser-name "<NAME>.",
:tournament "US Open",
:location "New York",
:date "2016-09-05"}
{:winner-name "<NAME>.",
:loser-name "<NAME>.",
:tournament "Toray Pan Pacific Open",
:location "Tokyo",
:date "2016-09-20"}
{:winner-name "<NAME>.",
:loser-name "<NAME>.",
:tournament "Toray Pan Pacific Open",
:location "Tokyo",
:date "2016-09-21"}])
(deftest matches-by-date
(let [lookup (zipmap (map :date matches) matches)]
(is (= {:winner-name "<NAME>.",
:loser-name "<NAME>.",
:tournament "US Open",
:location "New York",
:date "2016-08-31"}
(get lookup "2016-08-31")))
(is (= {:winner-name "<NAME>.",
:loser-name "<NAME>.",
:tournament "Toray Pan Pacific Open",
:location "Tokyo",
:date "2016-09-20"}
(get lookup "2016-09-20")))))
| true | (ns packt-clj.chapter-5-tests.exercise-5-04-test
(:require [clojure.test :as t :refer [deftest is testing]]))
(def matches
[{:winner-name "PI:NAME:<NAME>END_PI.",
:loser-name "PI:NAME:<NAME>END_PI.",
:tournament "US Open",
:location "New York",
:date "2016-08-29"}
{:winner-name "PI:NAME:<NAME>END_PI.",
:loser-name "PI:NAME:<NAME>END_PI.",
:tournament "US Open",
:location "New York",
:date "2016-08-31"}
{:winner-name "PI:NAME:<NAME>END_PI.",
:loser-name "PI:NAME:<NAME>END_PI.",
:tournament "US Open",
:location "New York",
:date "2016-09-02"}
{:winner-name "PI:NAME:<NAME>END_PI.",
:loser-name "PI:NAME:<NAME>END_PI.",
:tournament "US Open",
:location "New York",
:date "2016-09-05"}
{:winner-name "PI:NAME:<NAME>END_PI.",
:loser-name "PI:NAME:<NAME>END_PI.",
:tournament "Toray Pan Pacific Open",
:location "Tokyo",
:date "2016-09-20"}
{:winner-name "PI:NAME:<NAME>END_PI.",
:loser-name "PI:NAME:<NAME>END_PI.",
:tournament "Toray Pan Pacific Open",
:location "Tokyo",
:date "2016-09-21"}])
(deftest matches-by-date
(let [lookup (zipmap (map :date matches) matches)]
(is (= {:winner-name "PI:NAME:<NAME>END_PI.",
:loser-name "PI:NAME:<NAME>END_PI.",
:tournament "US Open",
:location "New York",
:date "2016-08-31"}
(get lookup "2016-08-31")))
(is (= {:winner-name "PI:NAME:<NAME>END_PI.",
:loser-name "PI:NAME:<NAME>END_PI.",
:tournament "Toray Pan Pacific Open",
:location "Tokyo",
:date "2016-09-20"}
(get lookup "2016-09-20")))))
|
[
{
"context": "r :refer :all]))\n\n(def mock-data\n [{:id 1 :name \"Foo\"}\n {:id 2 :name \"Bar\"}])\n\n(deftest render-test\n",
"end": 144,
"score": 0.9968588352203369,
"start": 141,
"tag": "NAME",
"value": "Foo"
},
{
"context": "mock-data\n [{:id 1 :name \"Foo\"}\n {:id 2 :name \"Bar\"}])\n\n(deftest render-test\n (testing \"transformin",
"end": 167,
"score": 0.9980625510215759,
"start": 164,
"tag": "NAME",
"value": "Bar"
}
] | test/clj/meetup/renderer_test.clj | jocrau/clojure-meetup | 7 | (ns meetup.renderer-test
(:require [clojure.test :refer :all]
[meetup.renderer :refer :all]))
(def mock-data
[{:id 1 :name "Foo"}
{:id 2 :name "Bar"}])
(deftest render-test
(testing "transforming items into a HTML list"
(let [result (render-list mock-data)]
(clojure.pprint/pprint result)
(is (re-find #"<li>Foo</li>" result))
(is (re-find #"<li>Bar</li>" result)))))
| 57961 | (ns meetup.renderer-test
(:require [clojure.test :refer :all]
[meetup.renderer :refer :all]))
(def mock-data
[{:id 1 :name "<NAME>"}
{:id 2 :name "<NAME>"}])
(deftest render-test
(testing "transforming items into a HTML list"
(let [result (render-list mock-data)]
(clojure.pprint/pprint result)
(is (re-find #"<li>Foo</li>" result))
(is (re-find #"<li>Bar</li>" result)))))
| true | (ns meetup.renderer-test
(:require [clojure.test :refer :all]
[meetup.renderer :refer :all]))
(def mock-data
[{:id 1 :name "PI:NAME:<NAME>END_PI"}
{:id 2 :name "PI:NAME:<NAME>END_PI"}])
(deftest render-test
(testing "transforming items into a HTML list"
(let [result (render-list mock-data)]
(clojure.pprint/pprint result)
(is (re-find #"<li>Foo</li>" result))
(is (re-find #"<li>Bar</li>" result)))))
|
[
{
"context": "ame (str\n (rand-nth [\"Oscar\" \"Karen\" \"Vlad\" \"Rebecca\" \"Conrad\"]) \" \"\n ",
"end": 956,
"score": 0.9998378157615662,
"start": 951,
"tag": "NAME",
"value": "Oscar"
},
{
"context": "\n (rand-nth [\"Oscar\" \"Karen\" \"Vlad\" \"Rebecca\" \"Conrad\"]) \" \"\n ",
"end": 964,
"score": 0.9997663497924805,
"start": 959,
"tag": "NAME",
"value": "Karen"
},
{
"context": " (rand-nth [\"Oscar\" \"Karen\" \"Vlad\" \"Rebecca\" \"Conrad\"]) \" \"\n ",
"end": 971,
"score": 0.9998142719268799,
"start": 967,
"tag": "NAME",
"value": "Vlad"
},
{
"context": " (rand-nth [\"Oscar\" \"Karen\" \"Vlad\" \"Rebecca\" \"Conrad\"]) \" \"\n (ran",
"end": 981,
"score": 0.9997947812080383,
"start": 974,
"tag": "NAME",
"value": "Rebecca"
},
{
"context": " (rand-nth [\"Oscar\" \"Karen\" \"Vlad\" \"Rebecca\" \"Conrad\"]) \" \"\n (rand-nth [\"M",
"end": 990,
"score": 0.999833345413208,
"start": 984,
"tag": "NAME",
"value": "Conrad"
},
{
"context": "d\"]) \" \"\n (rand-nth [\"Miller\" \"Stasčnyk\" \"Ronin\" \"Meyer\" \"Black\"]))\n ",
"end": 1045,
"score": 0.999748706817627,
"start": 1039,
"tag": "NAME",
"value": "Miller"
},
{
"context": " (rand-nth [\"Miller\" \"Stasčnyk\" \"Ronin\" \"Meyer\" \"Black\"]))\n ",
"end": 1056,
"score": 0.9997934103012085,
"start": 1048,
"tag": "NAME",
"value": "Stasčnyk"
},
{
"context": " (rand-nth [\"Miller\" \"Stasčnyk\" \"Ronin\" \"Meyer\" \"Black\"]))\n :role (r",
"end": 1064,
"score": 0.9998164772987366,
"start": 1059,
"tag": "NAME",
"value": "Ronin"
},
{
"context": " (rand-nth [\"Miller\" \"Stasčnyk\" \"Ronin\" \"Meyer\" \"Black\"]))\n :role (rand-nth ",
"end": 1072,
"score": 0.9998019337654114,
"start": 1067,
"tag": "NAME",
"value": "Meyer"
},
{
"context": " (rand-nth [\"Miller\" \"Stasčnyk\" \"Ronin\" \"Meyer\" \"Black\"]))\n :role (rand-nth [:admin ",
"end": 1080,
"score": 0.9998185038566589,
"start": 1075,
"tag": "NAME",
"value": "Black"
}
] | notebooks/pagination.clj | fuse-code/clerk | 1 | ;; # Pagination
(ns notebooks.pagination
(:require [babashka.fs :as fs]))
#_(nextjournal.clerk/show! "notebooks/pagination.clj")
(range)
(def notebooks
(clojure.java.io/file "notebooks"))
(def words-path "/usr/share/dict/words")
(when-let [words (and (fs/exists? words-path) (slurp words-path))]
(subs words 0 10100))
[notebooks]
(into #{} (map str) (file-seq notebooks))
(def r (range 100))
(map inc r)
[(mapv inc r)]
^:nextjournal.clerk/no-cache (shuffle r)
;; A long list.
(range 1000)
;; A somewhat large map.
(zipmap (range 1000) (map #(* % %) (range 1000)))
^:nextjournal.clerk/no-cache (shuffle (range 42))
(let [[first-three others] (split-at 3 [:A :A :B :B :C :C :D :D])]
{:first-three first-three
:others others})
(frequencies [:A :A :B :B :C :C :D :D])
(group-by first [[:A :B :B] [:B :C :C] [:C :A :A]])
(take 5
(repeatedly (fn []
{:name (str
(rand-nth ["Oscar" "Karen" "Vlad" "Rebecca" "Conrad"]) " "
(rand-nth ["Miller" "Stasčnyk" "Ronin" "Meyer" "Black"]))
:role (rand-nth [:admin :operator :manager :programmer :designer])
:id (java.util.UUID/randomUUID)
:created-at #inst "2021"})))
(defn flat->nested
[root coll]
(if-let [children (seq (filter #(= (:id root) (:parent %)) coll))]
(map #(assoc root :children (flat->nested % coll)) children)
(list root)))
(let [items (concat [{:id 0 :parent nil :name "item-0"}]
(for [x (range 1 5)]
{:id x :parent (dec x) :name (format "item-%d" x)}))]
(flat->nested (-> (filter #(= (:parent %) nil) items) first) items))
| 52897 | ;; # Pagination
(ns notebooks.pagination
(:require [babashka.fs :as fs]))
#_(nextjournal.clerk/show! "notebooks/pagination.clj")
(range)
(def notebooks
(clojure.java.io/file "notebooks"))
(def words-path "/usr/share/dict/words")
(when-let [words (and (fs/exists? words-path) (slurp words-path))]
(subs words 0 10100))
[notebooks]
(into #{} (map str) (file-seq notebooks))
(def r (range 100))
(map inc r)
[(mapv inc r)]
^:nextjournal.clerk/no-cache (shuffle r)
;; A long list.
(range 1000)
;; A somewhat large map.
(zipmap (range 1000) (map #(* % %) (range 1000)))
^:nextjournal.clerk/no-cache (shuffle (range 42))
(let [[first-three others] (split-at 3 [:A :A :B :B :C :C :D :D])]
{:first-three first-three
:others others})
(frequencies [:A :A :B :B :C :C :D :D])
(group-by first [[:A :B :B] [:B :C :C] [:C :A :A]])
(take 5
(repeatedly (fn []
{:name (str
(rand-nth ["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"]) " "
(rand-nth ["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"]))
:role (rand-nth [:admin :operator :manager :programmer :designer])
:id (java.util.UUID/randomUUID)
:created-at #inst "2021"})))
(defn flat->nested
[root coll]
(if-let [children (seq (filter #(= (:id root) (:parent %)) coll))]
(map #(assoc root :children (flat->nested % coll)) children)
(list root)))
(let [items (concat [{:id 0 :parent nil :name "item-0"}]
(for [x (range 1 5)]
{:id x :parent (dec x) :name (format "item-%d" x)}))]
(flat->nested (-> (filter #(= (:parent %) nil) items) first) items))
| true | ;; # Pagination
(ns notebooks.pagination
(:require [babashka.fs :as fs]))
#_(nextjournal.clerk/show! "notebooks/pagination.clj")
(range)
(def notebooks
(clojure.java.io/file "notebooks"))
(def words-path "/usr/share/dict/words")
(when-let [words (and (fs/exists? words-path) (slurp words-path))]
(subs words 0 10100))
[notebooks]
(into #{} (map str) (file-seq notebooks))
(def r (range 100))
(map inc r)
[(mapv inc r)]
^:nextjournal.clerk/no-cache (shuffle r)
;; A long list.
(range 1000)
;; A somewhat large map.
(zipmap (range 1000) (map #(* % %) (range 1000)))
^:nextjournal.clerk/no-cache (shuffle (range 42))
(let [[first-three others] (split-at 3 [:A :A :B :B :C :C :D :D])]
{:first-three first-three
:others others})
(frequencies [:A :A :B :B :C :C :D :D])
(group-by first [[:A :B :B] [:B :C :C] [:C :A :A]])
(take 5
(repeatedly (fn []
{:name (str
(rand-nth ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) " "
(rand-nth ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]))
:role (rand-nth [:admin :operator :manager :programmer :designer])
:id (java.util.UUID/randomUUID)
:created-at #inst "2021"})))
(defn flat->nested
[root coll]
(if-let [children (seq (filter #(= (:id root) (:parent %)) coll))]
(map #(assoc root :children (flat->nested % coll)) children)
(list root)))
(let [items (concat [{:id 0 :parent nil :name "item-0"}]
(for [x (range 1 5)]
{:id x :parent (dec x) :name (format "item-%d" x)}))]
(flat->nested (-> (filter #(= (:parent %) nil) items) first) items))
|
[
{
"context": " form-validation []\n (let [state (atom {:email \"a@b.c\"\n :phone \"+7913 000 0000\"\n",
"end": 1664,
"score": 0.5422419309616089,
"start": 1664,
"tag": "EMAIL",
"value": ""
}
] | pages/prais2/examples/form_validation.cljs | WintonCentre/prais2cljs | 1 | (ns prais2.examples.form-validation
(:require
[rum.core :as rum]
[prais2.examples.core :as core]))
(rum/defc validating-input < rum/reactive [ref fn]
[:input {:type "text"
:style {:width 170
:background-color (when-not (fn (rum/react ref))
(rum/react core/*color))}
:value (rum/react ref)
:on-change #(reset! ref (.. % -target -value))}])
(rum/defcc restricting-input < rum/reactive [comp ref fn]
[:input {:type "text"
:style {:width 170}
:value (rum/react ref)
:on-change #(let [new-val (.. % -target -value)]
(if (fn new-val)
(reset! ref new-val)
;; request-render is mandatory because sablono :input
;; keeps current value in input’s state and always applies changes to it
(rum/request-render comp)))}])
(rum/defcs restricting-input-native < rum/reactive [state ref fn]
(let [comp (:rum/react-component state)]
(js/React.DOM.input
#js {:type "text"
:style #js {:width 170}
:value (rum/react ref)
:onChange #(let [new-val (.. % -target -value)]
(when (fn new-val)
(reset! ref new-val))
;; need forceUpdate here because otherwise rendering will be delayed until requestAnimationFrame
;; and that breaks cursor position inside input
(.forceUpdate comp))})))
(rum/defc form-validation []
(let [state (atom {:email "a@b.c"
:phone "+7913 000 0000"
:age "22"})]
[:dl
[:dt "E-mail:"]
[:dd (validating-input (rum/cursor state [:email]) #(re-matches #"[^@]+@[^@.]+\..+" %))]
[:dt "Phone:"]
[:dd (restricting-input (rum/cursor state [:phone]) #(re-matches #"[0-9\- +()]*" %))]
[:dt "Age:"]
[:dd (restricting-input-native (rum/cursor state [:age]) #(re-matches #"([1-9][0-9]*)?" %))]]))
(defn mount! [mount-el]
(rum/mount (form-validation) mount-el))
| 91529 | (ns prais2.examples.form-validation
(:require
[rum.core :as rum]
[prais2.examples.core :as core]))
(rum/defc validating-input < rum/reactive [ref fn]
[:input {:type "text"
:style {:width 170
:background-color (when-not (fn (rum/react ref))
(rum/react core/*color))}
:value (rum/react ref)
:on-change #(reset! ref (.. % -target -value))}])
(rum/defcc restricting-input < rum/reactive [comp ref fn]
[:input {:type "text"
:style {:width 170}
:value (rum/react ref)
:on-change #(let [new-val (.. % -target -value)]
(if (fn new-val)
(reset! ref new-val)
;; request-render is mandatory because sablono :input
;; keeps current value in input’s state and always applies changes to it
(rum/request-render comp)))}])
(rum/defcs restricting-input-native < rum/reactive [state ref fn]
(let [comp (:rum/react-component state)]
(js/React.DOM.input
#js {:type "text"
:style #js {:width 170}
:value (rum/react ref)
:onChange #(let [new-val (.. % -target -value)]
(when (fn new-val)
(reset! ref new-val))
;; need forceUpdate here because otherwise rendering will be delayed until requestAnimationFrame
;; and that breaks cursor position inside input
(.forceUpdate comp))})))
(rum/defc form-validation []
(let [state (atom {:email "a<EMAIL>@b.c"
:phone "+7913 000 0000"
:age "22"})]
[:dl
[:dt "E-mail:"]
[:dd (validating-input (rum/cursor state [:email]) #(re-matches #"[^@]+@[^@.]+\..+" %))]
[:dt "Phone:"]
[:dd (restricting-input (rum/cursor state [:phone]) #(re-matches #"[0-9\- +()]*" %))]
[:dt "Age:"]
[:dd (restricting-input-native (rum/cursor state [:age]) #(re-matches #"([1-9][0-9]*)?" %))]]))
(defn mount! [mount-el]
(rum/mount (form-validation) mount-el))
| true | (ns prais2.examples.form-validation
(:require
[rum.core :as rum]
[prais2.examples.core :as core]))
(rum/defc validating-input < rum/reactive [ref fn]
[:input {:type "text"
:style {:width 170
:background-color (when-not (fn (rum/react ref))
(rum/react core/*color))}
:value (rum/react ref)
:on-change #(reset! ref (.. % -target -value))}])
(rum/defcc restricting-input < rum/reactive [comp ref fn]
[:input {:type "text"
:style {:width 170}
:value (rum/react ref)
:on-change #(let [new-val (.. % -target -value)]
(if (fn new-val)
(reset! ref new-val)
;; request-render is mandatory because sablono :input
;; keeps current value in input’s state and always applies changes to it
(rum/request-render comp)))}])
(rum/defcs restricting-input-native < rum/reactive [state ref fn]
(let [comp (:rum/react-component state)]
(js/React.DOM.input
#js {:type "text"
:style #js {:width 170}
:value (rum/react ref)
:onChange #(let [new-val (.. % -target -value)]
(when (fn new-val)
(reset! ref new-val))
;; need forceUpdate here because otherwise rendering will be delayed until requestAnimationFrame
;; and that breaks cursor position inside input
(.forceUpdate comp))})))
(rum/defc form-validation []
(let [state (atom {:email "aPI:EMAIL:<EMAIL>END_PI@b.c"
:phone "+7913 000 0000"
:age "22"})]
[:dl
[:dt "E-mail:"]
[:dd (validating-input (rum/cursor state [:email]) #(re-matches #"[^@]+@[^@.]+\..+" %))]
[:dt "Phone:"]
[:dd (restricting-input (rum/cursor state [:phone]) #(re-matches #"[0-9\- +()]*" %))]
[:dt "Age:"]
[:dd (restricting-input-native (rum/cursor state [:age]) #(re-matches #"([1-9][0-9]*)?" %))]]))
(defn mount! [mount-el]
(rum/mount (form-validation) mount-el))
|
[
{
"context": "; MIT License\n;\n; Copyright (c) 2017 Frederic Merizen & Kenny Williams\n;\n; Permission is hereby granted",
"end": 53,
"score": 0.9998394846916199,
"start": 37,
"tag": "NAME",
"value": "Frederic Merizen"
},
{
"context": " License\n;\n; Copyright (c) 2017 Frederic Merizen & Kenny Williams\n;\n; Permission is hereby granted, free of charge,",
"end": 70,
"score": 0.9997520446777344,
"start": 56,
"tag": "NAME",
"value": "Kenny Williams"
}
] | src/plumula/mimolette/impl.cljc | plumula/mimolette | 3 | ; MIT License
;
; Copyright (c) 2017 Frederic Merizen & Kenny Williams
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in all
; copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
; SOFTWARE.
(ns plumula.mimolette.impl
(:require [clojure.string :as string]
[#?(:clj clojure.test :cljs cljs.test) :as test]
#?(:cljs [cljs.analyzer]))
#?(:cljs (:require-macros plumula.mimolette.impl)))
(defprotocol SpecShim
"The functions from spec that we rely on, divorced from their namespace."
(abbrev-result [this x] "spec.test/abbrev-result")
(explain-out [this ed] "spec/explain-out")
(failure-val [this failure] "::spec.test/val"))
(defn success-report
"Returns a sequence of one message, which is suitable for consumption by
`test/do-report`, and that reports that the tests corresponding to `results`
succeeded. Should only be called if all tests did succeed.
The `results` argument should be the result of `spec.test/check`.
"
[results]
[{:type :pass
:message (str "Generative tests pass for "
(string/join ", " (map :sym results)))}])
(defn failure-report
"Returns a sequence of messages, each message suitable for consumption by
`test/do-report`. The messages describe the test failures in `results`.
Arguments:
- `spec-shim` should implement the `SpecShim` protocol
- `results` should be the result of `spec.test/check`
"
[spec-shim results]
(for [failed-check (filter :failure results)
:let [r (abbrev-result spec-shim failed-check)
failure (:failure r)]]
{:type :fail
:message (with-out-str (explain-out spec-shim failure))
:expected (->> r :spec rest (apply hash-map) :ret)
:actual (if (instance? #?(:clj Throwable :cljs js/Error) failure)
failure
(failure-val spec-shim failure))}))
(defn success?
"Takes the result of `spec.test/check`, and returns a boolean:
- true if all checks succeded
- false otherwise
"
[results]
(every? nil? (map :failure results)))
(defn print-report!
"Prints a test-report for `results`, formatting them with
- `report-success` if `success?` is true
- `report-failure` otherwise
Returns `success?`
"
[report-success report-failure results success?]
(doseq [:let [reporter (if success? report-success report-failure)
reports (reporter results)]
report reports]
(test/do-report report))
success?)
(defn report-results!
"Given a list of `results` from `spec.test/check`
- returns true if all checks succeeded, and false otherwise
- report the results to clojure.test, using `report-success` or
`report-failure` to format the results depending on whether all tests
succeeded or some failed
Arguments:
- `report-success` and `report-failure` should be functions that take the
result of `spec.test/check` and return a list of maps in the format expected
by `clojure.test/do-report`
- `results` should be the result of `spec.test/check`
"
[report-success report-failure results]
(->> results
success?
(print-report! report-success report-failure results)))
(defn cljs-env?
"Take the &env from a macro, and tell whether we are expanding into cljs."
[env]
(boolean (:ns env)))
(defmacro if-cljs
"Return then if we are generating cljs code and else for Clojure code.
https://groups.google.com/d/msg/clojurescript/iBY5HaQda4A/w1lAQi9_AwsJ"
[then else]
(if (cljs-env? &env) then else))
(defn normalise-opts
"Returns the map `opts`, with the :opts key (if present) replaced with the
host language specific `option-keyword`.
"
[opts canonical-keyword]
(let [stc (:opts opts)]
(cond-> (dissoc opts :opts)
stc (assoc canonical-keyword stc))))
(defmacro spec-test
"Check the function(s) named `sym-or-syms` against their specs.
Arguments:
- `check` a symbol with the `spec.test/check` macro’s fully qualified name
- `spec-shim` should implement the `SpecShim` protocol
- `sym-or-syms` a fully qualified symbol, or a list of fully qualified symbols.
The name(s) of the functions to check.
- `opts` a map of options for `clojure.spec.test/check`.
- The `:gen` key is handled by `cljs.spec.test/check` (see its documentation).
- The contents of the `:opts` key is passed on to
`clojure.test.check/quick-check` (see its documentation).
- Special case: inside the `:opts` key, the `:num-tests` key, which is not
handled by `quick-check`, is the number of checks that will be run for
each function (defaults to 1000).
"
[check spec-shim sym-or-syms opts]
`(let [opts# (->> (if-cljs :clojure.test.check/opts :clojure.spec.test.check/opts)
(normalise-opts ~opts))]
(->> (~check ~sym-or-syms opts#)
(report-results! success-report (partial failure-report ~spec-shim)))))
(defmacro deftest
"Define a new test, whether we’re running on Clojure or ClojureScript."
[name & body]
`(if-cljs
(cljs.test/deftest ~name ~@body)
(clojure.test/deftest ~name ~@body)))
(defmacro defspec-test
"Create a test named `name`, that checks the function(s) named `sym-or-syms`
against their specs.
Arguments:
- `check` a symbol with the `spec.test/check` macro’s fully qualified name
- `spec-shim` should implement the `SpecShim` protocol
- `name` a symbol.
- `sym-or-syms` a fully qualified symbol, or a list of fully qualified symbols.
The name(s) of the functions to check.
- `opts` a map of options for `clojure.spec.test/check`.
- The `:gen` key is handled by `cljs.spec.test/check` (see its documentation).
- The contents of the `:opts` key is passed on to
`clojure.test.check/quick-check` (see its documentation).
- Special case: inside the `:opts` key, the `:num-tests` key, which is not
handled by `quick-check`, is the number of checks that will be run for
each function (defaults to 1000).
"
[check spec-shim name sym-or-syms opts]
`(deftest ~name
(spec-test ~check ~spec-shim ~sym-or-syms ~opts)))
| 31158 | ; MIT License
;
; Copyright (c) 2017 <NAME> & <NAME>
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in all
; copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
; SOFTWARE.
(ns plumula.mimolette.impl
(:require [clojure.string :as string]
[#?(:clj clojure.test :cljs cljs.test) :as test]
#?(:cljs [cljs.analyzer]))
#?(:cljs (:require-macros plumula.mimolette.impl)))
(defprotocol SpecShim
"The functions from spec that we rely on, divorced from their namespace."
(abbrev-result [this x] "spec.test/abbrev-result")
(explain-out [this ed] "spec/explain-out")
(failure-val [this failure] "::spec.test/val"))
(defn success-report
"Returns a sequence of one message, which is suitable for consumption by
`test/do-report`, and that reports that the tests corresponding to `results`
succeeded. Should only be called if all tests did succeed.
The `results` argument should be the result of `spec.test/check`.
"
[results]
[{:type :pass
:message (str "Generative tests pass for "
(string/join ", " (map :sym results)))}])
(defn failure-report
"Returns a sequence of messages, each message suitable for consumption by
`test/do-report`. The messages describe the test failures in `results`.
Arguments:
- `spec-shim` should implement the `SpecShim` protocol
- `results` should be the result of `spec.test/check`
"
[spec-shim results]
(for [failed-check (filter :failure results)
:let [r (abbrev-result spec-shim failed-check)
failure (:failure r)]]
{:type :fail
:message (with-out-str (explain-out spec-shim failure))
:expected (->> r :spec rest (apply hash-map) :ret)
:actual (if (instance? #?(:clj Throwable :cljs js/Error) failure)
failure
(failure-val spec-shim failure))}))
(defn success?
"Takes the result of `spec.test/check`, and returns a boolean:
- true if all checks succeded
- false otherwise
"
[results]
(every? nil? (map :failure results)))
(defn print-report!
"Prints a test-report for `results`, formatting them with
- `report-success` if `success?` is true
- `report-failure` otherwise
Returns `success?`
"
[report-success report-failure results success?]
(doseq [:let [reporter (if success? report-success report-failure)
reports (reporter results)]
report reports]
(test/do-report report))
success?)
(defn report-results!
"Given a list of `results` from `spec.test/check`
- returns true if all checks succeeded, and false otherwise
- report the results to clojure.test, using `report-success` or
`report-failure` to format the results depending on whether all tests
succeeded or some failed
Arguments:
- `report-success` and `report-failure` should be functions that take the
result of `spec.test/check` and return a list of maps in the format expected
by `clojure.test/do-report`
- `results` should be the result of `spec.test/check`
"
[report-success report-failure results]
(->> results
success?
(print-report! report-success report-failure results)))
(defn cljs-env?
"Take the &env from a macro, and tell whether we are expanding into cljs."
[env]
(boolean (:ns env)))
(defmacro if-cljs
"Return then if we are generating cljs code and else for Clojure code.
https://groups.google.com/d/msg/clojurescript/iBY5HaQda4A/w1lAQi9_AwsJ"
[then else]
(if (cljs-env? &env) then else))
(defn normalise-opts
"Returns the map `opts`, with the :opts key (if present) replaced with the
host language specific `option-keyword`.
"
[opts canonical-keyword]
(let [stc (:opts opts)]
(cond-> (dissoc opts :opts)
stc (assoc canonical-keyword stc))))
(defmacro spec-test
"Check the function(s) named `sym-or-syms` against their specs.
Arguments:
- `check` a symbol with the `spec.test/check` macro’s fully qualified name
- `spec-shim` should implement the `SpecShim` protocol
- `sym-or-syms` a fully qualified symbol, or a list of fully qualified symbols.
The name(s) of the functions to check.
- `opts` a map of options for `clojure.spec.test/check`.
- The `:gen` key is handled by `cljs.spec.test/check` (see its documentation).
- The contents of the `:opts` key is passed on to
`clojure.test.check/quick-check` (see its documentation).
- Special case: inside the `:opts` key, the `:num-tests` key, which is not
handled by `quick-check`, is the number of checks that will be run for
each function (defaults to 1000).
"
[check spec-shim sym-or-syms opts]
`(let [opts# (->> (if-cljs :clojure.test.check/opts :clojure.spec.test.check/opts)
(normalise-opts ~opts))]
(->> (~check ~sym-or-syms opts#)
(report-results! success-report (partial failure-report ~spec-shim)))))
(defmacro deftest
"Define a new test, whether we’re running on Clojure or ClojureScript."
[name & body]
`(if-cljs
(cljs.test/deftest ~name ~@body)
(clojure.test/deftest ~name ~@body)))
(defmacro defspec-test
"Create a test named `name`, that checks the function(s) named `sym-or-syms`
against their specs.
Arguments:
- `check` a symbol with the `spec.test/check` macro’s fully qualified name
- `spec-shim` should implement the `SpecShim` protocol
- `name` a symbol.
- `sym-or-syms` a fully qualified symbol, or a list of fully qualified symbols.
The name(s) of the functions to check.
- `opts` a map of options for `clojure.spec.test/check`.
- The `:gen` key is handled by `cljs.spec.test/check` (see its documentation).
- The contents of the `:opts` key is passed on to
`clojure.test.check/quick-check` (see its documentation).
- Special case: inside the `:opts` key, the `:num-tests` key, which is not
handled by `quick-check`, is the number of checks that will be run for
each function (defaults to 1000).
"
[check spec-shim name sym-or-syms opts]
`(deftest ~name
(spec-test ~check ~spec-shim ~sym-or-syms ~opts)))
| true | ; MIT License
;
; Copyright (c) 2017 PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in all
; copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
; SOFTWARE.
(ns plumula.mimolette.impl
(:require [clojure.string :as string]
[#?(:clj clojure.test :cljs cljs.test) :as test]
#?(:cljs [cljs.analyzer]))
#?(:cljs (:require-macros plumula.mimolette.impl)))
(defprotocol SpecShim
"The functions from spec that we rely on, divorced from their namespace."
(abbrev-result [this x] "spec.test/abbrev-result")
(explain-out [this ed] "spec/explain-out")
(failure-val [this failure] "::spec.test/val"))
(defn success-report
"Returns a sequence of one message, which is suitable for consumption by
`test/do-report`, and that reports that the tests corresponding to `results`
succeeded. Should only be called if all tests did succeed.
The `results` argument should be the result of `spec.test/check`.
"
[results]
[{:type :pass
:message (str "Generative tests pass for "
(string/join ", " (map :sym results)))}])
(defn failure-report
"Returns a sequence of messages, each message suitable for consumption by
`test/do-report`. The messages describe the test failures in `results`.
Arguments:
- `spec-shim` should implement the `SpecShim` protocol
- `results` should be the result of `spec.test/check`
"
[spec-shim results]
(for [failed-check (filter :failure results)
:let [r (abbrev-result spec-shim failed-check)
failure (:failure r)]]
{:type :fail
:message (with-out-str (explain-out spec-shim failure))
:expected (->> r :spec rest (apply hash-map) :ret)
:actual (if (instance? #?(:clj Throwable :cljs js/Error) failure)
failure
(failure-val spec-shim failure))}))
(defn success?
"Takes the result of `spec.test/check`, and returns a boolean:
- true if all checks succeded
- false otherwise
"
[results]
(every? nil? (map :failure results)))
(defn print-report!
"Prints a test-report for `results`, formatting them with
- `report-success` if `success?` is true
- `report-failure` otherwise
Returns `success?`
"
[report-success report-failure results success?]
(doseq [:let [reporter (if success? report-success report-failure)
reports (reporter results)]
report reports]
(test/do-report report))
success?)
(defn report-results!
"Given a list of `results` from `spec.test/check`
- returns true if all checks succeeded, and false otherwise
- report the results to clojure.test, using `report-success` or
`report-failure` to format the results depending on whether all tests
succeeded or some failed
Arguments:
- `report-success` and `report-failure` should be functions that take the
result of `spec.test/check` and return a list of maps in the format expected
by `clojure.test/do-report`
- `results` should be the result of `spec.test/check`
"
[report-success report-failure results]
(->> results
success?
(print-report! report-success report-failure results)))
(defn cljs-env?
"Take the &env from a macro, and tell whether we are expanding into cljs."
[env]
(boolean (:ns env)))
(defmacro if-cljs
"Return then if we are generating cljs code and else for Clojure code.
https://groups.google.com/d/msg/clojurescript/iBY5HaQda4A/w1lAQi9_AwsJ"
[then else]
(if (cljs-env? &env) then else))
(defn normalise-opts
"Returns the map `opts`, with the :opts key (if present) replaced with the
host language specific `option-keyword`.
"
[opts canonical-keyword]
(let [stc (:opts opts)]
(cond-> (dissoc opts :opts)
stc (assoc canonical-keyword stc))))
(defmacro spec-test
"Check the function(s) named `sym-or-syms` against their specs.
Arguments:
- `check` a symbol with the `spec.test/check` macro’s fully qualified name
- `spec-shim` should implement the `SpecShim` protocol
- `sym-or-syms` a fully qualified symbol, or a list of fully qualified symbols.
The name(s) of the functions to check.
- `opts` a map of options for `clojure.spec.test/check`.
- The `:gen` key is handled by `cljs.spec.test/check` (see its documentation).
- The contents of the `:opts` key is passed on to
`clojure.test.check/quick-check` (see its documentation).
- Special case: inside the `:opts` key, the `:num-tests` key, which is not
handled by `quick-check`, is the number of checks that will be run for
each function (defaults to 1000).
"
[check spec-shim sym-or-syms opts]
`(let [opts# (->> (if-cljs :clojure.test.check/opts :clojure.spec.test.check/opts)
(normalise-opts ~opts))]
(->> (~check ~sym-or-syms opts#)
(report-results! success-report (partial failure-report ~spec-shim)))))
(defmacro deftest
"Define a new test, whether we’re running on Clojure or ClojureScript."
[name & body]
`(if-cljs
(cljs.test/deftest ~name ~@body)
(clojure.test/deftest ~name ~@body)))
(defmacro defspec-test
"Create a test named `name`, that checks the function(s) named `sym-or-syms`
against their specs.
Arguments:
- `check` a symbol with the `spec.test/check` macro’s fully qualified name
- `spec-shim` should implement the `SpecShim` protocol
- `name` a symbol.
- `sym-or-syms` a fully qualified symbol, or a list of fully qualified symbols.
The name(s) of the functions to check.
- `opts` a map of options for `clojure.spec.test/check`.
- The `:gen` key is handled by `cljs.spec.test/check` (see its documentation).
- The contents of the `:opts` key is passed on to
`clojure.test.check/quick-check` (see its documentation).
- Special case: inside the `:opts` key, the `:num-tests` key, which is not
handled by `quick-check`, is the number of checks that will be run for
each function (defaults to 1000).
"
[check spec-shim name sym-or-syms opts]
`(deftest ~name
(spec-test ~check ~spec-shim ~sym-or-syms ~opts)))
|
[
{
"context": "e]\n ))\n\n#_(template/eval \"<%= name %>\" {:name \"Nate\"})\n",
"end": 109,
"score": 0.9991288185119629,
"start": 105,
"tag": "NAME",
"value": "Nate"
}
] | src/lib/comb.clj | justone/bb-scripts | 24 | (ns lib.comb
(:require
[comb.template :as template]
))
#_(template/eval "<%= name %>" {:name "Nate"})
| 81818 | (ns lib.comb
(:require
[comb.template :as template]
))
#_(template/eval "<%= name %>" {:name "<NAME>"})
| true | (ns lib.comb
(:require
[comb.template :as template]
))
#_(template/eval "<%= name %>" {:name "PI:NAME:<NAME>END_PI"})
|
[
{
"context": " :placeholder \"Your Name\"\n ",
"end": 1433,
"score": 0.9962713718414307,
"start": 1424,
"tag": "NAME",
"value": "Your Name"
},
{
"context": " :placeholder \"Password\"\n ",
"end": 2400,
"score": 0.9269736409187317,
"start": 2392,
"tag": "PASSWORD",
"value": "Password"
}
] | src/app/views/register.cljs | skilbjo/compojure | 1 | (ns app.views.register
(:require [app.views.util :as util]
[reagent.core :as reagent]
[re-frame.core :refer [subscribe dispatch]]))
;; -- register ----------------------------------------------------------------
#_(defn register-user [event registration]
(.preventDefault event)
(dispatch [:register-user registration]))
(defn register []
[:div
[:p "register"]])
#_(defn register []
#_(let [default {:user "" :password ""}
registration (reagent/atom default)]
(fn []
(let [user (get @registration :user)
email (get @registration :email)
password (get @registration :password)
loading @(subscribe [:loading])
errors @(subscribe [:errors])]
[:div.auth-page
[:div.container.page
[:div.row
[:div.col-md-6.offset-md-3.col-xs-12
[:h1.text-xs-center "Sign up"]
[:p.text-xs-center
[:a {:href "#/login"} "Have an account?"]]
(when (:register-user errors)
[util/errors-list (:register-user errors)])
[:form {:on-submit #(register-user % @registration)}
[:fieldset.form-group
[:input.form-control.form-control-lg {:type "text"
:placeholder "Your Name"
:value user
:on-change #(swap! registration assoc :user (-> % .-target .-value))
:disabled (when (:register-user loading))}]]
[:fieldset.form-group
[:input.form-control.form-control-lg {:type "text"
:placeholder "Email"
:value email
:on-change #(swap! registration assoc :email (-> % .-target .-value))
:disabled (when (:register-user loading))}]]
[:fieldset.form-group
[:input.form-control.form-control-lg {:type "password"
:placeholder "Password"
:value password
:on-change #(swap! registration assoc :password (-> % .-target .-value))
:disabled (when (:register-user loading))}]]
[:button.btn.btn-lg.btn-primary.pull-xs-right {:class (when (:register-user loading) "disabled")} "Sign up"]]]]]]))))
| 103179 | (ns app.views.register
(:require [app.views.util :as util]
[reagent.core :as reagent]
[re-frame.core :refer [subscribe dispatch]]))
;; -- register ----------------------------------------------------------------
#_(defn register-user [event registration]
(.preventDefault event)
(dispatch [:register-user registration]))
(defn register []
[:div
[:p "register"]])
#_(defn register []
#_(let [default {:user "" :password ""}
registration (reagent/atom default)]
(fn []
(let [user (get @registration :user)
email (get @registration :email)
password (get @registration :password)
loading @(subscribe [:loading])
errors @(subscribe [:errors])]
[:div.auth-page
[:div.container.page
[:div.row
[:div.col-md-6.offset-md-3.col-xs-12
[:h1.text-xs-center "Sign up"]
[:p.text-xs-center
[:a {:href "#/login"} "Have an account?"]]
(when (:register-user errors)
[util/errors-list (:register-user errors)])
[:form {:on-submit #(register-user % @registration)}
[:fieldset.form-group
[:input.form-control.form-control-lg {:type "text"
:placeholder "<NAME>"
:value user
:on-change #(swap! registration assoc :user (-> % .-target .-value))
:disabled (when (:register-user loading))}]]
[:fieldset.form-group
[:input.form-control.form-control-lg {:type "text"
:placeholder "Email"
:value email
:on-change #(swap! registration assoc :email (-> % .-target .-value))
:disabled (when (:register-user loading))}]]
[:fieldset.form-group
[:input.form-control.form-control-lg {:type "password"
:placeholder "<PASSWORD>"
:value password
:on-change #(swap! registration assoc :password (-> % .-target .-value))
:disabled (when (:register-user loading))}]]
[:button.btn.btn-lg.btn-primary.pull-xs-right {:class (when (:register-user loading) "disabled")} "Sign up"]]]]]]))))
| true | (ns app.views.register
(:require [app.views.util :as util]
[reagent.core :as reagent]
[re-frame.core :refer [subscribe dispatch]]))
;; -- register ----------------------------------------------------------------
#_(defn register-user [event registration]
(.preventDefault event)
(dispatch [:register-user registration]))
(defn register []
[:div
[:p "register"]])
#_(defn register []
#_(let [default {:user "" :password ""}
registration (reagent/atom default)]
(fn []
(let [user (get @registration :user)
email (get @registration :email)
password (get @registration :password)
loading @(subscribe [:loading])
errors @(subscribe [:errors])]
[:div.auth-page
[:div.container.page
[:div.row
[:div.col-md-6.offset-md-3.col-xs-12
[:h1.text-xs-center "Sign up"]
[:p.text-xs-center
[:a {:href "#/login"} "Have an account?"]]
(when (:register-user errors)
[util/errors-list (:register-user errors)])
[:form {:on-submit #(register-user % @registration)}
[:fieldset.form-group
[:input.form-control.form-control-lg {:type "text"
:placeholder "PI:NAME:<NAME>END_PI"
:value user
:on-change #(swap! registration assoc :user (-> % .-target .-value))
:disabled (when (:register-user loading))}]]
[:fieldset.form-group
[:input.form-control.form-control-lg {:type "text"
:placeholder "Email"
:value email
:on-change #(swap! registration assoc :email (-> % .-target .-value))
:disabled (when (:register-user loading))}]]
[:fieldset.form-group
[:input.form-control.form-control-lg {:type "password"
:placeholder "PI:PASSWORD:<PASSWORD>END_PI"
:value password
:on-change #(swap! registration assoc :password (-> % .-target .-value))
:disabled (when (:register-user loading))}]]
[:button.btn.btn-lg.btn-primary.pull-xs-right {:class (when (:register-user loading) "disabled")} "Sign up"]]]]]]))))
|
[
{
"context": ";; Exercise 1.6\n\n\n;; Alyssa P. Hacker doesn't see why if needs to be provided as",
"end": 29,
"score": 0.8802472352981567,
"start": 21,
"tag": "NAME",
"value": "Alyssa P"
},
{
"context": ";; Exercise 1.6\n\n\n;; Alyssa P. Hacker doesn't see why if needs to be provided as a spec",
"end": 37,
"score": 0.6133633255958557,
"start": 32,
"tag": "NAME",
"value": "acker"
},
{
"context": "e in terms of cond?'' she asks.\n;; Alyssa's friend Eva Lu Ator claims this can indeed be done, and she defines a",
"end": 214,
"score": 0.9733592867851257,
"start": 203,
"tag": "NAME",
"value": "Eva Lu Ator"
}
] | src/sicp/chapter1/ex1_6.clj | yzernik/sicp-clojure | 0 | ;; Exercise 1.6
;; Alyssa P. Hacker doesn't see why if needs to be provided as a special form. ``Why
;; can't I just define it as an ordinary procedure in terms of cond?'' she asks.
;; Alyssa's friend Eva Lu Ator claims this can indeed be done, and she defines a new
;; version of if:
(defn new-if [predicate then-clause else-clause]
(cond predicate then-clause
:else else-clause))
;; Eva demonstrates the program for Alyssa:
;; (new-if (= 2 3) 0 5)
;; 5
;; (new-if (= 1 1) 0 5)
;; 0
;; Delighted, Alyssa uses new-if to rewrite the square-root program:
(defn square [x] (* x x))
(defn abs [x]
(if (< x 0)
(- x)
x))
(defn good-enough? [guess x]
(< (abs (- (square guess) x)) 0.001))
(defn average [x y]
(/ (+ x y) 2))
(defn improve [guess x]
(average guess (/ x guess)))
(defn sqrt-iter [guess x]
(new-if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
;; The sqr-iter procedure causes a stack overflow error.
| 91863 | ;; Exercise 1.6
;; <NAME>. H<NAME> doesn't see why if needs to be provided as a special form. ``Why
;; can't I just define it as an ordinary procedure in terms of cond?'' she asks.
;; Alyssa's friend <NAME> claims this can indeed be done, and she defines a new
;; version of if:
(defn new-if [predicate then-clause else-clause]
(cond predicate then-clause
:else else-clause))
;; Eva demonstrates the program for Alyssa:
;; (new-if (= 2 3) 0 5)
;; 5
;; (new-if (= 1 1) 0 5)
;; 0
;; Delighted, Alyssa uses new-if to rewrite the square-root program:
(defn square [x] (* x x))
(defn abs [x]
(if (< x 0)
(- x)
x))
(defn good-enough? [guess x]
(< (abs (- (square guess) x)) 0.001))
(defn average [x y]
(/ (+ x y) 2))
(defn improve [guess x]
(average guess (/ x guess)))
(defn sqrt-iter [guess x]
(new-if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
;; The sqr-iter procedure causes a stack overflow error.
| true | ;; Exercise 1.6
;; PI:NAME:<NAME>END_PI. HPI:NAME:<NAME>END_PI doesn't see why if needs to be provided as a special form. ``Why
;; can't I just define it as an ordinary procedure in terms of cond?'' she asks.
;; Alyssa's friend PI:NAME:<NAME>END_PI claims this can indeed be done, and she defines a new
;; version of if:
(defn new-if [predicate then-clause else-clause]
(cond predicate then-clause
:else else-clause))
;; Eva demonstrates the program for Alyssa:
;; (new-if (= 2 3) 0 5)
;; 5
;; (new-if (= 1 1) 0 5)
;; 0
;; Delighted, Alyssa uses new-if to rewrite the square-root program:
(defn square [x] (* x x))
(defn abs [x]
(if (< x 0)
(- x)
x))
(defn good-enough? [guess x]
(< (abs (- (square guess) x)) 0.001))
(defn average [x y]
(/ (+ x y) 2))
(defn improve [guess x]
(average guess (/ x guess)))
(defn sqrt-iter [guess x]
(new-if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
;; The sqr-iter procedure causes a stack overflow error.
|
[
{
"context": "! [{:db/id 1\n :name \"Herbert\"\n :occupation \"Chimney Sweep\"}]",
"end": 1826,
"score": 0.9997449517250061,
"start": 1819,
"tag": "NAME",
"value": "Herbert"
},
{
"context": "e \"Herbert\"\n :occupation \"Chimney Sweep\"}])\n\n (let [log (atom [])\n el (append",
"end": 1873,
"score": 0.9647558331489563,
"start": 1860,
"tag": "NAME",
"value": "Chimney Sweep"
},
{
"context": "nt @log)))\n\n (d/transact! [[:db/add 1 :name \"Frank\"]])\n (v/flush!)\n\n (is (= 2 (count @log)",
"end": 2215,
"score": 0.9996094703674316,
"start": 2210,
"tag": "NAME",
"value": "Frank"
},
{
"context": "sh!)\n\n (is (= 2 (count @log)))\n (is (= \"Frank\" (last @log)))\n\n (d/transact! [{:db/id 2 :na",
"end": 2287,
"score": 0.9996111989021301,
"start": 2282,
"tag": "NAME",
"value": "Frank"
},
{
"context": "ast @log)))\n\n (d/transact! [{:db/id 2 :name \"Gertrude\"}])\n (v/flush!)\n\n (is (= 2 (count @log)",
"end": 2349,
"score": 0.9995479583740234,
"start": 2341,
"tag": "NAME",
"value": "Gertrude"
},
{
"context": "r 2)\n\n (is (= 3 (count @log)))\n (is (= \"Gertrude\" (last @log))))))\n\n",
"end": 2473,
"score": 0.9994521141052246,
"start": 2465,
"tag": "NAME",
"value": "Gertrude"
}
] | re_view/test/re_view/state_test.cljs | braintripping/re-view | 32 | (ns re-view.state-test
(:require
[cljs.test :refer [deftest is are testing]]
[re-db.d :as d]
[re-view.core :as v :refer [defview]]))
(def append-el #(js/document.body.appendChild (js/document.createElement "div")))
(deftest local-state
(let [el (append-el)
render #(v/render-to-dom % el)]
(testing "atom from initial-state"
(let [log (atom [])
local-state (atom nil)
view (v/view
{:view/initial-state 0
:view/did-mount #(reset! local-state (:view/state %))}
[{:keys [view/state]}]
(swap! log conj @state)
[:div "hello"])]
(render (view))
(is (= @log [0]))
(swap! @local-state inc)
(v/flush!)
(is (= @log [0 1]))
(reset! @local-state "x")
(v/flush!)
(is (= @log [0 1 "x"]))))
(testing "passing an atom as state"
(let [the-atom (atom 111)
log (atom [])
view (v/view
{:view/state the-atom}
[this]
(swap! log conj @(:view/state this))
nil)]
(render (view))
(v/flush!)
(swap! the-atom inc)
(v/flush!)
(is (= @log [111 112]))))
(testing "passing an atom as :view/state prop"
(let [the-atom (atom 111)
log (atom [])
view (v/view
[this]
(swap! log conj @(:view/state this))
nil)]
(render (view {:view/state the-atom}))
(v/flush!)
(swap! the-atom inc)
(v/flush!)
(is (= @log [111 112]))))))
(deftest re-db
(testing "React to global state (re-db)"
(d/transact! [{:db/id 1
:name "Herbert"
:occupation "Chimney Sweep"}])
(let [log (atom [])
el (append-el)
view (v/view [{:keys [db/id]}]
(swap! log conj (d/get id :name))
[:div "hello"])
render #(v/render-to-dom (view {:db/id %}) el)]
(render 1)
(is (= 1 (count @log)))
(d/transact! [[:db/add 1 :name "Frank"]])
(v/flush!)
(is (= 2 (count @log)))
(is (= "Frank" (last @log)))
(d/transact! [{:db/id 2 :name "Gertrude"}])
(v/flush!)
(is (= 2 (count @log)))
(render 2)
(is (= 3 (count @log)))
(is (= "Gertrude" (last @log))))))
| 97875 | (ns re-view.state-test
(:require
[cljs.test :refer [deftest is are testing]]
[re-db.d :as d]
[re-view.core :as v :refer [defview]]))
(def append-el #(js/document.body.appendChild (js/document.createElement "div")))
(deftest local-state
(let [el (append-el)
render #(v/render-to-dom % el)]
(testing "atom from initial-state"
(let [log (atom [])
local-state (atom nil)
view (v/view
{:view/initial-state 0
:view/did-mount #(reset! local-state (:view/state %))}
[{:keys [view/state]}]
(swap! log conj @state)
[:div "hello"])]
(render (view))
(is (= @log [0]))
(swap! @local-state inc)
(v/flush!)
(is (= @log [0 1]))
(reset! @local-state "x")
(v/flush!)
(is (= @log [0 1 "x"]))))
(testing "passing an atom as state"
(let [the-atom (atom 111)
log (atom [])
view (v/view
{:view/state the-atom}
[this]
(swap! log conj @(:view/state this))
nil)]
(render (view))
(v/flush!)
(swap! the-atom inc)
(v/flush!)
(is (= @log [111 112]))))
(testing "passing an atom as :view/state prop"
(let [the-atom (atom 111)
log (atom [])
view (v/view
[this]
(swap! log conj @(:view/state this))
nil)]
(render (view {:view/state the-atom}))
(v/flush!)
(swap! the-atom inc)
(v/flush!)
(is (= @log [111 112]))))))
(deftest re-db
(testing "React to global state (re-db)"
(d/transact! [{:db/id 1
:name "<NAME>"
:occupation "<NAME>"}])
(let [log (atom [])
el (append-el)
view (v/view [{:keys [db/id]}]
(swap! log conj (d/get id :name))
[:div "hello"])
render #(v/render-to-dom (view {:db/id %}) el)]
(render 1)
(is (= 1 (count @log)))
(d/transact! [[:db/add 1 :name "<NAME>"]])
(v/flush!)
(is (= 2 (count @log)))
(is (= "<NAME>" (last @log)))
(d/transact! [{:db/id 2 :name "<NAME>"}])
(v/flush!)
(is (= 2 (count @log)))
(render 2)
(is (= 3 (count @log)))
(is (= "<NAME>" (last @log))))))
| true | (ns re-view.state-test
(:require
[cljs.test :refer [deftest is are testing]]
[re-db.d :as d]
[re-view.core :as v :refer [defview]]))
(def append-el #(js/document.body.appendChild (js/document.createElement "div")))
(deftest local-state
(let [el (append-el)
render #(v/render-to-dom % el)]
(testing "atom from initial-state"
(let [log (atom [])
local-state (atom nil)
view (v/view
{:view/initial-state 0
:view/did-mount #(reset! local-state (:view/state %))}
[{:keys [view/state]}]
(swap! log conj @state)
[:div "hello"])]
(render (view))
(is (= @log [0]))
(swap! @local-state inc)
(v/flush!)
(is (= @log [0 1]))
(reset! @local-state "x")
(v/flush!)
(is (= @log [0 1 "x"]))))
(testing "passing an atom as state"
(let [the-atom (atom 111)
log (atom [])
view (v/view
{:view/state the-atom}
[this]
(swap! log conj @(:view/state this))
nil)]
(render (view))
(v/flush!)
(swap! the-atom inc)
(v/flush!)
(is (= @log [111 112]))))
(testing "passing an atom as :view/state prop"
(let [the-atom (atom 111)
log (atom [])
view (v/view
[this]
(swap! log conj @(:view/state this))
nil)]
(render (view {:view/state the-atom}))
(v/flush!)
(swap! the-atom inc)
(v/flush!)
(is (= @log [111 112]))))))
(deftest re-db
(testing "React to global state (re-db)"
(d/transact! [{:db/id 1
:name "PI:NAME:<NAME>END_PI"
:occupation "PI:NAME:<NAME>END_PI"}])
(let [log (atom [])
el (append-el)
view (v/view [{:keys [db/id]}]
(swap! log conj (d/get id :name))
[:div "hello"])
render #(v/render-to-dom (view {:db/id %}) el)]
(render 1)
(is (= 1 (count @log)))
(d/transact! [[:db/add 1 :name "PI:NAME:<NAME>END_PI"]])
(v/flush!)
(is (= 2 (count @log)))
(is (= "PI:NAME:<NAME>END_PI" (last @log)))
(d/transact! [{:db/id 2 :name "PI:NAME:<NAME>END_PI"}])
(v/flush!)
(is (= 2 (count @log)))
(render 2)
(is (= 3 (count @log)))
(is (= "PI:NAME:<NAME>END_PI" (last @log))))))
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998028874397278,
"start": 96,
"tag": "NAME",
"value": "Ragnar Svensson"
},
{
"context": "-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold License version 1.0 ",
"end": 129,
"score": 0.9998188614845276,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] | editor/src/clj/editor/curve_grid.clj | cmarincia/defold | 0 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; 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.
(ns editor.curve-grid
(:require [dynamo.graph :as g]
[editor.colors :as colors]
[editor.geom :as geom]
[editor.gl :as gl]
[editor.types :as types]
[editor.camera :as c]
[editor.validation :as validation]
[editor.gl.pass :as pass])
(:import [editor.types AABB Camera]
[com.jogamp.opengl GL GL2]
[javax.vecmath Vector3d Vector4d Matrix3d Matrix4d Point3d]))
(set! *warn-on-reflection* true)
(def min-align (/ (Math/sqrt 2.0) 2.0))
(def grid-color colors/mid-grey)
(def x-axis-color colors/defold-white)
(def y-axis-color colors/defold-white)
(def z-axis-color colors/defold-white)
(defn render-grid-axis
[^GL2 gl ^doubles vx uidx start stop size vidx min max]
(doseq [u (range start stop size)]
(aset vx uidx ^double u)
(aset vx vidx ^double min)
(gl/gl-vertex-3dv gl vx 0)
(aset vx vidx ^double max)
(gl/gl-vertex-3dv gl vx 0)))
(defn render-grid
[gl fixed-axis size aabb]
;; draw across
(let [min-values (geom/as-array (types/min-p aabb))
max-values (geom/as-array (types/max-p aabb))
u-axis (mod (inc fixed-axis) 3)
u-min (nth min-values u-axis)
u-max (nth max-values u-axis)
v-axis (mod (inc u-axis) 3)
v-min (nth min-values v-axis)
v-max (nth max-values v-axis)
vertex (double-array 3)]
(aset vertex fixed-axis 0.0)
(render-grid-axis gl vertex v-axis v-min v-max size u-axis u-min u-max)))
(defn render-primary-axes
[^GL2 gl ^AABB aabb]
(gl/gl-color gl x-axis-color)
(gl/gl-vertex-3d gl (-> aabb types/min-p .x) 0.0 0.0)
(gl/gl-vertex-3d gl (-> aabb types/max-p .x) 0.0 0.0)
(gl/gl-color gl y-axis-color)
(gl/gl-vertex-3d gl 0.0 (-> aabb types/min-p .y) 0.0)
(gl/gl-vertex-3d gl 0.0 (-> aabb types/max-p .y) 0.0)
(gl/gl-vertex-3d gl 1.0 (-> aabb types/min-p .y) 0.0)
(gl/gl-vertex-3d gl 1.0 (-> aabb types/max-p .y) 0.0)
(gl/gl-color gl grid-color)
(doseq [i (range 4)]
(let [x (/ (inc i) 5.0)]
(gl/gl-vertex-3d gl x (-> aabb types/min-p .y) 0.0)
(gl/gl-vertex-3d gl x (-> aabb types/max-p .y) 0.0))))
(defn render-grid-sizes
[^GL2 gl ^doubles dir grids]
(doall
(for [grid-index (range 2) ; 0 1
axis [2] #_(range 3) ; 0 1 2
:let [ratio (nth (:ratios grids) grid-index)
alpha (Math/abs (* (aget dir axis) ratio))]]
(do
(gl/gl-color gl (colors/alpha grid-color alpha))
(render-grid gl axis
(nth (:sizes grids) grid-index)
(nth (:aabbs grids) grid-index))))))
(defn render-scaled-grids
[^GL2 gl pass renderables count]
(let [renderable (first renderables)
user-render-data (:user-render-data renderable)
camera (:camera user-render-data)
grids (:grids user-render-data)
view-matrix (c/camera-view-matrix camera)
dir (double-array 4)
_ (.getRow view-matrix 2 dir)]
(gl/gl-lines gl
(render-grid-sizes dir grids)
(render-primary-axes (apply geom/aabb-union (:aabbs grids))))))
(g/defnk grid-renderable
[camera grids]
{pass/transparent
[{:world-transform geom/Identity4d
:render-fn render-scaled-grids
:user-render-data {:camera camera
:grids grids}}]})
(def axis-vectors
[(Vector4d. 1.0 0.0 0.0 0.0)
(Vector4d. 0.0 1.0 0.0 0.0)
(Vector4d. 0.0 0.0 1.0 0.0)])
(defn as-unit-vector
[^Vector4d v]
(let [v-unit (Vector4d. v)]
(set! (. v-unit w) 0)
(.normalize v-unit)
v-unit))
(defn dot
^double [^Vector4d x ^Vector4d y]
(.dot x y))
(defn frustum-plane-projection
[^Vector4d plane1 ^Vector4d plane2]
(let [m (Matrix3d. 0.0 0.0 1.0
(.x plane1) (.y plane1) (.z plane1)
(.x plane2) (.y plane2) (.z plane2))
v (Point3d. 0.0 (- (.w plane1)) (- (.w plane2)))]
(.invert m)
(.transform m v)
v))
(defn frustum-projection-aabb
[planes]
(-> geom/null-aabb
(geom/aabb-incorporate (frustum-plane-projection (nth planes 0) (nth planes 2)))
(geom/aabb-incorporate (frustum-plane-projection (nth planes 0) (nth planes 3)))
(geom/aabb-incorporate (frustum-plane-projection (nth planes 1) (nth planes 2)))
(geom/aabb-incorporate (frustum-plane-projection (nth planes 1) (nth planes 3)))))
(defn grid-ratio [extent]
(let [exp (Math/log10 extent)]
(- 1.0 (- exp (Math/floor exp)))))
(defn small-grid-size [extent] (Math/pow 10.0 (dec (Math/floor (Math/log10 extent)))))
(defn large-grid-size [extent] (Math/pow 10.0 (Math/floor (Math/log10 extent))))
(defn grid-snap-down [a sz] (* sz (Math/floor (/ a sz))))
(defn grid-snap-up [a sz] (* sz (Math/ceil (/ a sz))))
(defn snap-out-to-grid
[^AABB aabb grid-size]
(types/->AABB (Point3d. (grid-snap-down (-> aabb types/min-p .x) grid-size)
(grid-snap-down (-> aabb types/min-p .y) grid-size)
(grid-snap-down (-> aabb types/min-p .z) grid-size))
(Point3d. (grid-snap-up (-> aabb types/max-p .x) grid-size)
(grid-snap-up (-> aabb types/max-p .y) grid-size)
(grid-snap-up (-> aabb types/max-p .z) grid-size))))
(g/defnk update-grids
[camera]
(let [frustum-planes (c/viewproj-frustum-planes camera)
far-z-plane (nth frustum-planes 5)
normal (as-unit-vector far-z-plane)
aabb (frustum-projection-aabb frustum-planes)
extent (.y (geom/aabb-extent aabb))
first-grid-ratio (grid-ratio extent)
grid-size-small (small-grid-size extent)
grid-size-large (large-grid-size extent)]
{:ratios [first-grid-ratio (- 1.0 first-grid-ratio)]
:sizes [grid-size-small grid-size-large]
:aabbs [(snap-out-to-grid aabb grid-size-small) (snap-out-to-grid aabb grid-size-large)]}))
(g/defnode Grid
(input camera Camera)
(property grid-color types/Color)
(property auto-grid g/Bool)
(property fixed-grid-size g/Int
(default 0))
(output grids g/Any :cached update-grids)
(output renderable pass/RenderData :cached grid-renderable))
| 44412 | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 <NAME>, <NAME>
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; 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.
(ns editor.curve-grid
(:require [dynamo.graph :as g]
[editor.colors :as colors]
[editor.geom :as geom]
[editor.gl :as gl]
[editor.types :as types]
[editor.camera :as c]
[editor.validation :as validation]
[editor.gl.pass :as pass])
(:import [editor.types AABB Camera]
[com.jogamp.opengl GL GL2]
[javax.vecmath Vector3d Vector4d Matrix3d Matrix4d Point3d]))
(set! *warn-on-reflection* true)
(def min-align (/ (Math/sqrt 2.0) 2.0))
(def grid-color colors/mid-grey)
(def x-axis-color colors/defold-white)
(def y-axis-color colors/defold-white)
(def z-axis-color colors/defold-white)
(defn render-grid-axis
[^GL2 gl ^doubles vx uidx start stop size vidx min max]
(doseq [u (range start stop size)]
(aset vx uidx ^double u)
(aset vx vidx ^double min)
(gl/gl-vertex-3dv gl vx 0)
(aset vx vidx ^double max)
(gl/gl-vertex-3dv gl vx 0)))
(defn render-grid
[gl fixed-axis size aabb]
;; draw across
(let [min-values (geom/as-array (types/min-p aabb))
max-values (geom/as-array (types/max-p aabb))
u-axis (mod (inc fixed-axis) 3)
u-min (nth min-values u-axis)
u-max (nth max-values u-axis)
v-axis (mod (inc u-axis) 3)
v-min (nth min-values v-axis)
v-max (nth max-values v-axis)
vertex (double-array 3)]
(aset vertex fixed-axis 0.0)
(render-grid-axis gl vertex v-axis v-min v-max size u-axis u-min u-max)))
(defn render-primary-axes
[^GL2 gl ^AABB aabb]
(gl/gl-color gl x-axis-color)
(gl/gl-vertex-3d gl (-> aabb types/min-p .x) 0.0 0.0)
(gl/gl-vertex-3d gl (-> aabb types/max-p .x) 0.0 0.0)
(gl/gl-color gl y-axis-color)
(gl/gl-vertex-3d gl 0.0 (-> aabb types/min-p .y) 0.0)
(gl/gl-vertex-3d gl 0.0 (-> aabb types/max-p .y) 0.0)
(gl/gl-vertex-3d gl 1.0 (-> aabb types/min-p .y) 0.0)
(gl/gl-vertex-3d gl 1.0 (-> aabb types/max-p .y) 0.0)
(gl/gl-color gl grid-color)
(doseq [i (range 4)]
(let [x (/ (inc i) 5.0)]
(gl/gl-vertex-3d gl x (-> aabb types/min-p .y) 0.0)
(gl/gl-vertex-3d gl x (-> aabb types/max-p .y) 0.0))))
(defn render-grid-sizes
[^GL2 gl ^doubles dir grids]
(doall
(for [grid-index (range 2) ; 0 1
axis [2] #_(range 3) ; 0 1 2
:let [ratio (nth (:ratios grids) grid-index)
alpha (Math/abs (* (aget dir axis) ratio))]]
(do
(gl/gl-color gl (colors/alpha grid-color alpha))
(render-grid gl axis
(nth (:sizes grids) grid-index)
(nth (:aabbs grids) grid-index))))))
(defn render-scaled-grids
[^GL2 gl pass renderables count]
(let [renderable (first renderables)
user-render-data (:user-render-data renderable)
camera (:camera user-render-data)
grids (:grids user-render-data)
view-matrix (c/camera-view-matrix camera)
dir (double-array 4)
_ (.getRow view-matrix 2 dir)]
(gl/gl-lines gl
(render-grid-sizes dir grids)
(render-primary-axes (apply geom/aabb-union (:aabbs grids))))))
(g/defnk grid-renderable
[camera grids]
{pass/transparent
[{:world-transform geom/Identity4d
:render-fn render-scaled-grids
:user-render-data {:camera camera
:grids grids}}]})
(def axis-vectors
[(Vector4d. 1.0 0.0 0.0 0.0)
(Vector4d. 0.0 1.0 0.0 0.0)
(Vector4d. 0.0 0.0 1.0 0.0)])
(defn as-unit-vector
[^Vector4d v]
(let [v-unit (Vector4d. v)]
(set! (. v-unit w) 0)
(.normalize v-unit)
v-unit))
(defn dot
^double [^Vector4d x ^Vector4d y]
(.dot x y))
(defn frustum-plane-projection
[^Vector4d plane1 ^Vector4d plane2]
(let [m (Matrix3d. 0.0 0.0 1.0
(.x plane1) (.y plane1) (.z plane1)
(.x plane2) (.y plane2) (.z plane2))
v (Point3d. 0.0 (- (.w plane1)) (- (.w plane2)))]
(.invert m)
(.transform m v)
v))
(defn frustum-projection-aabb
[planes]
(-> geom/null-aabb
(geom/aabb-incorporate (frustum-plane-projection (nth planes 0) (nth planes 2)))
(geom/aabb-incorporate (frustum-plane-projection (nth planes 0) (nth planes 3)))
(geom/aabb-incorporate (frustum-plane-projection (nth planes 1) (nth planes 2)))
(geom/aabb-incorporate (frustum-plane-projection (nth planes 1) (nth planes 3)))))
(defn grid-ratio [extent]
(let [exp (Math/log10 extent)]
(- 1.0 (- exp (Math/floor exp)))))
(defn small-grid-size [extent] (Math/pow 10.0 (dec (Math/floor (Math/log10 extent)))))
(defn large-grid-size [extent] (Math/pow 10.0 (Math/floor (Math/log10 extent))))
(defn grid-snap-down [a sz] (* sz (Math/floor (/ a sz))))
(defn grid-snap-up [a sz] (* sz (Math/ceil (/ a sz))))
(defn snap-out-to-grid
[^AABB aabb grid-size]
(types/->AABB (Point3d. (grid-snap-down (-> aabb types/min-p .x) grid-size)
(grid-snap-down (-> aabb types/min-p .y) grid-size)
(grid-snap-down (-> aabb types/min-p .z) grid-size))
(Point3d. (grid-snap-up (-> aabb types/max-p .x) grid-size)
(grid-snap-up (-> aabb types/max-p .y) grid-size)
(grid-snap-up (-> aabb types/max-p .z) grid-size))))
(g/defnk update-grids
[camera]
(let [frustum-planes (c/viewproj-frustum-planes camera)
far-z-plane (nth frustum-planes 5)
normal (as-unit-vector far-z-plane)
aabb (frustum-projection-aabb frustum-planes)
extent (.y (geom/aabb-extent aabb))
first-grid-ratio (grid-ratio extent)
grid-size-small (small-grid-size extent)
grid-size-large (large-grid-size extent)]
{:ratios [first-grid-ratio (- 1.0 first-grid-ratio)]
:sizes [grid-size-small grid-size-large]
:aabbs [(snap-out-to-grid aabb grid-size-small) (snap-out-to-grid aabb grid-size-large)]}))
(g/defnode Grid
(input camera Camera)
(property grid-color types/Color)
(property auto-grid g/Bool)
(property fixed-grid-size g/Int
(default 0))
(output grids g/Any :cached update-grids)
(output renderable pass/RenderData :cached grid-renderable))
| true | ;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; 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.
(ns editor.curve-grid
(:require [dynamo.graph :as g]
[editor.colors :as colors]
[editor.geom :as geom]
[editor.gl :as gl]
[editor.types :as types]
[editor.camera :as c]
[editor.validation :as validation]
[editor.gl.pass :as pass])
(:import [editor.types AABB Camera]
[com.jogamp.opengl GL GL2]
[javax.vecmath Vector3d Vector4d Matrix3d Matrix4d Point3d]))
(set! *warn-on-reflection* true)
(def min-align (/ (Math/sqrt 2.0) 2.0))
(def grid-color colors/mid-grey)
(def x-axis-color colors/defold-white)
(def y-axis-color colors/defold-white)
(def z-axis-color colors/defold-white)
(defn render-grid-axis
[^GL2 gl ^doubles vx uidx start stop size vidx min max]
(doseq [u (range start stop size)]
(aset vx uidx ^double u)
(aset vx vidx ^double min)
(gl/gl-vertex-3dv gl vx 0)
(aset vx vidx ^double max)
(gl/gl-vertex-3dv gl vx 0)))
(defn render-grid
[gl fixed-axis size aabb]
;; draw across
(let [min-values (geom/as-array (types/min-p aabb))
max-values (geom/as-array (types/max-p aabb))
u-axis (mod (inc fixed-axis) 3)
u-min (nth min-values u-axis)
u-max (nth max-values u-axis)
v-axis (mod (inc u-axis) 3)
v-min (nth min-values v-axis)
v-max (nth max-values v-axis)
vertex (double-array 3)]
(aset vertex fixed-axis 0.0)
(render-grid-axis gl vertex v-axis v-min v-max size u-axis u-min u-max)))
(defn render-primary-axes
[^GL2 gl ^AABB aabb]
(gl/gl-color gl x-axis-color)
(gl/gl-vertex-3d gl (-> aabb types/min-p .x) 0.0 0.0)
(gl/gl-vertex-3d gl (-> aabb types/max-p .x) 0.0 0.0)
(gl/gl-color gl y-axis-color)
(gl/gl-vertex-3d gl 0.0 (-> aabb types/min-p .y) 0.0)
(gl/gl-vertex-3d gl 0.0 (-> aabb types/max-p .y) 0.0)
(gl/gl-vertex-3d gl 1.0 (-> aabb types/min-p .y) 0.0)
(gl/gl-vertex-3d gl 1.0 (-> aabb types/max-p .y) 0.0)
(gl/gl-color gl grid-color)
(doseq [i (range 4)]
(let [x (/ (inc i) 5.0)]
(gl/gl-vertex-3d gl x (-> aabb types/min-p .y) 0.0)
(gl/gl-vertex-3d gl x (-> aabb types/max-p .y) 0.0))))
(defn render-grid-sizes
[^GL2 gl ^doubles dir grids]
(doall
(for [grid-index (range 2) ; 0 1
axis [2] #_(range 3) ; 0 1 2
:let [ratio (nth (:ratios grids) grid-index)
alpha (Math/abs (* (aget dir axis) ratio))]]
(do
(gl/gl-color gl (colors/alpha grid-color alpha))
(render-grid gl axis
(nth (:sizes grids) grid-index)
(nth (:aabbs grids) grid-index))))))
(defn render-scaled-grids
[^GL2 gl pass renderables count]
(let [renderable (first renderables)
user-render-data (:user-render-data renderable)
camera (:camera user-render-data)
grids (:grids user-render-data)
view-matrix (c/camera-view-matrix camera)
dir (double-array 4)
_ (.getRow view-matrix 2 dir)]
(gl/gl-lines gl
(render-grid-sizes dir grids)
(render-primary-axes (apply geom/aabb-union (:aabbs grids))))))
(g/defnk grid-renderable
[camera grids]
{pass/transparent
[{:world-transform geom/Identity4d
:render-fn render-scaled-grids
:user-render-data {:camera camera
:grids grids}}]})
(def axis-vectors
[(Vector4d. 1.0 0.0 0.0 0.0)
(Vector4d. 0.0 1.0 0.0 0.0)
(Vector4d. 0.0 0.0 1.0 0.0)])
(defn as-unit-vector
[^Vector4d v]
(let [v-unit (Vector4d. v)]
(set! (. v-unit w) 0)
(.normalize v-unit)
v-unit))
(defn dot
^double [^Vector4d x ^Vector4d y]
(.dot x y))
(defn frustum-plane-projection
[^Vector4d plane1 ^Vector4d plane2]
(let [m (Matrix3d. 0.0 0.0 1.0
(.x plane1) (.y plane1) (.z plane1)
(.x plane2) (.y plane2) (.z plane2))
v (Point3d. 0.0 (- (.w plane1)) (- (.w plane2)))]
(.invert m)
(.transform m v)
v))
(defn frustum-projection-aabb
[planes]
(-> geom/null-aabb
(geom/aabb-incorporate (frustum-plane-projection (nth planes 0) (nth planes 2)))
(geom/aabb-incorporate (frustum-plane-projection (nth planes 0) (nth planes 3)))
(geom/aabb-incorporate (frustum-plane-projection (nth planes 1) (nth planes 2)))
(geom/aabb-incorporate (frustum-plane-projection (nth planes 1) (nth planes 3)))))
(defn grid-ratio [extent]
(let [exp (Math/log10 extent)]
(- 1.0 (- exp (Math/floor exp)))))
(defn small-grid-size [extent] (Math/pow 10.0 (dec (Math/floor (Math/log10 extent)))))
(defn large-grid-size [extent] (Math/pow 10.0 (Math/floor (Math/log10 extent))))
(defn grid-snap-down [a sz] (* sz (Math/floor (/ a sz))))
(defn grid-snap-up [a sz] (* sz (Math/ceil (/ a sz))))
(defn snap-out-to-grid
[^AABB aabb grid-size]
(types/->AABB (Point3d. (grid-snap-down (-> aabb types/min-p .x) grid-size)
(grid-snap-down (-> aabb types/min-p .y) grid-size)
(grid-snap-down (-> aabb types/min-p .z) grid-size))
(Point3d. (grid-snap-up (-> aabb types/max-p .x) grid-size)
(grid-snap-up (-> aabb types/max-p .y) grid-size)
(grid-snap-up (-> aabb types/max-p .z) grid-size))))
(g/defnk update-grids
[camera]
(let [frustum-planes (c/viewproj-frustum-planes camera)
far-z-plane (nth frustum-planes 5)
normal (as-unit-vector far-z-plane)
aabb (frustum-projection-aabb frustum-planes)
extent (.y (geom/aabb-extent aabb))
first-grid-ratio (grid-ratio extent)
grid-size-small (small-grid-size extent)
grid-size-large (large-grid-size extent)]
{:ratios [first-grid-ratio (- 1.0 first-grid-ratio)]
:sizes [grid-size-small grid-size-large]
:aabbs [(snap-out-to-grid aabb grid-size-small) (snap-out-to-grid aabb grid-size-large)]}))
(g/defnode Grid
(input camera Camera)
(property grid-color types/Color)
(property auto-grid g/Bool)
(property fixed-grid-size g/Int
(default 0))
(output grids g/Any :cached update-grids)
(output renderable pass/RenderData :cached grid-renderable))
|
[
{
"context": ":reference-time (time/t -2 2013 2 12 4 30 0)}\n\n \"subito\"\n \"immediatamente\"\n \"in questo momento\"\n (date",
"end": 139,
"score": 0.9512903094291687,
"start": 133,
"tag": "NAME",
"value": "subito"
},
{
"context": "desso\"\n \"in giornata\"\n (datetime 2013 2 12)\n\n \"ieri\"\n (datetime 2013 2 11)\n\n \"domani\"\n (datetime 2",
"end": 301,
"score": 0.9878512024879456,
"start": 297,
"tag": "NAME",
"value": "ieri"
},
{
"context": "e 2013 2 12)\n\n \"ieri\"\n (datetime 2013 2 11)\n\n \"domani\"\n (datetime 2013 2 13)\n\n \"Il giorno dopo domani",
"end": 336,
"score": 0.9994070529937744,
"start": 330,
"tag": "NAME",
"value": "domani"
},
{
"context": "\"domani\"\n (datetime 2013 2 13)\n\n \"Il giorno dopo domani\"\n \"dopodomani\"\n (datetime 2013 2 14)\n\n \"Lunedì",
"end": 386,
"score": 0.9930888414382935,
"start": 380,
"tag": "NAME",
"value": "domani"
},
{
"context": "datetime 2013 2 13)\n\n \"Il giorno dopo domani\"\n \"dopodomani\"\n (datetime 2013 2 14)\n\n \"Lunedì 18 febbraio\"\n ",
"end": 401,
"score": 0.9857605695724487,
"start": 391,
"tag": "NAME",
"value": "dopodomani"
},
{
"context": "domani\"\n \"dopodomani\"\n (datetime 2013 2 14)\n\n \"Lunedì 18 febbraio\"\n (datetime 2013 2 18 :day-of-week 1",
"end": 436,
"score": 0.9981606006622314,
"start": 430,
"tag": "NAME",
"value": "Lunedì"
},
{
"context": "me 2013 2 18 :day-of-week 1 :day 18 :month 2)\n\n \"martedì\"\n \"Martedì 19\"\n \"ma 19\"\n (datetime 2013 2 19)\n",
"end": 516,
"score": 0.9995966553688049,
"start": 509,
"tag": "NAME",
"value": "martedì"
},
{
"context": " :day-of-week 1 :day 18 :month 2)\n\n \"martedì\"\n \"Martedì 19\"\n \"ma 19\"\n (datetime 2013 2 19)\n\n \"l'altro ",
"end": 528,
"score": 0.9994220733642578,
"start": 521,
"tag": "NAME",
"value": "Martedì"
},
{
"context": "-week 1 :day 18 :month 2)\n\n \"martedì\"\n \"Martedì 19\"\n \"ma 19\"\n (datetime 2013 2 19)\n\n \"l'altro ier",
"end": 531,
"score": 0.6184793710708618,
"start": 529,
"tag": "NAME",
"value": "19"
},
{
"context": "artedì 19\"\n \"ma 19\"\n (datetime 2013 2 19)\n\n \"l'altro ieri\"\n \"altroieri\"\n (datetime 2013 2 10)\n\n \"lunedi\"",
"end": 582,
"score": 0.9002160429954529,
"start": 572,
"tag": "NAME",
"value": "altro ieri"
},
{
"context": "a 19\"\n (datetime 2013 2 19)\n\n \"l'altro ieri\"\n \"altroieri\"\n (datetime 2013 2 10)\n\n \"lunedi\"\n \"lu.\"\n \"lu",
"end": 596,
"score": 0.978346586227417,
"start": 587,
"tag": "NAME",
"value": "altroieri"
},
{
"context": "ro ieri\"\n \"altroieri\"\n (datetime 2013 2 10)\n\n \"lunedi\"\n \"lu.\"\n \"lun\"\n (datetime 2013 2 18 :day-of-we",
"end": 631,
"score": 0.9963732957839966,
"start": 625,
"tag": "NAME",
"value": "lunedi"
},
{
"context": "ri\"\n (datetime 2013 2 10)\n\n \"lunedi\"\n \"lu.\"\n \"lun\"\n (datetime 2013 2 18 :day-of-week 1)\n\n \"lunedi",
"end": 647,
"score": 0.9894909262657166,
"start": 644,
"tag": "NAME",
"value": "lun"
},
{
"context": " \"lun\"\n (datetime 2013 2 18 :day-of-week 1)\n\n \"lunedi 18 febbraio\"\n (datetime 2013 2 18 :day-of-week 1",
"end": 697,
"score": 0.9168283343315125,
"start": 691,
"tag": "NAME",
"value": "lunedi"
},
{
"context": "me 2013 2 18 :day-of-week 1 :day 18 :month 2)\n\n \"Martedì\"\n (datetime 2013 2 19 :day-of-week 2)\n\n \"Mercol",
"end": 777,
"score": 0.9996880888938904,
"start": 770,
"tag": "NAME",
"value": "Martedì"
},
{
"context": "artedì\"\n (datetime 2013 2 19 :day-of-week 2)\n\n \"Mercoledì\"\n \"mer\"\n \"mer.\"\n (datetime 2013 2 13 :day-of-w",
"end": 830,
"score": 0.9997671246528625,
"start": 821,
"tag": "NAME",
"value": "Mercoledì"
},
{
"context": "etime 2013 2 19 :day-of-week 2)\n\n \"Mercoledì\"\n \"mer\"\n \"mer.\"\n (datetime 2013 2 13 :day-of-week 3)\n\n",
"end": 838,
"score": 0.9991720914840698,
"start": 835,
"tag": "NAME",
"value": "mer"
},
{
"context": " \"mer.\"\n (datetime 2013 2 13 :day-of-week 3)\n\n \"mercoledi 13 feb\"\n \"il 13 febbraio\"\n (datetime 2013 2 13 ",
"end": 900,
"score": 0.8740172386169434,
"start": 891,
"tag": "NAME",
"value": "mercoledi"
},
{
"context": "3 :day-of-week 3 :day 13 :month 2 :year 2013)\n\n \"giovedi\"\n \"gio\"\n (datetime 2013 2 14)\n\n \"venerdi\"\n \"v",
"end": 1085,
"score": 0.9898366332054138,
"start": 1078,
"tag": "NAME",
"value": "giovedi"
},
{
"context": "ek 3 :day 13 :month 2 :year 2013)\n\n \"giovedi\"\n \"gio\"\n (datetime 2013 2 14)\n\n \"venerdi\"\n \"venerdì\"\n",
"end": 1093,
"score": 0.9903990626335144,
"start": 1090,
"tag": "NAME",
"value": "gio"
},
{
"context": ")\n\n \"giovedi\"\n \"gio\"\n (datetime 2013 2 14)\n\n \"venerdi\"\n \"venerdì\"\n \"ven\"\n (datetime 2013 2 15)\n\n \"s",
"end": 1129,
"score": 0.9972923398017883,
"start": 1122,
"tag": "NAME",
"value": "venerdi"
},
{
"context": "i\"\n \"gio\"\n (datetime 2013 2 14)\n\n \"venerdi\"\n \"venerdì\"\n \"ven\"\n (datetime 2013 2 15)\n\n \"sabato\"\n \"sa",
"end": 1141,
"score": 0.9979193210601807,
"start": 1134,
"tag": "NAME",
"value": "venerdì"
},
{
"context": " (datetime 2013 2 14)\n\n \"venerdi\"\n \"venerdì\"\n \"ven\"\n (datetime 2013 2 15)\n\n \"sabato\"\n \"sab\"\n \"sa",
"end": 1149,
"score": 0.9820454716682434,
"start": 1146,
"tag": "NAME",
"value": "ven"
},
{
"context": "i\"\n \"venerdì\"\n \"ven\"\n (datetime 2013 2 15)\n\n \"sabato\"\n \"sab\"\n \"sab.\"\n (datetime 2013 2 16)\n\n \"dome",
"end": 1184,
"score": 0.9931003451347351,
"start": 1178,
"tag": "NAME",
"value": "sabato"
},
{
"context": "dì\"\n \"ven\"\n (datetime 2013 2 15)\n\n \"sabato\"\n \"sab\"\n \"sab.\"\n (datetime 2013 2 16)\n\n \"domenica\"\n ",
"end": 1192,
"score": 0.9411462545394897,
"start": 1189,
"tag": "NAME",
"value": "sab"
},
{
"context": "time 1974 10 31 :day 31 :month 10 :year 1974)\n\n \"martedì scorso\"\n (datetime 2013 2 5 :day-of-week 2)\n\n \"martedì",
"end": 1916,
"score": 0.7810614109039307,
"start": 1902,
"tag": "NAME",
"value": "martedì scorso"
},
{
"context": " scorso\"\n (datetime 2013 2 5 :day-of-week 2)\n\n \"martedì prossimo\"\n \"il martedì dopo\"\n (datetime 2013 2 19 :day-o",
"end": 1975,
"score": 0.8205026984214783,
"start": 1959,
"tag": "NAME",
"value": "martedì prossimo"
},
{
"context": "ì dopo\"\n (datetime 2013 2 19 :day-of-week 2)\n\n \"mercoledì prossimo\"\n ;\"mercoledi fra una settimana\"\n (dat",
"end": 2048,
"score": 0.6511400938034058,
"start": 2039,
"tag": "NAME",
"value": "mercoledì"
},
{
"context": "immacolata alle 18\"\n (datetime 2013 12 8 18)\n\n \"santo stefano\"\n (datetime 2013 12 26)\n\n ; Part of day (mornin",
"end": 8547,
"score": 0.9883956909179688,
"start": 8534,
"tag": "NAME",
"value": "santo stefano"
},
{
"context": "etime-interval [2013 2 12 18] [2013 2 13 00])\n\n \"domani mattina\"\n \"domattina\"\n (datetime-interval [2013 2 13 4]",
"end": 8755,
"score": 0.9969223141670227,
"start": 8741,
"tag": "NAME",
"value": "domani mattina"
},
{
"context": "3 2 12 18] [2013 2 13 00])\n\n \"domani mattina\"\n \"domattina\"\n (datetime-interval [2013 2 13 4] [2013 2 13 12",
"end": 8769,
"score": 0.9669929146766663,
"start": 8760,
"tag": "NAME",
"value": "domattina"
},
{
"context": "ime-interval [2013 2 12 4 30 00] [2013 2 18])\n\n \"stanotte\"\n (datetime-interval [2013 2 13 0] [2013 2 13 04",
"end": 8927,
"score": 0.9074872136116028,
"start": 8919,
"tag": "NAME",
"value": "stanotte"
},
{
"context": "etime-interval [2013 2 13 18] [2013 2 14 00])\n\n \"domani notte\"\n \"domani in nottata\"\n \"nella nottata di ",
"end": 9178,
"score": 0.8309353590011597,
"start": 9172,
"tag": "NAME",
"value": "domani"
},
{
"context": "rval [2013 2 13 18] [2013 2 14 00])\n\n \"domani notte\"\n \"domani in nottata\"\n \"nella nottata di domani",
"end": 9184,
"score": 0.5743398666381836,
"start": 9182,
"tag": "NAME",
"value": "te"
},
{
"context": "i notte\"\n \"domani in nottata\"\n \"nella nottata di domani\"\n \"nella notte di domani\"\n (datetime-interval [",
"end": 9234,
"score": 0.7496627569198608,
"start": 9228,
"tag": "NAME",
"value": "domani"
},
{
"context": "etime-interval [2013 2 14 00] [2013 2 14 04])\n\n \"domani a pranzo\"\n (datetime-interval [2013 2 13 12] [20",
"end": 9324,
"score": 0.7608771920204163,
"start": 9318,
"tag": "NAME",
"value": "domani"
},
{
"context": "val [2013 2 14 00] [2013 2 14 04])\n\n \"domani a pranzo\"\n (datetime-interval [2013 2 13 12] [2013 2 13 1",
"end": 9333,
"score": 0.7645261287689209,
"start": 9329,
"tag": "NAME",
"value": "anzo"
},
{
"context": "etime-interval [2013 2 13 12] [2013 2 13 14])\n\n \"ieri sera\"\n (datetime-interval [2013 2 11 18] [2013 2 12 0",
"end": 9400,
"score": 0.9905167818069458,
"start": 9391,
"tag": "NAME",
"value": "ieri sera"
},
{
"context": " (datetime 2013 4 25 16 0)\n\n \"3 del pomeriggio di domani\"\n \"15 del pomeriggio di domani\"\n (datetime 2",
"end": 14861,
"score": 0.6861318349838257,
"start": 14858,
"tag": "NAME",
"value": "dom"
},
{
"context": "14 12 :direction :before)\n\n \"da dopodomani\"\n \"da giovedì\"\n (datetime 2013 2 14 :direction :after)\n\n \"ne",
"end": 15332,
"score": 0.6397714614868164,
"start": 15326,
"tag": "NAME",
"value": "gioved"
},
{
"context": "45 0)\n\n \"10:30\"\n (datetime 2013 2 12 10 30)\n\n \"mattina\"\n \"mattinata\"\n \"mattino\"\n (datetime-interval [",
"end": 15644,
"score": 0.9994745254516602,
"start": 15637,
"tag": "NAME",
"value": "mattina"
},
{
"context": ":30\"\n (datetime 2013 2 12 10 30)\n\n \"mattina\"\n \"mattinata\"\n \"mattino\"\n (datetime-interval [2013 2 12 4] [",
"end": 15658,
"score": 0.9994786381721497,
"start": 15649,
"tag": "NAME",
"value": "mattinata"
},
{
"context": "me 2013 2 12 10 30)\n\n \"mattina\"\n \"mattinata\"\n \"mattino\"\n (datetime-interval [2013 2 12 4] [2013 2 12 12",
"end": 15670,
"score": 0.9983894228935242,
"start": 15663,
"tag": "NAME",
"value": "mattino"
},
{
"context": "tetime-interval [2013 2 12 4] [2013 2 12 12])\n\n \"prossimo lunedì\"\n (datetime 2013 2 25 :day-of-week 1)\n\n \"alle 1",
"end": 15742,
"score": 0.6079656481742859,
"start": 15727,
"tag": "NAME",
"value": "prossimo lunedì"
},
{
"context": "24\"\n \"a mezzanotte\"\n (datetime 2013 2 13 0)\n\n \"marzo\"\n \"in marzo\"\n (datetime 2013 3)\n)\n",
"end": 15903,
"score": 0.9975972771644592,
"start": 15898,
"tag": "NAME",
"value": "marzo"
}
] | resources/languages/it/corpus/time.clj | sebastianmika/duckling | 0 | (
; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30 0)}
"subito"
"immediatamente"
"in questo momento"
(datetime 2013 2 12 4 30 00)
"ora"
"di oggi"
"oggi"
"adesso"
"in giornata"
(datetime 2013 2 12)
"ieri"
(datetime 2013 2 11)
"domani"
(datetime 2013 2 13)
"Il giorno dopo domani"
"dopodomani"
(datetime 2013 2 14)
"Lunedì 18 febbraio"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"martedì"
"Martedì 19"
"ma 19"
(datetime 2013 2 19)
"l'altro ieri"
"altroieri"
(datetime 2013 2 10)
"lunedi"
"lu."
"lun"
(datetime 2013 2 18 :day-of-week 1)
"lunedi 18 febbraio"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"Martedì"
(datetime 2013 2 19 :day-of-week 2)
"Mercoledì"
"mer"
"mer."
(datetime 2013 2 13 :day-of-week 3)
"mercoledi 13 feb"
"il 13 febbraio"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2)
"il 13 febbraio 2013"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2 :year 2013)
"giovedi"
"gio"
(datetime 2013 2 14)
"venerdi"
"venerdì"
"ven"
(datetime 2013 2 15)
"sabato"
"sab"
"sab."
(datetime 2013 2 16)
"domenica"
"dom"
"dom."
(datetime 2013 2 17)
"domenica 10 febbraio"
(datetime 2013 2 10 :day-of-week 7 :day 13 :month 2) ; with current look-forward default...
"il 1 marzo"
"primo marzo"
"primo di marzo"
"il 1º marzo"
(datetime 2013 3 1 :day 1 :month 3)
"prima di marzo"
(datetime 2013 3)
"le idi di marzo"
"idi di marzo"
(datetime 2013 3 15 :month 3)
"3 marzo 2015"
"3/3/2015"
"3/3/15"
"2015-3-3"
"2015-03-03"
(datetime 2015 3 3 :day 3 :month 3 :year 2015)
"il 15 febbraio"
"15/2"
"il 15/02"
(datetime 2013 2 15 :day 15 :month 2)
"31/10/1974"
"31/10/74"
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"martedì scorso"
(datetime 2013 2 5 :day-of-week 2)
"martedì prossimo"
"il martedì dopo"
(datetime 2013 2 19 :day-of-week 2)
"mercoledì prossimo"
;"mercoledi fra una settimana"
(datetime 2013 2 20 :day-of-week 3)
"ottobre 2014"
(datetime 2014 10 :year 2014 :month 10)
;; Cycles
"l'ultima ora"
"nell'ultima ora"
(datetime 2013 2 12 3)
"questa settimana"
(datetime 2013 2 11 :grain :week)
"la settimana scorsa"
"la scorsa settimana"
"nella scorsa settimana"
"della settimana scorsa"
(datetime 2013 2 4 :grain :week)
"la settimana prossima"
"la prossima settimana"
"nella prossima settimana"
"settimana prossima"
"prossima settimana"
(datetime 2013 2 18 :grain :week)
"il mese scorso"
"nel mese scorso"
"nel mese passato"
"lo scorso mese"
"dello scorso mese"
(datetime 2013 1)
"il mese prossimo"
"il prossimo mese"
(datetime 2013 3)
"questo trimestre"
(datetime 2013 1 1 :grain :quarter)
"il prossimo trimestre"
"nel prossimo trimestre"
(datetime 2013 4 1 :grain :quarter)
"terzo trimestre"
"il terzo trimestre"
(datetime 2013 7 1 :grain :quarter)
"quarto trimestre 2018"
"il quarto trimestre 2018"
"del quarto trimestre 2018"
(datetime 2018 10 1 :grain :quarter)
"l'anno scorso"
(datetime 2012)
"quest'anno"
(datetime 2013)
"il prossimo anno"
(datetime 2014)
"ultima domenica"
;"domenica della scorsa settimana"
(datetime 2013 2 10 :day-of-week 7)
"lunedì di questa settimana"
(datetime 2013 2 11 :day-of-week 1)
"martedì di questa settimana"
(datetime 2013 2 12 :day-of-week 2)
"mercoledì di questa settimana"
(datetime 2013 2 13 :day-of-week 3)
"dopo domani alle 17"
"dopodomani alle 5 del pomeriggio"
(datetime 2013 2 14 17)
"ultimo lunedì di marzo"
(datetime 2013 3 25 :day-of-week 1)
"ultima domenica di marzo 2014"
(datetime 2014 3 30 :day-of-week 7)
"il terzo giorno di ottobre"
(datetime 2013 10 3)
"prima settimana di ottobre 2014"
(datetime 2014 10 6 :grain :week)
"la settimana del 6 ottobre"
"la settimana del 7 ott"
(datetime 2013 10 7 :grain :week)
"l'ultimo giorno di ottobre 2015"
"l'ultimo giorno dell'ottobre 2015"
(datetime 2015 10 31)
"l'ultima settimana di settembre 2014"
(datetime 2014 9 22 :grain :week)
;; nth of
"primo martedì di ottobre"
"primo martedì in ottobre"
"1° martedì del mese di ottobre"
"1º martedì del mese di ottobre"
(datetime 2013 10 1)
"terzo martedì di settembre 2014"
(datetime 2014 9 16)
"primo mercoledì di ottobre 2014"
(datetime 2014 10 1)
"secondo mercoledì di ottobre 2014"
(datetime 2014 10 8)
;; nth after
"terzo martedì dopo natale 2014"
(datetime 2015 1 13)
"il mese dopo natale 2015"
(datetime 2016 1)
;; Hours
"alle 3 di pomeriggio"
"le tre di pomeriggio"
"alle 3 del pomeriggio"
"le tre del pomeriggio"
(datetime 2013 2 12 15)
"circa alle 3 del pomeriggio" ;; FIXME pm overrides precision
(datetime 2013 2 12 15 :hour 3) ;; :precision "approximate"
"per le 15"
"verso le 15"
(datetime 2013 2 12 15) ;; :precision "approximate"
"verso sera"
(datetime-interval [2013 2 12 18] [2013 2 13 00]) ;; :precision "approximate"
"3:00"
"03:00"
(datetime 2013 2 13 3 0 :hour 3 :minute 0)
"15:15"
(datetime 2013 2 12 15 15 :hour 15 :minute 15)
"3:15 di pomeriggio"
"3:15 del pomeriggio"
"3 e un quarto di pomeriggio"
"tre e un quarto di pomeriggio"
(datetime 2013 2 12 15 15)
"alle tre e venti di pomeriggio"
"alle tre e venti del pomeriggio"
"3:20 di pomeriggio"
"3:20 del pomeriggio"
"15:20 del pomeriggio"
(datetime 2013 2 12 15 20)
"alle tre e venti"
"tre e 20"
"3 e 20"
"3:20"
"3 20"
(datetime 2013 2 13 3 20 :hour 3 :minute 20)
"15:30"
(datetime 2013 2 12 15 30 :hour 15 :minute 30)
"a mezzogiorno meno un quarto"
"mezzogiorno meno un quarto"
"un quarto a mezzogiorno"
"11:45 del mattino"
(datetime 2013 2 12 11 45 :hour 11 :minute 45)
"alle 3 del mattino"
(datetime 2013 2 13 3 :hour 3)
"alle 19:30 di venerdì 20 settembre"
"alle 19:30 venerdì 20 settembre"
"venerdì 20 settembre alle 19:30"
"il 20 settembre alle 19:30"
(datetime 2013 9 20 19 30 :hour 19 :minute 30 :day-of-week 5 :day 20 :month 9)
;; Involving periods ; look for grain-after-shift
"questo week-end"
"questo fine settimana"
"questo finesettimana"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"lunedi mattina"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
; Part of day (morning, afternoon...)
"15 febbraio al mattino"
"mattino di 15 febbraio"
(datetime-interval [2013 2 15 4] [2013 2 15 12])
"8 di stasera"
"8 della sera"
(datetime 2013 2 12 20)
;; Mixing date and time
"venerdì 20 settembre alle 7:30 del pomeriggio"
(datetime 2013 9 20 19 30 :hour 7 :minute 30 :meridiem :pm)
"alle 9 di sabato"
"sabato alle 9"
(datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am)
; Seasons
"quest'estate"
"questa estate"
"in estate"
(datetime-interval [2013 6 21] [2013 9 24])
"quest'inverno"
"questo inverno"
"in inverno"
(datetime-interval [2012 12 21] [2013 3 21])
"il prossimo autunno"
(datetime-interval [2014 9 23] [2014 12 22])
; IT holidays
"natale"
"il giorno di natale"
(datetime 2013 12 25)
"vigilia di natale"
"alla vigilia"
"la vigilia"
(datetime 2013 12 24)
"vigilia di capodanno"
"san silvestro"
(datetime 2013 12 31)
"notte di san silvestro"
(datetime-interval [2014 1 1 0] [2014 1 1 4])
"capodanno"
"primo dell'anno"
(datetime 2014 1 1)
"epifania"
"befana"
(datetime 2014 1 6)
"san valentino"
"festa degli innamorati"
(datetime 2013 2 14)
"festa del papà"
"festa del papa"
"festa di san giuseppe"
"san giuseppe"
(datetime 2013 3 19)
"anniversario della liberazione"
"la liberazione"
"alla liberazione"
(datetime 2013 4 25)
"festa del lavoro"
"festa dei lavoratori"
"giorno dei lavoratori"
"primo maggio"
(datetime 2013 5 1)
"festa della mamma"
(datetime 2013 5 12)
"festa della repubblica"
"la repubblica"
"repubblica"
(datetime 2013 6 2)
"ferragosto"
"assunzione"
(datetime 2013 8 15)
"halloween"
(datetime 2013 10 31)
"tutti i santi"
"ognissanti"
"festa dei santi"
"il giorno dei santi"
(datetime 2013 11 1)
"giorno dei morti"
"commemorazione dei defunti"
(datetime 2013 11 2)
"ai morti alle 2"
(datetime 2013 11 2 2)
"immacolata"
"immacolata concezione"
(datetime 2013 12 8)
"all'immacolata alle 18"
(datetime 2013 12 8 18)
"santo stefano"
(datetime 2013 12 26)
; Part of day (morning, afternoon...)
"questa sera"
"sta sera"
"stasera"
"in serata"
"nella sera"
(datetime-interval [2013 2 12 18] [2013 2 13 00])
"domani mattina"
"domattina"
(datetime-interval [2013 2 13 4] [2013 2 13 12])
"in settimana"
"per la settimana"
(datetime-interval [2013 2 12 4 30 00] [2013 2 18])
"stanotte"
(datetime-interval [2013 2 13 0] [2013 2 13 04])
"ultimo weekend"
(datetime-interval [2013 2 8 18] [2013 2 11 00])
"domani in serata"
"domani sera"
"nella serata di domani"
(datetime-interval [2013 2 13 18] [2013 2 14 00])
"domani notte"
"domani in nottata"
"nella nottata di domani"
"nella notte di domani"
(datetime-interval [2013 2 14 00] [2013 2 14 04])
"domani a pranzo"
(datetime-interval [2013 2 13 12] [2013 2 13 14])
"ieri sera"
(datetime-interval [2013 2 11 18] [2013 2 12 00])
"questo weekend"
"questo week-end"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"lunedì mattina"
"nella mattinata di lunedì"
"lunedì in mattinata"
"lunedì nella mattina"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
"il 15 febbraio in mattinata"
"mattina del 15 febbraio"
"15 febbraio mattina"
(datetime-interval [2013 2 15 4] [2013 2 15 12])
; Intervals involving cycles
"gli ultimi 2 secondi"
"gli ultimi due secondi"
"i 2 secondi passati"
"i due secondi passati"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"i prossimi 3 secondi"
"i prossimi tre secondi"
"nei prossimi tre secondi"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"gli ultimi 2 minuti"
"gli ultimi due minuti"
"i 2 minuti passati"
"i due minuti passati"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"i prossimi 3 minuti"
"nei prossimi 3 minuti"
"i prossimi tre minuti"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"le ultime 2 ore"
"le ultime due ore"
"nelle ultime due ore"
"le scorse due ore"
"le due ore scorse"
"le scorse 2 ore"
"le 2 ore scorse"
"nelle 2 ore scorse"
(datetime-interval [2013 2 12 2] [2013 2 12 4])
"le ultime 24 ore"
"le ultime ventiquattro ore"
"le 24 ore passate"
"nelle 24 ore scorse"
"le ventiquattro ore passate"
(datetime-interval [2013 2 11 4] [2013 2 12 4])
"le prossime 3 ore"
"le prossime tre ore"
"nelle prossime 3 ore"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"gli ultimi 2 giorni"
"gli ultimi due giorni"
"negli ultimi 2 giorni"
"i 2 giorni passati"
"i due giorni passati"
"nei due giorni passati"
"gli scorsi due giorni"
"i 2 giorni scorsi"
"i due giorni scorsi"
(datetime-interval [2013 2 10] [2013 2 12])
"i prossimi 3 giorni"
"i prossimi tre giorni"
"nei prossimi 3 giorni"
(datetime-interval [2013 2 13] [2013 2 16])
"i prossimi giorni"
"nei prossimi giorni"
(datetime-interval [2013 2 13] [2013 2 16])
"le ultime 2 settimane"
"le ultime due settimane"
"le 2 ultime settimane"
"le due ultime settimane"
"nelle 2 ultime settimane"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"le prossime 3 settimane"
"le prossime tre settimane"
"le 3 prossime settimane"
"nelle prossime 3 settimane"
"le tre prossime settimane"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"gli ultimi 2 mesi"
"gli ultimi due mesi"
"i 2 mesi passati"
"nei 2 mesi passati"
"i due mesi passati"
"i due mesi scorsi"
"i 2 mesi scorsi"
"negli scorsi due mesi"
"gli scorsi due mesi"
"gli scorsi 2 mesi"
(datetime-interval [2012 12] [2013 02])
"i prossimi 3 mesi"
"i prossimi tre mesi"
"i 3 prossimi mesi"
"i tre prossimi mesi"
"nei prossimi tre mesi"
(datetime-interval [2013 3] [2013 6])
"gli ultimi 2 anni"
"gli ultimi due anni"
"negli ultimi 2 anni"
"i 2 anni passati"
"i due anni passati"
"i 2 anni scorsi"
"i due anni scorsi"
"gli scorsi due anni"
"gli scorsi 2 anni"
(datetime-interval [2011] [2013])
"i prossimi 3 anni"
"i prossimi tre anni"
"nei tre prossimi anni"
(datetime-interval [2014] [2017])
; Explicit intervals
"13-15 luglio"
"dal 13 al 15 luglio"
"tra il 13 e il 15 luglio"
"tra 13 e 15 luglio"
"13 luglio - 15 luglio"
(datetime-interval [2013 7 13] [2013 7 16])
"8 ago - 12 ago"
(datetime-interval [2013 8 8] [2013 8 13])
"9:30 - 11:00"
(datetime-interval [2013 2 12 9 30] [2013 2 12 11 1])
"dalle 9:30 alle 11:00 di giovedì"
"tra le 9:30 e le 11:00 di giovedì"
"9:30 - 11:00 giovedì"
"giovedì dalle 9:30 alle 11:00"
"giovedì tra le 9:30 e le 11:00"
(datetime-interval [2013 2 14 9 30] [2013 2 14 11 1])
"dalle 9 alle 11 di giovedì"
"tra le 9 e le 11 di giovedì"
"9 - 11 giovedì"
"giovedì dalle nove alle undici"
"giovedì tra le nove e le undici"
(datetime-interval [2013 2 14 9] [2013 2 14 12])
"dalle tre all'una di giovedì"
(datetime-interval [2013 2 14 3] [2013 2 14 14])
"domani dalle 15:00 alle 17:00"
(datetime-interval [2013 2 13 15 00] [2013 2 13 17 01])
"11:30-13:30" ; go train this rule!
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
(datetime-interval [2013 2 12 11 30] [2013 2 12 13 31])
"13:30 di sabato 21 settembre"
"13:30 del 21 settembre"
(datetime 2013 9 21 13 30)
"in due settimane"
"per due settimane"
(datetime-interval [2013 2 12 4 30 0] [2013 2 26])
"fino alle 14:00"
(datetime-interval [2013 2 12 4 30 0] [2013 2 12 14 00])
"entro le 14:00"
(datetime 2013 2 12 14 0 :direction :before)
"entro la fine del mese"
(datetime 2013 3 :direction :before)
"entro la fine dell'anno"
(datetime 2014 :direction :before)
"fino alla fine del mese"
(datetime-interval [2013 2 12 4 30 0] [2013 3 1 0])
"fino alla fine dell'anno"
(datetime-interval [2013 2 12 4 30 0] [2014 1 1])
; Timezones
"4 CET"
(datetime 2013 2 12 4 :hour 4 :timezone "CET")
"16 CET"
(datetime 2013 2 12 16 :hour 16 :timezone "CET")
"giovedì alle 8:00 GMT"
(datetime 2013 2 14 8 00 :timezone "GMT")
;; Bookface tests
"domani alle 14"
(datetime 2013 2 13 14)
"alle 14"
"alle 2 del pomeriggio"
(datetime 2013 2 12 14)
"25/4 alle 16:00"
(datetime 2013 4 25 16 0)
"3 del pomeriggio di domani"
"15 del pomeriggio di domani"
(datetime 2013 2 13 15)
"dopo le 14"
"dalle 14"
(datetime 2013 2 12 14 :direction :after)
"domani dopo le 14"
"domani dalle 14"
(datetime 2013 2 13 14 :direction :after)
"prima delle 11"
(datetime 2013 2 12 11 :direction :before)
"dopodomani prima delle 11"
(datetime 2013 2 14 11 :direction :before)
"giovedì entro mezzogiorno"
(datetime 2013 2 14 12 :direction :before)
"da dopodomani"
"da giovedì"
(datetime 2013 2 14 :direction :after)
"nel pomeriggio"
(datetime-interval [2013 2 12 12] [2013 2 12 19])
"alle 13:30"
"13:30"
"1:30 del pomeriggio"
(datetime 2013 2 12 13 30)
"in 15 minuti"
"tra 15 minuti"
(datetime 2013 2 12 4 45 0)
"10:30"
(datetime 2013 2 12 10 30)
"mattina"
"mattinata"
"mattino"
(datetime-interval [2013 2 12 4] [2013 2 12 12])
"prossimo lunedì"
(datetime 2013 2 25 :day-of-week 1)
"alle 12"
"a mezzogiorno"
(datetime 2013 2 12 12)
"alle 24"
"a mezzanotte"
(datetime 2013 2 13 0)
"marzo"
"in marzo"
(datetime 2013 3)
)
| 67322 | (
; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30 0)}
"<NAME>"
"immediatamente"
"in questo momento"
(datetime 2013 2 12 4 30 00)
"ora"
"di oggi"
"oggi"
"adesso"
"in giornata"
(datetime 2013 2 12)
"<NAME>"
(datetime 2013 2 11)
"<NAME>"
(datetime 2013 2 13)
"Il giorno dopo <NAME>"
"<NAME>"
(datetime 2013 2 14)
"<NAME> 18 febbraio"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"<NAME>"
"<NAME> <NAME>"
"ma 19"
(datetime 2013 2 19)
"l'<NAME>"
"<NAME>"
(datetime 2013 2 10)
"<NAME>"
"lu."
"<NAME>"
(datetime 2013 2 18 :day-of-week 1)
"<NAME> 18 febbraio"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"<NAME>"
(datetime 2013 2 19 :day-of-week 2)
"<NAME>"
"<NAME>"
"mer."
(datetime 2013 2 13 :day-of-week 3)
"<NAME> 13 feb"
"il 13 febbraio"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2)
"il 13 febbraio 2013"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2 :year 2013)
"<NAME>"
"<NAME>"
(datetime 2013 2 14)
"<NAME>"
"<NAME>"
"<NAME>"
(datetime 2013 2 15)
"<NAME>"
"<NAME>"
"sab."
(datetime 2013 2 16)
"domenica"
"dom"
"dom."
(datetime 2013 2 17)
"domenica 10 febbraio"
(datetime 2013 2 10 :day-of-week 7 :day 13 :month 2) ; with current look-forward default...
"il 1 marzo"
"primo marzo"
"primo di marzo"
"il 1º marzo"
(datetime 2013 3 1 :day 1 :month 3)
"prima di marzo"
(datetime 2013 3)
"le idi di marzo"
"idi di marzo"
(datetime 2013 3 15 :month 3)
"3 marzo 2015"
"3/3/2015"
"3/3/15"
"2015-3-3"
"2015-03-03"
(datetime 2015 3 3 :day 3 :month 3 :year 2015)
"il 15 febbraio"
"15/2"
"il 15/02"
(datetime 2013 2 15 :day 15 :month 2)
"31/10/1974"
"31/10/74"
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"<NAME>"
(datetime 2013 2 5 :day-of-week 2)
"<NAME>"
"il martedì dopo"
(datetime 2013 2 19 :day-of-week 2)
"<NAME> prossimo"
;"mercoledi fra una settimana"
(datetime 2013 2 20 :day-of-week 3)
"ottobre 2014"
(datetime 2014 10 :year 2014 :month 10)
;; Cycles
"l'ultima ora"
"nell'ultima ora"
(datetime 2013 2 12 3)
"questa settimana"
(datetime 2013 2 11 :grain :week)
"la settimana scorsa"
"la scorsa settimana"
"nella scorsa settimana"
"della settimana scorsa"
(datetime 2013 2 4 :grain :week)
"la settimana prossima"
"la prossima settimana"
"nella prossima settimana"
"settimana prossima"
"prossima settimana"
(datetime 2013 2 18 :grain :week)
"il mese scorso"
"nel mese scorso"
"nel mese passato"
"lo scorso mese"
"dello scorso mese"
(datetime 2013 1)
"il mese prossimo"
"il prossimo mese"
(datetime 2013 3)
"questo trimestre"
(datetime 2013 1 1 :grain :quarter)
"il prossimo trimestre"
"nel prossimo trimestre"
(datetime 2013 4 1 :grain :quarter)
"terzo trimestre"
"il terzo trimestre"
(datetime 2013 7 1 :grain :quarter)
"quarto trimestre 2018"
"il quarto trimestre 2018"
"del quarto trimestre 2018"
(datetime 2018 10 1 :grain :quarter)
"l'anno scorso"
(datetime 2012)
"quest'anno"
(datetime 2013)
"il prossimo anno"
(datetime 2014)
"ultima domenica"
;"domenica della scorsa settimana"
(datetime 2013 2 10 :day-of-week 7)
"lunedì di questa settimana"
(datetime 2013 2 11 :day-of-week 1)
"martedì di questa settimana"
(datetime 2013 2 12 :day-of-week 2)
"mercoledì di questa settimana"
(datetime 2013 2 13 :day-of-week 3)
"dopo domani alle 17"
"dopodomani alle 5 del pomeriggio"
(datetime 2013 2 14 17)
"ultimo lunedì di marzo"
(datetime 2013 3 25 :day-of-week 1)
"ultima domenica di marzo 2014"
(datetime 2014 3 30 :day-of-week 7)
"il terzo giorno di ottobre"
(datetime 2013 10 3)
"prima settimana di ottobre 2014"
(datetime 2014 10 6 :grain :week)
"la settimana del 6 ottobre"
"la settimana del 7 ott"
(datetime 2013 10 7 :grain :week)
"l'ultimo giorno di ottobre 2015"
"l'ultimo giorno dell'ottobre 2015"
(datetime 2015 10 31)
"l'ultima settimana di settembre 2014"
(datetime 2014 9 22 :grain :week)
;; nth of
"primo martedì di ottobre"
"primo martedì in ottobre"
"1° martedì del mese di ottobre"
"1º martedì del mese di ottobre"
(datetime 2013 10 1)
"terzo martedì di settembre 2014"
(datetime 2014 9 16)
"primo mercoledì di ottobre 2014"
(datetime 2014 10 1)
"secondo mercoledì di ottobre 2014"
(datetime 2014 10 8)
;; nth after
"terzo martedì dopo natale 2014"
(datetime 2015 1 13)
"il mese dopo natale 2015"
(datetime 2016 1)
;; Hours
"alle 3 di pomeriggio"
"le tre di pomeriggio"
"alle 3 del pomeriggio"
"le tre del pomeriggio"
(datetime 2013 2 12 15)
"circa alle 3 del pomeriggio" ;; FIXME pm overrides precision
(datetime 2013 2 12 15 :hour 3) ;; :precision "approximate"
"per le 15"
"verso le 15"
(datetime 2013 2 12 15) ;; :precision "approximate"
"verso sera"
(datetime-interval [2013 2 12 18] [2013 2 13 00]) ;; :precision "approximate"
"3:00"
"03:00"
(datetime 2013 2 13 3 0 :hour 3 :minute 0)
"15:15"
(datetime 2013 2 12 15 15 :hour 15 :minute 15)
"3:15 di pomeriggio"
"3:15 del pomeriggio"
"3 e un quarto di pomeriggio"
"tre e un quarto di pomeriggio"
(datetime 2013 2 12 15 15)
"alle tre e venti di pomeriggio"
"alle tre e venti del pomeriggio"
"3:20 di pomeriggio"
"3:20 del pomeriggio"
"15:20 del pomeriggio"
(datetime 2013 2 12 15 20)
"alle tre e venti"
"tre e 20"
"3 e 20"
"3:20"
"3 20"
(datetime 2013 2 13 3 20 :hour 3 :minute 20)
"15:30"
(datetime 2013 2 12 15 30 :hour 15 :minute 30)
"a mezzogiorno meno un quarto"
"mezzogiorno meno un quarto"
"un quarto a mezzogiorno"
"11:45 del mattino"
(datetime 2013 2 12 11 45 :hour 11 :minute 45)
"alle 3 del mattino"
(datetime 2013 2 13 3 :hour 3)
"alle 19:30 di venerdì 20 settembre"
"alle 19:30 venerdì 20 settembre"
"venerdì 20 settembre alle 19:30"
"il 20 settembre alle 19:30"
(datetime 2013 9 20 19 30 :hour 19 :minute 30 :day-of-week 5 :day 20 :month 9)
;; Involving periods ; look for grain-after-shift
"questo week-end"
"questo fine settimana"
"questo finesettimana"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"lunedi mattina"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
; Part of day (morning, afternoon...)
"15 febbraio al mattino"
"mattino di 15 febbraio"
(datetime-interval [2013 2 15 4] [2013 2 15 12])
"8 di stasera"
"8 della sera"
(datetime 2013 2 12 20)
;; Mixing date and time
"venerdì 20 settembre alle 7:30 del pomeriggio"
(datetime 2013 9 20 19 30 :hour 7 :minute 30 :meridiem :pm)
"alle 9 di sabato"
"sabato alle 9"
(datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am)
; Seasons
"quest'estate"
"questa estate"
"in estate"
(datetime-interval [2013 6 21] [2013 9 24])
"quest'inverno"
"questo inverno"
"in inverno"
(datetime-interval [2012 12 21] [2013 3 21])
"il prossimo autunno"
(datetime-interval [2014 9 23] [2014 12 22])
; IT holidays
"natale"
"il giorno di natale"
(datetime 2013 12 25)
"vigilia di natale"
"alla vigilia"
"la vigilia"
(datetime 2013 12 24)
"vigilia di capodanno"
"san silvestro"
(datetime 2013 12 31)
"notte di san silvestro"
(datetime-interval [2014 1 1 0] [2014 1 1 4])
"capodanno"
"primo dell'anno"
(datetime 2014 1 1)
"epifania"
"befana"
(datetime 2014 1 6)
"san valentino"
"festa degli innamorati"
(datetime 2013 2 14)
"festa del papà"
"festa del papa"
"festa di san giuseppe"
"san giuseppe"
(datetime 2013 3 19)
"anniversario della liberazione"
"la liberazione"
"alla liberazione"
(datetime 2013 4 25)
"festa del lavoro"
"festa dei lavoratori"
"giorno dei lavoratori"
"primo maggio"
(datetime 2013 5 1)
"festa della mamma"
(datetime 2013 5 12)
"festa della repubblica"
"la repubblica"
"repubblica"
(datetime 2013 6 2)
"ferragosto"
"assunzione"
(datetime 2013 8 15)
"halloween"
(datetime 2013 10 31)
"tutti i santi"
"ognissanti"
"festa dei santi"
"il giorno dei santi"
(datetime 2013 11 1)
"giorno dei morti"
"commemorazione dei defunti"
(datetime 2013 11 2)
"ai morti alle 2"
(datetime 2013 11 2 2)
"immacolata"
"immacolata concezione"
(datetime 2013 12 8)
"all'immacolata alle 18"
(datetime 2013 12 8 18)
"<NAME>"
(datetime 2013 12 26)
; Part of day (morning, afternoon...)
"questa sera"
"sta sera"
"stasera"
"in serata"
"nella sera"
(datetime-interval [2013 2 12 18] [2013 2 13 00])
"<NAME>"
"<NAME>"
(datetime-interval [2013 2 13 4] [2013 2 13 12])
"in settimana"
"per la settimana"
(datetime-interval [2013 2 12 4 30 00] [2013 2 18])
"<NAME>"
(datetime-interval [2013 2 13 0] [2013 2 13 04])
"ultimo weekend"
(datetime-interval [2013 2 8 18] [2013 2 11 00])
"domani in serata"
"domani sera"
"nella serata di domani"
(datetime-interval [2013 2 13 18] [2013 2 14 00])
"<NAME> not<NAME>"
"domani in nottata"
"nella nottata di <NAME>"
"nella notte di domani"
(datetime-interval [2013 2 14 00] [2013 2 14 04])
"<NAME> a pr<NAME>"
(datetime-interval [2013 2 13 12] [2013 2 13 14])
"<NAME>"
(datetime-interval [2013 2 11 18] [2013 2 12 00])
"questo weekend"
"questo week-end"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"lunedì mattina"
"nella mattinata di lunedì"
"lunedì in mattinata"
"lunedì nella mattina"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
"il 15 febbraio in mattinata"
"mattina del 15 febbraio"
"15 febbraio mattina"
(datetime-interval [2013 2 15 4] [2013 2 15 12])
; Intervals involving cycles
"gli ultimi 2 secondi"
"gli ultimi due secondi"
"i 2 secondi passati"
"i due secondi passati"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"i prossimi 3 secondi"
"i prossimi tre secondi"
"nei prossimi tre secondi"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"gli ultimi 2 minuti"
"gli ultimi due minuti"
"i 2 minuti passati"
"i due minuti passati"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"i prossimi 3 minuti"
"nei prossimi 3 minuti"
"i prossimi tre minuti"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"le ultime 2 ore"
"le ultime due ore"
"nelle ultime due ore"
"le scorse due ore"
"le due ore scorse"
"le scorse 2 ore"
"le 2 ore scorse"
"nelle 2 ore scorse"
(datetime-interval [2013 2 12 2] [2013 2 12 4])
"le ultime 24 ore"
"le ultime ventiquattro ore"
"le 24 ore passate"
"nelle 24 ore scorse"
"le ventiquattro ore passate"
(datetime-interval [2013 2 11 4] [2013 2 12 4])
"le prossime 3 ore"
"le prossime tre ore"
"nelle prossime 3 ore"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"gli ultimi 2 giorni"
"gli ultimi due giorni"
"negli ultimi 2 giorni"
"i 2 giorni passati"
"i due giorni passati"
"nei due giorni passati"
"gli scorsi due giorni"
"i 2 giorni scorsi"
"i due giorni scorsi"
(datetime-interval [2013 2 10] [2013 2 12])
"i prossimi 3 giorni"
"i prossimi tre giorni"
"nei prossimi 3 giorni"
(datetime-interval [2013 2 13] [2013 2 16])
"i prossimi giorni"
"nei prossimi giorni"
(datetime-interval [2013 2 13] [2013 2 16])
"le ultime 2 settimane"
"le ultime due settimane"
"le 2 ultime settimane"
"le due ultime settimane"
"nelle 2 ultime settimane"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"le prossime 3 settimane"
"le prossime tre settimane"
"le 3 prossime settimane"
"nelle prossime 3 settimane"
"le tre prossime settimane"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"gli ultimi 2 mesi"
"gli ultimi due mesi"
"i 2 mesi passati"
"nei 2 mesi passati"
"i due mesi passati"
"i due mesi scorsi"
"i 2 mesi scorsi"
"negli scorsi due mesi"
"gli scorsi due mesi"
"gli scorsi 2 mesi"
(datetime-interval [2012 12] [2013 02])
"i prossimi 3 mesi"
"i prossimi tre mesi"
"i 3 prossimi mesi"
"i tre prossimi mesi"
"nei prossimi tre mesi"
(datetime-interval [2013 3] [2013 6])
"gli ultimi 2 anni"
"gli ultimi due anni"
"negli ultimi 2 anni"
"i 2 anni passati"
"i due anni passati"
"i 2 anni scorsi"
"i due anni scorsi"
"gli scorsi due anni"
"gli scorsi 2 anni"
(datetime-interval [2011] [2013])
"i prossimi 3 anni"
"i prossimi tre anni"
"nei tre prossimi anni"
(datetime-interval [2014] [2017])
; Explicit intervals
"13-15 luglio"
"dal 13 al 15 luglio"
"tra il 13 e il 15 luglio"
"tra 13 e 15 luglio"
"13 luglio - 15 luglio"
(datetime-interval [2013 7 13] [2013 7 16])
"8 ago - 12 ago"
(datetime-interval [2013 8 8] [2013 8 13])
"9:30 - 11:00"
(datetime-interval [2013 2 12 9 30] [2013 2 12 11 1])
"dalle 9:30 alle 11:00 di giovedì"
"tra le 9:30 e le 11:00 di giovedì"
"9:30 - 11:00 giovedì"
"giovedì dalle 9:30 alle 11:00"
"giovedì tra le 9:30 e le 11:00"
(datetime-interval [2013 2 14 9 30] [2013 2 14 11 1])
"dalle 9 alle 11 di giovedì"
"tra le 9 e le 11 di giovedì"
"9 - 11 giovedì"
"giovedì dalle nove alle undici"
"giovedì tra le nove e le undici"
(datetime-interval [2013 2 14 9] [2013 2 14 12])
"dalle tre all'una di giovedì"
(datetime-interval [2013 2 14 3] [2013 2 14 14])
"domani dalle 15:00 alle 17:00"
(datetime-interval [2013 2 13 15 00] [2013 2 13 17 01])
"11:30-13:30" ; go train this rule!
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
(datetime-interval [2013 2 12 11 30] [2013 2 12 13 31])
"13:30 di sabato 21 settembre"
"13:30 del 21 settembre"
(datetime 2013 9 21 13 30)
"in due settimane"
"per due settimane"
(datetime-interval [2013 2 12 4 30 0] [2013 2 26])
"fino alle 14:00"
(datetime-interval [2013 2 12 4 30 0] [2013 2 12 14 00])
"entro le 14:00"
(datetime 2013 2 12 14 0 :direction :before)
"entro la fine del mese"
(datetime 2013 3 :direction :before)
"entro la fine dell'anno"
(datetime 2014 :direction :before)
"fino alla fine del mese"
(datetime-interval [2013 2 12 4 30 0] [2013 3 1 0])
"fino alla fine dell'anno"
(datetime-interval [2013 2 12 4 30 0] [2014 1 1])
; Timezones
"4 CET"
(datetime 2013 2 12 4 :hour 4 :timezone "CET")
"16 CET"
(datetime 2013 2 12 16 :hour 16 :timezone "CET")
"giovedì alle 8:00 GMT"
(datetime 2013 2 14 8 00 :timezone "GMT")
;; Bookface tests
"domani alle 14"
(datetime 2013 2 13 14)
"alle 14"
"alle 2 del pomeriggio"
(datetime 2013 2 12 14)
"25/4 alle 16:00"
(datetime 2013 4 25 16 0)
"3 del pomeriggio di <NAME>ani"
"15 del pomeriggio di domani"
(datetime 2013 2 13 15)
"dopo le 14"
"dalle 14"
(datetime 2013 2 12 14 :direction :after)
"domani dopo le 14"
"domani dalle 14"
(datetime 2013 2 13 14 :direction :after)
"prima delle 11"
(datetime 2013 2 12 11 :direction :before)
"dopodomani prima delle 11"
(datetime 2013 2 14 11 :direction :before)
"giovedì entro mezzogiorno"
(datetime 2013 2 14 12 :direction :before)
"da dopodomani"
"da <NAME>ì"
(datetime 2013 2 14 :direction :after)
"nel pomeriggio"
(datetime-interval [2013 2 12 12] [2013 2 12 19])
"alle 13:30"
"13:30"
"1:30 del pomeriggio"
(datetime 2013 2 12 13 30)
"in 15 minuti"
"tra 15 minuti"
(datetime 2013 2 12 4 45 0)
"10:30"
(datetime 2013 2 12 10 30)
"<NAME>"
"<NAME>"
"<NAME>"
(datetime-interval [2013 2 12 4] [2013 2 12 12])
"<NAME>"
(datetime 2013 2 25 :day-of-week 1)
"alle 12"
"a mezzogiorno"
(datetime 2013 2 12 12)
"alle 24"
"a mezzanotte"
(datetime 2013 2 13 0)
"<NAME>"
"in marzo"
(datetime 2013 3)
)
| true | (
; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30 0)}
"PI:NAME:<NAME>END_PI"
"immediatamente"
"in questo momento"
(datetime 2013 2 12 4 30 00)
"ora"
"di oggi"
"oggi"
"adesso"
"in giornata"
(datetime 2013 2 12)
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 11)
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 13)
"Il giorno dopo PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 14)
"PI:NAME:<NAME>END_PI 18 febbraio"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
"ma 19"
(datetime 2013 2 19)
"l'PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 10)
"PI:NAME:<NAME>END_PI"
"lu."
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 18 :day-of-week 1)
"PI:NAME:<NAME>END_PI 18 febbraio"
(datetime 2013 2 18 :day-of-week 1 :day 18 :month 2)
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 19 :day-of-week 2)
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"mer."
(datetime 2013 2 13 :day-of-week 3)
"PI:NAME:<NAME>END_PI 13 feb"
"il 13 febbraio"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2)
"il 13 febbraio 2013"
(datetime 2013 2 13 :day-of-week 3 :day 13 :month 2 :year 2013)
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 14)
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 15)
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"sab."
(datetime 2013 2 16)
"domenica"
"dom"
"dom."
(datetime 2013 2 17)
"domenica 10 febbraio"
(datetime 2013 2 10 :day-of-week 7 :day 13 :month 2) ; with current look-forward default...
"il 1 marzo"
"primo marzo"
"primo di marzo"
"il 1º marzo"
(datetime 2013 3 1 :day 1 :month 3)
"prima di marzo"
(datetime 2013 3)
"le idi di marzo"
"idi di marzo"
(datetime 2013 3 15 :month 3)
"3 marzo 2015"
"3/3/2015"
"3/3/15"
"2015-3-3"
"2015-03-03"
(datetime 2015 3 3 :day 3 :month 3 :year 2015)
"il 15 febbraio"
"15/2"
"il 15/02"
(datetime 2013 2 15 :day 15 :month 2)
"31/10/1974"
"31/10/74"
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 5 :day-of-week 2)
"PI:NAME:<NAME>END_PI"
"il martedì dopo"
(datetime 2013 2 19 :day-of-week 2)
"PI:NAME:<NAME>END_PI prossimo"
;"mercoledi fra una settimana"
(datetime 2013 2 20 :day-of-week 3)
"ottobre 2014"
(datetime 2014 10 :year 2014 :month 10)
;; Cycles
"l'ultima ora"
"nell'ultima ora"
(datetime 2013 2 12 3)
"questa settimana"
(datetime 2013 2 11 :grain :week)
"la settimana scorsa"
"la scorsa settimana"
"nella scorsa settimana"
"della settimana scorsa"
(datetime 2013 2 4 :grain :week)
"la settimana prossima"
"la prossima settimana"
"nella prossima settimana"
"settimana prossima"
"prossima settimana"
(datetime 2013 2 18 :grain :week)
"il mese scorso"
"nel mese scorso"
"nel mese passato"
"lo scorso mese"
"dello scorso mese"
(datetime 2013 1)
"il mese prossimo"
"il prossimo mese"
(datetime 2013 3)
"questo trimestre"
(datetime 2013 1 1 :grain :quarter)
"il prossimo trimestre"
"nel prossimo trimestre"
(datetime 2013 4 1 :grain :quarter)
"terzo trimestre"
"il terzo trimestre"
(datetime 2013 7 1 :grain :quarter)
"quarto trimestre 2018"
"il quarto trimestre 2018"
"del quarto trimestre 2018"
(datetime 2018 10 1 :grain :quarter)
"l'anno scorso"
(datetime 2012)
"quest'anno"
(datetime 2013)
"il prossimo anno"
(datetime 2014)
"ultima domenica"
;"domenica della scorsa settimana"
(datetime 2013 2 10 :day-of-week 7)
"lunedì di questa settimana"
(datetime 2013 2 11 :day-of-week 1)
"martedì di questa settimana"
(datetime 2013 2 12 :day-of-week 2)
"mercoledì di questa settimana"
(datetime 2013 2 13 :day-of-week 3)
"dopo domani alle 17"
"dopodomani alle 5 del pomeriggio"
(datetime 2013 2 14 17)
"ultimo lunedì di marzo"
(datetime 2013 3 25 :day-of-week 1)
"ultima domenica di marzo 2014"
(datetime 2014 3 30 :day-of-week 7)
"il terzo giorno di ottobre"
(datetime 2013 10 3)
"prima settimana di ottobre 2014"
(datetime 2014 10 6 :grain :week)
"la settimana del 6 ottobre"
"la settimana del 7 ott"
(datetime 2013 10 7 :grain :week)
"l'ultimo giorno di ottobre 2015"
"l'ultimo giorno dell'ottobre 2015"
(datetime 2015 10 31)
"l'ultima settimana di settembre 2014"
(datetime 2014 9 22 :grain :week)
;; nth of
"primo martedì di ottobre"
"primo martedì in ottobre"
"1° martedì del mese di ottobre"
"1º martedì del mese di ottobre"
(datetime 2013 10 1)
"terzo martedì di settembre 2014"
(datetime 2014 9 16)
"primo mercoledì di ottobre 2014"
(datetime 2014 10 1)
"secondo mercoledì di ottobre 2014"
(datetime 2014 10 8)
;; nth after
"terzo martedì dopo natale 2014"
(datetime 2015 1 13)
"il mese dopo natale 2015"
(datetime 2016 1)
;; Hours
"alle 3 di pomeriggio"
"le tre di pomeriggio"
"alle 3 del pomeriggio"
"le tre del pomeriggio"
(datetime 2013 2 12 15)
"circa alle 3 del pomeriggio" ;; FIXME pm overrides precision
(datetime 2013 2 12 15 :hour 3) ;; :precision "approximate"
"per le 15"
"verso le 15"
(datetime 2013 2 12 15) ;; :precision "approximate"
"verso sera"
(datetime-interval [2013 2 12 18] [2013 2 13 00]) ;; :precision "approximate"
"3:00"
"03:00"
(datetime 2013 2 13 3 0 :hour 3 :minute 0)
"15:15"
(datetime 2013 2 12 15 15 :hour 15 :minute 15)
"3:15 di pomeriggio"
"3:15 del pomeriggio"
"3 e un quarto di pomeriggio"
"tre e un quarto di pomeriggio"
(datetime 2013 2 12 15 15)
"alle tre e venti di pomeriggio"
"alle tre e venti del pomeriggio"
"3:20 di pomeriggio"
"3:20 del pomeriggio"
"15:20 del pomeriggio"
(datetime 2013 2 12 15 20)
"alle tre e venti"
"tre e 20"
"3 e 20"
"3:20"
"3 20"
(datetime 2013 2 13 3 20 :hour 3 :minute 20)
"15:30"
(datetime 2013 2 12 15 30 :hour 15 :minute 30)
"a mezzogiorno meno un quarto"
"mezzogiorno meno un quarto"
"un quarto a mezzogiorno"
"11:45 del mattino"
(datetime 2013 2 12 11 45 :hour 11 :minute 45)
"alle 3 del mattino"
(datetime 2013 2 13 3 :hour 3)
"alle 19:30 di venerdì 20 settembre"
"alle 19:30 venerdì 20 settembre"
"venerdì 20 settembre alle 19:30"
"il 20 settembre alle 19:30"
(datetime 2013 9 20 19 30 :hour 19 :minute 30 :day-of-week 5 :day 20 :month 9)
;; Involving periods ; look for grain-after-shift
"questo week-end"
"questo fine settimana"
"questo finesettimana"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"lunedi mattina"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
; Part of day (morning, afternoon...)
"15 febbraio al mattino"
"mattino di 15 febbraio"
(datetime-interval [2013 2 15 4] [2013 2 15 12])
"8 di stasera"
"8 della sera"
(datetime 2013 2 12 20)
;; Mixing date and time
"venerdì 20 settembre alle 7:30 del pomeriggio"
(datetime 2013 9 20 19 30 :hour 7 :minute 30 :meridiem :pm)
"alle 9 di sabato"
"sabato alle 9"
(datetime 2013 2 16 9 :day-of-week 6 :hour 9 :meridiem :am)
; Seasons
"quest'estate"
"questa estate"
"in estate"
(datetime-interval [2013 6 21] [2013 9 24])
"quest'inverno"
"questo inverno"
"in inverno"
(datetime-interval [2012 12 21] [2013 3 21])
"il prossimo autunno"
(datetime-interval [2014 9 23] [2014 12 22])
; IT holidays
"natale"
"il giorno di natale"
(datetime 2013 12 25)
"vigilia di natale"
"alla vigilia"
"la vigilia"
(datetime 2013 12 24)
"vigilia di capodanno"
"san silvestro"
(datetime 2013 12 31)
"notte di san silvestro"
(datetime-interval [2014 1 1 0] [2014 1 1 4])
"capodanno"
"primo dell'anno"
(datetime 2014 1 1)
"epifania"
"befana"
(datetime 2014 1 6)
"san valentino"
"festa degli innamorati"
(datetime 2013 2 14)
"festa del papà"
"festa del papa"
"festa di san giuseppe"
"san giuseppe"
(datetime 2013 3 19)
"anniversario della liberazione"
"la liberazione"
"alla liberazione"
(datetime 2013 4 25)
"festa del lavoro"
"festa dei lavoratori"
"giorno dei lavoratori"
"primo maggio"
(datetime 2013 5 1)
"festa della mamma"
(datetime 2013 5 12)
"festa della repubblica"
"la repubblica"
"repubblica"
(datetime 2013 6 2)
"ferragosto"
"assunzione"
(datetime 2013 8 15)
"halloween"
(datetime 2013 10 31)
"tutti i santi"
"ognissanti"
"festa dei santi"
"il giorno dei santi"
(datetime 2013 11 1)
"giorno dei morti"
"commemorazione dei defunti"
(datetime 2013 11 2)
"ai morti alle 2"
(datetime 2013 11 2 2)
"immacolata"
"immacolata concezione"
(datetime 2013 12 8)
"all'immacolata alle 18"
(datetime 2013 12 8 18)
"PI:NAME:<NAME>END_PI"
(datetime 2013 12 26)
; Part of day (morning, afternoon...)
"questa sera"
"sta sera"
"stasera"
"in serata"
"nella sera"
(datetime-interval [2013 2 12 18] [2013 2 13 00])
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
(datetime-interval [2013 2 13 4] [2013 2 13 12])
"in settimana"
"per la settimana"
(datetime-interval [2013 2 12 4 30 00] [2013 2 18])
"PI:NAME:<NAME>END_PI"
(datetime-interval [2013 2 13 0] [2013 2 13 04])
"ultimo weekend"
(datetime-interval [2013 2 8 18] [2013 2 11 00])
"domani in serata"
"domani sera"
"nella serata di domani"
(datetime-interval [2013 2 13 18] [2013 2 14 00])
"PI:NAME:<NAME>END_PI notPI:NAME:<NAME>END_PI"
"domani in nottata"
"nella nottata di PI:NAME:<NAME>END_PI"
"nella notte di domani"
(datetime-interval [2013 2 14 00] [2013 2 14 04])
"PI:NAME:<NAME>END_PI a prPI:NAME:<NAME>END_PI"
(datetime-interval [2013 2 13 12] [2013 2 13 14])
"PI:NAME:<NAME>END_PI"
(datetime-interval [2013 2 11 18] [2013 2 12 00])
"questo weekend"
"questo week-end"
(datetime-interval [2013 2 15 18] [2013 2 18 00])
"lunedì mattina"
"nella mattinata di lunedì"
"lunedì in mattinata"
"lunedì nella mattina"
(datetime-interval [2013 2 18 4] [2013 2 18 12])
"il 15 febbraio in mattinata"
"mattina del 15 febbraio"
"15 febbraio mattina"
(datetime-interval [2013 2 15 4] [2013 2 15 12])
; Intervals involving cycles
"gli ultimi 2 secondi"
"gli ultimi due secondi"
"i 2 secondi passati"
"i due secondi passati"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"i prossimi 3 secondi"
"i prossimi tre secondi"
"nei prossimi tre secondi"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"gli ultimi 2 minuti"
"gli ultimi due minuti"
"i 2 minuti passati"
"i due minuti passati"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"i prossimi 3 minuti"
"nei prossimi 3 minuti"
"i prossimi tre minuti"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"le ultime 2 ore"
"le ultime due ore"
"nelle ultime due ore"
"le scorse due ore"
"le due ore scorse"
"le scorse 2 ore"
"le 2 ore scorse"
"nelle 2 ore scorse"
(datetime-interval [2013 2 12 2] [2013 2 12 4])
"le ultime 24 ore"
"le ultime ventiquattro ore"
"le 24 ore passate"
"nelle 24 ore scorse"
"le ventiquattro ore passate"
(datetime-interval [2013 2 11 4] [2013 2 12 4])
"le prossime 3 ore"
"le prossime tre ore"
"nelle prossime 3 ore"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"gli ultimi 2 giorni"
"gli ultimi due giorni"
"negli ultimi 2 giorni"
"i 2 giorni passati"
"i due giorni passati"
"nei due giorni passati"
"gli scorsi due giorni"
"i 2 giorni scorsi"
"i due giorni scorsi"
(datetime-interval [2013 2 10] [2013 2 12])
"i prossimi 3 giorni"
"i prossimi tre giorni"
"nei prossimi 3 giorni"
(datetime-interval [2013 2 13] [2013 2 16])
"i prossimi giorni"
"nei prossimi giorni"
(datetime-interval [2013 2 13] [2013 2 16])
"le ultime 2 settimane"
"le ultime due settimane"
"le 2 ultime settimane"
"le due ultime settimane"
"nelle 2 ultime settimane"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"le prossime 3 settimane"
"le prossime tre settimane"
"le 3 prossime settimane"
"nelle prossime 3 settimane"
"le tre prossime settimane"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"gli ultimi 2 mesi"
"gli ultimi due mesi"
"i 2 mesi passati"
"nei 2 mesi passati"
"i due mesi passati"
"i due mesi scorsi"
"i 2 mesi scorsi"
"negli scorsi due mesi"
"gli scorsi due mesi"
"gli scorsi 2 mesi"
(datetime-interval [2012 12] [2013 02])
"i prossimi 3 mesi"
"i prossimi tre mesi"
"i 3 prossimi mesi"
"i tre prossimi mesi"
"nei prossimi tre mesi"
(datetime-interval [2013 3] [2013 6])
"gli ultimi 2 anni"
"gli ultimi due anni"
"negli ultimi 2 anni"
"i 2 anni passati"
"i due anni passati"
"i 2 anni scorsi"
"i due anni scorsi"
"gli scorsi due anni"
"gli scorsi 2 anni"
(datetime-interval [2011] [2013])
"i prossimi 3 anni"
"i prossimi tre anni"
"nei tre prossimi anni"
(datetime-interval [2014] [2017])
; Explicit intervals
"13-15 luglio"
"dal 13 al 15 luglio"
"tra il 13 e il 15 luglio"
"tra 13 e 15 luglio"
"13 luglio - 15 luglio"
(datetime-interval [2013 7 13] [2013 7 16])
"8 ago - 12 ago"
(datetime-interval [2013 8 8] [2013 8 13])
"9:30 - 11:00"
(datetime-interval [2013 2 12 9 30] [2013 2 12 11 1])
"dalle 9:30 alle 11:00 di giovedì"
"tra le 9:30 e le 11:00 di giovedì"
"9:30 - 11:00 giovedì"
"giovedì dalle 9:30 alle 11:00"
"giovedì tra le 9:30 e le 11:00"
(datetime-interval [2013 2 14 9 30] [2013 2 14 11 1])
"dalle 9 alle 11 di giovedì"
"tra le 9 e le 11 di giovedì"
"9 - 11 giovedì"
"giovedì dalle nove alle undici"
"giovedì tra le nove e le undici"
(datetime-interval [2013 2 14 9] [2013 2 14 12])
"dalle tre all'una di giovedì"
(datetime-interval [2013 2 14 3] [2013 2 14 14])
"domani dalle 15:00 alle 17:00"
(datetime-interval [2013 2 13 15 00] [2013 2 13 17 01])
"11:30-13:30" ; go train this rule!
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
"11:30-13:30"
(datetime-interval [2013 2 12 11 30] [2013 2 12 13 31])
"13:30 di sabato 21 settembre"
"13:30 del 21 settembre"
(datetime 2013 9 21 13 30)
"in due settimane"
"per due settimane"
(datetime-interval [2013 2 12 4 30 0] [2013 2 26])
"fino alle 14:00"
(datetime-interval [2013 2 12 4 30 0] [2013 2 12 14 00])
"entro le 14:00"
(datetime 2013 2 12 14 0 :direction :before)
"entro la fine del mese"
(datetime 2013 3 :direction :before)
"entro la fine dell'anno"
(datetime 2014 :direction :before)
"fino alla fine del mese"
(datetime-interval [2013 2 12 4 30 0] [2013 3 1 0])
"fino alla fine dell'anno"
(datetime-interval [2013 2 12 4 30 0] [2014 1 1])
; Timezones
"4 CET"
(datetime 2013 2 12 4 :hour 4 :timezone "CET")
"16 CET"
(datetime 2013 2 12 16 :hour 16 :timezone "CET")
"giovedì alle 8:00 GMT"
(datetime 2013 2 14 8 00 :timezone "GMT")
;; Bookface tests
"domani alle 14"
(datetime 2013 2 13 14)
"alle 14"
"alle 2 del pomeriggio"
(datetime 2013 2 12 14)
"25/4 alle 16:00"
(datetime 2013 4 25 16 0)
"3 del pomeriggio di PI:NAME:<NAME>END_PIani"
"15 del pomeriggio di domani"
(datetime 2013 2 13 15)
"dopo le 14"
"dalle 14"
(datetime 2013 2 12 14 :direction :after)
"domani dopo le 14"
"domani dalle 14"
(datetime 2013 2 13 14 :direction :after)
"prima delle 11"
(datetime 2013 2 12 11 :direction :before)
"dopodomani prima delle 11"
(datetime 2013 2 14 11 :direction :before)
"giovedì entro mezzogiorno"
(datetime 2013 2 14 12 :direction :before)
"da dopodomani"
"da PI:NAME:<NAME>END_PIì"
(datetime 2013 2 14 :direction :after)
"nel pomeriggio"
(datetime-interval [2013 2 12 12] [2013 2 12 19])
"alle 13:30"
"13:30"
"1:30 del pomeriggio"
(datetime 2013 2 12 13 30)
"in 15 minuti"
"tra 15 minuti"
(datetime 2013 2 12 4 45 0)
"10:30"
(datetime 2013 2 12 10 30)
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
(datetime-interval [2013 2 12 4] [2013 2 12 12])
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 25 :day-of-week 1)
"alle 12"
"a mezzogiorno"
(datetime 2013 2 12 12)
"alle 24"
"a mezzanotte"
(datetime 2013 2 13 0)
"PI:NAME:<NAME>END_PI"
"in marzo"
(datetime 2013 3)
)
|
[
{
"context": "ibility\\\":\\\"missing-required-key\\\",\\\"password\\\":\\\"missing-required-key\\\"}}\"))\n\n (fact \"visibility must be valid\"\n ",
"end": 2235,
"score": 0.9834877848625183,
"start": 2215,
"tag": "PASSWORD",
"value": "missing-required-key"
},
{
"context": " (str \"/page/save_settings/\" page-id) {:password \"secret\" :tags [\"tag\" \"another tag\"] :visibility \"passwor",
"end": 3647,
"score": 0.9985936284065247,
"start": 3641,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": " (str \"/page/save_settings/\" page-id) {:password \"secret\" :tags [] :visibility \"password\"})) => 200\n\n ",
"end": 4263,
"score": 0.9940410256385803,
"start": 4257,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": " (str \"/page/save_settings/\" page-id) {:password \"not-saved\" :tags [] :visibility \"private\"}))\n (",
"end": 4412,
"score": 0.9994401335716248,
"start": 4403,
"tag": "PASSWORD",
"value": "not-saved"
}
] | test_old/clj/salava/page/settings_test.clj | Vilikkki/salava | 17 | (ns salava.page.settings-test
(:require [midje.sweet :refer :all]
[salava.core.migrator :as migrator]
[salava.test-utils :refer [test-api-request login! logout! test-user-credentials]]
[salava.core.helper :refer [dump]]))
(def test-user 1)
(def page-id 1)
(def page-owned-by-another-user 3)
(facts "about editing page settings"
(fact "user must be logged in to view page settings"
(:status (test-api-request :get (str "/page/settings/" page-id))) => 401)
(apply login! (test-user-credentials test-user))
(fact "user cannot access the settings of the page owned by another user"
(let [{:keys [status body]} (test-api-request :get (str "/page/settings/" page-owned-by-another-user))]
status => 500
body => "{\"errors\":\"(not (map? nil))\"}"))
(let [{:keys [status body]} (test-api-request :get (str "/page/settings/" page-id))]
(fact "page settings can be fetched for editing"
status => 200)
(fact "page has valid attributes"
(keys body) => (just [:description :tags :first_name :password :name :visible_before :visible_after :theme :ctime :id :padding :last_name :user_id :border :visibility :mtime] :in-any-order)))
(logout!))
(facts "about saving page settings"
(fact "user must be logged in to save page settings"
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 401)
(apply login! (test-user-credentials test-user))
(fact "user must be owner of the page"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-owned-by-another-user) {:password "" :tags [] :visibility "private"})]
status => 200
(:status body) => "error"))
(fact "visibility, password and tags are required"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {})]
status => 400
body => "{\"errors\":{\"tags\":\"missing-required-key\",\"visibility\":\"missing-required-key\",\"password\":\"missing-required-key\"}}"))
(fact "visibility must be valid"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "not-valid"})]
status => 400
body => "{\"errors\":{\"visibility\":\"(not (#{\\\"internal\\\" \\\"private\\\" \\\"password\\\" \\\"public\\\"} \\\"not-valid\\\"))\"}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200)
(fact "tags must be a collection of strings"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags "not-valid" :visibility "private"})]
status => 400
body => "{\"errors\":{\"tags\":\"(not (sequential? \\\"not-valid\\\"))\"}}")
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [0 1] :visibility "private"})]
status => 400
body => "{\"errors\":{\"tags\":[\"(not (instance? java.lang.String 0))\",\"(not (instance? java.lang.String 1))\"]}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "secret" :tags ["tag" "another tag"] :visibility "password"})) => 200)
(fact "password must be valid"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password 0 :tags [] :visibility "password"})]
status => 400
body => "{\"errors\":{\"password\":\"(not (instance? java.lang.String 0))\"}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "secret" :tags [] :visibility "password"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "not-saved" :tags [] :visibility "private"}))
(let [{:keys [body]} (test-api-request :get (str "/page/settings/" page-id))]
(:password body) => "")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "password"}))
(let [{:keys [body]} (test-api-request :get (str "/page/settings/" page-id))]
(:visibility body) => "private"))
(logout!))
(migrator/reset-seeds (migrator/test-config)) | 14035 | (ns salava.page.settings-test
(:require [midje.sweet :refer :all]
[salava.core.migrator :as migrator]
[salava.test-utils :refer [test-api-request login! logout! test-user-credentials]]
[salava.core.helper :refer [dump]]))
(def test-user 1)
(def page-id 1)
(def page-owned-by-another-user 3)
(facts "about editing page settings"
(fact "user must be logged in to view page settings"
(:status (test-api-request :get (str "/page/settings/" page-id))) => 401)
(apply login! (test-user-credentials test-user))
(fact "user cannot access the settings of the page owned by another user"
(let [{:keys [status body]} (test-api-request :get (str "/page/settings/" page-owned-by-another-user))]
status => 500
body => "{\"errors\":\"(not (map? nil))\"}"))
(let [{:keys [status body]} (test-api-request :get (str "/page/settings/" page-id))]
(fact "page settings can be fetched for editing"
status => 200)
(fact "page has valid attributes"
(keys body) => (just [:description :tags :first_name :password :name :visible_before :visible_after :theme :ctime :id :padding :last_name :user_id :border :visibility :mtime] :in-any-order)))
(logout!))
(facts "about saving page settings"
(fact "user must be logged in to save page settings"
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 401)
(apply login! (test-user-credentials test-user))
(fact "user must be owner of the page"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-owned-by-another-user) {:password "" :tags [] :visibility "private"})]
status => 200
(:status body) => "error"))
(fact "visibility, password and tags are required"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {})]
status => 400
body => "{\"errors\":{\"tags\":\"missing-required-key\",\"visibility\":\"missing-required-key\",\"password\":\"<PASSWORD>\"}}"))
(fact "visibility must be valid"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "not-valid"})]
status => 400
body => "{\"errors\":{\"visibility\":\"(not (#{\\\"internal\\\" \\\"private\\\" \\\"password\\\" \\\"public\\\"} \\\"not-valid\\\"))\"}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200)
(fact "tags must be a collection of strings"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags "not-valid" :visibility "private"})]
status => 400
body => "{\"errors\":{\"tags\":\"(not (sequential? \\\"not-valid\\\"))\"}}")
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [0 1] :visibility "private"})]
status => 400
body => "{\"errors\":{\"tags\":[\"(not (instance? java.lang.String 0))\",\"(not (instance? java.lang.String 1))\"]}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "<PASSWORD>" :tags ["tag" "another tag"] :visibility "password"})) => 200)
(fact "password must be valid"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password 0 :tags [] :visibility "password"})]
status => 400
body => "{\"errors\":{\"password\":\"(not (instance? java.lang.String 0))\"}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "<PASSWORD>" :tags [] :visibility "password"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "<PASSWORD>" :tags [] :visibility "private"}))
(let [{:keys [body]} (test-api-request :get (str "/page/settings/" page-id))]
(:password body) => "")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "password"}))
(let [{:keys [body]} (test-api-request :get (str "/page/settings/" page-id))]
(:visibility body) => "private"))
(logout!))
(migrator/reset-seeds (migrator/test-config)) | true | (ns salava.page.settings-test
(:require [midje.sweet :refer :all]
[salava.core.migrator :as migrator]
[salava.test-utils :refer [test-api-request login! logout! test-user-credentials]]
[salava.core.helper :refer [dump]]))
(def test-user 1)
(def page-id 1)
(def page-owned-by-another-user 3)
(facts "about editing page settings"
(fact "user must be logged in to view page settings"
(:status (test-api-request :get (str "/page/settings/" page-id))) => 401)
(apply login! (test-user-credentials test-user))
(fact "user cannot access the settings of the page owned by another user"
(let [{:keys [status body]} (test-api-request :get (str "/page/settings/" page-owned-by-another-user))]
status => 500
body => "{\"errors\":\"(not (map? nil))\"}"))
(let [{:keys [status body]} (test-api-request :get (str "/page/settings/" page-id))]
(fact "page settings can be fetched for editing"
status => 200)
(fact "page has valid attributes"
(keys body) => (just [:description :tags :first_name :password :name :visible_before :visible_after :theme :ctime :id :padding :last_name :user_id :border :visibility :mtime] :in-any-order)))
(logout!))
(facts "about saving page settings"
(fact "user must be logged in to save page settings"
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 401)
(apply login! (test-user-credentials test-user))
(fact "user must be owner of the page"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-owned-by-another-user) {:password "" :tags [] :visibility "private"})]
status => 200
(:status body) => "error"))
(fact "visibility, password and tags are required"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {})]
status => 400
body => "{\"errors\":{\"tags\":\"missing-required-key\",\"visibility\":\"missing-required-key\",\"password\":\"PI:PASSWORD:<PASSWORD>END_PI\"}}"))
(fact "visibility must be valid"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "not-valid"})]
status => 400
body => "{\"errors\":{\"visibility\":\"(not (#{\\\"internal\\\" \\\"private\\\" \\\"password\\\" \\\"public\\\"} \\\"not-valid\\\"))\"}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200)
(fact "tags must be a collection of strings"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags "not-valid" :visibility "private"})]
status => 400
body => "{\"errors\":{\"tags\":\"(not (sequential? \\\"not-valid\\\"))\"}}")
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [0 1] :visibility "private"})]
status => 400
body => "{\"errors\":{\"tags\":[\"(not (instance? java.lang.String 0))\",\"(not (instance? java.lang.String 1))\"]}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "PI:PASSWORD:<PASSWORD>END_PI" :tags ["tag" "another tag"] :visibility "password"})) => 200)
(fact "password must be valid"
(let [{:keys [status body]} (test-api-request :post (str "/page/save_settings/" page-id) {:password 0 :tags [] :visibility "password"})]
status => 400
body => "{\"errors\":{\"password\":\"(not (instance? java.lang.String 0))\"}}")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "private"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "PI:PASSWORD:<PASSWORD>END_PI" :tags [] :visibility "password"})) => 200
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "PI:PASSWORD:<PASSWORD>END_PI" :tags [] :visibility "private"}))
(let [{:keys [body]} (test-api-request :get (str "/page/settings/" page-id))]
(:password body) => "")
(:status (test-api-request :post (str "/page/save_settings/" page-id) {:password "" :tags [] :visibility "password"}))
(let [{:keys [body]} (test-api-request :get (str "/page/settings/" page-id))]
(:visibility body) => "private"))
(logout!))
(migrator/reset-seeds (migrator/test-config)) |
[
{
"context": "tests for crawling functions\n;;\n;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>.\n;;\n;; Licensed under t",
"end": 94,
"score": 0.9998586177825928,
"start": 81,
"tag": "NAME",
"value": "F.M. de Waard"
},
{
"context": "s\n;;\n;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>.\n;;\n;; Licensed under the Apache License, Versio",
"end": 119,
"score": 0.9999318718910217,
"start": 107,
"tag": "EMAIL",
"value": "fmw@vixu.com"
}
] | test/alida/test/crawl.clj | fmw/alida | 6 | ;; test/alida/test/crawl.clj: tests for crawling functions
;;
;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>.
;;
;; 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.
(ns alida.test.crawl
(:use [clojure.test]
[clj-http.fake]
[alida.test.helpers
:only [with-test-db
+test-db+
dummy-routes
get-filename-from-uri
dummy-health-food-uris]]
[alida.crawl] :reload)
(:require [clj-http.client :as http-client]
[clj-time.core :as time-core]
[clj-time.format :as time-format]
[clj-time.coerce :as time-coerce]
[com.ashafa.clutch :as clutch]
[net.cgrand.enlive-html :as enlive]
[alida.util :as util]
[alida.db :as db])
(:import [java.io StringReader]))
(deftest test-crawled-in-last-hour?
(is (false? (crawled-in-last-hour? nil)))
(is (false? (crawled-in-last-hour? {:crawled-at nil})))
(is (false? (crawled-in-last-hour?
{:crawled-at "2012-02-17T05:58:49.591Z"})))
(is (false? (crawled-in-last-hour?
{:crawled-at (time-format/unparse
(time-format/formatters :date-time)
(time-core/minus (time-core/now)
(time-core/minutes 61)))})))
(is (true? (crawled-in-last-hour?
{:crawled-at (time-format/unparse
(time-format/formatters :date-time)
(time-core/minus (time-core/now)
(time-core/minutes 59)))}))))
(deftest test-get-page
(with-fake-routes dummy-routes
(are [uri]
(= (get-page uri)
{:trace-redirects [uri]
:status 200
:headers {}
:body (slurp (str "resources/test-data/dummy-shop/"
(get-filename-from-uri uri)))})
"http://www.dummyhealthfoodstore.com/index.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/macallan.html"
"http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/glp-westminster.html"
"http://www.dummyhealthfoodstore.com/glp-meridian.html"
"http://www.dummyhealthfoodstore.com/blackwoods-flake.html"
"http://www.dummyhealthfoodstore.com/navy-rolls.html"
"http://www.dummyhealthfoodstore.com/london-mixture.html"))
(testing "expect nil instead of an exception"
(is (= (get-page "foo") nil))))
(deftest test-same-domain?
(is (same-domain? "http://www.dummyhealthfoodstore.com/navy-rolls.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/foo.bar"))
(is (not (same-domain? "http://www.vixu.com/"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/foo.bar"))))
(deftest test-get-links-for-selector
(with-fake-routes dummy-routes
(testing "try grabbing all links from a page"
(is (= (sort-by
:uri
(get-links-for-selector
"http://www.dummyhealthfoodstore.com/glp-westminster.html"
(:body
(http-client/get
"http://www.dummyhealthfoodstore.com/glp-westminster.html"))
{:selector [:a]}))
(sort-by
:uri
[{:selectors nil
:uri "http://www.dummyhealthfoodstore.com/en/About.html"}
{:selectors nil
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/pipe-tobacco.html")}
{:selectors nil
:uri "http://www.dummyhealthfoodstore.com/nl"}
{:selectors nil
:uri "http://www.dummyhealthfoodstore.com/"}
{:selectors nil
:uri "http://www.dummyhealthfoodstore.com/en/Contact.html"}
{:selectors nil
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/whisky.html")}]))))
(testing "test uri filtering with a regular expression"
(is (= (get-links-for-selector
"http://www.dummyhealthfoodstore.com/glp-westminster.html"
(:body
(http-client/get
"http://www.dummyhealthfoodstore.com/glp-westminster.html"))
{:selector [:a]
:path-filter #"^/products.+"})
[{:selectors nil
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/pipe-tobacco.html")}
{:selectors nil
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/whisky.html")}])))))
(deftest test-directed-crawl
(with-fake-routes dummy-routes
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(is
(=
(sort-by
:uri
@(directed-crawl "test-directed-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.dummyhealthfoodstore.com/index.html"
[{:selector [:ul#menu :a]
:path-filter #"^/products.+"
:next [{:selector [[:div#content] [:a]]}]}]))
(sort-by
:uri
@(directed-crawl "test-directed-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.dummyhealthfoodstore.com/index.html"
[{:selector [:ul#menu :a]
:path-filter #"^/products.+"
:next [{:selector [[:div#content] [:a]]
:next [{:selector [:ul#menu :a]
:path-filter #"^/products.+"}]}
{:selector [:ul#menu :a]
:path-filter #"^/products.+"}]}]))
(sort-by
:uri
(map (fn [uri]
(zipmap [:type
:crawl-tag
:crawl-timestamp
:uri
:crawled-at
:trace-redirects
:status
:headers
:body]
["crawled-page"
"test-directed-crawl"
"2012-05-13T21:52:58.114Z"
uri
"2012-05-13T21:52:58.114Z"
[uri]
200
{}
(slurp (str "resources/test-data/dummy-shop/"
(get-filename-from-uri uri)))]))
dummy-health-food-uris)))))
(testing "make sure that sleep time is respected"
(let [[first-page-crawled-at
second-page-crawled-at
third-page-crawled-at]
(map #(time-format/parse (time-format/formatters :date-time) %)
(map
:crawled-at
@(directed-crawl
"test-directed-crawl"
(util/make-timestamp)
100
"http://www.dummyhealthfoodstore.com/index.html"
[{:selector [:ul#menu :a]
:path-filter #"^/products/whisky.html"
:next [{:selector
[:ul#menu :a]
:path-filter
#"^/products/pipe-tobacco.html"}]}])))]
(are [page-crawled-at-times]
(> (- (time-coerce/to-long (second page-crawled-at-times))
(time-coerce/to-long (first page-crawled-at-times)))
100)
[first-page-crawled-at second-page-crawled-at]
[second-page-crawled-at third-page-crawled-at])))))
(deftest test-weighted-crawl
(with-fake-routes dummy-routes
(testing "try a full crawl"
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))
link-checker-fn
(fn [uri]
(not
(nil?
(re-matches #"http://www.deeply-nested.*" uri))))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn
link-checker-fn)
(let [results (map :value
(clutch/get-view +test-db+ "views" "pages"))]
(are [n page]
(= (dissoc (nth results n) :_id :_rev)
(let [uri (str "http://www.deeply-nested-dummy.com/"
page)
filename (str
"resources/test-data/deeply-nested/"
page)]
{:type "crawled-page"
:crawl-tag "test-weighted-crawl"
:crawl-timestamp "2012-05-13T21:52:58.114Z"
:status 200
:score (float 0.1)
:trace-redirects [uri]
:crawled-at "2012-05-13T21:52:58.114Z"
:uri uri
:headers {}
:body (slurp filename)}))
0 "index.html"
1 "nested-0a.html"
2 "nested-0b.html"
3 "nested-1a.html"
4 "nested-1b.html"
5 "nested-2a.html"
6 "nested-2b.html"
7 "nested-3a.html"
8 "nested-3b.html"
9 "nested-4a.html"
10 "nested-4b.html"
11 "nested-5a.html"
12 "nested-5b.html"
13 "nested-6a.html"
14 "nested-6b.html"
15 "nested-7a.html"
16 "nested-7b.html"
17 "nested-8a.html"
18 "nested-8b.html"
19 "nested-9a.html"
20 "nested-9b.html"))))))
(testing "test partly restricting page storage with page-scoring-fn"
(with-test-db
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(if (= (first
(:content
(first (enlive/select
(enlive/html-resource
(StringReader. (:body request-data)))
[:title]))))
"Nested 0")
0 ;; don't store if the title is "Nested 0"
(float 0.1)))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
(let [results (map :value
(clutch/get-view +test-db+ "views" "pages"))]
(is (= (count results) 19))
(are [n page]
(= (dissoc (nth results n) :_id :_rev)
(let [uri (str "http://www.deeply-nested-dummy.com/"
page)
filename (str
"resources/test-data/deeply-nested/"
page)]
{:type "crawled-page"
:crawl-tag "test-weighted-crawl"
:crawl-timestamp "2012-05-13T21:52:58.114Z"
:status 200
:score (float 0.1)
:trace-redirects [uri]
:crawled-at "2012-05-13T21:52:58.114Z"
:uri uri
:headers {}
:body (slurp filename)}))
0 "index.html"
1 "nested-1a.html"
2 "nested-1b.html"
3 "nested-2a.html"
4 "nested-2b.html"
5 "nested-3a.html"
6 "nested-3b.html"
7 "nested-4a.html"
8 "nested-4b.html"
9 "nested-5a.html"
10 "nested-5b.html"
11 "nested-6a.html"
12 "nested-6b.html"
13 "nested-7a.html"
14 "nested-7b.html"
15 "nested-8a.html"
16 "nested-8b.html"
17 "nested-9a.html"
18 "nested-9b.html"))))))
(testing "test partly restricting crawling with page-scoring-fn"
(with-test-db
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(if (some
#{(first
(:content
(first (enlive/select
(enlive/html-resource
(StringReader. (:body request-data)))
[:title]))))}
["Nested"
"Nested 0"
"Nested 1"
"Nested 2"
"Nested 3"])
(float 0.1)
-0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
(let [results (map :value
(clutch/get-view +test-db+ "views" "pages"))]
(is (= (count results) 9))
(are [n page]
(= (dissoc (nth results n) :_id :_rev)
(let [uri (str "http://www.deeply-nested-dummy.com/"
page)
filename (str
"resources/test-data/deeply-nested/"
page)]
{:type "crawled-page"
:crawl-tag "test-weighted-crawl"
:crawl-timestamp "2012-05-13T21:52:58.114Z"
:status 200
:score (float 0.1)
:trace-redirects [uri]
:crawled-at "2012-05-13T21:52:58.114Z"
:uri uri
:headers {}
:body (slurp filename)}))
0 "index.html"
1 "nested-0a.html"
2 "nested-0b.html"
3 "nested-1a.html"
4 "nested-1b.html"
5 "nested-2a.html"
6 "nested-2b.html"
7 "nested-3a.html"
8 "nested-3b.html"))))))
(testing "test partly restricting crawling with link-checker-fn"
(with-test-db
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))
link-checker-fn
(fn [uri]
(if (some
#{uri}
["http://www.deeply-nested-dummy.com/index.html"
"http://www.deeply-nested-dummy.com/nested-0a.html"
"http://www.deeply-nested-dummy.com/nested-0b.html"
"http://www.deeply-nested-dummy.com/nested-1a.html"
"http://www.deeply-nested-dummy.com/nested-1b.html"
"http://www.deeply-nested-dummy.com/nested-2a.html"
"http://www.deeply-nested-dummy.com/nested-2b.html"
"http://www.deeply-nested-dummy.com/nested-3a.html"
"http://www.deeply-nested-dummy.com/nested-3b.html"])
true
false))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn
link-checker-fn)
(let [results (map :value
(clutch/get-view +test-db+ "views" "pages"))]
(is (= (count results) 9))
(are [n page]
(= (dissoc (nth results n) :_id :_rev)
(let [uri (str "http://www.deeply-nested-dummy.com/"
page)
filename (str
"resources/test-data/deeply-nested/"
page)]
{:type "crawled-page"
:crawl-tag "test-weighted-crawl"
:crawl-timestamp "2012-05-13T21:52:58.114Z"
:status 200
:score (float 0.1)
:trace-redirects [uri]
:crawled-at "2012-05-13T21:52:58.114Z"
:uri uri
:headers {}
:body (slurp filename)}))
0 "index.html"
1 "nested-0a.html"
2 "nested-0b.html"
3 "nested-1a.html"
4 "nested-1b.html"
5 "nested-2a.html"
6 "nested-2b.html"
7 "nested-3a.html"
8 "nested-3b.html"))))))
(testing "make sure that pages aren't recrawled within the hour"
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
(is (= (count (clutch/get-view +test-db+ "views" "pages")) 21)))))
(testing "make sure that sleep time is respected"
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
100
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
(let [crawled-times
(map #(time-coerce/to-long
(time-format/parse
(time-format/formatters :date-time)
(:crawled-at (:value %))))
(sort-by #(:crawled-at (:value %))
(clutch/get-view +test-db+ "views" "pages")))]
(is (= (count crawled-times) 21))
(are [v]
(> (- (nth crawled-times (second v))
(nth crawled-times (first v)))
100)
[0 1]
[1 2]
[2 3]
[3 4]
[4 5]
[5 6]
[6 7]
[7 8]
[8 9]
[9 10]
[10 11]
[11 12]
[12 13]
[13 14]
[14 15]
[15 16]
[17 18]
[18 19]
[19 20])))))
(testing "test if external links are handled"
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
0
"http://www.dummyhealthfoodstore.com/index.html"
1000
page-scoring-fn)
;; give the second thread some time to catch up
(Thread/sleep 200)
(is
(=
(map #(:uri (:value %))
(clutch/get-view +test-db+ "views" "pages"))
["http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/blackwoods-flake.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/glp-meridian.html"
"http://www.dummyhealthfoodstore.com/glp-westminster.html"
"http://www.dummyhealthfoodstore.com/index.html"
"http://www.dummyhealthfoodstore.com/london-mixture.html"
"http://www.dummyhealthfoodstore.com/macallan.html"
"http://www.dummyhealthfoodstore.com/navy-rolls.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.vixu.com/"])))))
(testing "test if max-depth is respected"
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
0
"http://www.deeply-nested-dummy.com/index.html"
3
page-scoring-fn)
(is
(=
(map #(:uri (:value %))
(clutch/get-view +test-db+ "views" "pages"))
["http://www.deeply-nested-dummy.com/index.html"
"http://www.deeply-nested-dummy.com/nested-0a.html"
"http://www.deeply-nested-dummy.com/nested-0b.html"
"http://www.deeply-nested-dummy.com/nested-1a.html"
"http://www.deeply-nested-dummy.com/nested-1b.html"
"http://www.deeply-nested-dummy.com/nested-2a.html"
"http://www.deeply-nested-dummy.com/nested-2b.html"]))))))) | 32392 | ;; test/alida/test/crawl.clj: tests for crawling functions
;;
;; Copyright 2012, <NAME> & Vixu.com <<EMAIL>>.
;;
;; 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.
(ns alida.test.crawl
(:use [clojure.test]
[clj-http.fake]
[alida.test.helpers
:only [with-test-db
+test-db+
dummy-routes
get-filename-from-uri
dummy-health-food-uris]]
[alida.crawl] :reload)
(:require [clj-http.client :as http-client]
[clj-time.core :as time-core]
[clj-time.format :as time-format]
[clj-time.coerce :as time-coerce]
[com.ashafa.clutch :as clutch]
[net.cgrand.enlive-html :as enlive]
[alida.util :as util]
[alida.db :as db])
(:import [java.io StringReader]))
(deftest test-crawled-in-last-hour?
(is (false? (crawled-in-last-hour? nil)))
(is (false? (crawled-in-last-hour? {:crawled-at nil})))
(is (false? (crawled-in-last-hour?
{:crawled-at "2012-02-17T05:58:49.591Z"})))
(is (false? (crawled-in-last-hour?
{:crawled-at (time-format/unparse
(time-format/formatters :date-time)
(time-core/minus (time-core/now)
(time-core/minutes 61)))})))
(is (true? (crawled-in-last-hour?
{:crawled-at (time-format/unparse
(time-format/formatters :date-time)
(time-core/minus (time-core/now)
(time-core/minutes 59)))}))))
(deftest test-get-page
(with-fake-routes dummy-routes
(are [uri]
(= (get-page uri)
{:trace-redirects [uri]
:status 200
:headers {}
:body (slurp (str "resources/test-data/dummy-shop/"
(get-filename-from-uri uri)))})
"http://www.dummyhealthfoodstore.com/index.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/macallan.html"
"http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/glp-westminster.html"
"http://www.dummyhealthfoodstore.com/glp-meridian.html"
"http://www.dummyhealthfoodstore.com/blackwoods-flake.html"
"http://www.dummyhealthfoodstore.com/navy-rolls.html"
"http://www.dummyhealthfoodstore.com/london-mixture.html"))
(testing "expect nil instead of an exception"
(is (= (get-page "foo") nil))))
(deftest test-same-domain?
(is (same-domain? "http://www.dummyhealthfoodstore.com/navy-rolls.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/foo.bar"))
(is (not (same-domain? "http://www.vixu.com/"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/foo.bar"))))
(deftest test-get-links-for-selector
(with-fake-routes dummy-routes
(testing "try grabbing all links from a page"
(is (= (sort-by
:uri
(get-links-for-selector
"http://www.dummyhealthfoodstore.com/glp-westminster.html"
(:body
(http-client/get
"http://www.dummyhealthfoodstore.com/glp-westminster.html"))
{:selector [:a]}))
(sort-by
:uri
[{:selectors nil
:uri "http://www.dummyhealthfoodstore.com/en/About.html"}
{:selectors nil
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/pipe-tobacco.html")}
{:selectors nil
:uri "http://www.dummyhealthfoodstore.com/nl"}
{:selectors nil
:uri "http://www.dummyhealthfoodstore.com/"}
{:selectors nil
:uri "http://www.dummyhealthfoodstore.com/en/Contact.html"}
{:selectors nil
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/whisky.html")}]))))
(testing "test uri filtering with a regular expression"
(is (= (get-links-for-selector
"http://www.dummyhealthfoodstore.com/glp-westminster.html"
(:body
(http-client/get
"http://www.dummyhealthfoodstore.com/glp-westminster.html"))
{:selector [:a]
:path-filter #"^/products.+"})
[{:selectors nil
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/pipe-tobacco.html")}
{:selectors nil
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/whisky.html")}])))))
(deftest test-directed-crawl
(with-fake-routes dummy-routes
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(is
(=
(sort-by
:uri
@(directed-crawl "test-directed-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.dummyhealthfoodstore.com/index.html"
[{:selector [:ul#menu :a]
:path-filter #"^/products.+"
:next [{:selector [[:div#content] [:a]]}]}]))
(sort-by
:uri
@(directed-crawl "test-directed-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.dummyhealthfoodstore.com/index.html"
[{:selector [:ul#menu :a]
:path-filter #"^/products.+"
:next [{:selector [[:div#content] [:a]]
:next [{:selector [:ul#menu :a]
:path-filter #"^/products.+"}]}
{:selector [:ul#menu :a]
:path-filter #"^/products.+"}]}]))
(sort-by
:uri
(map (fn [uri]
(zipmap [:type
:crawl-tag
:crawl-timestamp
:uri
:crawled-at
:trace-redirects
:status
:headers
:body]
["crawled-page"
"test-directed-crawl"
"2012-05-13T21:52:58.114Z"
uri
"2012-05-13T21:52:58.114Z"
[uri]
200
{}
(slurp (str "resources/test-data/dummy-shop/"
(get-filename-from-uri uri)))]))
dummy-health-food-uris)))))
(testing "make sure that sleep time is respected"
(let [[first-page-crawled-at
second-page-crawled-at
third-page-crawled-at]
(map #(time-format/parse (time-format/formatters :date-time) %)
(map
:crawled-at
@(directed-crawl
"test-directed-crawl"
(util/make-timestamp)
100
"http://www.dummyhealthfoodstore.com/index.html"
[{:selector [:ul#menu :a]
:path-filter #"^/products/whisky.html"
:next [{:selector
[:ul#menu :a]
:path-filter
#"^/products/pipe-tobacco.html"}]}])))]
(are [page-crawled-at-times]
(> (- (time-coerce/to-long (second page-crawled-at-times))
(time-coerce/to-long (first page-crawled-at-times)))
100)
[first-page-crawled-at second-page-crawled-at]
[second-page-crawled-at third-page-crawled-at])))))
(deftest test-weighted-crawl
(with-fake-routes dummy-routes
(testing "try a full crawl"
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))
link-checker-fn
(fn [uri]
(not
(nil?
(re-matches #"http://www.deeply-nested.*" uri))))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn
link-checker-fn)
(let [results (map :value
(clutch/get-view +test-db+ "views" "pages"))]
(are [n page]
(= (dissoc (nth results n) :_id :_rev)
(let [uri (str "http://www.deeply-nested-dummy.com/"
page)
filename (str
"resources/test-data/deeply-nested/"
page)]
{:type "crawled-page"
:crawl-tag "test-weighted-crawl"
:crawl-timestamp "2012-05-13T21:52:58.114Z"
:status 200
:score (float 0.1)
:trace-redirects [uri]
:crawled-at "2012-05-13T21:52:58.114Z"
:uri uri
:headers {}
:body (slurp filename)}))
0 "index.html"
1 "nested-0a.html"
2 "nested-0b.html"
3 "nested-1a.html"
4 "nested-1b.html"
5 "nested-2a.html"
6 "nested-2b.html"
7 "nested-3a.html"
8 "nested-3b.html"
9 "nested-4a.html"
10 "nested-4b.html"
11 "nested-5a.html"
12 "nested-5b.html"
13 "nested-6a.html"
14 "nested-6b.html"
15 "nested-7a.html"
16 "nested-7b.html"
17 "nested-8a.html"
18 "nested-8b.html"
19 "nested-9a.html"
20 "nested-9b.html"))))))
(testing "test partly restricting page storage with page-scoring-fn"
(with-test-db
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(if (= (first
(:content
(first (enlive/select
(enlive/html-resource
(StringReader. (:body request-data)))
[:title]))))
"Nested 0")
0 ;; don't store if the title is "Nested 0"
(float 0.1)))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
(let [results (map :value
(clutch/get-view +test-db+ "views" "pages"))]
(is (= (count results) 19))
(are [n page]
(= (dissoc (nth results n) :_id :_rev)
(let [uri (str "http://www.deeply-nested-dummy.com/"
page)
filename (str
"resources/test-data/deeply-nested/"
page)]
{:type "crawled-page"
:crawl-tag "test-weighted-crawl"
:crawl-timestamp "2012-05-13T21:52:58.114Z"
:status 200
:score (float 0.1)
:trace-redirects [uri]
:crawled-at "2012-05-13T21:52:58.114Z"
:uri uri
:headers {}
:body (slurp filename)}))
0 "index.html"
1 "nested-1a.html"
2 "nested-1b.html"
3 "nested-2a.html"
4 "nested-2b.html"
5 "nested-3a.html"
6 "nested-3b.html"
7 "nested-4a.html"
8 "nested-4b.html"
9 "nested-5a.html"
10 "nested-5b.html"
11 "nested-6a.html"
12 "nested-6b.html"
13 "nested-7a.html"
14 "nested-7b.html"
15 "nested-8a.html"
16 "nested-8b.html"
17 "nested-9a.html"
18 "nested-9b.html"))))))
(testing "test partly restricting crawling with page-scoring-fn"
(with-test-db
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(if (some
#{(first
(:content
(first (enlive/select
(enlive/html-resource
(StringReader. (:body request-data)))
[:title]))))}
["Nested"
"Nested 0"
"Nested 1"
"Nested 2"
"Nested 3"])
(float 0.1)
-0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
(let [results (map :value
(clutch/get-view +test-db+ "views" "pages"))]
(is (= (count results) 9))
(are [n page]
(= (dissoc (nth results n) :_id :_rev)
(let [uri (str "http://www.deeply-nested-dummy.com/"
page)
filename (str
"resources/test-data/deeply-nested/"
page)]
{:type "crawled-page"
:crawl-tag "test-weighted-crawl"
:crawl-timestamp "2012-05-13T21:52:58.114Z"
:status 200
:score (float 0.1)
:trace-redirects [uri]
:crawled-at "2012-05-13T21:52:58.114Z"
:uri uri
:headers {}
:body (slurp filename)}))
0 "index.html"
1 "nested-0a.html"
2 "nested-0b.html"
3 "nested-1a.html"
4 "nested-1b.html"
5 "nested-2a.html"
6 "nested-2b.html"
7 "nested-3a.html"
8 "nested-3b.html"))))))
(testing "test partly restricting crawling with link-checker-fn"
(with-test-db
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))
link-checker-fn
(fn [uri]
(if (some
#{uri}
["http://www.deeply-nested-dummy.com/index.html"
"http://www.deeply-nested-dummy.com/nested-0a.html"
"http://www.deeply-nested-dummy.com/nested-0b.html"
"http://www.deeply-nested-dummy.com/nested-1a.html"
"http://www.deeply-nested-dummy.com/nested-1b.html"
"http://www.deeply-nested-dummy.com/nested-2a.html"
"http://www.deeply-nested-dummy.com/nested-2b.html"
"http://www.deeply-nested-dummy.com/nested-3a.html"
"http://www.deeply-nested-dummy.com/nested-3b.html"])
true
false))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn
link-checker-fn)
(let [results (map :value
(clutch/get-view +test-db+ "views" "pages"))]
(is (= (count results) 9))
(are [n page]
(= (dissoc (nth results n) :_id :_rev)
(let [uri (str "http://www.deeply-nested-dummy.com/"
page)
filename (str
"resources/test-data/deeply-nested/"
page)]
{:type "crawled-page"
:crawl-tag "test-weighted-crawl"
:crawl-timestamp "2012-05-13T21:52:58.114Z"
:status 200
:score (float 0.1)
:trace-redirects [uri]
:crawled-at "2012-05-13T21:52:58.114Z"
:uri uri
:headers {}
:body (slurp filename)}))
0 "index.html"
1 "nested-0a.html"
2 "nested-0b.html"
3 "nested-1a.html"
4 "nested-1b.html"
5 "nested-2a.html"
6 "nested-2b.html"
7 "nested-3a.html"
8 "nested-3b.html"))))))
(testing "make sure that pages aren't recrawled within the hour"
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
(is (= (count (clutch/get-view +test-db+ "views" "pages")) 21)))))
(testing "make sure that sleep time is respected"
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
100
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
(let [crawled-times
(map #(time-coerce/to-long
(time-format/parse
(time-format/formatters :date-time)
(:crawled-at (:value %))))
(sort-by #(:crawled-at (:value %))
(clutch/get-view +test-db+ "views" "pages")))]
(is (= (count crawled-times) 21))
(are [v]
(> (- (nth crawled-times (second v))
(nth crawled-times (first v)))
100)
[0 1]
[1 2]
[2 3]
[3 4]
[4 5]
[5 6]
[6 7]
[7 8]
[8 9]
[9 10]
[10 11]
[11 12]
[12 13]
[13 14]
[14 15]
[15 16]
[17 18]
[18 19]
[19 20])))))
(testing "test if external links are handled"
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
0
"http://www.dummyhealthfoodstore.com/index.html"
1000
page-scoring-fn)
;; give the second thread some time to catch up
(Thread/sleep 200)
(is
(=
(map #(:uri (:value %))
(clutch/get-view +test-db+ "views" "pages"))
["http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/blackwoods-flake.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/glp-meridian.html"
"http://www.dummyhealthfoodstore.com/glp-westminster.html"
"http://www.dummyhealthfoodstore.com/index.html"
"http://www.dummyhealthfoodstore.com/london-mixture.html"
"http://www.dummyhealthfoodstore.com/macallan.html"
"http://www.dummyhealthfoodstore.com/navy-rolls.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.vixu.com/"])))))
(testing "test if max-depth is respected"
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
0
"http://www.deeply-nested-dummy.com/index.html"
3
page-scoring-fn)
(is
(=
(map #(:uri (:value %))
(clutch/get-view +test-db+ "views" "pages"))
["http://www.deeply-nested-dummy.com/index.html"
"http://www.deeply-nested-dummy.com/nested-0a.html"
"http://www.deeply-nested-dummy.com/nested-0b.html"
"http://www.deeply-nested-dummy.com/nested-1a.html"
"http://www.deeply-nested-dummy.com/nested-1b.html"
"http://www.deeply-nested-dummy.com/nested-2a.html"
"http://www.deeply-nested-dummy.com/nested-2b.html"]))))))) | true | ;; test/alida/test/crawl.clj: tests for crawling functions
;;
;; Copyright 2012, PI:NAME:<NAME>END_PI & Vixu.com <PI:EMAIL:<EMAIL>END_PI>.
;;
;; 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.
(ns alida.test.crawl
(:use [clojure.test]
[clj-http.fake]
[alida.test.helpers
:only [with-test-db
+test-db+
dummy-routes
get-filename-from-uri
dummy-health-food-uris]]
[alida.crawl] :reload)
(:require [clj-http.client :as http-client]
[clj-time.core :as time-core]
[clj-time.format :as time-format]
[clj-time.coerce :as time-coerce]
[com.ashafa.clutch :as clutch]
[net.cgrand.enlive-html :as enlive]
[alida.util :as util]
[alida.db :as db])
(:import [java.io StringReader]))
(deftest test-crawled-in-last-hour?
(is (false? (crawled-in-last-hour? nil)))
(is (false? (crawled-in-last-hour? {:crawled-at nil})))
(is (false? (crawled-in-last-hour?
{:crawled-at "2012-02-17T05:58:49.591Z"})))
(is (false? (crawled-in-last-hour?
{:crawled-at (time-format/unparse
(time-format/formatters :date-time)
(time-core/minus (time-core/now)
(time-core/minutes 61)))})))
(is (true? (crawled-in-last-hour?
{:crawled-at (time-format/unparse
(time-format/formatters :date-time)
(time-core/minus (time-core/now)
(time-core/minutes 59)))}))))
(deftest test-get-page
(with-fake-routes dummy-routes
(are [uri]
(= (get-page uri)
{:trace-redirects [uri]
:status 200
:headers {}
:body (slurp (str "resources/test-data/dummy-shop/"
(get-filename-from-uri uri)))})
"http://www.dummyhealthfoodstore.com/index.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/macallan.html"
"http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/glp-westminster.html"
"http://www.dummyhealthfoodstore.com/glp-meridian.html"
"http://www.dummyhealthfoodstore.com/blackwoods-flake.html"
"http://www.dummyhealthfoodstore.com/navy-rolls.html"
"http://www.dummyhealthfoodstore.com/london-mixture.html"))
(testing "expect nil instead of an exception"
(is (= (get-page "foo") nil))))
(deftest test-same-domain?
(is (same-domain? "http://www.dummyhealthfoodstore.com/navy-rolls.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/foo.bar"))
(is (not (same-domain? "http://www.vixu.com/"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/foo.bar"))))
(deftest test-get-links-for-selector
(with-fake-routes dummy-routes
(testing "try grabbing all links from a page"
(is (= (sort-by
:uri
(get-links-for-selector
"http://www.dummyhealthfoodstore.com/glp-westminster.html"
(:body
(http-client/get
"http://www.dummyhealthfoodstore.com/glp-westminster.html"))
{:selector [:a]}))
(sort-by
:uri
[{:selectors nil
:uri "http://www.dummyhealthfoodstore.com/en/About.html"}
{:selectors nil
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/pipe-tobacco.html")}
{:selectors nil
:uri "http://www.dummyhealthfoodstore.com/nl"}
{:selectors nil
:uri "http://www.dummyhealthfoodstore.com/"}
{:selectors nil
:uri "http://www.dummyhealthfoodstore.com/en/Contact.html"}
{:selectors nil
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/whisky.html")}]))))
(testing "test uri filtering with a regular expression"
(is (= (get-links-for-selector
"http://www.dummyhealthfoodstore.com/glp-westminster.html"
(:body
(http-client/get
"http://www.dummyhealthfoodstore.com/glp-westminster.html"))
{:selector [:a]
:path-filter #"^/products.+"})
[{:selectors nil
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/pipe-tobacco.html")}
{:selectors nil
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/whisky.html")}])))))
(deftest test-directed-crawl
(with-fake-routes dummy-routes
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(is
(=
(sort-by
:uri
@(directed-crawl "test-directed-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.dummyhealthfoodstore.com/index.html"
[{:selector [:ul#menu :a]
:path-filter #"^/products.+"
:next [{:selector [[:div#content] [:a]]}]}]))
(sort-by
:uri
@(directed-crawl "test-directed-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.dummyhealthfoodstore.com/index.html"
[{:selector [:ul#menu :a]
:path-filter #"^/products.+"
:next [{:selector [[:div#content] [:a]]
:next [{:selector [:ul#menu :a]
:path-filter #"^/products.+"}]}
{:selector [:ul#menu :a]
:path-filter #"^/products.+"}]}]))
(sort-by
:uri
(map (fn [uri]
(zipmap [:type
:crawl-tag
:crawl-timestamp
:uri
:crawled-at
:trace-redirects
:status
:headers
:body]
["crawled-page"
"test-directed-crawl"
"2012-05-13T21:52:58.114Z"
uri
"2012-05-13T21:52:58.114Z"
[uri]
200
{}
(slurp (str "resources/test-data/dummy-shop/"
(get-filename-from-uri uri)))]))
dummy-health-food-uris)))))
(testing "make sure that sleep time is respected"
(let [[first-page-crawled-at
second-page-crawled-at
third-page-crawled-at]
(map #(time-format/parse (time-format/formatters :date-time) %)
(map
:crawled-at
@(directed-crawl
"test-directed-crawl"
(util/make-timestamp)
100
"http://www.dummyhealthfoodstore.com/index.html"
[{:selector [:ul#menu :a]
:path-filter #"^/products/whisky.html"
:next [{:selector
[:ul#menu :a]
:path-filter
#"^/products/pipe-tobacco.html"}]}])))]
(are [page-crawled-at-times]
(> (- (time-coerce/to-long (second page-crawled-at-times))
(time-coerce/to-long (first page-crawled-at-times)))
100)
[first-page-crawled-at second-page-crawled-at]
[second-page-crawled-at third-page-crawled-at])))))
(deftest test-weighted-crawl
(with-fake-routes dummy-routes
(testing "try a full crawl"
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))
link-checker-fn
(fn [uri]
(not
(nil?
(re-matches #"http://www.deeply-nested.*" uri))))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn
link-checker-fn)
(let [results (map :value
(clutch/get-view +test-db+ "views" "pages"))]
(are [n page]
(= (dissoc (nth results n) :_id :_rev)
(let [uri (str "http://www.deeply-nested-dummy.com/"
page)
filename (str
"resources/test-data/deeply-nested/"
page)]
{:type "crawled-page"
:crawl-tag "test-weighted-crawl"
:crawl-timestamp "2012-05-13T21:52:58.114Z"
:status 200
:score (float 0.1)
:trace-redirects [uri]
:crawled-at "2012-05-13T21:52:58.114Z"
:uri uri
:headers {}
:body (slurp filename)}))
0 "index.html"
1 "nested-0a.html"
2 "nested-0b.html"
3 "nested-1a.html"
4 "nested-1b.html"
5 "nested-2a.html"
6 "nested-2b.html"
7 "nested-3a.html"
8 "nested-3b.html"
9 "nested-4a.html"
10 "nested-4b.html"
11 "nested-5a.html"
12 "nested-5b.html"
13 "nested-6a.html"
14 "nested-6b.html"
15 "nested-7a.html"
16 "nested-7b.html"
17 "nested-8a.html"
18 "nested-8b.html"
19 "nested-9a.html"
20 "nested-9b.html"))))))
(testing "test partly restricting page storage with page-scoring-fn"
(with-test-db
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(if (= (first
(:content
(first (enlive/select
(enlive/html-resource
(StringReader. (:body request-data)))
[:title]))))
"Nested 0")
0 ;; don't store if the title is "Nested 0"
(float 0.1)))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
(let [results (map :value
(clutch/get-view +test-db+ "views" "pages"))]
(is (= (count results) 19))
(are [n page]
(= (dissoc (nth results n) :_id :_rev)
(let [uri (str "http://www.deeply-nested-dummy.com/"
page)
filename (str
"resources/test-data/deeply-nested/"
page)]
{:type "crawled-page"
:crawl-tag "test-weighted-crawl"
:crawl-timestamp "2012-05-13T21:52:58.114Z"
:status 200
:score (float 0.1)
:trace-redirects [uri]
:crawled-at "2012-05-13T21:52:58.114Z"
:uri uri
:headers {}
:body (slurp filename)}))
0 "index.html"
1 "nested-1a.html"
2 "nested-1b.html"
3 "nested-2a.html"
4 "nested-2b.html"
5 "nested-3a.html"
6 "nested-3b.html"
7 "nested-4a.html"
8 "nested-4b.html"
9 "nested-5a.html"
10 "nested-5b.html"
11 "nested-6a.html"
12 "nested-6b.html"
13 "nested-7a.html"
14 "nested-7b.html"
15 "nested-8a.html"
16 "nested-8b.html"
17 "nested-9a.html"
18 "nested-9b.html"))))))
(testing "test partly restricting crawling with page-scoring-fn"
(with-test-db
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(if (some
#{(first
(:content
(first (enlive/select
(enlive/html-resource
(StringReader. (:body request-data)))
[:title]))))}
["Nested"
"Nested 0"
"Nested 1"
"Nested 2"
"Nested 3"])
(float 0.1)
-0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
(let [results (map :value
(clutch/get-view +test-db+ "views" "pages"))]
(is (= (count results) 9))
(are [n page]
(= (dissoc (nth results n) :_id :_rev)
(let [uri (str "http://www.deeply-nested-dummy.com/"
page)
filename (str
"resources/test-data/deeply-nested/"
page)]
{:type "crawled-page"
:crawl-tag "test-weighted-crawl"
:crawl-timestamp "2012-05-13T21:52:58.114Z"
:status 200
:score (float 0.1)
:trace-redirects [uri]
:crawled-at "2012-05-13T21:52:58.114Z"
:uri uri
:headers {}
:body (slurp filename)}))
0 "index.html"
1 "nested-0a.html"
2 "nested-0b.html"
3 "nested-1a.html"
4 "nested-1b.html"
5 "nested-2a.html"
6 "nested-2b.html"
7 "nested-3a.html"
8 "nested-3b.html"))))))
(testing "test partly restricting crawling with link-checker-fn"
(with-test-db
(with-redefs [util/make-timestamp #(str "2012-05-13T21:52:58.114Z")]
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))
link-checker-fn
(fn [uri]
(if (some
#{uri}
["http://www.deeply-nested-dummy.com/index.html"
"http://www.deeply-nested-dummy.com/nested-0a.html"
"http://www.deeply-nested-dummy.com/nested-0b.html"
"http://www.deeply-nested-dummy.com/nested-1a.html"
"http://www.deeply-nested-dummy.com/nested-1b.html"
"http://www.deeply-nested-dummy.com/nested-2a.html"
"http://www.deeply-nested-dummy.com/nested-2b.html"
"http://www.deeply-nested-dummy.com/nested-3a.html"
"http://www.deeply-nested-dummy.com/nested-3b.html"])
true
false))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
"2012-05-13T21:52:58.114Z"
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn
link-checker-fn)
(let [results (map :value
(clutch/get-view +test-db+ "views" "pages"))]
(is (= (count results) 9))
(are [n page]
(= (dissoc (nth results n) :_id :_rev)
(let [uri (str "http://www.deeply-nested-dummy.com/"
page)
filename (str
"resources/test-data/deeply-nested/"
page)]
{:type "crawled-page"
:crawl-tag "test-weighted-crawl"
:crawl-timestamp "2012-05-13T21:52:58.114Z"
:status 200
:score (float 0.1)
:trace-redirects [uri]
:crawled-at "2012-05-13T21:52:58.114Z"
:uri uri
:headers {}
:body (slurp filename)}))
0 "index.html"
1 "nested-0a.html"
2 "nested-0b.html"
3 "nested-1a.html"
4 "nested-1b.html"
5 "nested-2a.html"
6 "nested-2b.html"
7 "nested-3a.html"
8 "nested-3b.html"))))))
(testing "make sure that pages aren't recrawled within the hour"
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
0
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
(is (= (count (clutch/get-view +test-db+ "views" "pages")) 21)))))
(testing "make sure that sleep time is respected"
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
100
"http://www.deeply-nested-dummy.com/index.html"
1000
page-scoring-fn)
(let [crawled-times
(map #(time-coerce/to-long
(time-format/parse
(time-format/formatters :date-time)
(:crawled-at (:value %))))
(sort-by #(:crawled-at (:value %))
(clutch/get-view +test-db+ "views" "pages")))]
(is (= (count crawled-times) 21))
(are [v]
(> (- (nth crawled-times (second v))
(nth crawled-times (first v)))
100)
[0 1]
[1 2]
[2 3]
[3 4]
[4 5]
[5 6]
[6 7]
[7 8]
[8 9]
[9 10]
[10 11]
[11 12]
[12 13]
[13 14]
[14 15]
[15 16]
[17 18]
[18 19]
[19 20])))))
(testing "test if external links are handled"
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
0
"http://www.dummyhealthfoodstore.com/index.html"
1000
page-scoring-fn)
;; give the second thread some time to catch up
(Thread/sleep 200)
(is
(=
(map #(:uri (:value %))
(clutch/get-view +test-db+ "views" "pages"))
["http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/blackwoods-flake.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/glp-meridian.html"
"http://www.dummyhealthfoodstore.com/glp-westminster.html"
"http://www.dummyhealthfoodstore.com/index.html"
"http://www.dummyhealthfoodstore.com/london-mixture.html"
"http://www.dummyhealthfoodstore.com/macallan.html"
"http://www.dummyhealthfoodstore.com/navy-rolls.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.vixu.com/"])))))
(testing "test if max-depth is respected"
(with-test-db
(db/create-views +test-db+)
(let [page-scoring-fn
(fn [uri depth request-data]
(float 0.1))]
@(weighted-crawl +test-db+
"test-weighted-crawl"
(util/make-timestamp)
0
"http://www.deeply-nested-dummy.com/index.html"
3
page-scoring-fn)
(is
(=
(map #(:uri (:value %))
(clutch/get-view +test-db+ "views" "pages"))
["http://www.deeply-nested-dummy.com/index.html"
"http://www.deeply-nested-dummy.com/nested-0a.html"
"http://www.deeply-nested-dummy.com/nested-0b.html"
"http://www.deeply-nested-dummy.com/nested-1a.html"
"http://www.deeply-nested-dummy.com/nested-1b.html"
"http://www.deeply-nested-dummy.com/nested-2a.html"
"http://www.deeply-nested-dummy.com/nested-2b.html"]))))))) |
[
{
"context": "llo \" name))\n\n(defn bad [name]\n (.endsWith name \" Smith\"))\n",
"end": 173,
"score": 0.9772918224334717,
"start": 168,
"tag": "NAME",
"value": "Smith"
}
] | gradle-clojure-plugin/src/compatTest/projects/LeinClojureProjectTest/src/basic_project/core.clj | rdsr/gradle-clojure | 53 | (ns basic-project.core)
(defprotocol ITest)
(defn hello [name]
(println "Generating message for" name)
(str "Hello " name))
(defn bad [name]
(.endsWith name " Smith"))
| 17839 | (ns basic-project.core)
(defprotocol ITest)
(defn hello [name]
(println "Generating message for" name)
(str "Hello " name))
(defn bad [name]
(.endsWith name " <NAME>"))
| true | (ns basic-project.core)
(defprotocol ITest)
(defn hello [name]
(println "Generating message for" name)
(str "Hello " name))
(defn bad [name]
(.endsWith name " PI:NAME:<NAME>END_PI"))
|
[
{
"context": "oot parser written with parsec\n Copyright : (c) Karl Cronburg, 2018\n License : BSD3\n Maintainer : karl@c",
"end": 180,
"score": 0.9998966455459595,
"start": 167,
"tag": "NAME",
"value": "Karl Cronburg"
},
{
"context": "ronburg, 2018\n License : BSD3\n Maintainer : karl@cs.tufts.edu\n Stability : experimental\n Portability : POSI",
"end": 241,
"score": 0.9999290108680725,
"start": 224,
"tag": "EMAIL",
"value": "karl@cs.tufts.edu"
}
] | src/Language/ANTLR4/Boot/Parser.hs.boot | jsarracino/antlr-haskell | 46 | {-#LANGUAGE QuasiQuotes, TemplateHaskell#-}
{-|
Module : Language.ANTLR4.Boot.Parser
Description : ANTLR4 boot parser written with parsec
Copyright : (c) Karl Cronburg, 2018
License : BSD3
Maintainer : karl@cs.tufts.edu
Stability : experimental
Portability : POSIX
-}
module Language.ANTLR4.Boot.Parser where
-- syntax (Exp)
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import qualified Debug.Trace as D (trace, traceM)
import qualified Language.Haskell.Meta as LHM
-- monadic ops
import Control.Monad (mapM)
-- parsec
import Text.ParserCombinators.Parsec
import qualified Text.Parsec.String as PS
import qualified Text.Parsec.Prim as PP
import qualified Text.Parsec.Token as PT
import qualified Text.Parsec.Expr as PE
import qualified Text.Parsec.Combinator as PC
import Text.ParserCombinators.Parsec.Language (haskellStyle, reservedOpNames, reservedNames
, commentLine, commentStart, commentEnd)
import Text.ParserCombinators.Parsec.Pos (newPos)
-- text munging
import Data.Char
import Language.ANTLR4.Boot.Syntax
import Language.ANTLR4.Regex (parseRegex, regexP)
--traceM s = D.traceM ("[ANTLR4.Boot.Parser] " ++ s)
traceM = return
------------------------------------------------------------------------------
-- Or-Try Combinator (tries two parsers, one after the other)
(<||>) a b = try a <|> try b
parseANTLR :: SourceName -> Line -> Column -> String -> Either ParseError [G4]
parseANTLR fileName line column input =
PP.parse result fileName input
where
result = do
setPosition (newPos fileName line column)
whiteSpace
x <- gExps
traceM $ show x
eof <|> errorParse
return x
errorParse = do
rest <- manyTill anyToken eof
unexpected $ '"' : rest ++ "\""
gExps :: PS.Parser [G4]
gExps = concat <$> many1 gExp
gExp :: PS.Parser [G4]
gExp = do
traceM "gExp"
whiteSpace
xs <- grammarP <||> lexerP <||> prodP
traceM $ show xs
return xs
grammarP :: PS.Parser [G4]
grammarP = do
reserved "grammar"
h <- upper
t <- manyTill anyToken (reservedOp ";")
traceM $ show $ Grammar (h : t)
return [Grammar (h : t)]
-- | Assumptions:
--
-- * Directives must be on a single line.
-- *
prodP :: PS.Parser [G4]
prodP = do
h <- lower
t <- manyTill anyChar (reservedOp ":")
traceM $ "[prodP] " ++ trim (h : t)
rhsList <- sepBy1 rhsP (traceM "rhsList..." >> reservedOp "|")
traceM $ "[prodP.rhsList] " ++ show rhsList
reservedOp ";"
traceM "prodP returning..."
return [Prod (trim (h : t)) (concat rhsList)]
where
rhsP = do
mPred <- optionMaybe predP
traceM $ "[rhsP0] " ++ show mPred
alphaList <- many alphaP
traceM $ "[rhsP] " ++ show alphaList
mMute <- optionMaybe muteP
pDir <- optionMaybe directiveP
whiteSpace
return [PRHS alphaList mPred mMute pDir]
alphaP = termP <||> nonTermP
termP = do
whiteSpace
char '\''
traceM "[prodP.termP.s] "
s <- manyTill anyChar $ char '\''
whiteSpace
traceM $ "[prodP.termP.s] " ++ show s
return $ GTerm NoAnnot s
nonTermP = do
s <- identifier
traceM $ "[nonTermP] " ++ s
return $ GNonTerm NoAnnot s
predP = do
traceM "[predP]"
reservedOp "{"
haskellParseExpTill "}?"
muteP = do
traceM "[muteP]"
reservedOp "{"
haskellParseExpTill "}"
directiveP = do
whiteSpace
symbol "->"
whiteSpace
str <- manyTill anyChar (char '\n')
whiteSpace
traceM $ "[directiveP]" ++ show str
return (toDirective $ trim $ str)
-- TODO: not use getInput
rEOF = do
y <- getInput
return (case y of
'-':'>':_ -> True
';':_ -> True
_ -> False)
toDirective [] = LowerD []
toDirective s@(h:rst)
| isUpper h = UpperD s
| otherwise = LowerD s
lexerP :: PS.Parser [G4]
lexerP = do
mAnnot <- optionMaybe annot
h <- upper
t <- manyTill anyChar (reservedOp ":")
traceM $ "Lexeme Name: " ++ (h:t)
r <- regexP rEOF
traceM $ "Regex: " ++ show r
optionMaybe $ symbol "->"
mDir <- optionMaybe $ manyTill anyToken (reservedOp ";")
return $ [Lex mAnnot (trim (h : t)) (LRHS r (toDirective <$> trim <$> mDir))]
where
annot = fragment -- <||> ....
fragment = do
reserved "fragment"
return Fragment
-- Parser combinators end
haskellParseExpTill :: String -> PS.Parser Exp
haskellParseExpTill op = do {
_ <- whiteSpace
; str <- manyTill anyChar (reservedOp op)
; haskellParseExp str
}
haskellParseExp :: String -> PS.Parser Exp
haskellParseExp str =
case LHM.parseExp str of
Left err -> error err -- PP.parserZero
Right expTH -> return expTH
whiteSpaceOrComment = comment <||> whiteSpace
where
comment = do
whiteSpace
reservedOp "//"
(manyTill anyChar $ try $ string "\n") <||> (manyTill anyChar $ try $ string "\r")
return ()
------------------------------------------------------------------------------
-- Lexer
lexer :: PT.TokenParser ()
lexer = PT.makeTokenParser $ haskellStyle
{ reservedOpNames = [";", "|", ":", "{", "}", "}?", "'"]
, reservedNames = ["grammar"]
, commentLine = "//"
, commentStart = "/*"
, commentEnd = "*/"
}
whiteSpace = PT.whiteSpace lexer
identifier = PT.identifier lexer
operator = PT.operator lexer
reserved = PT.reserved lexer
reservedOp = PT.reservedOp lexer
charLiteral = PT.charLiteral lexer
stringLiteral = PT.stringLiteral lexer
integer = PT.integer lexer
natural = PT.natural lexer
commaSep1 = PT.commaSep1 lexer
parens = PT.parens lexer
braces = PT.braces lexer
brackets = PT.brackets lexer
symbol = PT.symbol lexer
expr = PE.buildExpressionParser table term
<?> "expression"
term = natural
<?> "simple expression"
table = [ [prefix "-" negate, prefix "+" id ] ]
prefix name fun = PE.Prefix $ reservedOp name >> return fun
-- http://stackoverflow.com/a/6270382
trim xs = dropSpaceTail "" $ dropWhile isSpace xs
dropSpaceTail maybeStuff "" = ""
dropSpaceTail maybeStuff (x:xs)
| isSpace x = dropSpaceTail (x:maybeStuff) xs
| null maybeStuff = x : dropSpaceTail "" xs
| otherwise = reverse maybeStuff ++ x : dropSpaceTail "" xs
| 101795 | {-#LANGUAGE QuasiQuotes, TemplateHaskell#-}
{-|
Module : Language.ANTLR4.Boot.Parser
Description : ANTLR4 boot parser written with parsec
Copyright : (c) <NAME>, 2018
License : BSD3
Maintainer : <EMAIL>
Stability : experimental
Portability : POSIX
-}
module Language.ANTLR4.Boot.Parser where
-- syntax (Exp)
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import qualified Debug.Trace as D (trace, traceM)
import qualified Language.Haskell.Meta as LHM
-- monadic ops
import Control.Monad (mapM)
-- parsec
import Text.ParserCombinators.Parsec
import qualified Text.Parsec.String as PS
import qualified Text.Parsec.Prim as PP
import qualified Text.Parsec.Token as PT
import qualified Text.Parsec.Expr as PE
import qualified Text.Parsec.Combinator as PC
import Text.ParserCombinators.Parsec.Language (haskellStyle, reservedOpNames, reservedNames
, commentLine, commentStart, commentEnd)
import Text.ParserCombinators.Parsec.Pos (newPos)
-- text munging
import Data.Char
import Language.ANTLR4.Boot.Syntax
import Language.ANTLR4.Regex (parseRegex, regexP)
--traceM s = D.traceM ("[ANTLR4.Boot.Parser] " ++ s)
traceM = return
------------------------------------------------------------------------------
-- Or-Try Combinator (tries two parsers, one after the other)
(<||>) a b = try a <|> try b
parseANTLR :: SourceName -> Line -> Column -> String -> Either ParseError [G4]
parseANTLR fileName line column input =
PP.parse result fileName input
where
result = do
setPosition (newPos fileName line column)
whiteSpace
x <- gExps
traceM $ show x
eof <|> errorParse
return x
errorParse = do
rest <- manyTill anyToken eof
unexpected $ '"' : rest ++ "\""
gExps :: PS.Parser [G4]
gExps = concat <$> many1 gExp
gExp :: PS.Parser [G4]
gExp = do
traceM "gExp"
whiteSpace
xs <- grammarP <||> lexerP <||> prodP
traceM $ show xs
return xs
grammarP :: PS.Parser [G4]
grammarP = do
reserved "grammar"
h <- upper
t <- manyTill anyToken (reservedOp ";")
traceM $ show $ Grammar (h : t)
return [Grammar (h : t)]
-- | Assumptions:
--
-- * Directives must be on a single line.
-- *
prodP :: PS.Parser [G4]
prodP = do
h <- lower
t <- manyTill anyChar (reservedOp ":")
traceM $ "[prodP] " ++ trim (h : t)
rhsList <- sepBy1 rhsP (traceM "rhsList..." >> reservedOp "|")
traceM $ "[prodP.rhsList] " ++ show rhsList
reservedOp ";"
traceM "prodP returning..."
return [Prod (trim (h : t)) (concat rhsList)]
where
rhsP = do
mPred <- optionMaybe predP
traceM $ "[rhsP0] " ++ show mPred
alphaList <- many alphaP
traceM $ "[rhsP] " ++ show alphaList
mMute <- optionMaybe muteP
pDir <- optionMaybe directiveP
whiteSpace
return [PRHS alphaList mPred mMute pDir]
alphaP = termP <||> nonTermP
termP = do
whiteSpace
char '\''
traceM "[prodP.termP.s] "
s <- manyTill anyChar $ char '\''
whiteSpace
traceM $ "[prodP.termP.s] " ++ show s
return $ GTerm NoAnnot s
nonTermP = do
s <- identifier
traceM $ "[nonTermP] " ++ s
return $ GNonTerm NoAnnot s
predP = do
traceM "[predP]"
reservedOp "{"
haskellParseExpTill "}?"
muteP = do
traceM "[muteP]"
reservedOp "{"
haskellParseExpTill "}"
directiveP = do
whiteSpace
symbol "->"
whiteSpace
str <- manyTill anyChar (char '\n')
whiteSpace
traceM $ "[directiveP]" ++ show str
return (toDirective $ trim $ str)
-- TODO: not use getInput
rEOF = do
y <- getInput
return (case y of
'-':'>':_ -> True
';':_ -> True
_ -> False)
toDirective [] = LowerD []
toDirective s@(h:rst)
| isUpper h = UpperD s
| otherwise = LowerD s
lexerP :: PS.Parser [G4]
lexerP = do
mAnnot <- optionMaybe annot
h <- upper
t <- manyTill anyChar (reservedOp ":")
traceM $ "Lexeme Name: " ++ (h:t)
r <- regexP rEOF
traceM $ "Regex: " ++ show r
optionMaybe $ symbol "->"
mDir <- optionMaybe $ manyTill anyToken (reservedOp ";")
return $ [Lex mAnnot (trim (h : t)) (LRHS r (toDirective <$> trim <$> mDir))]
where
annot = fragment -- <||> ....
fragment = do
reserved "fragment"
return Fragment
-- Parser combinators end
haskellParseExpTill :: String -> PS.Parser Exp
haskellParseExpTill op = do {
_ <- whiteSpace
; str <- manyTill anyChar (reservedOp op)
; haskellParseExp str
}
haskellParseExp :: String -> PS.Parser Exp
haskellParseExp str =
case LHM.parseExp str of
Left err -> error err -- PP.parserZero
Right expTH -> return expTH
whiteSpaceOrComment = comment <||> whiteSpace
where
comment = do
whiteSpace
reservedOp "//"
(manyTill anyChar $ try $ string "\n") <||> (manyTill anyChar $ try $ string "\r")
return ()
------------------------------------------------------------------------------
-- Lexer
lexer :: PT.TokenParser ()
lexer = PT.makeTokenParser $ haskellStyle
{ reservedOpNames = [";", "|", ":", "{", "}", "}?", "'"]
, reservedNames = ["grammar"]
, commentLine = "//"
, commentStart = "/*"
, commentEnd = "*/"
}
whiteSpace = PT.whiteSpace lexer
identifier = PT.identifier lexer
operator = PT.operator lexer
reserved = PT.reserved lexer
reservedOp = PT.reservedOp lexer
charLiteral = PT.charLiteral lexer
stringLiteral = PT.stringLiteral lexer
integer = PT.integer lexer
natural = PT.natural lexer
commaSep1 = PT.commaSep1 lexer
parens = PT.parens lexer
braces = PT.braces lexer
brackets = PT.brackets lexer
symbol = PT.symbol lexer
expr = PE.buildExpressionParser table term
<?> "expression"
term = natural
<?> "simple expression"
table = [ [prefix "-" negate, prefix "+" id ] ]
prefix name fun = PE.Prefix $ reservedOp name >> return fun
-- http://stackoverflow.com/a/6270382
trim xs = dropSpaceTail "" $ dropWhile isSpace xs
dropSpaceTail maybeStuff "" = ""
dropSpaceTail maybeStuff (x:xs)
| isSpace x = dropSpaceTail (x:maybeStuff) xs
| null maybeStuff = x : dropSpaceTail "" xs
| otherwise = reverse maybeStuff ++ x : dropSpaceTail "" xs
| true | {-#LANGUAGE QuasiQuotes, TemplateHaskell#-}
{-|
Module : Language.ANTLR4.Boot.Parser
Description : ANTLR4 boot parser written with parsec
Copyright : (c) PI:NAME:<NAME>END_PI, 2018
License : BSD3
Maintainer : PI:EMAIL:<EMAIL>END_PI
Stability : experimental
Portability : POSIX
-}
module Language.ANTLR4.Boot.Parser where
-- syntax (Exp)
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import qualified Debug.Trace as D (trace, traceM)
import qualified Language.Haskell.Meta as LHM
-- monadic ops
import Control.Monad (mapM)
-- parsec
import Text.ParserCombinators.Parsec
import qualified Text.Parsec.String as PS
import qualified Text.Parsec.Prim as PP
import qualified Text.Parsec.Token as PT
import qualified Text.Parsec.Expr as PE
import qualified Text.Parsec.Combinator as PC
import Text.ParserCombinators.Parsec.Language (haskellStyle, reservedOpNames, reservedNames
, commentLine, commentStart, commentEnd)
import Text.ParserCombinators.Parsec.Pos (newPos)
-- text munging
import Data.Char
import Language.ANTLR4.Boot.Syntax
import Language.ANTLR4.Regex (parseRegex, regexP)
--traceM s = D.traceM ("[ANTLR4.Boot.Parser] " ++ s)
traceM = return
------------------------------------------------------------------------------
-- Or-Try Combinator (tries two parsers, one after the other)
(<||>) a b = try a <|> try b
parseANTLR :: SourceName -> Line -> Column -> String -> Either ParseError [G4]
parseANTLR fileName line column input =
PP.parse result fileName input
where
result = do
setPosition (newPos fileName line column)
whiteSpace
x <- gExps
traceM $ show x
eof <|> errorParse
return x
errorParse = do
rest <- manyTill anyToken eof
unexpected $ '"' : rest ++ "\""
gExps :: PS.Parser [G4]
gExps = concat <$> many1 gExp
gExp :: PS.Parser [G4]
gExp = do
traceM "gExp"
whiteSpace
xs <- grammarP <||> lexerP <||> prodP
traceM $ show xs
return xs
grammarP :: PS.Parser [G4]
grammarP = do
reserved "grammar"
h <- upper
t <- manyTill anyToken (reservedOp ";")
traceM $ show $ Grammar (h : t)
return [Grammar (h : t)]
-- | Assumptions:
--
-- * Directives must be on a single line.
-- *
prodP :: PS.Parser [G4]
prodP = do
h <- lower
t <- manyTill anyChar (reservedOp ":")
traceM $ "[prodP] " ++ trim (h : t)
rhsList <- sepBy1 rhsP (traceM "rhsList..." >> reservedOp "|")
traceM $ "[prodP.rhsList] " ++ show rhsList
reservedOp ";"
traceM "prodP returning..."
return [Prod (trim (h : t)) (concat rhsList)]
where
rhsP = do
mPred <- optionMaybe predP
traceM $ "[rhsP0] " ++ show mPred
alphaList <- many alphaP
traceM $ "[rhsP] " ++ show alphaList
mMute <- optionMaybe muteP
pDir <- optionMaybe directiveP
whiteSpace
return [PRHS alphaList mPred mMute pDir]
alphaP = termP <||> nonTermP
termP = do
whiteSpace
char '\''
traceM "[prodP.termP.s] "
s <- manyTill anyChar $ char '\''
whiteSpace
traceM $ "[prodP.termP.s] " ++ show s
return $ GTerm NoAnnot s
nonTermP = do
s <- identifier
traceM $ "[nonTermP] " ++ s
return $ GNonTerm NoAnnot s
predP = do
traceM "[predP]"
reservedOp "{"
haskellParseExpTill "}?"
muteP = do
traceM "[muteP]"
reservedOp "{"
haskellParseExpTill "}"
directiveP = do
whiteSpace
symbol "->"
whiteSpace
str <- manyTill anyChar (char '\n')
whiteSpace
traceM $ "[directiveP]" ++ show str
return (toDirective $ trim $ str)
-- TODO: not use getInput
rEOF = do
y <- getInput
return (case y of
'-':'>':_ -> True
';':_ -> True
_ -> False)
toDirective [] = LowerD []
toDirective s@(h:rst)
| isUpper h = UpperD s
| otherwise = LowerD s
lexerP :: PS.Parser [G4]
lexerP = do
mAnnot <- optionMaybe annot
h <- upper
t <- manyTill anyChar (reservedOp ":")
traceM $ "Lexeme Name: " ++ (h:t)
r <- regexP rEOF
traceM $ "Regex: " ++ show r
optionMaybe $ symbol "->"
mDir <- optionMaybe $ manyTill anyToken (reservedOp ";")
return $ [Lex mAnnot (trim (h : t)) (LRHS r (toDirective <$> trim <$> mDir))]
where
annot = fragment -- <||> ....
fragment = do
reserved "fragment"
return Fragment
-- Parser combinators end
haskellParseExpTill :: String -> PS.Parser Exp
haskellParseExpTill op = do {
_ <- whiteSpace
; str <- manyTill anyChar (reservedOp op)
; haskellParseExp str
}
haskellParseExp :: String -> PS.Parser Exp
haskellParseExp str =
case LHM.parseExp str of
Left err -> error err -- PP.parserZero
Right expTH -> return expTH
whiteSpaceOrComment = comment <||> whiteSpace
where
comment = do
whiteSpace
reservedOp "//"
(manyTill anyChar $ try $ string "\n") <||> (manyTill anyChar $ try $ string "\r")
return ()
------------------------------------------------------------------------------
-- Lexer
lexer :: PT.TokenParser ()
lexer = PT.makeTokenParser $ haskellStyle
{ reservedOpNames = [";", "|", ":", "{", "}", "}?", "'"]
, reservedNames = ["grammar"]
, commentLine = "//"
, commentStart = "/*"
, commentEnd = "*/"
}
whiteSpace = PT.whiteSpace lexer
identifier = PT.identifier lexer
operator = PT.operator lexer
reserved = PT.reserved lexer
reservedOp = PT.reservedOp lexer
charLiteral = PT.charLiteral lexer
stringLiteral = PT.stringLiteral lexer
integer = PT.integer lexer
natural = PT.natural lexer
commaSep1 = PT.commaSep1 lexer
parens = PT.parens lexer
braces = PT.braces lexer
brackets = PT.brackets lexer
symbol = PT.symbol lexer
expr = PE.buildExpressionParser table term
<?> "expression"
term = natural
<?> "simple expression"
table = [ [prefix "-" negate, prefix "+" id ] ]
prefix name fun = PE.Prefix $ reservedOp name >> return fun
-- http://stackoverflow.com/a/6270382
trim xs = dropSpaceTail "" $ dropWhile isSpace xs
dropSpaceTail maybeStuff "" = ""
dropSpaceTail maybeStuff (x:xs)
| isSpace x = dropSpaceTail (x:maybeStuff) xs
| null maybeStuff = x : dropSpaceTail "" xs
| otherwise = reverse maybeStuff ++ x : dropSpaceTail "" xs
|
[
{
"context": "hy\n (u/update-user (merge foo {:username \"foo\" :password \"123\"}))\n (u/get-user id) => (",
"end": 675,
"score": 0.9861178994178772,
"start": 672,
"tag": "USERNAME",
"value": "foo"
},
{
"context": "pdate-user (merge foo {:username \"foo\" :password \"123\"}))\n (u/get-user id) => (merge foo {:user",
"end": 691,
"score": 0.9993753433227539,
"start": 688,
"tag": "PASSWORD",
"value": "123"
},
{
"context": " (u/get-user id) => (merge foo {:username \"foo\" :password \"123\"})\n (u/delete-user id)\n ",
"end": 750,
"score": 0.9388178586959839,
"start": 747,
"tag": "USERNAME",
"value": "foo"
},
{
"context": "ser id) => (merge foo {:username \"foo\" :password \"123\"})\n (u/delete-user id)\n (u/user-e",
"end": 766,
"score": 0.999386727809906,
"start": 763,
"tag": "PASSWORD",
"value": "123"
}
] | test/re_core/integration/persistency.clj | celestial-ops/core | 1 | (ns re-core.integration.persistency
"Integration test for persistency that use a redis instance"
(:refer-clojure :exclude [type])
(:import clojure.lang.ExceptionInfo)
(:require
[re-core.fixtures.data :refer (foo)]
[re-core.fixtures.core :refer (with-conf is-type?)]
[re-core.fixtures.populate :refer (re-initlize)]
[re-core.persistency.users :as u])
(:use midje.sweet))
(with-conf
(with-state-changes [(before :facts (re-initlize))]
(fact "generated crud user ops" :integration :redis
(let [id (u/add-user foo)]
(u/get-user id) => foo
(u/user-exists? id) => truthy
(u/update-user (merge foo {:username "foo" :password "123"}))
(u/get-user id) => (merge foo {:username "foo" :password "123"})
(u/delete-user id)
(u/user-exists? id) => falsey))
(fact "non valid user" :integration :redis
(u/add-user (dissoc foo :username)) =>
(throws ExceptionInfo (is-type? :re-core.persistency.users/non-valid-user))
(u/update-user (dissoc foo :username)) =>
(throws ExceptionInfo (is-type? :re-core.persistency.users/non-valid-user)))))
| 86414 | (ns re-core.integration.persistency
"Integration test for persistency that use a redis instance"
(:refer-clojure :exclude [type])
(:import clojure.lang.ExceptionInfo)
(:require
[re-core.fixtures.data :refer (foo)]
[re-core.fixtures.core :refer (with-conf is-type?)]
[re-core.fixtures.populate :refer (re-initlize)]
[re-core.persistency.users :as u])
(:use midje.sweet))
(with-conf
(with-state-changes [(before :facts (re-initlize))]
(fact "generated crud user ops" :integration :redis
(let [id (u/add-user foo)]
(u/get-user id) => foo
(u/user-exists? id) => truthy
(u/update-user (merge foo {:username "foo" :password "<PASSWORD>"}))
(u/get-user id) => (merge foo {:username "foo" :password "<PASSWORD>"})
(u/delete-user id)
(u/user-exists? id) => falsey))
(fact "non valid user" :integration :redis
(u/add-user (dissoc foo :username)) =>
(throws ExceptionInfo (is-type? :re-core.persistency.users/non-valid-user))
(u/update-user (dissoc foo :username)) =>
(throws ExceptionInfo (is-type? :re-core.persistency.users/non-valid-user)))))
| true | (ns re-core.integration.persistency
"Integration test for persistency that use a redis instance"
(:refer-clojure :exclude [type])
(:import clojure.lang.ExceptionInfo)
(:require
[re-core.fixtures.data :refer (foo)]
[re-core.fixtures.core :refer (with-conf is-type?)]
[re-core.fixtures.populate :refer (re-initlize)]
[re-core.persistency.users :as u])
(:use midje.sweet))
(with-conf
(with-state-changes [(before :facts (re-initlize))]
(fact "generated crud user ops" :integration :redis
(let [id (u/add-user foo)]
(u/get-user id) => foo
(u/user-exists? id) => truthy
(u/update-user (merge foo {:username "foo" :password "PI:PASSWORD:<PASSWORD>END_PI"}))
(u/get-user id) => (merge foo {:username "foo" :password "PI:PASSWORD:<PASSWORD>END_PI"})
(u/delete-user id)
(u/user-exists? id) => falsey))
(fact "non valid user" :integration :redis
(u/add-user (dissoc foo :username)) =>
(throws ExceptionInfo (is-type? :re-core.persistency.users/non-valid-user))
(u/update-user (dissoc foo :username)) =>
(throws ExceptionInfo (is-type? :re-core.persistency.users/non-valid-user)))))
|
[
{
"context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.bixby.plugs.file",
"end": 597,
"score": 0.9998542666435242,
"start": 584,
"tag": "NAME",
"value": "Kenneth Leung"
}
] | src/main/clojure/czlab/bixby/plugs/files.clj | llnek/skaro | 0 | ;; 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.
;;
;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.
(ns czlab.bixby.plugs.files
"Implementation for FilePicker."
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[czlab.basal.util :as u]
[czlab.basal.io :as i]
[czlab.bixby.core :as b]
[czlab.bixby.plugs.loops :as l]
[czlab.basal.core :as c :refer [n#]])
(:import [java.util Timer Properties ResourceBundle]
[java.io FileFilter File IOException]
[clojure.lang APersistentMap]
[org.apache.commons.io.filefilter
SuffixFileFilter
PrefixFileFilter
RegexFileFilter
FileFileFilter]
[org.apache.commons.io.monitor
FileAlterationListener
FileAlterationMonitor
FileAlterationObserver
FileAlterationListenerAdaptor]
[org.apache.commons.io FileUtils]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* false)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord FileMsg []
c/Idable
(id [_] (:id _))
c/Hierarchical
(parent [me] (:source me)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- evt<>
[co fname fp action]
(c/object<> FileMsg
:source co
:file (io/file fp)
:original-fname fname
:id (str "FileMsg#" (u/seqint2))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- post-poll
"Only look for new files."
[{{:keys [recv-folder]} :conf :as plug} f action]
(let [orig (i/fname f)]
(when-some
[cf (if (and recv-folder
(not= action :FP-DELETED))
(c/try! (c/doto->> (io/file recv-folder orig)
(FileUtils/moveFile ^File f))))]
(b/dispatch (evt<> plug orig cf action)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- init2
[conf]
(letfn
[(to-fmask [mask]
(cond (cs/starts-with? mask "*.")
(SuffixFileFilter. (subs mask 1))
(cs/ends-with? mask "*")
(PrefixFileFilter.
(subs mask 0 (- (n# mask) 1)))
(not-empty mask)
(RegexFileFilter. ^String mask)
:else
FileFileFilter/FILE))]
(let [{:keys [fmask]
dest :recv-folder
root :target-folder} conf]
(assert (c/hgl? root)
(c/fmt "Bad root-folder %s." root))
(c/info (str "source dir: %s\n"
"receiving dir: %s") root dest)
(assoc conf
:fmask (to-fmask (str fmask))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- file-mon<>
[plug]
(let [{:keys [target-folder
interval-secs
^FileFilter fmask]} (:conf plug)]
[(FileAlterationMonitor. (b/s2ms interval-secs))
(-> (io/file target-folder) (FileAlterationObserver. fmask))]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord FilePickerPlugin [server _id info conf]
c/Hierarchical
(parent [_] server)
c/Idable
(id [_] _id)
c/Initable
(init [me arg]
(update-in me
[:conf]
#(-> (c/merge+ % arg)
b/expand-vars* b/prevar-cfg init2)))
c/Finzable
(finz [_] (c/stop _))
c/Startable
(start [_]
(c/start _ nil))
(start [me arg]
(let [[^FileAlterationMonitor mon
^FileAlterationObserver obs] (file-mon<> me)
plug (assoc me :monitor mon)]
(.addListener obs (proxy [FileAlterationListenerAdaptor][]
(onFileCreate [f]
(post-poll plug f :FP-CREATED))
(onFileChange [f]
(post-poll plug f :FP-CHANGED))
(onFileDelete [f]
(post-poll plug f :FP-DELETED))))
(.addObserver mon obs)
(l/cfg-timer (Timer. true)
#(do (c/info "apache io monitor starting...")
(.start ^FileAlterationMonitor mon)) conf false)
plug))
(stop [me]
(c/info "apache io monitor stopping...")
(some-> ^FileAlterationMonitor (:monitor me) .stop)
(assoc me :monitor nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def
^{:doc ""}
FilePickerSpec
{:info {:name "File Picker"
:version "1.0.0"}
:conf {:$pluggable ::file-picker<>
:$action nil
:$error nil
:interval-secs 300
:delay-secs 0
:fmask ""
:recv-folder "/home/joe"
:target-folder "/home/dropbox"}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn file-picker<>
"Create a File Picker Plugin."
{:arglists '([server id]
[server id options])}
([_ id]
(file-picker<> _ id FilePickerSpec))
([server id {:keys [info conf]}]
(FilePickerPlugin. server id info conf)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| 76906 | ;; 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.
;;
;; Copyright © 2013-2022, <NAME>. All rights reserved.
(ns czlab.bixby.plugs.files
"Implementation for FilePicker."
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[czlab.basal.util :as u]
[czlab.basal.io :as i]
[czlab.bixby.core :as b]
[czlab.bixby.plugs.loops :as l]
[czlab.basal.core :as c :refer [n#]])
(:import [java.util Timer Properties ResourceBundle]
[java.io FileFilter File IOException]
[clojure.lang APersistentMap]
[org.apache.commons.io.filefilter
SuffixFileFilter
PrefixFileFilter
RegexFileFilter
FileFileFilter]
[org.apache.commons.io.monitor
FileAlterationListener
FileAlterationMonitor
FileAlterationObserver
FileAlterationListenerAdaptor]
[org.apache.commons.io FileUtils]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* false)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord FileMsg []
c/Idable
(id [_] (:id _))
c/Hierarchical
(parent [me] (:source me)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- evt<>
[co fname fp action]
(c/object<> FileMsg
:source co
:file (io/file fp)
:original-fname fname
:id (str "FileMsg#" (u/seqint2))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- post-poll
"Only look for new files."
[{{:keys [recv-folder]} :conf :as plug} f action]
(let [orig (i/fname f)]
(when-some
[cf (if (and recv-folder
(not= action :FP-DELETED))
(c/try! (c/doto->> (io/file recv-folder orig)
(FileUtils/moveFile ^File f))))]
(b/dispatch (evt<> plug orig cf action)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- init2
[conf]
(letfn
[(to-fmask [mask]
(cond (cs/starts-with? mask "*.")
(SuffixFileFilter. (subs mask 1))
(cs/ends-with? mask "*")
(PrefixFileFilter.
(subs mask 0 (- (n# mask) 1)))
(not-empty mask)
(RegexFileFilter. ^String mask)
:else
FileFileFilter/FILE))]
(let [{:keys [fmask]
dest :recv-folder
root :target-folder} conf]
(assert (c/hgl? root)
(c/fmt "Bad root-folder %s." root))
(c/info (str "source dir: %s\n"
"receiving dir: %s") root dest)
(assoc conf
:fmask (to-fmask (str fmask))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- file-mon<>
[plug]
(let [{:keys [target-folder
interval-secs
^FileFilter fmask]} (:conf plug)]
[(FileAlterationMonitor. (b/s2ms interval-secs))
(-> (io/file target-folder) (FileAlterationObserver. fmask))]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord FilePickerPlugin [server _id info conf]
c/Hierarchical
(parent [_] server)
c/Idable
(id [_] _id)
c/Initable
(init [me arg]
(update-in me
[:conf]
#(-> (c/merge+ % arg)
b/expand-vars* b/prevar-cfg init2)))
c/Finzable
(finz [_] (c/stop _))
c/Startable
(start [_]
(c/start _ nil))
(start [me arg]
(let [[^FileAlterationMonitor mon
^FileAlterationObserver obs] (file-mon<> me)
plug (assoc me :monitor mon)]
(.addListener obs (proxy [FileAlterationListenerAdaptor][]
(onFileCreate [f]
(post-poll plug f :FP-CREATED))
(onFileChange [f]
(post-poll plug f :FP-CHANGED))
(onFileDelete [f]
(post-poll plug f :FP-DELETED))))
(.addObserver mon obs)
(l/cfg-timer (Timer. true)
#(do (c/info "apache io monitor starting...")
(.start ^FileAlterationMonitor mon)) conf false)
plug))
(stop [me]
(c/info "apache io monitor stopping...")
(some-> ^FileAlterationMonitor (:monitor me) .stop)
(assoc me :monitor nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def
^{:doc ""}
FilePickerSpec
{:info {:name "File Picker"
:version "1.0.0"}
:conf {:$pluggable ::file-picker<>
:$action nil
:$error nil
:interval-secs 300
:delay-secs 0
:fmask ""
:recv-folder "/home/joe"
:target-folder "/home/dropbox"}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn file-picker<>
"Create a File Picker Plugin."
{:arglists '([server id]
[server id options])}
([_ id]
(file-picker<> _ id FilePickerSpec))
([server id {:keys [info conf]}]
(FilePickerPlugin. server id info conf)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| true | ;; 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.
;;
;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved.
(ns czlab.bixby.plugs.files
"Implementation for FilePicker."
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[czlab.basal.util :as u]
[czlab.basal.io :as i]
[czlab.bixby.core :as b]
[czlab.bixby.plugs.loops :as l]
[czlab.basal.core :as c :refer [n#]])
(:import [java.util Timer Properties ResourceBundle]
[java.io FileFilter File IOException]
[clojure.lang APersistentMap]
[org.apache.commons.io.filefilter
SuffixFileFilter
PrefixFileFilter
RegexFileFilter
FileFileFilter]
[org.apache.commons.io.monitor
FileAlterationListener
FileAlterationMonitor
FileAlterationObserver
FileAlterationListenerAdaptor]
[org.apache.commons.io FileUtils]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* false)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord FileMsg []
c/Idable
(id [_] (:id _))
c/Hierarchical
(parent [me] (:source me)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- evt<>
[co fname fp action]
(c/object<> FileMsg
:source co
:file (io/file fp)
:original-fname fname
:id (str "FileMsg#" (u/seqint2))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- post-poll
"Only look for new files."
[{{:keys [recv-folder]} :conf :as plug} f action]
(let [orig (i/fname f)]
(when-some
[cf (if (and recv-folder
(not= action :FP-DELETED))
(c/try! (c/doto->> (io/file recv-folder orig)
(FileUtils/moveFile ^File f))))]
(b/dispatch (evt<> plug orig cf action)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- init2
[conf]
(letfn
[(to-fmask [mask]
(cond (cs/starts-with? mask "*.")
(SuffixFileFilter. (subs mask 1))
(cs/ends-with? mask "*")
(PrefixFileFilter.
(subs mask 0 (- (n# mask) 1)))
(not-empty mask)
(RegexFileFilter. ^String mask)
:else
FileFileFilter/FILE))]
(let [{:keys [fmask]
dest :recv-folder
root :target-folder} conf]
(assert (c/hgl? root)
(c/fmt "Bad root-folder %s." root))
(c/info (str "source dir: %s\n"
"receiving dir: %s") root dest)
(assoc conf
:fmask (to-fmask (str fmask))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- file-mon<>
[plug]
(let [{:keys [target-folder
interval-secs
^FileFilter fmask]} (:conf plug)]
[(FileAlterationMonitor. (b/s2ms interval-secs))
(-> (io/file target-folder) (FileAlterationObserver. fmask))]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord FilePickerPlugin [server _id info conf]
c/Hierarchical
(parent [_] server)
c/Idable
(id [_] _id)
c/Initable
(init [me arg]
(update-in me
[:conf]
#(-> (c/merge+ % arg)
b/expand-vars* b/prevar-cfg init2)))
c/Finzable
(finz [_] (c/stop _))
c/Startable
(start [_]
(c/start _ nil))
(start [me arg]
(let [[^FileAlterationMonitor mon
^FileAlterationObserver obs] (file-mon<> me)
plug (assoc me :monitor mon)]
(.addListener obs (proxy [FileAlterationListenerAdaptor][]
(onFileCreate [f]
(post-poll plug f :FP-CREATED))
(onFileChange [f]
(post-poll plug f :FP-CHANGED))
(onFileDelete [f]
(post-poll plug f :FP-DELETED))))
(.addObserver mon obs)
(l/cfg-timer (Timer. true)
#(do (c/info "apache io monitor starting...")
(.start ^FileAlterationMonitor mon)) conf false)
plug))
(stop [me]
(c/info "apache io monitor stopping...")
(some-> ^FileAlterationMonitor (:monitor me) .stop)
(assoc me :monitor nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def
^{:doc ""}
FilePickerSpec
{:info {:name "File Picker"
:version "1.0.0"}
:conf {:$pluggable ::file-picker<>
:$action nil
:$error nil
:interval-secs 300
:delay-secs 0
:fmask ""
:recv-folder "/home/joe"
:target-folder "/home/dropbox"}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn file-picker<>
"Create a File Picker Plugin."
{:arglists '([server id]
[server id options])}
([_ id]
(file-picker<> _ id FilePickerSpec))
([server id {:keys [info conf]}]
(FilePickerPlugin. server id info conf)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
|
[
{
"context": " :threadID \"t_1\"\n :threadName \"Jing and Bill\"\n :authorName \"Bill\"\n ",
"end": 422,
"score": 0.9991786479949951,
"start": 409,
"tag": "NAME",
"value": "Jing and Bill"
},
{
"context": "Name \"Jing and Bill\"\n :authorName \"Bill\"\n :text \"Hey Jing want to give a F",
"end": 457,
"score": 0.999778151512146,
"start": 453,
"tag": "NAME",
"value": "Bill"
},
{
"context": " :authorName \"Bill\"\n :text \"Hey Jing want to give a Flux talk at ForwardJS?\"\n ",
"end": 490,
"score": 0.9939073920249939,
"start": 486,
"tag": "NAME",
"value": "Jing"
},
{
"context": " :threadID \"t_1\"\n :threadName \"Jing and Bill\"\n :authorName \"Bill\"\n ",
"end": 695,
"score": 0.9992706179618835,
"start": 682,
"tag": "NAME",
"value": "Jing and Bill"
},
{
"context": "Name \"Jing and Bill\"\n :authorName \"Bill\"\n :text \"Seems like a pretty cool ",
"end": 730,
"score": 0.9997825622558594,
"start": 726,
"tag": "NAME",
"value": "Bill"
},
{
"context": " :threadID \"t_1\"\n :threadName \"Jing and Bill\"\n :authorName \"Jing\"\n ",
"end": 957,
"score": 0.9991201162338257,
"start": 944,
"tag": "NAME",
"value": "Jing and Bill"
},
{
"context": "Name \"Jing and Bill\"\n :authorName \"Jing\"\n :text \"Sounds good. Will they b",
"end": 992,
"score": 0.9997718334197998,
"start": 988,
"tag": "NAME",
"value": "Jing"
},
{
"context": " :threadID \"t_2\"\n :threadName \"Dave and Bill\"\n :authorName \"Bill\"\n ",
"end": 1226,
"score": 0.9947370290756226,
"start": 1213,
"tag": "NAME",
"value": "Dave and Bill"
},
{
"context": "Name \"Dave and Bill\"\n :authorName \"Bill\"\n :text \"Hey Dave want to get a be",
"end": 1261,
"score": 0.999795138835907,
"start": 1257,
"tag": "NAME",
"value": "Bill"
},
{
"context": " :authorName \"Bill\"\n :text \"Hey Dave want to get a beer after the conference?\"\n ",
"end": 1294,
"score": 0.9993773102760315,
"start": 1290,
"tag": "NAME",
"value": "Dave"
},
{
"context": " :threadID \"t_2\"\n :threadName \"Dave and Bill\"\n :authorName \"Dave\"\n ",
"end": 1501,
"score": 0.9992324709892273,
"start": 1488,
"tag": "NAME",
"value": "Dave and Bill"
},
{
"context": "Name \"Dave and Bill\"\n :authorName \"Dave\"\n :text \"Totally! Meet you at the",
"end": 1536,
"score": 0.999762237071991,
"start": 1532,
"tag": "NAME",
"value": "Dave"
},
{
"context": "e \"Functional Heads\"\n :authorName \"Bill\"\n :text \"Hey Brian are you going t",
"end": 1801,
"score": 0.9997718930244446,
"start": 1797,
"tag": "NAME",
"value": "Bill"
},
{
"context": " :authorName \"Bill\"\n :text \"Hey Brian are you going to be talking about functional stuf",
"end": 1835,
"score": 0.9938368797302246,
"start": 1830,
"tag": "NAME",
"value": "Brian"
},
{
"context": " :threadID \"t_3\"\n :threadName \"Bill and Brian\"\n :authorName \"Brian\"\n ",
"end": 2054,
"score": 0.996797502040863,
"start": 2040,
"tag": "NAME",
"value": "Bill and Brian"
},
{
"context": "ame \"Bill and Brian\"\n :authorName \"Brian\"\n :text \"At ForwardJS? Yeah of co",
"end": 2090,
"score": 0.9998282194137573,
"start": 2085,
"tag": "NAME",
"value": "Brian"
}
] | src/om_chat/core.cljs | colinf/om-chat-base | 5 | (ns om-chat.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [goog.dom :as gdom]
[om.next :as om :refer-macros [defui]]
[om.dom :as dom]
[cljs-time.core :as dt]
[cljs-time.coerce :as dt2]))
(enable-console-print!)
(def raw-data [
{
:id "m_1"
:threadID "t_1"
:threadName "Jing and Bill"
:authorName "Bill"
:text "Hey Jing want to give a Flux talk at ForwardJS?"
:timestamp (- (dt/now) 99999)}
{
:id "m_2"
:threadID "t_1"
:threadName "Jing and Bill"
:authorName "Bill"
:text "Seems like a pretty cool conference."
:timestamp (- (dt/now) 89999)}
{
:id "m_3"
:threadID "t_1"
:threadName "Jing and Bill"
:authorName "Jing"
:text "Sounds good. Will they be serving dessert?"
:timestamp (- (dt/now) 79999)}
{
:id "m_4"
:threadID "t_2"
:threadName "Dave and Bill"
:authorName "Bill"
:text "Hey Dave want to get a beer after the conference?"
:timestamp (- (dt/now) 69999)}
{
:id "m_5"
:threadID "t_2"
:threadName "Dave and Bill"
:authorName "Dave"
:text "Totally! Meet you at the hotel bar."
:timestamp (- (dt/now) 59999)}
{
:id "m_6"
:threadID "t_3"
:threadName "Functional Heads"
:authorName "Bill"
:text "Hey Brian are you going to be talking about functional stuff?"
:timestamp (- (dt/now) 49999)}
{
:id "m_7"
:threadID "t_3"
:threadName "Bill and Brian"
:authorName "Brian"
:text "At ForwardJS? Yeah of course. See you there!"
:timestamp (- (dt/now) 39999)}])
(defn convert-message [{:keys [id authorName text timestamp] :as msg}]
{:message/id id
:message/author-name authorName
:message/text text
:message/date (dt2/to-date timestamp)
}
)
(defn threads-by-id [coll msg]
(let [{:keys [id threadID threadName timestamp]} msg]
(if (contains? coll threadID)
(assoc-in coll [threadID :thread/messages id]
(convert-message msg))
(assoc coll threadID
{:thread/id threadID
:thread/name threadName
:thread/messages {id (convert-message msg)}
})
))
)
(defn threads [coll msg]
(let [{:keys [id threadID threadName timestamp]} msg
{:keys [thread/id]} (last coll)
last-msg-idx (dec (count coll))]
(if (= id threadID)
(update-in coll [last-msg-idx :thread/messages] conj (convert-message msg))
(conj coll
{:thread/id threadID
:thread/name threadName
:thread/messages [(convert-message msg)]
})
))
)
(defui MessageSection
static om/Ident
(ident [this {:keys [message/id]}]
[:messages/by-id id])
static om/IQuery
(query [this]
[:message/id :message/author-name :message/date :message/text])
Object
(render [this]
(dom/div #js{:className "message-section"}
"Message section...")))
(def message-section (om/factory MessageSection))
(defui ThreadSection
static om/Ident
(ident [this {:keys [thread/id]}]
[:threads/by-id id])
static om/IQuery
(query [this]
[:thread/id :thread/name :thread/read :thread/selected
{:thread/last-message [:message/date :message/text]}
{:thread/messages (om/get-query MessageSection)}])
Object
(render [this]
(dom/div #js{:className "thread-section"}
"Thread Section...")
))
(def thread-section (om/factory ThreadSection))
(defui ChatApp
static om/IQuery
(query [this]
[{:threads (om/get-query ThreadSection)}])
Object
(render [this]
(let [{:keys [threads]} (om/props this)]
(dom/div #js{:className "chatapp"}
(thread-section threads)
(message-section (last threads))))))
(defmulti read om/dispatch)
(defmethod read :default
[{:keys [state] :as env} k _]
(let [st @state]
(if (contains? st k)
{:value (get st k)}
{:remote true})))
(def reconciler
(om/reconciler {:state {:threads (reduce threads [] raw-data)}
:parser (om/parser {:read read})}))
(om/add-root! reconciler
ChatApp
(gdom/getElement "app"))
| 73535 | (ns om-chat.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [goog.dom :as gdom]
[om.next :as om :refer-macros [defui]]
[om.dom :as dom]
[cljs-time.core :as dt]
[cljs-time.coerce :as dt2]))
(enable-console-print!)
(def raw-data [
{
:id "m_1"
:threadID "t_1"
:threadName "<NAME>"
:authorName "<NAME>"
:text "Hey <NAME> want to give a Flux talk at ForwardJS?"
:timestamp (- (dt/now) 99999)}
{
:id "m_2"
:threadID "t_1"
:threadName "<NAME>"
:authorName "<NAME>"
:text "Seems like a pretty cool conference."
:timestamp (- (dt/now) 89999)}
{
:id "m_3"
:threadID "t_1"
:threadName "<NAME>"
:authorName "<NAME>"
:text "Sounds good. Will they be serving dessert?"
:timestamp (- (dt/now) 79999)}
{
:id "m_4"
:threadID "t_2"
:threadName "<NAME>"
:authorName "<NAME>"
:text "Hey <NAME> want to get a beer after the conference?"
:timestamp (- (dt/now) 69999)}
{
:id "m_5"
:threadID "t_2"
:threadName "<NAME>"
:authorName "<NAME>"
:text "Totally! Meet you at the hotel bar."
:timestamp (- (dt/now) 59999)}
{
:id "m_6"
:threadID "t_3"
:threadName "Functional Heads"
:authorName "<NAME>"
:text "Hey <NAME> are you going to be talking about functional stuff?"
:timestamp (- (dt/now) 49999)}
{
:id "m_7"
:threadID "t_3"
:threadName "<NAME>"
:authorName "<NAME>"
:text "At ForwardJS? Yeah of course. See you there!"
:timestamp (- (dt/now) 39999)}])
(defn convert-message [{:keys [id authorName text timestamp] :as msg}]
{:message/id id
:message/author-name authorName
:message/text text
:message/date (dt2/to-date timestamp)
}
)
(defn threads-by-id [coll msg]
(let [{:keys [id threadID threadName timestamp]} msg]
(if (contains? coll threadID)
(assoc-in coll [threadID :thread/messages id]
(convert-message msg))
(assoc coll threadID
{:thread/id threadID
:thread/name threadName
:thread/messages {id (convert-message msg)}
})
))
)
(defn threads [coll msg]
(let [{:keys [id threadID threadName timestamp]} msg
{:keys [thread/id]} (last coll)
last-msg-idx (dec (count coll))]
(if (= id threadID)
(update-in coll [last-msg-idx :thread/messages] conj (convert-message msg))
(conj coll
{:thread/id threadID
:thread/name threadName
:thread/messages [(convert-message msg)]
})
))
)
(defui MessageSection
static om/Ident
(ident [this {:keys [message/id]}]
[:messages/by-id id])
static om/IQuery
(query [this]
[:message/id :message/author-name :message/date :message/text])
Object
(render [this]
(dom/div #js{:className "message-section"}
"Message section...")))
(def message-section (om/factory MessageSection))
(defui ThreadSection
static om/Ident
(ident [this {:keys [thread/id]}]
[:threads/by-id id])
static om/IQuery
(query [this]
[:thread/id :thread/name :thread/read :thread/selected
{:thread/last-message [:message/date :message/text]}
{:thread/messages (om/get-query MessageSection)}])
Object
(render [this]
(dom/div #js{:className "thread-section"}
"Thread Section...")
))
(def thread-section (om/factory ThreadSection))
(defui ChatApp
static om/IQuery
(query [this]
[{:threads (om/get-query ThreadSection)}])
Object
(render [this]
(let [{:keys [threads]} (om/props this)]
(dom/div #js{:className "chatapp"}
(thread-section threads)
(message-section (last threads))))))
(defmulti read om/dispatch)
(defmethod read :default
[{:keys [state] :as env} k _]
(let [st @state]
(if (contains? st k)
{:value (get st k)}
{:remote true})))
(def reconciler
(om/reconciler {:state {:threads (reduce threads [] raw-data)}
:parser (om/parser {:read read})}))
(om/add-root! reconciler
ChatApp
(gdom/getElement "app"))
| true | (ns om-chat.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [goog.dom :as gdom]
[om.next :as om :refer-macros [defui]]
[om.dom :as dom]
[cljs-time.core :as dt]
[cljs-time.coerce :as dt2]))
(enable-console-print!)
(def raw-data [
{
:id "m_1"
:threadID "t_1"
:threadName "PI:NAME:<NAME>END_PI"
:authorName "PI:NAME:<NAME>END_PI"
:text "Hey PI:NAME:<NAME>END_PI want to give a Flux talk at ForwardJS?"
:timestamp (- (dt/now) 99999)}
{
:id "m_2"
:threadID "t_1"
:threadName "PI:NAME:<NAME>END_PI"
:authorName "PI:NAME:<NAME>END_PI"
:text "Seems like a pretty cool conference."
:timestamp (- (dt/now) 89999)}
{
:id "m_3"
:threadID "t_1"
:threadName "PI:NAME:<NAME>END_PI"
:authorName "PI:NAME:<NAME>END_PI"
:text "Sounds good. Will they be serving dessert?"
:timestamp (- (dt/now) 79999)}
{
:id "m_4"
:threadID "t_2"
:threadName "PI:NAME:<NAME>END_PI"
:authorName "PI:NAME:<NAME>END_PI"
:text "Hey PI:NAME:<NAME>END_PI want to get a beer after the conference?"
:timestamp (- (dt/now) 69999)}
{
:id "m_5"
:threadID "t_2"
:threadName "PI:NAME:<NAME>END_PI"
:authorName "PI:NAME:<NAME>END_PI"
:text "Totally! Meet you at the hotel bar."
:timestamp (- (dt/now) 59999)}
{
:id "m_6"
:threadID "t_3"
:threadName "Functional Heads"
:authorName "PI:NAME:<NAME>END_PI"
:text "Hey PI:NAME:<NAME>END_PI are you going to be talking about functional stuff?"
:timestamp (- (dt/now) 49999)}
{
:id "m_7"
:threadID "t_3"
:threadName "PI:NAME:<NAME>END_PI"
:authorName "PI:NAME:<NAME>END_PI"
:text "At ForwardJS? Yeah of course. See you there!"
:timestamp (- (dt/now) 39999)}])
(defn convert-message [{:keys [id authorName text timestamp] :as msg}]
{:message/id id
:message/author-name authorName
:message/text text
:message/date (dt2/to-date timestamp)
}
)
(defn threads-by-id [coll msg]
(let [{:keys [id threadID threadName timestamp]} msg]
(if (contains? coll threadID)
(assoc-in coll [threadID :thread/messages id]
(convert-message msg))
(assoc coll threadID
{:thread/id threadID
:thread/name threadName
:thread/messages {id (convert-message msg)}
})
))
)
(defn threads [coll msg]
(let [{:keys [id threadID threadName timestamp]} msg
{:keys [thread/id]} (last coll)
last-msg-idx (dec (count coll))]
(if (= id threadID)
(update-in coll [last-msg-idx :thread/messages] conj (convert-message msg))
(conj coll
{:thread/id threadID
:thread/name threadName
:thread/messages [(convert-message msg)]
})
))
)
(defui MessageSection
static om/Ident
(ident [this {:keys [message/id]}]
[:messages/by-id id])
static om/IQuery
(query [this]
[:message/id :message/author-name :message/date :message/text])
Object
(render [this]
(dom/div #js{:className "message-section"}
"Message section...")))
(def message-section (om/factory MessageSection))
(defui ThreadSection
static om/Ident
(ident [this {:keys [thread/id]}]
[:threads/by-id id])
static om/IQuery
(query [this]
[:thread/id :thread/name :thread/read :thread/selected
{:thread/last-message [:message/date :message/text]}
{:thread/messages (om/get-query MessageSection)}])
Object
(render [this]
(dom/div #js{:className "thread-section"}
"Thread Section...")
))
(def thread-section (om/factory ThreadSection))
(defui ChatApp
static om/IQuery
(query [this]
[{:threads (om/get-query ThreadSection)}])
Object
(render [this]
(let [{:keys [threads]} (om/props this)]
(dom/div #js{:className "chatapp"}
(thread-section threads)
(message-section (last threads))))))
(defmulti read om/dispatch)
(defmethod read :default
[{:keys [state] :as env} k _]
(let [st @state]
(if (contains? st k)
{:value (get st k)}
{:remote true})))
(def reconciler
(om/reconciler {:state {:threads (reduce threads [] raw-data)}
:parser (om/parser {:read read})}))
(om/add-root! reconciler
ChatApp
(gdom/getElement "app"))
|
[
{
"context": "(def config-meta\n {:entity/legolas ^:elf {:name \"Legolas\" :age 2931}})\n\n(deftest lazy-read-test\n (testing",
"end": 259,
"score": 0.9992977380752563,
"start": 252,
"tag": "NAME",
"value": "Legolas"
}
] | test/integrant_tools/edn_test.clj | mhondshorst/integrant-tools | 2 | (ns integrant-tools.edn-test
(:require [clojure.test :refer :all]
[integrant-tools.edn :as it.edn]))
(def config-str
"#:lotr{:quote #it/str [\"Not all those who wander are lost.\"]}")
(def config-meta
{:entity/legolas ^:elf {:name "Legolas" :age 2931}})
(deftest lazy-read-test
(testing "Test that reading a config string (with reader tag) and writing it
back to a string produces the same result."
(is (= config-str
(-> config-str
(it.edn/lazy-read)
(it.edn/meta-str)))))
(testing "Test that metadata isn't lost after writing and reading data."
(is (= {:elf true}
(-> config-meta
(it.edn/meta-str)
(it.edn/lazy-read)
:entity/legolas
meta)))))
| 56289 | (ns integrant-tools.edn-test
(:require [clojure.test :refer :all]
[integrant-tools.edn :as it.edn]))
(def config-str
"#:lotr{:quote #it/str [\"Not all those who wander are lost.\"]}")
(def config-meta
{:entity/legolas ^:elf {:name "<NAME>" :age 2931}})
(deftest lazy-read-test
(testing "Test that reading a config string (with reader tag) and writing it
back to a string produces the same result."
(is (= config-str
(-> config-str
(it.edn/lazy-read)
(it.edn/meta-str)))))
(testing "Test that metadata isn't lost after writing and reading data."
(is (= {:elf true}
(-> config-meta
(it.edn/meta-str)
(it.edn/lazy-read)
:entity/legolas
meta)))))
| true | (ns integrant-tools.edn-test
(:require [clojure.test :refer :all]
[integrant-tools.edn :as it.edn]))
(def config-str
"#:lotr{:quote #it/str [\"Not all those who wander are lost.\"]}")
(def config-meta
{:entity/legolas ^:elf {:name "PI:NAME:<NAME>END_PI" :age 2931}})
(deftest lazy-read-test
(testing "Test that reading a config string (with reader tag) and writing it
back to a string produces the same result."
(is (= config-str
(-> config-str
(it.edn/lazy-read)
(it.edn/meta-str)))))
(testing "Test that metadata isn't lost after writing and reading data."
(is (= {:elf true}
(-> config-meta
(it.edn/meta-str)
(it.edn/lazy-read)
:entity/legolas
meta)))))
|
[
{
"context": ";; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and\n;; distributi",
"end": 36,
"score": 0.9998637437820435,
"start": 18,
"tag": "NAME",
"value": "Stephen C. Gilardi"
},
{
"context": "nternal definitions for clojure.contrib.sql\n;;\n;; scgilardi (gmail)\n;; Created 3 October 2008\n\n(ns clojure.c",
"end": 541,
"score": 0.9451514482498169,
"start": 532,
"tag": "USERNAME",
"value": "scgilardi"
}
] | ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/sql/internal.clj | allertonm/Couverjure | 3 | ;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and
;; distribution terms for this software are covered by the Eclipse Public
;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
;; be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other,
;; from this software.
;;
;; internal definitions for clojure.contrib.sql
;;
;; scgilardi (gmail)
;; Created 3 October 2008
(ns clojure.contrib.sql.internal
(:use
(clojure.contrib
[except :only (throwf throw-arg)]
[java-utils :only (as-properties)]
[seq-utils :only (indexed)]))
(:import
(clojure.lang RT)
(java.sql BatchUpdateException DriverManager SQLException Statement)
(java.util Hashtable Map)
(javax.naming InitialContext Name)
(javax.sql DataSource)))
(def *db* {:connection nil :level 0})
(def special-counts
{Statement/EXECUTE_FAILED "EXECUTE_FAILED"
Statement/SUCCESS_NO_INFO "SUCCESS_NO_INFO"})
(defn find-connection*
"Returns the current database connection (or nil if there is none)"
[]
(:connection *db*))
(defn connection*
"Returns the current database connection (or throws if there is none)"
[]
(or (find-connection*)
(throwf "no current database connection")))
(defn rollback
"Accessor for the rollback flag on the current connection"
([]
(deref (:rollback *db*)))
([val]
(swap! (:rollback *db*) (fn [_] val))))
(defn get-connection
"Creates a connection to a database. db-spec is a map containing values
for one of the following parameter sets:
Factory:
:factory (required) a function of one argument, a map of params
(others) (optional) passed to the factory function in a map
DriverManager:
:classname (required) a String, the jdbc driver class name
:subprotocol (required) a String, the jdbc subprotocol
:subname (required) a String, the jdbc subname
(others) (optional) passed to the driver as properties.
DataSource:
:datasource (required) a javax.sql.DataSource
:username (optional) a String
:password (optional) a String, required if :username is supplied
JNDI:
:name (required) a String or javax.naming.Name
:environment (optional) a java.util.Map"
[{:keys [factory
classname subprotocol subname
datasource username password
name environment]
:as db-spec}]
(cond
factory
(factory (dissoc db-spec :factory))
(and classname subprotocol subname)
(let [url (format "jdbc:%s:%s" subprotocol subname)
etc (dissoc db-spec :classname :subprotocol :subname)]
(RT/loadClassForName classname)
(DriverManager/getConnection url (as-properties etc)))
(and datasource username password)
(.getConnection datasource username password)
datasource
(.getConnection datasource)
name
(let [env (and environment (Hashtable. environment))
context (InitialContext. env)
datasource (.lookup context name)]
(.getConnection datasource))
:else
(throw-arg "db-spec %s is missing a required parameter" db-spec)))
(defn with-connection*
"Evaluates func in the context of a new connection to a database then
closes the connection."
[db-spec func]
(with-open [con (get-connection db-spec)]
(binding [*db* (assoc *db*
:connection con :level 0 :rollback (atom false))]
(func))))
(defn print-sql-exception
"Prints the contents of an SQLException to stream"
[stream exception]
(.println
stream
(format (str "%s:" \newline
" Message: %s" \newline
" SQLState: %s" \newline
" Error Code: %d")
(.getSimpleName (class exception))
(.getMessage exception)
(.getSQLState exception)
(.getErrorCode exception))))
(defn print-sql-exception-chain
"Prints a chain of SQLExceptions to stream"
[stream exception]
(loop [e exception]
(when e
(print-sql-exception stream e)
(recur (.getNextException e)))))
(defn print-update-counts
"Prints the update counts from a BatchUpdateException to stream"
[stream exception]
(.println stream "Update counts:")
(doseq [[index count] (indexed (.getUpdateCounts exception))]
(.println stream (format " Statement %d: %s"
index
(get special-counts count count)))))
(defn throw-rollback
"Sets rollback and throws a wrapped exception"
[e]
(rollback true)
(throwf e "transaction rolled back: %s" (.getMessage e)))
(defn transaction*
"Evaluates func as a transaction on the open database connection. Any
nested transactions are absorbed into the outermost transaction. By
default, all database updates are committed together as a group after
evaluating the outermost body, or rolled back on any uncaught
exception. If rollback is set within scope of the outermost transaction,
the entire transaction will be rolled back rather than committed when
complete."
[func]
(binding [*db* (update-in *db* [:level] inc)]
(if (= (:level *db*) 1)
(let [con (connection*)
auto-commit (.getAutoCommit con)]
(io!
(.setAutoCommit con false)
(try
(func)
(catch BatchUpdateException e
(print-update-counts *err* e)
(print-sql-exception-chain *err* e)
(throw-rollback e))
(catch SQLException e
(print-sql-exception-chain *err* e)
(throw-rollback e))
(catch Exception e
(throw-rollback e))
(finally
(if (rollback)
(.rollback con)
(.commit con))
(rollback false)
(.setAutoCommit con auto-commit)))))
(func))))
(defn with-query-results*
"Executes a query, then evaluates func passing in a seq of the results as
an argument. The first argument is a vector containing the (optionally
parameterized) sql query string followed by values for any parameters."
[[sql & params :as sql-params] func]
(when-not (vector? sql-params)
(throw-arg "\"%s\" expected %s %s, found %s %s"
"sql-params"
"vector"
"[sql param*]"
(.getName (class sql-params))
(pr-str sql-params)))
(with-open [stmt (.prepareStatement (connection*) sql)]
(doseq [[index value] (map vector (iterate inc 1) params)]
(.setObject stmt index value))
(with-open [rset (.executeQuery stmt)]
(func (resultset-seq rset)))))
| 3849 | ;; Copyright (c) <NAME>. All rights reserved. The use and
;; distribution terms for this software are covered by the Eclipse Public
;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
;; be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other,
;; from this software.
;;
;; internal definitions for clojure.contrib.sql
;;
;; scgilardi (gmail)
;; Created 3 October 2008
(ns clojure.contrib.sql.internal
(:use
(clojure.contrib
[except :only (throwf throw-arg)]
[java-utils :only (as-properties)]
[seq-utils :only (indexed)]))
(:import
(clojure.lang RT)
(java.sql BatchUpdateException DriverManager SQLException Statement)
(java.util Hashtable Map)
(javax.naming InitialContext Name)
(javax.sql DataSource)))
(def *db* {:connection nil :level 0})
(def special-counts
{Statement/EXECUTE_FAILED "EXECUTE_FAILED"
Statement/SUCCESS_NO_INFO "SUCCESS_NO_INFO"})
(defn find-connection*
"Returns the current database connection (or nil if there is none)"
[]
(:connection *db*))
(defn connection*
"Returns the current database connection (or throws if there is none)"
[]
(or (find-connection*)
(throwf "no current database connection")))
(defn rollback
"Accessor for the rollback flag on the current connection"
([]
(deref (:rollback *db*)))
([val]
(swap! (:rollback *db*) (fn [_] val))))
(defn get-connection
"Creates a connection to a database. db-spec is a map containing values
for one of the following parameter sets:
Factory:
:factory (required) a function of one argument, a map of params
(others) (optional) passed to the factory function in a map
DriverManager:
:classname (required) a String, the jdbc driver class name
:subprotocol (required) a String, the jdbc subprotocol
:subname (required) a String, the jdbc subname
(others) (optional) passed to the driver as properties.
DataSource:
:datasource (required) a javax.sql.DataSource
:username (optional) a String
:password (optional) a String, required if :username is supplied
JNDI:
:name (required) a String or javax.naming.Name
:environment (optional) a java.util.Map"
[{:keys [factory
classname subprotocol subname
datasource username password
name environment]
:as db-spec}]
(cond
factory
(factory (dissoc db-spec :factory))
(and classname subprotocol subname)
(let [url (format "jdbc:%s:%s" subprotocol subname)
etc (dissoc db-spec :classname :subprotocol :subname)]
(RT/loadClassForName classname)
(DriverManager/getConnection url (as-properties etc)))
(and datasource username password)
(.getConnection datasource username password)
datasource
(.getConnection datasource)
name
(let [env (and environment (Hashtable. environment))
context (InitialContext. env)
datasource (.lookup context name)]
(.getConnection datasource))
:else
(throw-arg "db-spec %s is missing a required parameter" db-spec)))
(defn with-connection*
"Evaluates func in the context of a new connection to a database then
closes the connection."
[db-spec func]
(with-open [con (get-connection db-spec)]
(binding [*db* (assoc *db*
:connection con :level 0 :rollback (atom false))]
(func))))
(defn print-sql-exception
"Prints the contents of an SQLException to stream"
[stream exception]
(.println
stream
(format (str "%s:" \newline
" Message: %s" \newline
" SQLState: %s" \newline
" Error Code: %d")
(.getSimpleName (class exception))
(.getMessage exception)
(.getSQLState exception)
(.getErrorCode exception))))
(defn print-sql-exception-chain
"Prints a chain of SQLExceptions to stream"
[stream exception]
(loop [e exception]
(when e
(print-sql-exception stream e)
(recur (.getNextException e)))))
(defn print-update-counts
"Prints the update counts from a BatchUpdateException to stream"
[stream exception]
(.println stream "Update counts:")
(doseq [[index count] (indexed (.getUpdateCounts exception))]
(.println stream (format " Statement %d: %s"
index
(get special-counts count count)))))
(defn throw-rollback
"Sets rollback and throws a wrapped exception"
[e]
(rollback true)
(throwf e "transaction rolled back: %s" (.getMessage e)))
(defn transaction*
"Evaluates func as a transaction on the open database connection. Any
nested transactions are absorbed into the outermost transaction. By
default, all database updates are committed together as a group after
evaluating the outermost body, or rolled back on any uncaught
exception. If rollback is set within scope of the outermost transaction,
the entire transaction will be rolled back rather than committed when
complete."
[func]
(binding [*db* (update-in *db* [:level] inc)]
(if (= (:level *db*) 1)
(let [con (connection*)
auto-commit (.getAutoCommit con)]
(io!
(.setAutoCommit con false)
(try
(func)
(catch BatchUpdateException e
(print-update-counts *err* e)
(print-sql-exception-chain *err* e)
(throw-rollback e))
(catch SQLException e
(print-sql-exception-chain *err* e)
(throw-rollback e))
(catch Exception e
(throw-rollback e))
(finally
(if (rollback)
(.rollback con)
(.commit con))
(rollback false)
(.setAutoCommit con auto-commit)))))
(func))))
(defn with-query-results*
"Executes a query, then evaluates func passing in a seq of the results as
an argument. The first argument is a vector containing the (optionally
parameterized) sql query string followed by values for any parameters."
[[sql & params :as sql-params] func]
(when-not (vector? sql-params)
(throw-arg "\"%s\" expected %s %s, found %s %s"
"sql-params"
"vector"
"[sql param*]"
(.getName (class sql-params))
(pr-str sql-params)))
(with-open [stmt (.prepareStatement (connection*) sql)]
(doseq [[index value] (map vector (iterate inc 1) params)]
(.setObject stmt index value))
(with-open [rset (.executeQuery stmt)]
(func (resultset-seq rset)))))
| true | ;; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. The use and
;; distribution terms for this software are covered by the Eclipse Public
;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
;; be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other,
;; from this software.
;;
;; internal definitions for clojure.contrib.sql
;;
;; scgilardi (gmail)
;; Created 3 October 2008
(ns clojure.contrib.sql.internal
(:use
(clojure.contrib
[except :only (throwf throw-arg)]
[java-utils :only (as-properties)]
[seq-utils :only (indexed)]))
(:import
(clojure.lang RT)
(java.sql BatchUpdateException DriverManager SQLException Statement)
(java.util Hashtable Map)
(javax.naming InitialContext Name)
(javax.sql DataSource)))
(def *db* {:connection nil :level 0})
(def special-counts
{Statement/EXECUTE_FAILED "EXECUTE_FAILED"
Statement/SUCCESS_NO_INFO "SUCCESS_NO_INFO"})
(defn find-connection*
"Returns the current database connection (or nil if there is none)"
[]
(:connection *db*))
(defn connection*
"Returns the current database connection (or throws if there is none)"
[]
(or (find-connection*)
(throwf "no current database connection")))
(defn rollback
"Accessor for the rollback flag on the current connection"
([]
(deref (:rollback *db*)))
([val]
(swap! (:rollback *db*) (fn [_] val))))
(defn get-connection
"Creates a connection to a database. db-spec is a map containing values
for one of the following parameter sets:
Factory:
:factory (required) a function of one argument, a map of params
(others) (optional) passed to the factory function in a map
DriverManager:
:classname (required) a String, the jdbc driver class name
:subprotocol (required) a String, the jdbc subprotocol
:subname (required) a String, the jdbc subname
(others) (optional) passed to the driver as properties.
DataSource:
:datasource (required) a javax.sql.DataSource
:username (optional) a String
:password (optional) a String, required if :username is supplied
JNDI:
:name (required) a String or javax.naming.Name
:environment (optional) a java.util.Map"
[{:keys [factory
classname subprotocol subname
datasource username password
name environment]
:as db-spec}]
(cond
factory
(factory (dissoc db-spec :factory))
(and classname subprotocol subname)
(let [url (format "jdbc:%s:%s" subprotocol subname)
etc (dissoc db-spec :classname :subprotocol :subname)]
(RT/loadClassForName classname)
(DriverManager/getConnection url (as-properties etc)))
(and datasource username password)
(.getConnection datasource username password)
datasource
(.getConnection datasource)
name
(let [env (and environment (Hashtable. environment))
context (InitialContext. env)
datasource (.lookup context name)]
(.getConnection datasource))
:else
(throw-arg "db-spec %s is missing a required parameter" db-spec)))
(defn with-connection*
"Evaluates func in the context of a new connection to a database then
closes the connection."
[db-spec func]
(with-open [con (get-connection db-spec)]
(binding [*db* (assoc *db*
:connection con :level 0 :rollback (atom false))]
(func))))
(defn print-sql-exception
"Prints the contents of an SQLException to stream"
[stream exception]
(.println
stream
(format (str "%s:" \newline
" Message: %s" \newline
" SQLState: %s" \newline
" Error Code: %d")
(.getSimpleName (class exception))
(.getMessage exception)
(.getSQLState exception)
(.getErrorCode exception))))
(defn print-sql-exception-chain
"Prints a chain of SQLExceptions to stream"
[stream exception]
(loop [e exception]
(when e
(print-sql-exception stream e)
(recur (.getNextException e)))))
(defn print-update-counts
"Prints the update counts from a BatchUpdateException to stream"
[stream exception]
(.println stream "Update counts:")
(doseq [[index count] (indexed (.getUpdateCounts exception))]
(.println stream (format " Statement %d: %s"
index
(get special-counts count count)))))
(defn throw-rollback
"Sets rollback and throws a wrapped exception"
[e]
(rollback true)
(throwf e "transaction rolled back: %s" (.getMessage e)))
(defn transaction*
"Evaluates func as a transaction on the open database connection. Any
nested transactions are absorbed into the outermost transaction. By
default, all database updates are committed together as a group after
evaluating the outermost body, or rolled back on any uncaught
exception. If rollback is set within scope of the outermost transaction,
the entire transaction will be rolled back rather than committed when
complete."
[func]
(binding [*db* (update-in *db* [:level] inc)]
(if (= (:level *db*) 1)
(let [con (connection*)
auto-commit (.getAutoCommit con)]
(io!
(.setAutoCommit con false)
(try
(func)
(catch BatchUpdateException e
(print-update-counts *err* e)
(print-sql-exception-chain *err* e)
(throw-rollback e))
(catch SQLException e
(print-sql-exception-chain *err* e)
(throw-rollback e))
(catch Exception e
(throw-rollback e))
(finally
(if (rollback)
(.rollback con)
(.commit con))
(rollback false)
(.setAutoCommit con auto-commit)))))
(func))))
(defn with-query-results*
"Executes a query, then evaluates func passing in a seq of the results as
an argument. The first argument is a vector containing the (optionally
parameterized) sql query string followed by values for any parameters."
[[sql & params :as sql-params] func]
(when-not (vector? sql-params)
(throw-arg "\"%s\" expected %s %s, found %s %s"
"sql-params"
"vector"
"[sql param*]"
(.getName (class sql-params))
(pr-str sql-params)))
(with-open [stmt (.prepareStatement (connection*) sql)]
(doseq [[index value] (map vector (iterate inc 1) params)]
(.setObject stmt index value))
(with-open [rset (.executeQuery stmt)]
(func (resultset-seq rset)))))
|
[
{
"context": "; Copyright (c) 2021 Mikołaj Kuranowski\n; SPDX-License-Identifier: WTFPL\n(ns day12a\n (:r",
"end": 39,
"score": 0.9995422959327698,
"start": 21,
"tag": "NAME",
"value": "Mikołaj Kuranowski"
}
] | src/day12a.clj | MKuranowski/AdventOfCode2020 | 0 | ; Copyright (c) 2021 Mikołaj Kuranowski
; SPDX-License-Identifier: WTFPL
(ns day12a
(:require [core]
[clojure.math.numeric-tower :refer [abs]]))
(def rot-lookup
{\N {90 \E, 180 \S, 270 \W}
\E {90 \S, 180 \W, 270 \N}
\S {90 \W, 180 \N, 270 \E}
\W {90 \N, 180 \E, 270 \S}})
(defn read-navi [filename]
(->> filename
core/lines-from-file
(map #(list (first %) (core/parse-int (subs % 1))))))
(defn exec-navi [all-instructions]
(loop [instructions all-instructions
e 0
n 0
heading \E]
(if (seq instructions)
(let [[i arg] (first instructions)]
(case i
\N (recur (rest instructions) e (+ n arg) heading)
\E (recur (rest instructions) (+ e arg) n heading)
\S (recur (rest instructions) e (- n arg) heading)
\W (recur (rest instructions) (- e arg) n heading)
\L (recur (rest instructions) e n ((rot-lookup heading) (- 360 arg)))
\R (recur (rest instructions) e n ((rot-lookup heading) arg))
\F (recur (cons (list heading arg) (rest instructions)) e n heading)))
(list e n))))
(defn manhattan-dist
[[x y]] (+ (abs x) (abs y)))
(defn -main [filename]
(->> filename
read-navi
exec-navi
manhattan-dist
prn))
| 115805 | ; Copyright (c) 2021 <NAME>
; SPDX-License-Identifier: WTFPL
(ns day12a
(:require [core]
[clojure.math.numeric-tower :refer [abs]]))
(def rot-lookup
{\N {90 \E, 180 \S, 270 \W}
\E {90 \S, 180 \W, 270 \N}
\S {90 \W, 180 \N, 270 \E}
\W {90 \N, 180 \E, 270 \S}})
(defn read-navi [filename]
(->> filename
core/lines-from-file
(map #(list (first %) (core/parse-int (subs % 1))))))
(defn exec-navi [all-instructions]
(loop [instructions all-instructions
e 0
n 0
heading \E]
(if (seq instructions)
(let [[i arg] (first instructions)]
(case i
\N (recur (rest instructions) e (+ n arg) heading)
\E (recur (rest instructions) (+ e arg) n heading)
\S (recur (rest instructions) e (- n arg) heading)
\W (recur (rest instructions) (- e arg) n heading)
\L (recur (rest instructions) e n ((rot-lookup heading) (- 360 arg)))
\R (recur (rest instructions) e n ((rot-lookup heading) arg))
\F (recur (cons (list heading arg) (rest instructions)) e n heading)))
(list e n))))
(defn manhattan-dist
[[x y]] (+ (abs x) (abs y)))
(defn -main [filename]
(->> filename
read-navi
exec-navi
manhattan-dist
prn))
| true | ; Copyright (c) 2021 PI:NAME:<NAME>END_PI
; SPDX-License-Identifier: WTFPL
(ns day12a
(:require [core]
[clojure.math.numeric-tower :refer [abs]]))
(def rot-lookup
{\N {90 \E, 180 \S, 270 \W}
\E {90 \S, 180 \W, 270 \N}
\S {90 \W, 180 \N, 270 \E}
\W {90 \N, 180 \E, 270 \S}})
(defn read-navi [filename]
(->> filename
core/lines-from-file
(map #(list (first %) (core/parse-int (subs % 1))))))
(defn exec-navi [all-instructions]
(loop [instructions all-instructions
e 0
n 0
heading \E]
(if (seq instructions)
(let [[i arg] (first instructions)]
(case i
\N (recur (rest instructions) e (+ n arg) heading)
\E (recur (rest instructions) (+ e arg) n heading)
\S (recur (rest instructions) e (- n arg) heading)
\W (recur (rest instructions) (- e arg) n heading)
\L (recur (rest instructions) e n ((rot-lookup heading) (- 360 arg)))
\R (recur (rest instructions) e n ((rot-lookup heading) arg))
\F (recur (cons (list heading arg) (rest instructions)) e n heading)))
(list e n))))
(defn manhattan-dist
[[x y]] (+ (abs x) (abs y)))
(defn -main [filename]
(->> filename
read-navi
exec-navi
manhattan-dist
prn))
|
[
{
"context": "id3.basics-util :as util]\n ))\n\n(def cursor-key :b07-make-raw-elements)\n\n(def height 100)\n(def width 100)\n\n(defn example",
"end": 189,
"score": 0.8745425343513489,
"start": 168,
"tag": "KEY",
"value": "b07-make-raw-elements"
}
] | src/basics/rid3/b07_make_raw_elements.cljs | ryanechternacht/rid3 | 153 | (ns rid3.b07-make-raw-elements
(:require
[reagent.core :as reagent]
[rid3.core :as rid3 :refer [rid3->]]
[rid3.basics-util :as util]
))
(def cursor-key :b07-make-raw-elements)
(def height 100)
(def width 100)
(defn example [app-state]
(let [viz-ratom (reagent/cursor app-state [cursor-key])]
(fn [app-state]
[:div
[:h4 "7) element on top of another element ... using the "
[:em ":raw"]
" piece kind (roughly same as 2, but different implementation)"]
[util/link-source (name cursor-key)]
[rid3/viz
{:id "b07"
:ratom viz-ratom
:svg {:did-mount (fn [node ratom]
(rid3-> node
{:height height
:width width}))}
;; Using a :raw piece is like an escape hatch from
;; rid3. However, this means that a lot of the conveniences
;; that rid3 provides, you now have to perform manually.
:pieces
[{:kind :raw
;; Note: you do not supply a :class tag anymore
;; Note: you do not supply a :tag key anymore. You will have
;; to manually append and select your own elements
:did-mount (fn [ratom]
;; note: you are no longer passed a node argument
(let [node-main-container (js/d3.select "#b07 .rid3-main-container")]
(rid3-> node-main-container
(.append "rect")
{:class "some-raw-element"
:x 0
:y 0
:height height
:width width
:fill "lightgrey"
:stroke "grey"
:stroke-width 2})))
;; Special note: the :did-mount function is *not* default
;; to the :did-upate function like the other kinds of
;; pieces
}
{:kind :elem
:class "some-raw-element-on-top"
:did-mount (fn [node ratom]
(let [node-main-container (js/d3.select "#b07 .rid3-main-container")]
(rid3-> node-main-container
(.append "circle")
{:class "some-raw-element-on-top"
:cx (/ width 2)
:cy (/ height 2)
:r 20
:fill "green"})))}]
}]])))
| 35237 | (ns rid3.b07-make-raw-elements
(:require
[reagent.core :as reagent]
[rid3.core :as rid3 :refer [rid3->]]
[rid3.basics-util :as util]
))
(def cursor-key :<KEY>)
(def height 100)
(def width 100)
(defn example [app-state]
(let [viz-ratom (reagent/cursor app-state [cursor-key])]
(fn [app-state]
[:div
[:h4 "7) element on top of another element ... using the "
[:em ":raw"]
" piece kind (roughly same as 2, but different implementation)"]
[util/link-source (name cursor-key)]
[rid3/viz
{:id "b07"
:ratom viz-ratom
:svg {:did-mount (fn [node ratom]
(rid3-> node
{:height height
:width width}))}
;; Using a :raw piece is like an escape hatch from
;; rid3. However, this means that a lot of the conveniences
;; that rid3 provides, you now have to perform manually.
:pieces
[{:kind :raw
;; Note: you do not supply a :class tag anymore
;; Note: you do not supply a :tag key anymore. You will have
;; to manually append and select your own elements
:did-mount (fn [ratom]
;; note: you are no longer passed a node argument
(let [node-main-container (js/d3.select "#b07 .rid3-main-container")]
(rid3-> node-main-container
(.append "rect")
{:class "some-raw-element"
:x 0
:y 0
:height height
:width width
:fill "lightgrey"
:stroke "grey"
:stroke-width 2})))
;; Special note: the :did-mount function is *not* default
;; to the :did-upate function like the other kinds of
;; pieces
}
{:kind :elem
:class "some-raw-element-on-top"
:did-mount (fn [node ratom]
(let [node-main-container (js/d3.select "#b07 .rid3-main-container")]
(rid3-> node-main-container
(.append "circle")
{:class "some-raw-element-on-top"
:cx (/ width 2)
:cy (/ height 2)
:r 20
:fill "green"})))}]
}]])))
| true | (ns rid3.b07-make-raw-elements
(:require
[reagent.core :as reagent]
[rid3.core :as rid3 :refer [rid3->]]
[rid3.basics-util :as util]
))
(def cursor-key :PI:KEY:<KEY>END_PI)
(def height 100)
(def width 100)
(defn example [app-state]
(let [viz-ratom (reagent/cursor app-state [cursor-key])]
(fn [app-state]
[:div
[:h4 "7) element on top of another element ... using the "
[:em ":raw"]
" piece kind (roughly same as 2, but different implementation)"]
[util/link-source (name cursor-key)]
[rid3/viz
{:id "b07"
:ratom viz-ratom
:svg {:did-mount (fn [node ratom]
(rid3-> node
{:height height
:width width}))}
;; Using a :raw piece is like an escape hatch from
;; rid3. However, this means that a lot of the conveniences
;; that rid3 provides, you now have to perform manually.
:pieces
[{:kind :raw
;; Note: you do not supply a :class tag anymore
;; Note: you do not supply a :tag key anymore. You will have
;; to manually append and select your own elements
:did-mount (fn [ratom]
;; note: you are no longer passed a node argument
(let [node-main-container (js/d3.select "#b07 .rid3-main-container")]
(rid3-> node-main-container
(.append "rect")
{:class "some-raw-element"
:x 0
:y 0
:height height
:width width
:fill "lightgrey"
:stroke "grey"
:stroke-width 2})))
;; Special note: the :did-mount function is *not* default
;; to the :did-upate function like the other kinds of
;; pieces
}
{:kind :elem
:class "some-raw-element-on-top"
:did-mount (fn [node ratom]
(let [node-main-container (js/d3.select "#b07 .rid3-main-container")]
(rid3-> node-main-container
(.append "circle")
{:class "some-raw-element-on-top"
:cx (/ width 2)
:cy (/ height 2)
:r 20
:fill "green"})))}]
}]])))
|
[
{
"context": ";; The MIT License\r\n;; \r\n;; Copyright (c) 2011 John Svazic\r\n;; \r\n;; Permission is hereby granted, free of ch",
"end": 58,
"score": 0.9998143315315247,
"start": 47,
"tag": "NAME",
"value": "John Svazic"
}
] | clojure/src/net/auxesia/core.clj | Srivani-Y/Hello-wolrld | 159 | ;; The MIT License
;;
;; Copyright (c) 2011 John Svazic
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;; THE SOFTWARE.
(ns net.auxesia.core
"This namespace defines the main driver for the 'Hello, world!'
genetic algorithm application."
(:require [net.auxesia.population :as population]
[net.auxesia.chromosome :as chromosome])
(:gen-class))
(defn -main
"This is the main function used for command-line execution."
[& args]
(let [size (int 2048)
crossover (float 0.8)
elitism (float 0.01)
mutation (float 0.03)
max-gen (int 16384)]
(loop [g (int 0)
p (population/generate size crossover elitism mutation)]
(let [best (first (:population p))]
(do
(println "Generation" g (apply str (:gene best)))
(cond
(== 0 (:fitness best)) best
(>= g max-gen) best
:default (recur (inc g) (population/evolve p)))))))) | 63608 | ;; The MIT License
;;
;; Copyright (c) 2011 <NAME>
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;; THE SOFTWARE.
(ns net.auxesia.core
"This namespace defines the main driver for the 'Hello, world!'
genetic algorithm application."
(:require [net.auxesia.population :as population]
[net.auxesia.chromosome :as chromosome])
(:gen-class))
(defn -main
"This is the main function used for command-line execution."
[& args]
(let [size (int 2048)
crossover (float 0.8)
elitism (float 0.01)
mutation (float 0.03)
max-gen (int 16384)]
(loop [g (int 0)
p (population/generate size crossover elitism mutation)]
(let [best (first (:population p))]
(do
(println "Generation" g (apply str (:gene best)))
(cond
(== 0 (:fitness best)) best
(>= g max-gen) best
:default (recur (inc g) (population/evolve p)))))))) | true | ;; The MIT License
;;
;; Copyright (c) 2011 PI:NAME:<NAME>END_PI
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;; THE SOFTWARE.
(ns net.auxesia.core
"This namespace defines the main driver for the 'Hello, world!'
genetic algorithm application."
(:require [net.auxesia.population :as population]
[net.auxesia.chromosome :as chromosome])
(:gen-class))
(defn -main
"This is the main function used for command-line execution."
[& args]
(let [size (int 2048)
crossover (float 0.8)
elitism (float 0.01)
mutation (float 0.03)
max-gen (int 16384)]
(loop [g (int 0)
p (population/generate size crossover elitism mutation)]
(let [best (first (:population p))]
(do
(println "Generation" g (apply str (:gene best)))
(cond
(== 0 (:fitness best)) best
(>= g max-gen) best
:default (recur (inc g) (population/evolve p)))))))) |
[
{
"context": ";-\n; Copyright 2009-2015 © Meikel Brandmeyer.\n; All rights reserved.\n;\n; Licensed under the EU",
"end": 44,
"score": 0.9998763799667358,
"start": 27,
"tag": "NAME",
"value": "Meikel Brandmeyer"
}
] | src/main/resources/clojuresque/util.clj | chali/nebula-clojure-plugin | 18 | ;-
; Copyright 2009-2015 © Meikel Brandmeyer.
; All rights reserved.
;
; Licensed under the EUPL V.1.1 (cf. file EUPL-1.1 distributed with the
; source code.) Translations in other european languages available at
; https://joinup.ec.europa.eu/software/page/eupl.
;
; Alternatively, you may choose to use the software under the MIT license
; (cf. file MIT distributed with the source code).
(ns clojuresque.util
(:import
clojure.lang.LineNumberingPushbackReader)
(:require
[clojure.edn :as edn]
[clojure.java.io :as io]))
(defn namespace-of-file
[file]
(let [of-interest '#{ns clojure.core/ns in-ns clojure.core/in-ns}
eof (Object.)
input (LineNumberingPushbackReader. (io/reader file))
in-seq (take-while #(not (identical? % eof))
(repeatedly #(read input false eof)))
candidate (first
(drop-while
#(or (not (instance? clojure.lang.ISeq %))
(not (contains? of-interest (first %))))
in-seq))]
(when candidate
(second candidate))))
(defn namespaces
[files]
(distinct (keep namespace-of-file files)))
(defn safe-require
[& nspaces]
(binding [*unchecked-math* *unchecked-math*
*warn-on-reflection* *warn-on-reflection*]
(apply require nspaces)))
(defn resolve-required
[fully-qualified-sym]
(let [slash (.indexOf ^String fully-qualified-sym "/")
nspace (symbol (subs fully-qualified-sym 0 slash))
hfn (symbol (subs fully-qualified-sym (inc slash)))]
(safe-require nspace)
(ns-resolve nspace hfn)))
(defmacro deftask
[task-name & fntail]
`(let [driver# (fn ~(symbol (str (name task-name) "-task-driver"))
~fntail)]
(defn ~task-name
[]
(let [options# (edn/read (LineNumberingPushbackReader. *in*))]
(driver# options#)))))
| 52599 | ;-
; Copyright 2009-2015 © <NAME>.
; All rights reserved.
;
; Licensed under the EUPL V.1.1 (cf. file EUPL-1.1 distributed with the
; source code.) Translations in other european languages available at
; https://joinup.ec.europa.eu/software/page/eupl.
;
; Alternatively, you may choose to use the software under the MIT license
; (cf. file MIT distributed with the source code).
(ns clojuresque.util
(:import
clojure.lang.LineNumberingPushbackReader)
(:require
[clojure.edn :as edn]
[clojure.java.io :as io]))
(defn namespace-of-file
[file]
(let [of-interest '#{ns clojure.core/ns in-ns clojure.core/in-ns}
eof (Object.)
input (LineNumberingPushbackReader. (io/reader file))
in-seq (take-while #(not (identical? % eof))
(repeatedly #(read input false eof)))
candidate (first
(drop-while
#(or (not (instance? clojure.lang.ISeq %))
(not (contains? of-interest (first %))))
in-seq))]
(when candidate
(second candidate))))
(defn namespaces
[files]
(distinct (keep namespace-of-file files)))
(defn safe-require
[& nspaces]
(binding [*unchecked-math* *unchecked-math*
*warn-on-reflection* *warn-on-reflection*]
(apply require nspaces)))
(defn resolve-required
[fully-qualified-sym]
(let [slash (.indexOf ^String fully-qualified-sym "/")
nspace (symbol (subs fully-qualified-sym 0 slash))
hfn (symbol (subs fully-qualified-sym (inc slash)))]
(safe-require nspace)
(ns-resolve nspace hfn)))
(defmacro deftask
[task-name & fntail]
`(let [driver# (fn ~(symbol (str (name task-name) "-task-driver"))
~fntail)]
(defn ~task-name
[]
(let [options# (edn/read (LineNumberingPushbackReader. *in*))]
(driver# options#)))))
| true | ;-
; Copyright 2009-2015 © PI:NAME:<NAME>END_PI.
; All rights reserved.
;
; Licensed under the EUPL V.1.1 (cf. file EUPL-1.1 distributed with the
; source code.) Translations in other european languages available at
; https://joinup.ec.europa.eu/software/page/eupl.
;
; Alternatively, you may choose to use the software under the MIT license
; (cf. file MIT distributed with the source code).
(ns clojuresque.util
(:import
clojure.lang.LineNumberingPushbackReader)
(:require
[clojure.edn :as edn]
[clojure.java.io :as io]))
(defn namespace-of-file
[file]
(let [of-interest '#{ns clojure.core/ns in-ns clojure.core/in-ns}
eof (Object.)
input (LineNumberingPushbackReader. (io/reader file))
in-seq (take-while #(not (identical? % eof))
(repeatedly #(read input false eof)))
candidate (first
(drop-while
#(or (not (instance? clojure.lang.ISeq %))
(not (contains? of-interest (first %))))
in-seq))]
(when candidate
(second candidate))))
(defn namespaces
[files]
(distinct (keep namespace-of-file files)))
(defn safe-require
[& nspaces]
(binding [*unchecked-math* *unchecked-math*
*warn-on-reflection* *warn-on-reflection*]
(apply require nspaces)))
(defn resolve-required
[fully-qualified-sym]
(let [slash (.indexOf ^String fully-qualified-sym "/")
nspace (symbol (subs fully-qualified-sym 0 slash))
hfn (symbol (subs fully-qualified-sym (inc slash)))]
(safe-require nspace)
(ns-resolve nspace hfn)))
(defmacro deftask
[task-name & fntail]
`(let [driver# (fn ~(symbol (str (name task-name) "-task-driver"))
~fntail)]
(defn ~task-name
[]
(let [options# (edn/read (LineNumberingPushbackReader. *in*))]
(driver# options#)))))
|
[
{
"context": "; Map\n(def book {\"title\" \"Oliver Twist\" \"author\" \"Dickens\" \"published\" 1838})\n(get book \"title\") ;=> \"Olive",
"end": 885,
"score": 0.9995222687721252,
"start": 878,
"tag": "NAME",
"value": "Dickens"
},
{
"context": "(def another-book {:title \"Oliver Twist\" :author \"Dickens\" :published 1838})\n(:author another-book) ;=> \"Di",
"end": 1079,
"score": 0.9995708465576172,
"start": 1072,
"tag": "NAME",
"value": "Dickens"
},
{
"context": "ns\" :published 1838})\n(:author another-book) ;=> \"Dickens\"\n(def updated-book (assoc another-book :rating 5)",
"end": 1134,
"score": 0.9985535144805908,
"start": 1127,
"tag": "NAME",
"value": "Dickens"
},
{
"context": "0))\n\n;; progn is called simply do\n(do\n (println \"Do\")\n (println \"Re\")\n (println \"Mi\")\n 50)\n\n;; whe",
"end": 1451,
"score": 0.917320191860199,
"start": 1449,
"tag": "NAME",
"value": "Do"
},
{
"context": "called simply do\n(do\n (println \"Do\")\n (println \"Re\")\n (println \"Mi\")\n 50)\n\n;; when is same as emac",
"end": 1468,
"score": 0.9292613863945007,
"start": 1466,
"tag": "NAME",
"value": "Re"
},
{
"context": "(do\n (println \"Do\")\n (println \"Re\")\n (println \"Mi\")\n 50)\n\n;; when is same as emacs\n(when true\n (p",
"end": 1485,
"score": 0.9545521140098572,
"start": 1483,
"tag": "NAME",
"value": "Mi"
},
{
"context": "\n\n;; when is same as emacs\n(when true\n (println \"Do\")\n (println \"Re\")\n (println \"Mi\"))\n\n;; Function",
"end": 1545,
"score": 0.9130617380142212,
"start": 1543,
"tag": "NAME",
"value": "Do"
},
{
"context": " as emacs\n(when true\n (println \"Do\")\n (println \"Re\")\n (println \"Mi\"))\n\n;; Functions\n(defn double-it",
"end": 1562,
"score": 0.9458449482917786,
"start": 1560,
"tag": "NAME",
"value": "Re"
},
{
"context": "rue\n (println \"Do\")\n (println \"Re\")\n (println \"Mi\"))\n\n;; Functions\n(defn double-it [x] (* 2 x))\n;; ",
"end": 1579,
"score": 0.9652937054634094,
"start": 1577,
"tag": "NAME",
"value": "Mi"
}
] | cheatsheets/clojure.clj | peterprotwell/dotfiles | 0 | ;; Clojure
;; Commas are always whitespace
;; () != nil in Clojure
;; Don't quote the empty list
;; In the repl, _ from irb is called *1
;; Run one test: lein test :only namespace_name/test_name
;; Number
42
;; String
"hello"
;; Character
\a
;; Boolean, only false and nil are falsy
(if true (println "Yep"))
;; Symbol
(def my-symbol 22/7)
(= 'hello (symbol "hello")) ;=> true
;; Keyword (more common than symbols) (why?)
:keyword
(= :hello (keyword "hello")) ;=> true
;; List
(function arg1 arg2 arg3)
(+ 1 2 3)
;; The usual suspects
(def words '("foo" "bar" "qux"))
(first words) ;=> "foo"
(rest words) ;=> ("bar" "qux")
;; You've also got next, which is subtly different from rest
(rest ()) ;=> ()
(next ()) ;=> nil
;; Vector, simply evaluates each item in order
(def letters [:a :b :c :d])
(nth letters 2) ;=> :c
;; Map
(def book {"title" "Oliver Twist" "author" "Dickens" "published" 1838})
(get book "title") ;=> "Oliver Twist"
(book "title") ;=> "Oliver Twist"
;; Can also treat keyword keys as function
(def another-book {:title "Oliver Twist" :author "Dickens" :published 1838})
(:author another-book) ;=> "Dickens"
(def updated-book (assoc another-book :rating 5)) ;=> a new map
;; Set
#{1 2 "three" :four 0x5}
;; The numbers 1 to 100
(range 1 101)
;; Simple assertions for framework-less testing
(assert (= 1 1))
(assert (not= 2 3))
;; Mathematical equality
(assert (== 1 1.0))
;; progn is called simply do
(do
(println "Do")
(println "Re")
(println "Mi")
50)
;; when is same as emacs
(when true
(println "Do")
(println "Re")
(println "Mi"))
;; Functions
(defn double-it [x] (* 2 x))
;; Or as a lambda
(def double-it (fn [x] (* 2 x)))
;; http://funcall.blogspot.com/2009/03/not-lisp-again.html
(def dx 0.0001)
(defn deriv [f]
(fn [x]
(/ (- (f (+ x dx)) (f x))
dx)))
(defn cube [x] (* x x x))
(def cube-deriv (deriv cube))
(defn three-x-squared [x] (* 3 (* x x)))
(cube-deriv 2) ;=> 12.000600010022566
(three-x-squared 2) ;=> 12
(cube-deriv 3) ;=> 27.00090001006572
(three-x-squared 3) ;=> 27
(cube-deriv 4) ;=> 48.00120000993502
(three-x-squared 4) ;=> 48
;; require
(require '[path.to.file :as alias])
| 19314 | ;; Clojure
;; Commas are always whitespace
;; () != nil in Clojure
;; Don't quote the empty list
;; In the repl, _ from irb is called *1
;; Run one test: lein test :only namespace_name/test_name
;; Number
42
;; String
"hello"
;; Character
\a
;; Boolean, only false and nil are falsy
(if true (println "Yep"))
;; Symbol
(def my-symbol 22/7)
(= 'hello (symbol "hello")) ;=> true
;; Keyword (more common than symbols) (why?)
:keyword
(= :hello (keyword "hello")) ;=> true
;; List
(function arg1 arg2 arg3)
(+ 1 2 3)
;; The usual suspects
(def words '("foo" "bar" "qux"))
(first words) ;=> "foo"
(rest words) ;=> ("bar" "qux")
;; You've also got next, which is subtly different from rest
(rest ()) ;=> ()
(next ()) ;=> nil
;; Vector, simply evaluates each item in order
(def letters [:a :b :c :d])
(nth letters 2) ;=> :c
;; Map
(def book {"title" "Oliver Twist" "author" "<NAME>" "published" 1838})
(get book "title") ;=> "Oliver Twist"
(book "title") ;=> "Oliver Twist"
;; Can also treat keyword keys as function
(def another-book {:title "Oliver Twist" :author "<NAME>" :published 1838})
(:author another-book) ;=> "<NAME>"
(def updated-book (assoc another-book :rating 5)) ;=> a new map
;; Set
#{1 2 "three" :four 0x5}
;; The numbers 1 to 100
(range 1 101)
;; Simple assertions for framework-less testing
(assert (= 1 1))
(assert (not= 2 3))
;; Mathematical equality
(assert (== 1 1.0))
;; progn is called simply do
(do
(println "<NAME>")
(println "<NAME>")
(println "<NAME>")
50)
;; when is same as emacs
(when true
(println "<NAME>")
(println "<NAME>")
(println "<NAME>"))
;; Functions
(defn double-it [x] (* 2 x))
;; Or as a lambda
(def double-it (fn [x] (* 2 x)))
;; http://funcall.blogspot.com/2009/03/not-lisp-again.html
(def dx 0.0001)
(defn deriv [f]
(fn [x]
(/ (- (f (+ x dx)) (f x))
dx)))
(defn cube [x] (* x x x))
(def cube-deriv (deriv cube))
(defn three-x-squared [x] (* 3 (* x x)))
(cube-deriv 2) ;=> 12.000600010022566
(three-x-squared 2) ;=> 12
(cube-deriv 3) ;=> 27.00090001006572
(three-x-squared 3) ;=> 27
(cube-deriv 4) ;=> 48.00120000993502
(three-x-squared 4) ;=> 48
;; require
(require '[path.to.file :as alias])
| true | ;; Clojure
;; Commas are always whitespace
;; () != nil in Clojure
;; Don't quote the empty list
;; In the repl, _ from irb is called *1
;; Run one test: lein test :only namespace_name/test_name
;; Number
42
;; String
"hello"
;; Character
\a
;; Boolean, only false and nil are falsy
(if true (println "Yep"))
;; Symbol
(def my-symbol 22/7)
(= 'hello (symbol "hello")) ;=> true
;; Keyword (more common than symbols) (why?)
:keyword
(= :hello (keyword "hello")) ;=> true
;; List
(function arg1 arg2 arg3)
(+ 1 2 3)
;; The usual suspects
(def words '("foo" "bar" "qux"))
(first words) ;=> "foo"
(rest words) ;=> ("bar" "qux")
;; You've also got next, which is subtly different from rest
(rest ()) ;=> ()
(next ()) ;=> nil
;; Vector, simply evaluates each item in order
(def letters [:a :b :c :d])
(nth letters 2) ;=> :c
;; Map
(def book {"title" "Oliver Twist" "author" "PI:NAME:<NAME>END_PI" "published" 1838})
(get book "title") ;=> "Oliver Twist"
(book "title") ;=> "Oliver Twist"
;; Can also treat keyword keys as function
(def another-book {:title "Oliver Twist" :author "PI:NAME:<NAME>END_PI" :published 1838})
(:author another-book) ;=> "PI:NAME:<NAME>END_PI"
(def updated-book (assoc another-book :rating 5)) ;=> a new map
;; Set
#{1 2 "three" :four 0x5}
;; The numbers 1 to 100
(range 1 101)
;; Simple assertions for framework-less testing
(assert (= 1 1))
(assert (not= 2 3))
;; Mathematical equality
(assert (== 1 1.0))
;; progn is called simply do
(do
(println "PI:NAME:<NAME>END_PI")
(println "PI:NAME:<NAME>END_PI")
(println "PI:NAME:<NAME>END_PI")
50)
;; when is same as emacs
(when true
(println "PI:NAME:<NAME>END_PI")
(println "PI:NAME:<NAME>END_PI")
(println "PI:NAME:<NAME>END_PI"))
;; Functions
(defn double-it [x] (* 2 x))
;; Or as a lambda
(def double-it (fn [x] (* 2 x)))
;; http://funcall.blogspot.com/2009/03/not-lisp-again.html
(def dx 0.0001)
(defn deriv [f]
(fn [x]
(/ (- (f (+ x dx)) (f x))
dx)))
(defn cube [x] (* x x x))
(def cube-deriv (deriv cube))
(defn three-x-squared [x] (* 3 (* x x)))
(cube-deriv 2) ;=> 12.000600010022566
(three-x-squared 2) ;=> 12
(cube-deriv 3) ;=> 27.00090001006572
(three-x-squared 3) ;=> 27
(cube-deriv 4) ;=> 48.00120000993502
(three-x-squared 4) ;=> 48
;; require
(require '[path.to.file :as alias])
|
[
{
"context": "ns to help work with musical time.\"\n :author \"Jeff Rose\"}\n overtone.music.rhythm\n (:use [overtone.music",
"end": 80,
"score": 0.9998738169670105,
"start": 71,
"tag": "NAME",
"value": "Jeff Rose"
}
] | src/overtone/music/rhythm.clj | samaaron/overtone | 2 | (ns
^{:doc "Functions to help work with musical time."
:author "Jeff Rose"}
overtone.music.rhythm
(:use [overtone.music time]))
; Rhythm
; * a resting heart rate is 60-80 bpm
; * around 150 induces an excited state
; A rhythm system should let us refer to time in terms of rhythmic units like beat, bar, measure,
; and it should convert these units to real time units (ms) based on the current BPM and signature settings.
(defn beat-ms
"Convert 'b' beats to milliseconds at the given 'bpm'."
[b bpm] (* (/ 60000.0 bpm) b))
;(defn bar-ms
; "Convert b bars to milliseconds at the current bpm."
; ([] (bar 1))
; ([b] (* (bar 1) (first @*signature) b)))
; A metronome is a linear function that given a beat count returns the time in milliseconds.
;
; tpb = ticks-per-beat
(defn metronome
"A metronome is a beat management function. Tell it what BPM you want,
and it will output beat timestamps accordingly. Call the returned function
with no arguments to get the next beat number, or pass it a beat number
to get the timestamp to play a note at that beat.
(def m (metronome 128))
(m) ; => <current beat number>
(m 200) ; => <timestamp of beat 200>
(m :bpm 140) ; => set bpm to 140"
[bpm]
(let [start (atom (now))
tick-ms (atom (beat-ms 1 bpm))]
(fn
([] (inc (long (/ (- (now) @start) @tick-ms))))
([beat] (+ (* beat @tick-ms) @start))
([_ bpm]
(let [tms (beat-ms 1 bpm)
cur-beat (long (/ (- (now) @start) @tick-ms))
new-start (- (now) (* tms cur-beat))]
(reset! tick-ms tms)
(reset! start new-start))
[:bpm bpm]))))
(comment defprotocol IMetronome
(start [this])
(stop [this])
(beat [this])
(tick [this])
(bpm [this] [this bpm]))
;== Grooves
;
; A groove represents a pattern of velocities and timing modifications that is
; applied to a sequence of notes to adjust the feel.
;
; * swing
; * jazz groove, latin groove
; * techno grooves (hard on beat one)
; * make something more driving, or more layed back...
| 76449 | (ns
^{:doc "Functions to help work with musical time."
:author "<NAME>"}
overtone.music.rhythm
(:use [overtone.music time]))
; Rhythm
; * a resting heart rate is 60-80 bpm
; * around 150 induces an excited state
; A rhythm system should let us refer to time in terms of rhythmic units like beat, bar, measure,
; and it should convert these units to real time units (ms) based on the current BPM and signature settings.
(defn beat-ms
"Convert 'b' beats to milliseconds at the given 'bpm'."
[b bpm] (* (/ 60000.0 bpm) b))
;(defn bar-ms
; "Convert b bars to milliseconds at the current bpm."
; ([] (bar 1))
; ([b] (* (bar 1) (first @*signature) b)))
; A metronome is a linear function that given a beat count returns the time in milliseconds.
;
; tpb = ticks-per-beat
(defn metronome
"A metronome is a beat management function. Tell it what BPM you want,
and it will output beat timestamps accordingly. Call the returned function
with no arguments to get the next beat number, or pass it a beat number
to get the timestamp to play a note at that beat.
(def m (metronome 128))
(m) ; => <current beat number>
(m 200) ; => <timestamp of beat 200>
(m :bpm 140) ; => set bpm to 140"
[bpm]
(let [start (atom (now))
tick-ms (atom (beat-ms 1 bpm))]
(fn
([] (inc (long (/ (- (now) @start) @tick-ms))))
([beat] (+ (* beat @tick-ms) @start))
([_ bpm]
(let [tms (beat-ms 1 bpm)
cur-beat (long (/ (- (now) @start) @tick-ms))
new-start (- (now) (* tms cur-beat))]
(reset! tick-ms tms)
(reset! start new-start))
[:bpm bpm]))))
(comment defprotocol IMetronome
(start [this])
(stop [this])
(beat [this])
(tick [this])
(bpm [this] [this bpm]))
;== Grooves
;
; A groove represents a pattern of velocities and timing modifications that is
; applied to a sequence of notes to adjust the feel.
;
; * swing
; * jazz groove, latin groove
; * techno grooves (hard on beat one)
; * make something more driving, or more layed back...
| true | (ns
^{:doc "Functions to help work with musical time."
:author "PI:NAME:<NAME>END_PI"}
overtone.music.rhythm
(:use [overtone.music time]))
; Rhythm
; * a resting heart rate is 60-80 bpm
; * around 150 induces an excited state
; A rhythm system should let us refer to time in terms of rhythmic units like beat, bar, measure,
; and it should convert these units to real time units (ms) based on the current BPM and signature settings.
(defn beat-ms
"Convert 'b' beats to milliseconds at the given 'bpm'."
[b bpm] (* (/ 60000.0 bpm) b))
;(defn bar-ms
; "Convert b bars to milliseconds at the current bpm."
; ([] (bar 1))
; ([b] (* (bar 1) (first @*signature) b)))
; A metronome is a linear function that given a beat count returns the time in milliseconds.
;
; tpb = ticks-per-beat
(defn metronome
"A metronome is a beat management function. Tell it what BPM you want,
and it will output beat timestamps accordingly. Call the returned function
with no arguments to get the next beat number, or pass it a beat number
to get the timestamp to play a note at that beat.
(def m (metronome 128))
(m) ; => <current beat number>
(m 200) ; => <timestamp of beat 200>
(m :bpm 140) ; => set bpm to 140"
[bpm]
(let [start (atom (now))
tick-ms (atom (beat-ms 1 bpm))]
(fn
([] (inc (long (/ (- (now) @start) @tick-ms))))
([beat] (+ (* beat @tick-ms) @start))
([_ bpm]
(let [tms (beat-ms 1 bpm)
cur-beat (long (/ (- (now) @start) @tick-ms))
new-start (- (now) (* tms cur-beat))]
(reset! tick-ms tms)
(reset! start new-start))
[:bpm bpm]))))
(comment defprotocol IMetronome
(start [this])
(stop [this])
(beat [this])
(tick [this])
(bpm [this] [this bpm]))
;== Grooves
;
; A groove represents a pattern of velocities and timing modifications that is
; applied to a sequence of notes to adjust the feel.
;
; * swing
; * jazz groove, latin groove
; * techno grooves (hard on beat one)
; * make something more driving, or more layed back...
|
[
{
"context": "db/id {:comments [:db/id :title {:author [:db/id :username]}]}] (::dfi/query ready-state)))))\n\n (behavior \"",
"end": 3402,
"score": 0.7307901382446289,
"start": 3394,
"tag": "USERNAME",
"value": "username"
},
{
"context": "x 1}) {:comments [:db/id :title {:author [:db/id :username]}]}] (::dfi/query ready-state)))))\n\n (behavior \"",
"end": 3714,
"score": 0.9624320864677429,
"start": 3706,
"tag": "USERNAME",
"value": "username"
},
{
"context": "es\"\n (let [state (atom {:users/by-id {4 {:name \"Joe\"}}\n :t {1 {:id 1}}",
"end": 21829,
"score": 0.997910737991333,
"start": 21826,
"tag": "NAME",
"value": "Joe"
},
{
"context": "nt\"\n (let [state (atom {:users/by-id {4 {:name \"Joe\"}}\n :t {1 {:id 1}}",
"end": 22753,
"score": 0.9996880292892456,
"start": 22750,
"tag": "NAME",
"value": "Joe"
}
] | src/test/fulcro/client/data_fetch_spec.cljs | weirp/fulcrodev | 0 | (ns fulcro.client.data-fetch-spec
(:require
[fulcro.client.data-fetch :as df]
[fulcro.client.impl.data-fetch :as dfi]
[fulcro.client.util :as util]
[goog.log :as glog]
[om.next :as om :refer [defui]]
[cljs.test :refer-macros [is are]]
[fulcro-spec.core :refer
[specification behavior assertions provided component when-mocking]]
[fulcro.client.mutations :as m]
[fulcro.client.logging :as log]
[om.next.protocols :as omp]
[fulcro.client.core :as fc]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; SETUP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defui ^:once Person
static om/IQuery (query [_] [:db/id :username :name])
static om/Ident (ident [_ props] [:person/id (:db/id props)]))
(defui ^:once Comment
static om/IQuery (query [this] [:db/id :title {:author (om/get-query Person)}])
static om/Ident (ident [this props] [:comments/id (:db/id props)]))
(defui ^:once Item
static om/IQuery (query [this] [:db/id :name {:comments (om/get-query Comment)}])
static om/Ident (ident [this props] [:items/id (:db/id props)]))
(defui ^:once Panel
static om/IQuery (query [this] [:db/id {:items (om/get-query Item)}])
static om/Ident (ident [this props] [:panel/id (:db/id props)]))
(defui ^:once PanelRoot
static om/IQuery (query [this] [{:panel (om/get-query Panel)}]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; TESTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(specification "Data states"
(behavior "are properly initialized."
(is (df/data-state? (dfi/make-data-state :ready)))
(try (dfi/make-data-state :invalid-key)
(catch :default e
(is (= (.-message e) "INVALID DATA STATE TYPE: :invalid-key")))))
(behavior "can by identified by type."
(is (df/ready? (dfi/make-data-state :ready)))
(is (df/failed? (dfi/make-data-state :failed)))
(is (df/loading? (dfi/make-data-state :loading)))
(is (not (df/ready? (dfi/make-data-state :failed))))
(is (not (df/failed? "foo")))))
(specification "Processed ready states"
(let [make-ready-marker (fn [without-set]
(dfi/ready-state
{:ident [:item/by-id 1]
:field :comments
:without without-set
:query (om/focus-query (om/get-query Item) [:comments])}))
without-join (make-ready-marker #{:author})
without-prop (make-ready-marker #{:username})
without-multi-prop (make-ready-marker #{:db/id})]
(assertions
"remove the :without portion of the query on joins"
(dfi/data-query without-join) => [{[:item/by-id 1] [{:comments [:db/id :title]}]}]
"remove the :without portion of the query on props"
(dfi/data-query without-prop) => [{[:item/by-id 1] [{:comments [:db/id :title {:author [:db/id :name]}]}]}]
"remove the :without portion when keyword appears in multiple places in the query"
(dfi/data-query without-multi-prop) => [{[:item/by-id 1] [{:comments [:title {:author [:username :name]}]}]}]))
(behavior "can elide top-level keys from the query"
(let [ready-state (dfi/ready-state {:query (om/get-query Item) :without #{:name}})]
(is (= [:db/id {:comments [:db/id :title {:author [:db/id :username]}]}] (::dfi/query ready-state)))))
(behavior "can include parameters when eliding top-level keys from the query"
(let [ready-state (dfi/ready-state {:query (om/get-query Item) :without #{:name} :params {:db/id {:x 1}}})]
(is (= '[(:db/id {:x 1}) {:comments [:db/id :title {:author [:db/id :username]}]}] (::dfi/query ready-state)))))
(behavior "can elide keywords from a union query"
(assertions
(om/ast->query
(dfi/elide-ast-nodes
(om/query->ast [{:current-tab {:panel [:data] :console [:data] :dashboard [:data]}}])
#{:console}))
=> [{:current-tab {:panel [:data] :dashboard [:data]}}])))
(specification "Load parameters"
(let [query-with-params (:query (df/load-params* :prop Person {:params {:n 1}}))
ident-query-with-params (:query (df/load-params* [:person/by-id 1] Person {:params {:n 1}}))]
(assertions
"Always include a vector for refresh"
(df/load-params* :prop Person {}) =fn=> #(vector? (:refresh %))
(df/load-params* [:person/by-id 1] Person {}) =fn=> #(vector? (:refresh %))
"Accepts nil for subquery and params"
(:query (df/load-params* [:person/by-id 1] nil {})) => [[:person/by-id 1]]
"Constructs query with parameters when subquery is nil"
(:query (df/load-params* [:person/by-id 1] nil {:params {:x 1}})) => '[([:person/by-id 1] {:x 1})]
"Constructs a JOIN query (without params)"
(:query (df/load-params* :prop Person {})) => [{:prop (om/get-query Person)}]
(:query (df/load-params* [:person/by-id 1] Person {})) => [{[:person/by-id 1] (om/get-query Person)}]
"Honors target for property-based join"
(:target (df/load-params* :prop Person {:target [:a :b]})) => [:a :b]
"Constructs a JOIN query (with params)"
query-with-params =fn=> (fn [q] (= q `[({:prop ~(om/get-query Person)} {:n 1})]))
ident-query-with-params =fn=> (fn [q] (= q `[({[:person/by-id 1] ~(om/get-query Person)} {:n 1})])))
(provided "uses computed-refresh to augment the refresh list"
(df/computed-refresh explicit k t) =1x=> :computed-refresh
(let [params (df/load-params* :k Person {})]
(assertions
"includes the computed refresh list as refresh"
(:refresh params) => :computed-refresh)))))
(specification "Load auto-refresh"
(component "computed-refresh"
(assertions
"Adds the load-key ident to refresh (as a non-duplicate)"
(#'df/computed-refresh [:a] [:table 1] nil) => [:a [:table 1]]
(#'df/computed-refresh [:a [:table 1]] [:table 1] nil) => [:a [:table 1]]
"Adds the load-key keyword to refresh (non-duplicate, when there is no target)"
(#'df/computed-refresh [:a] :b nil) => [:a :b]
(#'df/computed-refresh [:a :b] :b nil) => [:a :b]
"Adds the target's first two elements as an ident to refresh (when target has 2+ elements)"
(#'df/computed-refresh [:a] :b [:x 3 :boo]) => [:a [:x 3]]
(#'df/computed-refresh [:a] :b [:x 3]) => [:a [:x 3]]
"Adds the target's first element as a kw to refresh (when target has 1 element)"
(#'df/computed-refresh [:a] :b [:x]) => [:a :x])))
(specification "Load mutation expressions"
(let [mutation-expr (df/load-mutation {:refresh [:a :b] :query [:my-query]})
mutation (first mutation-expr)]
(assertions
"are vectors"
mutation-expr =fn=> vector?
"include an fulcro/load with mutation arguments"
mutation =fn=> list?
(first mutation) => 'fulcro/load
"always do a follow-on read for :ui/loading-data"
mutation-expr =fn=> #(some (fn [k] (= k :ui/loading-data)) %)
"include user-driven follow-on-reads"
mutation-expr =fn=> #(some (fn [k] (= k :a)) %)
mutation-expr =fn=> #(some (fn [k] (= k :b)) %))))
(specification "The load function"
(when-mocking
(df/load-params* key query config) => :mutation-args
(df/load-mutation args) => (do
(assertions
"creates mutation arguments"
args => :mutation-args)
:mutation)
(om/transact! c tx) => (do (assertions
"uses the passed component/app in transact!"
c => :component
"uses the mutation created by load-mutation"
tx => :mutation))
(om/component? c) => true
(df/load :component :x Person {})))
(specification "The load-action function"
(let [state-atom (atom {})]
(when-mocking
(df/load-params* key query config) => {:refresh [] :query [:x]}
(df/load-action state-atom :x Person {})
(let [query (-> @state-atom :fulcro/ready-to-load first ::dfi/query)]
(assertions
"State atom ends up with a proper load marker"
query => [:x])))))
(specification "Lazy loading"
(component "Loading a field within a component"
(let [query (om/get-query Item)]
(provided "properly calls transact"
(om/get-ident c) =2x=> [:item/by-id 10]
(om/get-query c) =1x=> query
(om/transact! c tx) =1x=> (let [params (-> tx first second)
follow-on-reads (set (-> tx rest))]
(assertions
"includes :ui/loading-data in the follow-on reads"
(contains? follow-on-reads :ui/loading-data) => true
"includes ident of component in the follow-on reads"
(contains? follow-on-reads [:item/by-id 10]) => true
"does the transact on the component"
c => 'component
"includes the component's ident in the marker."
(:ident params) => [:item/by-id 10]
"focuses the query to the specified field."
(:query params) => [{:comments [:db/id :title {:author [:db/id :username :name]}]}]
"includes the parameters."
(:params params) => {:sort :by-name}
"includes the subquery exclusions."
(:without params) => #{:excluded-attr}
"includes the post-processing callback."
(:post-mutation params) => 'foo
"includes the error fallback"
(:fallback params) => 'bar))
(df/load-field 'component :comments
:without #{:excluded-attr}
:params {:sort :by-name}
:post-mutation 'foo
:fallback 'bar))))
(component "Loading a field from within another mutation"
(let [app-state (atom {})]
(df/load-field-action app-state Item [:item/by-id 3] :comments :without #{:author})
(let [marker (first (get-in @app-state [:fulcro/ready-to-load]))]
(assertions
"places a ready marker in the app state"
marker =fn=> (fn [marker] (df/ready? marker))
"includes the focused query"
(dfi/data-query marker) => [{[:item/by-id 3] [{:comments [:db/id :title]}]}])))))
(specification "full-query"
(let [item-ready-markers [(dfi/ready-state {:ident [:db/id 1] :field :author :query [{:author [:name]}]})
(dfi/ready-state {:ident [:db/id 2] :field :author :query [{:author [:name]}]})]
top-level-markers [(dfi/ready-state {:query [{:questions [:db/id :name]}]})
(dfi/ready-state {:query [{:answers [:db/id :name]}]})]]
(behavior "composes items queries"
(is (= [{[:db/id 1] [{:author [:name]}]} {[:db/id 2] [{:author [:name]}]}] (dfi/full-query item-ready-markers))))
(behavior "composes top-level queries"
(is (= [{:questions [:db/id :name]} {:answers [:db/id :name]}] (dfi/full-query top-level-markers))))))
(specification "data-query-key of a fetch marker's query"
(assertions
"is the first keyword of simple props"
(dfi/data-query-key {::dfi/query [:a :b :c]}) => :a
"is the first keyword the first join"
(dfi/data-query-key {::dfi/query [{:a [:x :y]} :b {:c [:z]}]}) => :a
"tolerates parameters"
(dfi/data-query-key {::dfi/query '[({:a [:x :y]} {:n 1}) :b {:c [:z]}]}) => :a
(dfi/data-query-key {::dfi/query '[(:a {:n 1}) :b {:c [:z]}]}) => :a))
(defn mark-loading-mutate [])
(defn mark-loading-fallback [])
(defmethod m/mutate 'mark-loading-test/callback [e k p] {:action #(mark-loading-mutate)})
(defmethod m/mutate 'mark-loading-test/fallback [_ _ _] {:action #(mark-loading-fallback)})
(specification "The inject-query-params function"
(let [prop-ast (om/query->ast [:a :b :c])
prop-params {:a {:x 1} :c {:y 2}}
join-ast (om/query->ast [:a {:things [:name]}])
join-params {:things {:start 1}}
existing-params-ast (om/query->ast '[(:a {:x 1})])
existing-params-overwrite {:a {:x 2}}]
(assertions
"can add parameters to a top-level query property"
(om/ast->query (dfi/inject-query-params prop-ast prop-params)) => '[(:a {:x 1}) :b (:c {:y 2})]
"can add parameters to a top-level join property"
(om/ast->query (dfi/inject-query-params join-ast join-params)) => '[:a ({:things [:name]} {:start 1})]
"merges new parameters over existing ones"
(om/ast->query (dfi/inject-query-params existing-params-ast existing-params-overwrite)) => '[(:a {:x 2})])
(behavior "Warns about parameters that cannot be joined to the query"
(let [ast (om/query->ast [:a :b])
params {:c {:x 1}}]
(when-mocking
(glog/error obj msg) => (is (= "Error: You attempted to add parameters for #{:c} to top-level key(s) of [:a :b]" msg))
(dfi/inject-query-params ast params)
)))))
(specification "set-global-loading"
(let [loading-state (atom {:ui/loading-data true
:fulcro/loads-in-progress #{1}})
not-loading-state (atom {:ui/loading-data true
:fulcro/loads-in-progress #{}})]
(when-mocking
(om/app-state r) => not-loading-state
(dfi/set-global-loading :reconciler)
(assertions
"clears the marker if nothing is in the loading set"
(-> @not-loading-state :ui/loading-data) => false))
(when-mocking
(om/app-state r) => loading-state
(dfi/set-global-loading :reconciler)
(assertions
"sets the marker if anything is in the loading set"
(-> @loading-state :ui/loading-data) => true))))
(specification "Rendering lazily loaded data"
(let [ready-props {:ui/fetch-state (dfi/make-data-state :ready)}
loading-props (update ready-props :ui/fetch-state dfi/set-loading!)
failed-props (update ready-props :ui/fetch-state dfi/set-failed!)
props {:foo :bar}]
(letfn [(ready-override [_] :ready-override)
(loading-override [_] :loading-override)
(failed-override [_] :failed-override)
(not-present [_] :not-present)
(present [props] (if (nil? props) :baz (:foo props)))]
(assertions
"When props are ready to load, runs ready-render"
(df/lazily-loaded present ready-props :ready-render ready-override) => :ready-override
"When props are loading, runs loading-render"
(df/lazily-loaded present loading-props :loading-render loading-override) => :loading-override
"When loading the props failed, runs failed-render"
(df/lazily-loaded present failed-props :failed-render failed-override) => :failed-override
"When the props are nil and not-present-renderer provided, runs not-present-render"
(df/lazily-loaded present nil :not-present-render not-present) => :not-present
"When the props are nil without a not-present-renderer, runs data-render"
(df/lazily-loaded present nil) => :baz
"When props are loaded, runs data-render."
(df/lazily-loaded present props) => :bar))))
(defmethod m/mutate 'qrp-loaded-callback [{:keys [state]} n p] (swap! state assoc :callback-done true :callback-params p))
(specification "Query response processing (loaded-callback with post mutation)"
(let [item (dfi/set-loading! (dfi/ready-state {:ident [:item 2]
:query [:id :b]
:refresh [:x :y]
:post-mutation 'qrp-loaded-callback
:post-mutation-params {:x 1}}))
state (atom {:fulcro/loads-in-progress #{(dfi/data-uuid item)}
:item {2 {:id :original-data}}})
items [item]
queued (atom [])
rendered (atom false)
merged (atom false)
globally-marked (atom false)
loaded-cb (dfi/loaded-callback :reconciler)
response {:id 2}]
(when-mocking
(om/app-state r) => state
(om/merge! r resp query) => (reset! merged true)
(util/force-render r ks) => (reset! rendered ks)
(dfi/set-global-loading r) => (reset! globally-marked true)
(loaded-cb response items)
(assertions
"Merges response with app state"
@merged => true
"Runs post-mutations"
(:callback-done @state) => true
(:callback-params @state) => {:x 1}
"Triggers a render for :ui/loading-data and any addl keys requested by mutations"
@rendered => [:ui/loading-data :x :y]
"Removes loading markers for results that didn't materialize"
(get-in @state (dfi/data-path item) :fail) => nil
"Updates the global loading marker"
@globally-marked => true))))
(specification "Query response processing (loaded-callback with no post-mutations)"
(let [item (dfi/set-loading! (dfi/ready-state {:ident [:item 2] :query [:id :b] :refresh [:a]}))
state (atom {:fulcro/loads-in-progress #{(dfi/data-uuid item)}
:item {2 {:id :original-data}}})
items [item]
queued (atom [])
rendered (atom false)
merged (atom false)
globally-marked (atom false)
loaded-cb (dfi/loaded-callback :reconciler)
response {:id 2}]
(when-mocking
(om/app-state r) => state
(om/merge! r resp query) => (reset! merged true)
(util/force-render r items) => (reset! queued (set items))
(dfi/set-global-loading r) => (reset! globally-marked true)
(loaded-cb response items)
(assertions
"Merges response with app state"
@merged => true
"Queues the refresh items for refresh"
@queued =fn=> #(contains? % :a)
"Queues the global loading marker for refresh"
@queued =fn=> #(contains? % :ui/loading-data)
"Removes loading markers for results that didn't materialize"
(get-in @state (dfi/data-path item) :fail) => nil
"Updates the global loading marker"
@globally-marked => true))))
(defmethod m/mutate 'qrp-error-fallback [{:keys [state]} n p] (swap! state assoc :fallback-done true))
(specification "Query response processing (error-callback)"
(let [item (dfi/set-loading! (dfi/ready-state {:ident [:item 2] :query [:id :b] :fallback 'qrp-error-fallback :refresh [:x :y]}))
state (atom {:fulcro/loads-in-progress #{(dfi/data-uuid item)}
:item {2 {:id :original-data}}})
items [item]
globally-marked (atom false)
queued (atom [])
rendered (atom false)
error-cb (dfi/error-callback :reconciler)
response {:id 2}]
(when-mocking
(om/app-state r) => state
(dfi/set-global-loading r) => (reset! globally-marked true)
(om/force-root-render! r) => (assertions
"Triggers render at root"
r => :reconciler)
(error-cb response items))
(assertions
"Runs fallbacks"
(:fallback-done @state) => true
"Rewrites load markers as error markers"
(dfi/failed? (get-in @state (conj (dfi/data-path item) :ui/fetch-state) :fail)) => true
"Updates the global loading marker"
@globally-marked => true)))
(specification "fetch marker data-path"
(assertions
"is the field path for a load-field marker"
(dfi/data-path {::dfi/ident [:obj 1] ::dfi/field :f}) => [:obj 1 :f]
"is an ident if the query key is an ident"
(dfi/data-path {::dfi/query [{[:a 1] [:prop]}]}) => [:a 1]
"is the data-query-key by default"
(dfi/data-path {::dfi/query [:obj]}) => [:obj]
"is the explicit target if supplied"
(dfi/data-path {::dfi/target [:a :b]}) => [:a :b]))
(specification "Load markers for field loading"
(let [state (atom {:t {1 {:id 1}
2 {:id 2}}})
item-1 (dfi/ready-state {:query [:comments] :ident [:t 1] :field :comments :target [:top]})
item-2 (dfi/ready-state {:query [:comments] :ident [:t 2] :field :comments :marker false})]
(dfi/place-load-markers state [item-1 item-2])
(assertions
"ignore targeting"
(get-in @state [:top]) => nil
"are placed in app state only when the fetch requests a marker"
(get-in @state [:t 1 :comments]) =fn=> #(contains? % :ui/fetch-state)
(get-in @state [:t 2]) => {:id 2}
"are tracked by UUID in :fulcro/loads-in-progress"
(get @state :fulcro/loads-in-progress) =fn=> #(= 2 (count %)))))
(specification "Load markers for regular (top-level) queries"
(let [state (atom {:users/by-id {4 {:name "Joe"}}
:t {1 {:id 1}}})
item-1 (dfi/ready-state {:query [{:users [:name]}]})
item-2 (dfi/ready-state {:query [:some-value]})
item-3 (dfi/ready-state {:query [{:users [:name]}] :target [:t 1 :user]})
item-4 (dfi/ready-state {:query [:some-value] :target [:t 1 :value]})]
(dfi/place-load-markers state [item-1 item-2 item-3 item-4])
(assertions
"Default to being placed in app root at the first key of the query"
(get @state :users) =fn=> #(contains? % :ui/fetch-state)
(get @state :some-value) =fn=> #(contains? % :ui/fetch-state)
"Will appear at alternate target locations"
(get-in @state [:t 1 :user]) =fn=> #(contains? % :ui/fetch-state)
(get-in @state [:t 1 :value]) =fn=> #(contains? % :ui/fetch-state))))
(specification "Load markers when loading with an ident"
(let [state (atom {:users/by-id {4 {:name "Joe"}}
:t {1 {:id 1}}})
item-2 (dfi/ready-state {:query [{[:users/by-id 3] [:name]}] :target [:t 1 :user]})
item-3 (dfi/ready-state {:query [{[:users/by-id 4] [:name]}]})]
(dfi/place-load-markers state [item-2 item-3])
(assertions
"Ignore explicit targeting"
(get-in @state [:t 1 :user :ui/fetch-state]) => nil
"Only place a marker if there is already an object in the table"
(get-in @state [:users/by-id 3 :ui/fetch-state]) => nil
(get-in @state [:users/by-id 4 :ui/fetch-state]) =fn=> map?)))
(specification "relocating server results"
(behavior "Does nothing if the item is based on a simple query with no targeting"
(let [simple-state-atom (atom {:a [[:x 1]]})
simple-items #{(dfi/ready-state {:query [{:a [:x]}]})}]
(dfi/relocate-targeted-results simple-state-atom simple-items)
(assertions
@simple-state-atom => {:a [[:x 1]]})))
(behavior "Does nothing if the item is a field query"
(let [simple-state-atom (atom {:a [[:x 1]]})
mistargeted-items #{(dfi/ready-state {:ident [:obj 1] :field :boo :query [:boo] :target [:obj 1 :boo]})}]
(dfi/relocate-targeted-results simple-state-atom mistargeted-items)
(assertions
@simple-state-atom => {:a [[:x 1]]})))
(behavior "Moves simple query results to explicit target"
(let [simple-state-atom (atom {:a [[:x 1]]})
maptarget-state-atom (atom {:a [[:x 1]]
:obj {1 {:boo {:n 1}}}})
vectarget-state-atom (atom {:a [[:x 1]]
:obj {1 {:boo []}}})
targeted-items #{(dfi/ready-state {:query [{:a [:x]}] :target [:obj 1 :boo]})}]
(dfi/relocate-targeted-results simple-state-atom targeted-items)
(dfi/relocate-targeted-results maptarget-state-atom targeted-items)
(dfi/relocate-targeted-results vectarget-state-atom targeted-items)
(assertions
@simple-state-atom => {:obj {1 {:boo [[:x 1]]}}}
@maptarget-state-atom => {:obj {1 {:boo [[:x 1]]}}}
@vectarget-state-atom => {:obj {1 {:boo [[:x 1]]}}}))))
(specification "Splits items to load by join key / ident kind."
(let [q-a-x {::dfi/query [{:a [:x]}]}
q-a-y {::dfi/query [{:a [:y]}]}
q-a-z {::dfi/query [{:a [:z]}]}
q-a-w {::dfi/query [{:a [:w]}]}
q-b-x {::dfi/query [{:b [:x]}]}
q-c-x {::dfi/query [{[:c 999] [:x]}]}
q-c-y {::dfi/query [{[:c 999] [:y]}]}
q-c-z {::dfi/query [{[:c 998] [:z]}]}
q-c-w {::dfi/query [{[:c 998] [:w]}]}
q-ab-x {::dfi/query [{:a [:x]} {:b [:x]}]}
q-bc-x {::dfi/query [{:b [:x]} {:c [:x]}]}
q-cd-x {::dfi/query [{:c [:x]} {:d [:x]}]}
q-de-x {::dfi/query [{:d [:x]} {:e [:x]}]}]
(assertions
"loads all items immediately when no join key conflicts, preserving order"
(dfi/split-items-ready-to-load [q-a-x]) => [[q-a-x] []]
(dfi/split-items-ready-to-load [q-a-x q-b-x]) => [[q-a-x q-b-x] []]
(dfi/split-items-ready-to-load [q-a-x q-c-x]) => [[q-a-x q-c-x] []]
(dfi/split-items-ready-to-load [q-a-x q-b-x q-c-x]) => [[q-a-x q-b-x q-c-x] []]
"defers loading when join key conflict, preserving order where possible"
(dfi/split-items-ready-to-load [q-a-x q-a-y q-a-z q-a-w]) => [[q-a-x] [q-a-y q-a-z q-a-w]]
(dfi/split-items-ready-to-load [q-a-y q-a-z q-a-w]) => [[q-a-y] [q-a-z q-a-w]]
(dfi/split-items-ready-to-load [q-a-z q-a-w]) => [[q-a-z] [q-a-w]]
(dfi/split-items-ready-to-load [q-a-w]) => [[q-a-w] []]
"defers loading when ident key conflict, preserving order where possible"
(dfi/split-items-ready-to-load [q-c-x q-c-y q-c-z q-c-w]) => [[q-c-x] [q-c-y q-c-z q-c-w]]
(dfi/split-items-ready-to-load [q-c-y q-c-z q-c-w]) => [[q-c-y] [q-c-z q-c-w]]
(dfi/split-items-ready-to-load [q-c-z q-c-w]) => [[q-c-z] [q-c-w]]
(dfi/split-items-ready-to-load [q-c-w]) => [[q-c-w] []]
"defers loading when any key conflicts, preserving order where possible"
(dfi/split-items-ready-to-load
[q-a-x q-a-y q-a-z
q-b-x
q-c-x q-c-y q-c-z]) => [[q-a-x q-b-x q-c-x] [q-a-y q-a-z q-c-y q-c-z]]
"defers loading when join keys partially conflict, preserving order where possible"
(dfi/split-items-ready-to-load [q-ab-x q-bc-x q-cd-x q-de-x]) => [[q-ab-x q-cd-x] [q-bc-x q-de-x]]
(dfi/split-items-ready-to-load [q-bc-x q-de-x]) => [[q-bc-x q-de-x] []])))
| 111915 | (ns fulcro.client.data-fetch-spec
(:require
[fulcro.client.data-fetch :as df]
[fulcro.client.impl.data-fetch :as dfi]
[fulcro.client.util :as util]
[goog.log :as glog]
[om.next :as om :refer [defui]]
[cljs.test :refer-macros [is are]]
[fulcro-spec.core :refer
[specification behavior assertions provided component when-mocking]]
[fulcro.client.mutations :as m]
[fulcro.client.logging :as log]
[om.next.protocols :as omp]
[fulcro.client.core :as fc]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; SETUP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defui ^:once Person
static om/IQuery (query [_] [:db/id :username :name])
static om/Ident (ident [_ props] [:person/id (:db/id props)]))
(defui ^:once Comment
static om/IQuery (query [this] [:db/id :title {:author (om/get-query Person)}])
static om/Ident (ident [this props] [:comments/id (:db/id props)]))
(defui ^:once Item
static om/IQuery (query [this] [:db/id :name {:comments (om/get-query Comment)}])
static om/Ident (ident [this props] [:items/id (:db/id props)]))
(defui ^:once Panel
static om/IQuery (query [this] [:db/id {:items (om/get-query Item)}])
static om/Ident (ident [this props] [:panel/id (:db/id props)]))
(defui ^:once PanelRoot
static om/IQuery (query [this] [{:panel (om/get-query Panel)}]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; TESTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(specification "Data states"
(behavior "are properly initialized."
(is (df/data-state? (dfi/make-data-state :ready)))
(try (dfi/make-data-state :invalid-key)
(catch :default e
(is (= (.-message e) "INVALID DATA STATE TYPE: :invalid-key")))))
(behavior "can by identified by type."
(is (df/ready? (dfi/make-data-state :ready)))
(is (df/failed? (dfi/make-data-state :failed)))
(is (df/loading? (dfi/make-data-state :loading)))
(is (not (df/ready? (dfi/make-data-state :failed))))
(is (not (df/failed? "foo")))))
(specification "Processed ready states"
(let [make-ready-marker (fn [without-set]
(dfi/ready-state
{:ident [:item/by-id 1]
:field :comments
:without without-set
:query (om/focus-query (om/get-query Item) [:comments])}))
without-join (make-ready-marker #{:author})
without-prop (make-ready-marker #{:username})
without-multi-prop (make-ready-marker #{:db/id})]
(assertions
"remove the :without portion of the query on joins"
(dfi/data-query without-join) => [{[:item/by-id 1] [{:comments [:db/id :title]}]}]
"remove the :without portion of the query on props"
(dfi/data-query without-prop) => [{[:item/by-id 1] [{:comments [:db/id :title {:author [:db/id :name]}]}]}]
"remove the :without portion when keyword appears in multiple places in the query"
(dfi/data-query without-multi-prop) => [{[:item/by-id 1] [{:comments [:title {:author [:username :name]}]}]}]))
(behavior "can elide top-level keys from the query"
(let [ready-state (dfi/ready-state {:query (om/get-query Item) :without #{:name}})]
(is (= [:db/id {:comments [:db/id :title {:author [:db/id :username]}]}] (::dfi/query ready-state)))))
(behavior "can include parameters when eliding top-level keys from the query"
(let [ready-state (dfi/ready-state {:query (om/get-query Item) :without #{:name} :params {:db/id {:x 1}}})]
(is (= '[(:db/id {:x 1}) {:comments [:db/id :title {:author [:db/id :username]}]}] (::dfi/query ready-state)))))
(behavior "can elide keywords from a union query"
(assertions
(om/ast->query
(dfi/elide-ast-nodes
(om/query->ast [{:current-tab {:panel [:data] :console [:data] :dashboard [:data]}}])
#{:console}))
=> [{:current-tab {:panel [:data] :dashboard [:data]}}])))
(specification "Load parameters"
(let [query-with-params (:query (df/load-params* :prop Person {:params {:n 1}}))
ident-query-with-params (:query (df/load-params* [:person/by-id 1] Person {:params {:n 1}}))]
(assertions
"Always include a vector for refresh"
(df/load-params* :prop Person {}) =fn=> #(vector? (:refresh %))
(df/load-params* [:person/by-id 1] Person {}) =fn=> #(vector? (:refresh %))
"Accepts nil for subquery and params"
(:query (df/load-params* [:person/by-id 1] nil {})) => [[:person/by-id 1]]
"Constructs query with parameters when subquery is nil"
(:query (df/load-params* [:person/by-id 1] nil {:params {:x 1}})) => '[([:person/by-id 1] {:x 1})]
"Constructs a JOIN query (without params)"
(:query (df/load-params* :prop Person {})) => [{:prop (om/get-query Person)}]
(:query (df/load-params* [:person/by-id 1] Person {})) => [{[:person/by-id 1] (om/get-query Person)}]
"Honors target for property-based join"
(:target (df/load-params* :prop Person {:target [:a :b]})) => [:a :b]
"Constructs a JOIN query (with params)"
query-with-params =fn=> (fn [q] (= q `[({:prop ~(om/get-query Person)} {:n 1})]))
ident-query-with-params =fn=> (fn [q] (= q `[({[:person/by-id 1] ~(om/get-query Person)} {:n 1})])))
(provided "uses computed-refresh to augment the refresh list"
(df/computed-refresh explicit k t) =1x=> :computed-refresh
(let [params (df/load-params* :k Person {})]
(assertions
"includes the computed refresh list as refresh"
(:refresh params) => :computed-refresh)))))
(specification "Load auto-refresh"
(component "computed-refresh"
(assertions
"Adds the load-key ident to refresh (as a non-duplicate)"
(#'df/computed-refresh [:a] [:table 1] nil) => [:a [:table 1]]
(#'df/computed-refresh [:a [:table 1]] [:table 1] nil) => [:a [:table 1]]
"Adds the load-key keyword to refresh (non-duplicate, when there is no target)"
(#'df/computed-refresh [:a] :b nil) => [:a :b]
(#'df/computed-refresh [:a :b] :b nil) => [:a :b]
"Adds the target's first two elements as an ident to refresh (when target has 2+ elements)"
(#'df/computed-refresh [:a] :b [:x 3 :boo]) => [:a [:x 3]]
(#'df/computed-refresh [:a] :b [:x 3]) => [:a [:x 3]]
"Adds the target's first element as a kw to refresh (when target has 1 element)"
(#'df/computed-refresh [:a] :b [:x]) => [:a :x])))
(specification "Load mutation expressions"
(let [mutation-expr (df/load-mutation {:refresh [:a :b] :query [:my-query]})
mutation (first mutation-expr)]
(assertions
"are vectors"
mutation-expr =fn=> vector?
"include an fulcro/load with mutation arguments"
mutation =fn=> list?
(first mutation) => 'fulcro/load
"always do a follow-on read for :ui/loading-data"
mutation-expr =fn=> #(some (fn [k] (= k :ui/loading-data)) %)
"include user-driven follow-on-reads"
mutation-expr =fn=> #(some (fn [k] (= k :a)) %)
mutation-expr =fn=> #(some (fn [k] (= k :b)) %))))
(specification "The load function"
(when-mocking
(df/load-params* key query config) => :mutation-args
(df/load-mutation args) => (do
(assertions
"creates mutation arguments"
args => :mutation-args)
:mutation)
(om/transact! c tx) => (do (assertions
"uses the passed component/app in transact!"
c => :component
"uses the mutation created by load-mutation"
tx => :mutation))
(om/component? c) => true
(df/load :component :x Person {})))
(specification "The load-action function"
(let [state-atom (atom {})]
(when-mocking
(df/load-params* key query config) => {:refresh [] :query [:x]}
(df/load-action state-atom :x Person {})
(let [query (-> @state-atom :fulcro/ready-to-load first ::dfi/query)]
(assertions
"State atom ends up with a proper load marker"
query => [:x])))))
(specification "Lazy loading"
(component "Loading a field within a component"
(let [query (om/get-query Item)]
(provided "properly calls transact"
(om/get-ident c) =2x=> [:item/by-id 10]
(om/get-query c) =1x=> query
(om/transact! c tx) =1x=> (let [params (-> tx first second)
follow-on-reads (set (-> tx rest))]
(assertions
"includes :ui/loading-data in the follow-on reads"
(contains? follow-on-reads :ui/loading-data) => true
"includes ident of component in the follow-on reads"
(contains? follow-on-reads [:item/by-id 10]) => true
"does the transact on the component"
c => 'component
"includes the component's ident in the marker."
(:ident params) => [:item/by-id 10]
"focuses the query to the specified field."
(:query params) => [{:comments [:db/id :title {:author [:db/id :username :name]}]}]
"includes the parameters."
(:params params) => {:sort :by-name}
"includes the subquery exclusions."
(:without params) => #{:excluded-attr}
"includes the post-processing callback."
(:post-mutation params) => 'foo
"includes the error fallback"
(:fallback params) => 'bar))
(df/load-field 'component :comments
:without #{:excluded-attr}
:params {:sort :by-name}
:post-mutation 'foo
:fallback 'bar))))
(component "Loading a field from within another mutation"
(let [app-state (atom {})]
(df/load-field-action app-state Item [:item/by-id 3] :comments :without #{:author})
(let [marker (first (get-in @app-state [:fulcro/ready-to-load]))]
(assertions
"places a ready marker in the app state"
marker =fn=> (fn [marker] (df/ready? marker))
"includes the focused query"
(dfi/data-query marker) => [{[:item/by-id 3] [{:comments [:db/id :title]}]}])))))
(specification "full-query"
(let [item-ready-markers [(dfi/ready-state {:ident [:db/id 1] :field :author :query [{:author [:name]}]})
(dfi/ready-state {:ident [:db/id 2] :field :author :query [{:author [:name]}]})]
top-level-markers [(dfi/ready-state {:query [{:questions [:db/id :name]}]})
(dfi/ready-state {:query [{:answers [:db/id :name]}]})]]
(behavior "composes items queries"
(is (= [{[:db/id 1] [{:author [:name]}]} {[:db/id 2] [{:author [:name]}]}] (dfi/full-query item-ready-markers))))
(behavior "composes top-level queries"
(is (= [{:questions [:db/id :name]} {:answers [:db/id :name]}] (dfi/full-query top-level-markers))))))
(specification "data-query-key of a fetch marker's query"
(assertions
"is the first keyword of simple props"
(dfi/data-query-key {::dfi/query [:a :b :c]}) => :a
"is the first keyword the first join"
(dfi/data-query-key {::dfi/query [{:a [:x :y]} :b {:c [:z]}]}) => :a
"tolerates parameters"
(dfi/data-query-key {::dfi/query '[({:a [:x :y]} {:n 1}) :b {:c [:z]}]}) => :a
(dfi/data-query-key {::dfi/query '[(:a {:n 1}) :b {:c [:z]}]}) => :a))
(defn mark-loading-mutate [])
(defn mark-loading-fallback [])
(defmethod m/mutate 'mark-loading-test/callback [e k p] {:action #(mark-loading-mutate)})
(defmethod m/mutate 'mark-loading-test/fallback [_ _ _] {:action #(mark-loading-fallback)})
(specification "The inject-query-params function"
(let [prop-ast (om/query->ast [:a :b :c])
prop-params {:a {:x 1} :c {:y 2}}
join-ast (om/query->ast [:a {:things [:name]}])
join-params {:things {:start 1}}
existing-params-ast (om/query->ast '[(:a {:x 1})])
existing-params-overwrite {:a {:x 2}}]
(assertions
"can add parameters to a top-level query property"
(om/ast->query (dfi/inject-query-params prop-ast prop-params)) => '[(:a {:x 1}) :b (:c {:y 2})]
"can add parameters to a top-level join property"
(om/ast->query (dfi/inject-query-params join-ast join-params)) => '[:a ({:things [:name]} {:start 1})]
"merges new parameters over existing ones"
(om/ast->query (dfi/inject-query-params existing-params-ast existing-params-overwrite)) => '[(:a {:x 2})])
(behavior "Warns about parameters that cannot be joined to the query"
(let [ast (om/query->ast [:a :b])
params {:c {:x 1}}]
(when-mocking
(glog/error obj msg) => (is (= "Error: You attempted to add parameters for #{:c} to top-level key(s) of [:a :b]" msg))
(dfi/inject-query-params ast params)
)))))
(specification "set-global-loading"
(let [loading-state (atom {:ui/loading-data true
:fulcro/loads-in-progress #{1}})
not-loading-state (atom {:ui/loading-data true
:fulcro/loads-in-progress #{}})]
(when-mocking
(om/app-state r) => not-loading-state
(dfi/set-global-loading :reconciler)
(assertions
"clears the marker if nothing is in the loading set"
(-> @not-loading-state :ui/loading-data) => false))
(when-mocking
(om/app-state r) => loading-state
(dfi/set-global-loading :reconciler)
(assertions
"sets the marker if anything is in the loading set"
(-> @loading-state :ui/loading-data) => true))))
(specification "Rendering lazily loaded data"
(let [ready-props {:ui/fetch-state (dfi/make-data-state :ready)}
loading-props (update ready-props :ui/fetch-state dfi/set-loading!)
failed-props (update ready-props :ui/fetch-state dfi/set-failed!)
props {:foo :bar}]
(letfn [(ready-override [_] :ready-override)
(loading-override [_] :loading-override)
(failed-override [_] :failed-override)
(not-present [_] :not-present)
(present [props] (if (nil? props) :baz (:foo props)))]
(assertions
"When props are ready to load, runs ready-render"
(df/lazily-loaded present ready-props :ready-render ready-override) => :ready-override
"When props are loading, runs loading-render"
(df/lazily-loaded present loading-props :loading-render loading-override) => :loading-override
"When loading the props failed, runs failed-render"
(df/lazily-loaded present failed-props :failed-render failed-override) => :failed-override
"When the props are nil and not-present-renderer provided, runs not-present-render"
(df/lazily-loaded present nil :not-present-render not-present) => :not-present
"When the props are nil without a not-present-renderer, runs data-render"
(df/lazily-loaded present nil) => :baz
"When props are loaded, runs data-render."
(df/lazily-loaded present props) => :bar))))
(defmethod m/mutate 'qrp-loaded-callback [{:keys [state]} n p] (swap! state assoc :callback-done true :callback-params p))
(specification "Query response processing (loaded-callback with post mutation)"
(let [item (dfi/set-loading! (dfi/ready-state {:ident [:item 2]
:query [:id :b]
:refresh [:x :y]
:post-mutation 'qrp-loaded-callback
:post-mutation-params {:x 1}}))
state (atom {:fulcro/loads-in-progress #{(dfi/data-uuid item)}
:item {2 {:id :original-data}}})
items [item]
queued (atom [])
rendered (atom false)
merged (atom false)
globally-marked (atom false)
loaded-cb (dfi/loaded-callback :reconciler)
response {:id 2}]
(when-mocking
(om/app-state r) => state
(om/merge! r resp query) => (reset! merged true)
(util/force-render r ks) => (reset! rendered ks)
(dfi/set-global-loading r) => (reset! globally-marked true)
(loaded-cb response items)
(assertions
"Merges response with app state"
@merged => true
"Runs post-mutations"
(:callback-done @state) => true
(:callback-params @state) => {:x 1}
"Triggers a render for :ui/loading-data and any addl keys requested by mutations"
@rendered => [:ui/loading-data :x :y]
"Removes loading markers for results that didn't materialize"
(get-in @state (dfi/data-path item) :fail) => nil
"Updates the global loading marker"
@globally-marked => true))))
(specification "Query response processing (loaded-callback with no post-mutations)"
(let [item (dfi/set-loading! (dfi/ready-state {:ident [:item 2] :query [:id :b] :refresh [:a]}))
state (atom {:fulcro/loads-in-progress #{(dfi/data-uuid item)}
:item {2 {:id :original-data}}})
items [item]
queued (atom [])
rendered (atom false)
merged (atom false)
globally-marked (atom false)
loaded-cb (dfi/loaded-callback :reconciler)
response {:id 2}]
(when-mocking
(om/app-state r) => state
(om/merge! r resp query) => (reset! merged true)
(util/force-render r items) => (reset! queued (set items))
(dfi/set-global-loading r) => (reset! globally-marked true)
(loaded-cb response items)
(assertions
"Merges response with app state"
@merged => true
"Queues the refresh items for refresh"
@queued =fn=> #(contains? % :a)
"Queues the global loading marker for refresh"
@queued =fn=> #(contains? % :ui/loading-data)
"Removes loading markers for results that didn't materialize"
(get-in @state (dfi/data-path item) :fail) => nil
"Updates the global loading marker"
@globally-marked => true))))
(defmethod m/mutate 'qrp-error-fallback [{:keys [state]} n p] (swap! state assoc :fallback-done true))
(specification "Query response processing (error-callback)"
(let [item (dfi/set-loading! (dfi/ready-state {:ident [:item 2] :query [:id :b] :fallback 'qrp-error-fallback :refresh [:x :y]}))
state (atom {:fulcro/loads-in-progress #{(dfi/data-uuid item)}
:item {2 {:id :original-data}}})
items [item]
globally-marked (atom false)
queued (atom [])
rendered (atom false)
error-cb (dfi/error-callback :reconciler)
response {:id 2}]
(when-mocking
(om/app-state r) => state
(dfi/set-global-loading r) => (reset! globally-marked true)
(om/force-root-render! r) => (assertions
"Triggers render at root"
r => :reconciler)
(error-cb response items))
(assertions
"Runs fallbacks"
(:fallback-done @state) => true
"Rewrites load markers as error markers"
(dfi/failed? (get-in @state (conj (dfi/data-path item) :ui/fetch-state) :fail)) => true
"Updates the global loading marker"
@globally-marked => true)))
(specification "fetch marker data-path"
(assertions
"is the field path for a load-field marker"
(dfi/data-path {::dfi/ident [:obj 1] ::dfi/field :f}) => [:obj 1 :f]
"is an ident if the query key is an ident"
(dfi/data-path {::dfi/query [{[:a 1] [:prop]}]}) => [:a 1]
"is the data-query-key by default"
(dfi/data-path {::dfi/query [:obj]}) => [:obj]
"is the explicit target if supplied"
(dfi/data-path {::dfi/target [:a :b]}) => [:a :b]))
(specification "Load markers for field loading"
(let [state (atom {:t {1 {:id 1}
2 {:id 2}}})
item-1 (dfi/ready-state {:query [:comments] :ident [:t 1] :field :comments :target [:top]})
item-2 (dfi/ready-state {:query [:comments] :ident [:t 2] :field :comments :marker false})]
(dfi/place-load-markers state [item-1 item-2])
(assertions
"ignore targeting"
(get-in @state [:top]) => nil
"are placed in app state only when the fetch requests a marker"
(get-in @state [:t 1 :comments]) =fn=> #(contains? % :ui/fetch-state)
(get-in @state [:t 2]) => {:id 2}
"are tracked by UUID in :fulcro/loads-in-progress"
(get @state :fulcro/loads-in-progress) =fn=> #(= 2 (count %)))))
(specification "Load markers for regular (top-level) queries"
(let [state (atom {:users/by-id {4 {:name "<NAME>"}}
:t {1 {:id 1}}})
item-1 (dfi/ready-state {:query [{:users [:name]}]})
item-2 (dfi/ready-state {:query [:some-value]})
item-3 (dfi/ready-state {:query [{:users [:name]}] :target [:t 1 :user]})
item-4 (dfi/ready-state {:query [:some-value] :target [:t 1 :value]})]
(dfi/place-load-markers state [item-1 item-2 item-3 item-4])
(assertions
"Default to being placed in app root at the first key of the query"
(get @state :users) =fn=> #(contains? % :ui/fetch-state)
(get @state :some-value) =fn=> #(contains? % :ui/fetch-state)
"Will appear at alternate target locations"
(get-in @state [:t 1 :user]) =fn=> #(contains? % :ui/fetch-state)
(get-in @state [:t 1 :value]) =fn=> #(contains? % :ui/fetch-state))))
(specification "Load markers when loading with an ident"
(let [state (atom {:users/by-id {4 {:name "<NAME>"}}
:t {1 {:id 1}}})
item-2 (dfi/ready-state {:query [{[:users/by-id 3] [:name]}] :target [:t 1 :user]})
item-3 (dfi/ready-state {:query [{[:users/by-id 4] [:name]}]})]
(dfi/place-load-markers state [item-2 item-3])
(assertions
"Ignore explicit targeting"
(get-in @state [:t 1 :user :ui/fetch-state]) => nil
"Only place a marker if there is already an object in the table"
(get-in @state [:users/by-id 3 :ui/fetch-state]) => nil
(get-in @state [:users/by-id 4 :ui/fetch-state]) =fn=> map?)))
(specification "relocating server results"
(behavior "Does nothing if the item is based on a simple query with no targeting"
(let [simple-state-atom (atom {:a [[:x 1]]})
simple-items #{(dfi/ready-state {:query [{:a [:x]}]})}]
(dfi/relocate-targeted-results simple-state-atom simple-items)
(assertions
@simple-state-atom => {:a [[:x 1]]})))
(behavior "Does nothing if the item is a field query"
(let [simple-state-atom (atom {:a [[:x 1]]})
mistargeted-items #{(dfi/ready-state {:ident [:obj 1] :field :boo :query [:boo] :target [:obj 1 :boo]})}]
(dfi/relocate-targeted-results simple-state-atom mistargeted-items)
(assertions
@simple-state-atom => {:a [[:x 1]]})))
(behavior "Moves simple query results to explicit target"
(let [simple-state-atom (atom {:a [[:x 1]]})
maptarget-state-atom (atom {:a [[:x 1]]
:obj {1 {:boo {:n 1}}}})
vectarget-state-atom (atom {:a [[:x 1]]
:obj {1 {:boo []}}})
targeted-items #{(dfi/ready-state {:query [{:a [:x]}] :target [:obj 1 :boo]})}]
(dfi/relocate-targeted-results simple-state-atom targeted-items)
(dfi/relocate-targeted-results maptarget-state-atom targeted-items)
(dfi/relocate-targeted-results vectarget-state-atom targeted-items)
(assertions
@simple-state-atom => {:obj {1 {:boo [[:x 1]]}}}
@maptarget-state-atom => {:obj {1 {:boo [[:x 1]]}}}
@vectarget-state-atom => {:obj {1 {:boo [[:x 1]]}}}))))
(specification "Splits items to load by join key / ident kind."
(let [q-a-x {::dfi/query [{:a [:x]}]}
q-a-y {::dfi/query [{:a [:y]}]}
q-a-z {::dfi/query [{:a [:z]}]}
q-a-w {::dfi/query [{:a [:w]}]}
q-b-x {::dfi/query [{:b [:x]}]}
q-c-x {::dfi/query [{[:c 999] [:x]}]}
q-c-y {::dfi/query [{[:c 999] [:y]}]}
q-c-z {::dfi/query [{[:c 998] [:z]}]}
q-c-w {::dfi/query [{[:c 998] [:w]}]}
q-ab-x {::dfi/query [{:a [:x]} {:b [:x]}]}
q-bc-x {::dfi/query [{:b [:x]} {:c [:x]}]}
q-cd-x {::dfi/query [{:c [:x]} {:d [:x]}]}
q-de-x {::dfi/query [{:d [:x]} {:e [:x]}]}]
(assertions
"loads all items immediately when no join key conflicts, preserving order"
(dfi/split-items-ready-to-load [q-a-x]) => [[q-a-x] []]
(dfi/split-items-ready-to-load [q-a-x q-b-x]) => [[q-a-x q-b-x] []]
(dfi/split-items-ready-to-load [q-a-x q-c-x]) => [[q-a-x q-c-x] []]
(dfi/split-items-ready-to-load [q-a-x q-b-x q-c-x]) => [[q-a-x q-b-x q-c-x] []]
"defers loading when join key conflict, preserving order where possible"
(dfi/split-items-ready-to-load [q-a-x q-a-y q-a-z q-a-w]) => [[q-a-x] [q-a-y q-a-z q-a-w]]
(dfi/split-items-ready-to-load [q-a-y q-a-z q-a-w]) => [[q-a-y] [q-a-z q-a-w]]
(dfi/split-items-ready-to-load [q-a-z q-a-w]) => [[q-a-z] [q-a-w]]
(dfi/split-items-ready-to-load [q-a-w]) => [[q-a-w] []]
"defers loading when ident key conflict, preserving order where possible"
(dfi/split-items-ready-to-load [q-c-x q-c-y q-c-z q-c-w]) => [[q-c-x] [q-c-y q-c-z q-c-w]]
(dfi/split-items-ready-to-load [q-c-y q-c-z q-c-w]) => [[q-c-y] [q-c-z q-c-w]]
(dfi/split-items-ready-to-load [q-c-z q-c-w]) => [[q-c-z] [q-c-w]]
(dfi/split-items-ready-to-load [q-c-w]) => [[q-c-w] []]
"defers loading when any key conflicts, preserving order where possible"
(dfi/split-items-ready-to-load
[q-a-x q-a-y q-a-z
q-b-x
q-c-x q-c-y q-c-z]) => [[q-a-x q-b-x q-c-x] [q-a-y q-a-z q-c-y q-c-z]]
"defers loading when join keys partially conflict, preserving order where possible"
(dfi/split-items-ready-to-load [q-ab-x q-bc-x q-cd-x q-de-x]) => [[q-ab-x q-cd-x] [q-bc-x q-de-x]]
(dfi/split-items-ready-to-load [q-bc-x q-de-x]) => [[q-bc-x q-de-x] []])))
| true | (ns fulcro.client.data-fetch-spec
(:require
[fulcro.client.data-fetch :as df]
[fulcro.client.impl.data-fetch :as dfi]
[fulcro.client.util :as util]
[goog.log :as glog]
[om.next :as om :refer [defui]]
[cljs.test :refer-macros [is are]]
[fulcro-spec.core :refer
[specification behavior assertions provided component when-mocking]]
[fulcro.client.mutations :as m]
[fulcro.client.logging :as log]
[om.next.protocols :as omp]
[fulcro.client.core :as fc]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; SETUP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defui ^:once Person
static om/IQuery (query [_] [:db/id :username :name])
static om/Ident (ident [_ props] [:person/id (:db/id props)]))
(defui ^:once Comment
static om/IQuery (query [this] [:db/id :title {:author (om/get-query Person)}])
static om/Ident (ident [this props] [:comments/id (:db/id props)]))
(defui ^:once Item
static om/IQuery (query [this] [:db/id :name {:comments (om/get-query Comment)}])
static om/Ident (ident [this props] [:items/id (:db/id props)]))
(defui ^:once Panel
static om/IQuery (query [this] [:db/id {:items (om/get-query Item)}])
static om/Ident (ident [this props] [:panel/id (:db/id props)]))
(defui ^:once PanelRoot
static om/IQuery (query [this] [{:panel (om/get-query Panel)}]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; TESTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(specification "Data states"
(behavior "are properly initialized."
(is (df/data-state? (dfi/make-data-state :ready)))
(try (dfi/make-data-state :invalid-key)
(catch :default e
(is (= (.-message e) "INVALID DATA STATE TYPE: :invalid-key")))))
(behavior "can by identified by type."
(is (df/ready? (dfi/make-data-state :ready)))
(is (df/failed? (dfi/make-data-state :failed)))
(is (df/loading? (dfi/make-data-state :loading)))
(is (not (df/ready? (dfi/make-data-state :failed))))
(is (not (df/failed? "foo")))))
(specification "Processed ready states"
(let [make-ready-marker (fn [without-set]
(dfi/ready-state
{:ident [:item/by-id 1]
:field :comments
:without without-set
:query (om/focus-query (om/get-query Item) [:comments])}))
without-join (make-ready-marker #{:author})
without-prop (make-ready-marker #{:username})
without-multi-prop (make-ready-marker #{:db/id})]
(assertions
"remove the :without portion of the query on joins"
(dfi/data-query without-join) => [{[:item/by-id 1] [{:comments [:db/id :title]}]}]
"remove the :without portion of the query on props"
(dfi/data-query without-prop) => [{[:item/by-id 1] [{:comments [:db/id :title {:author [:db/id :name]}]}]}]
"remove the :without portion when keyword appears in multiple places in the query"
(dfi/data-query without-multi-prop) => [{[:item/by-id 1] [{:comments [:title {:author [:username :name]}]}]}]))
(behavior "can elide top-level keys from the query"
(let [ready-state (dfi/ready-state {:query (om/get-query Item) :without #{:name}})]
(is (= [:db/id {:comments [:db/id :title {:author [:db/id :username]}]}] (::dfi/query ready-state)))))
(behavior "can include parameters when eliding top-level keys from the query"
(let [ready-state (dfi/ready-state {:query (om/get-query Item) :without #{:name} :params {:db/id {:x 1}}})]
(is (= '[(:db/id {:x 1}) {:comments [:db/id :title {:author [:db/id :username]}]}] (::dfi/query ready-state)))))
(behavior "can elide keywords from a union query"
(assertions
(om/ast->query
(dfi/elide-ast-nodes
(om/query->ast [{:current-tab {:panel [:data] :console [:data] :dashboard [:data]}}])
#{:console}))
=> [{:current-tab {:panel [:data] :dashboard [:data]}}])))
(specification "Load parameters"
(let [query-with-params (:query (df/load-params* :prop Person {:params {:n 1}}))
ident-query-with-params (:query (df/load-params* [:person/by-id 1] Person {:params {:n 1}}))]
(assertions
"Always include a vector for refresh"
(df/load-params* :prop Person {}) =fn=> #(vector? (:refresh %))
(df/load-params* [:person/by-id 1] Person {}) =fn=> #(vector? (:refresh %))
"Accepts nil for subquery and params"
(:query (df/load-params* [:person/by-id 1] nil {})) => [[:person/by-id 1]]
"Constructs query with parameters when subquery is nil"
(:query (df/load-params* [:person/by-id 1] nil {:params {:x 1}})) => '[([:person/by-id 1] {:x 1})]
"Constructs a JOIN query (without params)"
(:query (df/load-params* :prop Person {})) => [{:prop (om/get-query Person)}]
(:query (df/load-params* [:person/by-id 1] Person {})) => [{[:person/by-id 1] (om/get-query Person)}]
"Honors target for property-based join"
(:target (df/load-params* :prop Person {:target [:a :b]})) => [:a :b]
"Constructs a JOIN query (with params)"
query-with-params =fn=> (fn [q] (= q `[({:prop ~(om/get-query Person)} {:n 1})]))
ident-query-with-params =fn=> (fn [q] (= q `[({[:person/by-id 1] ~(om/get-query Person)} {:n 1})])))
(provided "uses computed-refresh to augment the refresh list"
(df/computed-refresh explicit k t) =1x=> :computed-refresh
(let [params (df/load-params* :k Person {})]
(assertions
"includes the computed refresh list as refresh"
(:refresh params) => :computed-refresh)))))
(specification "Load auto-refresh"
(component "computed-refresh"
(assertions
"Adds the load-key ident to refresh (as a non-duplicate)"
(#'df/computed-refresh [:a] [:table 1] nil) => [:a [:table 1]]
(#'df/computed-refresh [:a [:table 1]] [:table 1] nil) => [:a [:table 1]]
"Adds the load-key keyword to refresh (non-duplicate, when there is no target)"
(#'df/computed-refresh [:a] :b nil) => [:a :b]
(#'df/computed-refresh [:a :b] :b nil) => [:a :b]
"Adds the target's first two elements as an ident to refresh (when target has 2+ elements)"
(#'df/computed-refresh [:a] :b [:x 3 :boo]) => [:a [:x 3]]
(#'df/computed-refresh [:a] :b [:x 3]) => [:a [:x 3]]
"Adds the target's first element as a kw to refresh (when target has 1 element)"
(#'df/computed-refresh [:a] :b [:x]) => [:a :x])))
(specification "Load mutation expressions"
(let [mutation-expr (df/load-mutation {:refresh [:a :b] :query [:my-query]})
mutation (first mutation-expr)]
(assertions
"are vectors"
mutation-expr =fn=> vector?
"include an fulcro/load with mutation arguments"
mutation =fn=> list?
(first mutation) => 'fulcro/load
"always do a follow-on read for :ui/loading-data"
mutation-expr =fn=> #(some (fn [k] (= k :ui/loading-data)) %)
"include user-driven follow-on-reads"
mutation-expr =fn=> #(some (fn [k] (= k :a)) %)
mutation-expr =fn=> #(some (fn [k] (= k :b)) %))))
(specification "The load function"
(when-mocking
(df/load-params* key query config) => :mutation-args
(df/load-mutation args) => (do
(assertions
"creates mutation arguments"
args => :mutation-args)
:mutation)
(om/transact! c tx) => (do (assertions
"uses the passed component/app in transact!"
c => :component
"uses the mutation created by load-mutation"
tx => :mutation))
(om/component? c) => true
(df/load :component :x Person {})))
(specification "The load-action function"
(let [state-atom (atom {})]
(when-mocking
(df/load-params* key query config) => {:refresh [] :query [:x]}
(df/load-action state-atom :x Person {})
(let [query (-> @state-atom :fulcro/ready-to-load first ::dfi/query)]
(assertions
"State atom ends up with a proper load marker"
query => [:x])))))
(specification "Lazy loading"
(component "Loading a field within a component"
(let [query (om/get-query Item)]
(provided "properly calls transact"
(om/get-ident c) =2x=> [:item/by-id 10]
(om/get-query c) =1x=> query
(om/transact! c tx) =1x=> (let [params (-> tx first second)
follow-on-reads (set (-> tx rest))]
(assertions
"includes :ui/loading-data in the follow-on reads"
(contains? follow-on-reads :ui/loading-data) => true
"includes ident of component in the follow-on reads"
(contains? follow-on-reads [:item/by-id 10]) => true
"does the transact on the component"
c => 'component
"includes the component's ident in the marker."
(:ident params) => [:item/by-id 10]
"focuses the query to the specified field."
(:query params) => [{:comments [:db/id :title {:author [:db/id :username :name]}]}]
"includes the parameters."
(:params params) => {:sort :by-name}
"includes the subquery exclusions."
(:without params) => #{:excluded-attr}
"includes the post-processing callback."
(:post-mutation params) => 'foo
"includes the error fallback"
(:fallback params) => 'bar))
(df/load-field 'component :comments
:without #{:excluded-attr}
:params {:sort :by-name}
:post-mutation 'foo
:fallback 'bar))))
(component "Loading a field from within another mutation"
(let [app-state (atom {})]
(df/load-field-action app-state Item [:item/by-id 3] :comments :without #{:author})
(let [marker (first (get-in @app-state [:fulcro/ready-to-load]))]
(assertions
"places a ready marker in the app state"
marker =fn=> (fn [marker] (df/ready? marker))
"includes the focused query"
(dfi/data-query marker) => [{[:item/by-id 3] [{:comments [:db/id :title]}]}])))))
(specification "full-query"
(let [item-ready-markers [(dfi/ready-state {:ident [:db/id 1] :field :author :query [{:author [:name]}]})
(dfi/ready-state {:ident [:db/id 2] :field :author :query [{:author [:name]}]})]
top-level-markers [(dfi/ready-state {:query [{:questions [:db/id :name]}]})
(dfi/ready-state {:query [{:answers [:db/id :name]}]})]]
(behavior "composes items queries"
(is (= [{[:db/id 1] [{:author [:name]}]} {[:db/id 2] [{:author [:name]}]}] (dfi/full-query item-ready-markers))))
(behavior "composes top-level queries"
(is (= [{:questions [:db/id :name]} {:answers [:db/id :name]}] (dfi/full-query top-level-markers))))))
(specification "data-query-key of a fetch marker's query"
(assertions
"is the first keyword of simple props"
(dfi/data-query-key {::dfi/query [:a :b :c]}) => :a
"is the first keyword the first join"
(dfi/data-query-key {::dfi/query [{:a [:x :y]} :b {:c [:z]}]}) => :a
"tolerates parameters"
(dfi/data-query-key {::dfi/query '[({:a [:x :y]} {:n 1}) :b {:c [:z]}]}) => :a
(dfi/data-query-key {::dfi/query '[(:a {:n 1}) :b {:c [:z]}]}) => :a))
(defn mark-loading-mutate [])
(defn mark-loading-fallback [])
(defmethod m/mutate 'mark-loading-test/callback [e k p] {:action #(mark-loading-mutate)})
(defmethod m/mutate 'mark-loading-test/fallback [_ _ _] {:action #(mark-loading-fallback)})
(specification "The inject-query-params function"
(let [prop-ast (om/query->ast [:a :b :c])
prop-params {:a {:x 1} :c {:y 2}}
join-ast (om/query->ast [:a {:things [:name]}])
join-params {:things {:start 1}}
existing-params-ast (om/query->ast '[(:a {:x 1})])
existing-params-overwrite {:a {:x 2}}]
(assertions
"can add parameters to a top-level query property"
(om/ast->query (dfi/inject-query-params prop-ast prop-params)) => '[(:a {:x 1}) :b (:c {:y 2})]
"can add parameters to a top-level join property"
(om/ast->query (dfi/inject-query-params join-ast join-params)) => '[:a ({:things [:name]} {:start 1})]
"merges new parameters over existing ones"
(om/ast->query (dfi/inject-query-params existing-params-ast existing-params-overwrite)) => '[(:a {:x 2})])
(behavior "Warns about parameters that cannot be joined to the query"
(let [ast (om/query->ast [:a :b])
params {:c {:x 1}}]
(when-mocking
(glog/error obj msg) => (is (= "Error: You attempted to add parameters for #{:c} to top-level key(s) of [:a :b]" msg))
(dfi/inject-query-params ast params)
)))))
(specification "set-global-loading"
(let [loading-state (atom {:ui/loading-data true
:fulcro/loads-in-progress #{1}})
not-loading-state (atom {:ui/loading-data true
:fulcro/loads-in-progress #{}})]
(when-mocking
(om/app-state r) => not-loading-state
(dfi/set-global-loading :reconciler)
(assertions
"clears the marker if nothing is in the loading set"
(-> @not-loading-state :ui/loading-data) => false))
(when-mocking
(om/app-state r) => loading-state
(dfi/set-global-loading :reconciler)
(assertions
"sets the marker if anything is in the loading set"
(-> @loading-state :ui/loading-data) => true))))
(specification "Rendering lazily loaded data"
(let [ready-props {:ui/fetch-state (dfi/make-data-state :ready)}
loading-props (update ready-props :ui/fetch-state dfi/set-loading!)
failed-props (update ready-props :ui/fetch-state dfi/set-failed!)
props {:foo :bar}]
(letfn [(ready-override [_] :ready-override)
(loading-override [_] :loading-override)
(failed-override [_] :failed-override)
(not-present [_] :not-present)
(present [props] (if (nil? props) :baz (:foo props)))]
(assertions
"When props are ready to load, runs ready-render"
(df/lazily-loaded present ready-props :ready-render ready-override) => :ready-override
"When props are loading, runs loading-render"
(df/lazily-loaded present loading-props :loading-render loading-override) => :loading-override
"When loading the props failed, runs failed-render"
(df/lazily-loaded present failed-props :failed-render failed-override) => :failed-override
"When the props are nil and not-present-renderer provided, runs not-present-render"
(df/lazily-loaded present nil :not-present-render not-present) => :not-present
"When the props are nil without a not-present-renderer, runs data-render"
(df/lazily-loaded present nil) => :baz
"When props are loaded, runs data-render."
(df/lazily-loaded present props) => :bar))))
(defmethod m/mutate 'qrp-loaded-callback [{:keys [state]} n p] (swap! state assoc :callback-done true :callback-params p))
(specification "Query response processing (loaded-callback with post mutation)"
(let [item (dfi/set-loading! (dfi/ready-state {:ident [:item 2]
:query [:id :b]
:refresh [:x :y]
:post-mutation 'qrp-loaded-callback
:post-mutation-params {:x 1}}))
state (atom {:fulcro/loads-in-progress #{(dfi/data-uuid item)}
:item {2 {:id :original-data}}})
items [item]
queued (atom [])
rendered (atom false)
merged (atom false)
globally-marked (atom false)
loaded-cb (dfi/loaded-callback :reconciler)
response {:id 2}]
(when-mocking
(om/app-state r) => state
(om/merge! r resp query) => (reset! merged true)
(util/force-render r ks) => (reset! rendered ks)
(dfi/set-global-loading r) => (reset! globally-marked true)
(loaded-cb response items)
(assertions
"Merges response with app state"
@merged => true
"Runs post-mutations"
(:callback-done @state) => true
(:callback-params @state) => {:x 1}
"Triggers a render for :ui/loading-data and any addl keys requested by mutations"
@rendered => [:ui/loading-data :x :y]
"Removes loading markers for results that didn't materialize"
(get-in @state (dfi/data-path item) :fail) => nil
"Updates the global loading marker"
@globally-marked => true))))
(specification "Query response processing (loaded-callback with no post-mutations)"
(let [item (dfi/set-loading! (dfi/ready-state {:ident [:item 2] :query [:id :b] :refresh [:a]}))
state (atom {:fulcro/loads-in-progress #{(dfi/data-uuid item)}
:item {2 {:id :original-data}}})
items [item]
queued (atom [])
rendered (atom false)
merged (atom false)
globally-marked (atom false)
loaded-cb (dfi/loaded-callback :reconciler)
response {:id 2}]
(when-mocking
(om/app-state r) => state
(om/merge! r resp query) => (reset! merged true)
(util/force-render r items) => (reset! queued (set items))
(dfi/set-global-loading r) => (reset! globally-marked true)
(loaded-cb response items)
(assertions
"Merges response with app state"
@merged => true
"Queues the refresh items for refresh"
@queued =fn=> #(contains? % :a)
"Queues the global loading marker for refresh"
@queued =fn=> #(contains? % :ui/loading-data)
"Removes loading markers for results that didn't materialize"
(get-in @state (dfi/data-path item) :fail) => nil
"Updates the global loading marker"
@globally-marked => true))))
(defmethod m/mutate 'qrp-error-fallback [{:keys [state]} n p] (swap! state assoc :fallback-done true))
(specification "Query response processing (error-callback)"
(let [item (dfi/set-loading! (dfi/ready-state {:ident [:item 2] :query [:id :b] :fallback 'qrp-error-fallback :refresh [:x :y]}))
state (atom {:fulcro/loads-in-progress #{(dfi/data-uuid item)}
:item {2 {:id :original-data}}})
items [item]
globally-marked (atom false)
queued (atom [])
rendered (atom false)
error-cb (dfi/error-callback :reconciler)
response {:id 2}]
(when-mocking
(om/app-state r) => state
(dfi/set-global-loading r) => (reset! globally-marked true)
(om/force-root-render! r) => (assertions
"Triggers render at root"
r => :reconciler)
(error-cb response items))
(assertions
"Runs fallbacks"
(:fallback-done @state) => true
"Rewrites load markers as error markers"
(dfi/failed? (get-in @state (conj (dfi/data-path item) :ui/fetch-state) :fail)) => true
"Updates the global loading marker"
@globally-marked => true)))
(specification "fetch marker data-path"
(assertions
"is the field path for a load-field marker"
(dfi/data-path {::dfi/ident [:obj 1] ::dfi/field :f}) => [:obj 1 :f]
"is an ident if the query key is an ident"
(dfi/data-path {::dfi/query [{[:a 1] [:prop]}]}) => [:a 1]
"is the data-query-key by default"
(dfi/data-path {::dfi/query [:obj]}) => [:obj]
"is the explicit target if supplied"
(dfi/data-path {::dfi/target [:a :b]}) => [:a :b]))
(specification "Load markers for field loading"
(let [state (atom {:t {1 {:id 1}
2 {:id 2}}})
item-1 (dfi/ready-state {:query [:comments] :ident [:t 1] :field :comments :target [:top]})
item-2 (dfi/ready-state {:query [:comments] :ident [:t 2] :field :comments :marker false})]
(dfi/place-load-markers state [item-1 item-2])
(assertions
"ignore targeting"
(get-in @state [:top]) => nil
"are placed in app state only when the fetch requests a marker"
(get-in @state [:t 1 :comments]) =fn=> #(contains? % :ui/fetch-state)
(get-in @state [:t 2]) => {:id 2}
"are tracked by UUID in :fulcro/loads-in-progress"
(get @state :fulcro/loads-in-progress) =fn=> #(= 2 (count %)))))
(specification "Load markers for regular (top-level) queries"
(let [state (atom {:users/by-id {4 {:name "PI:NAME:<NAME>END_PI"}}
:t {1 {:id 1}}})
item-1 (dfi/ready-state {:query [{:users [:name]}]})
item-2 (dfi/ready-state {:query [:some-value]})
item-3 (dfi/ready-state {:query [{:users [:name]}] :target [:t 1 :user]})
item-4 (dfi/ready-state {:query [:some-value] :target [:t 1 :value]})]
(dfi/place-load-markers state [item-1 item-2 item-3 item-4])
(assertions
"Default to being placed in app root at the first key of the query"
(get @state :users) =fn=> #(contains? % :ui/fetch-state)
(get @state :some-value) =fn=> #(contains? % :ui/fetch-state)
"Will appear at alternate target locations"
(get-in @state [:t 1 :user]) =fn=> #(contains? % :ui/fetch-state)
(get-in @state [:t 1 :value]) =fn=> #(contains? % :ui/fetch-state))))
(specification "Load markers when loading with an ident"
(let [state (atom {:users/by-id {4 {:name "PI:NAME:<NAME>END_PI"}}
:t {1 {:id 1}}})
item-2 (dfi/ready-state {:query [{[:users/by-id 3] [:name]}] :target [:t 1 :user]})
item-3 (dfi/ready-state {:query [{[:users/by-id 4] [:name]}]})]
(dfi/place-load-markers state [item-2 item-3])
(assertions
"Ignore explicit targeting"
(get-in @state [:t 1 :user :ui/fetch-state]) => nil
"Only place a marker if there is already an object in the table"
(get-in @state [:users/by-id 3 :ui/fetch-state]) => nil
(get-in @state [:users/by-id 4 :ui/fetch-state]) =fn=> map?)))
(specification "relocating server results"
(behavior "Does nothing if the item is based on a simple query with no targeting"
(let [simple-state-atom (atom {:a [[:x 1]]})
simple-items #{(dfi/ready-state {:query [{:a [:x]}]})}]
(dfi/relocate-targeted-results simple-state-atom simple-items)
(assertions
@simple-state-atom => {:a [[:x 1]]})))
(behavior "Does nothing if the item is a field query"
(let [simple-state-atom (atom {:a [[:x 1]]})
mistargeted-items #{(dfi/ready-state {:ident [:obj 1] :field :boo :query [:boo] :target [:obj 1 :boo]})}]
(dfi/relocate-targeted-results simple-state-atom mistargeted-items)
(assertions
@simple-state-atom => {:a [[:x 1]]})))
(behavior "Moves simple query results to explicit target"
(let [simple-state-atom (atom {:a [[:x 1]]})
maptarget-state-atom (atom {:a [[:x 1]]
:obj {1 {:boo {:n 1}}}})
vectarget-state-atom (atom {:a [[:x 1]]
:obj {1 {:boo []}}})
targeted-items #{(dfi/ready-state {:query [{:a [:x]}] :target [:obj 1 :boo]})}]
(dfi/relocate-targeted-results simple-state-atom targeted-items)
(dfi/relocate-targeted-results maptarget-state-atom targeted-items)
(dfi/relocate-targeted-results vectarget-state-atom targeted-items)
(assertions
@simple-state-atom => {:obj {1 {:boo [[:x 1]]}}}
@maptarget-state-atom => {:obj {1 {:boo [[:x 1]]}}}
@vectarget-state-atom => {:obj {1 {:boo [[:x 1]]}}}))))
(specification "Splits items to load by join key / ident kind."
(let [q-a-x {::dfi/query [{:a [:x]}]}
q-a-y {::dfi/query [{:a [:y]}]}
q-a-z {::dfi/query [{:a [:z]}]}
q-a-w {::dfi/query [{:a [:w]}]}
q-b-x {::dfi/query [{:b [:x]}]}
q-c-x {::dfi/query [{[:c 999] [:x]}]}
q-c-y {::dfi/query [{[:c 999] [:y]}]}
q-c-z {::dfi/query [{[:c 998] [:z]}]}
q-c-w {::dfi/query [{[:c 998] [:w]}]}
q-ab-x {::dfi/query [{:a [:x]} {:b [:x]}]}
q-bc-x {::dfi/query [{:b [:x]} {:c [:x]}]}
q-cd-x {::dfi/query [{:c [:x]} {:d [:x]}]}
q-de-x {::dfi/query [{:d [:x]} {:e [:x]}]}]
(assertions
"loads all items immediately when no join key conflicts, preserving order"
(dfi/split-items-ready-to-load [q-a-x]) => [[q-a-x] []]
(dfi/split-items-ready-to-load [q-a-x q-b-x]) => [[q-a-x q-b-x] []]
(dfi/split-items-ready-to-load [q-a-x q-c-x]) => [[q-a-x q-c-x] []]
(dfi/split-items-ready-to-load [q-a-x q-b-x q-c-x]) => [[q-a-x q-b-x q-c-x] []]
"defers loading when join key conflict, preserving order where possible"
(dfi/split-items-ready-to-load [q-a-x q-a-y q-a-z q-a-w]) => [[q-a-x] [q-a-y q-a-z q-a-w]]
(dfi/split-items-ready-to-load [q-a-y q-a-z q-a-w]) => [[q-a-y] [q-a-z q-a-w]]
(dfi/split-items-ready-to-load [q-a-z q-a-w]) => [[q-a-z] [q-a-w]]
(dfi/split-items-ready-to-load [q-a-w]) => [[q-a-w] []]
"defers loading when ident key conflict, preserving order where possible"
(dfi/split-items-ready-to-load [q-c-x q-c-y q-c-z q-c-w]) => [[q-c-x] [q-c-y q-c-z q-c-w]]
(dfi/split-items-ready-to-load [q-c-y q-c-z q-c-w]) => [[q-c-y] [q-c-z q-c-w]]
(dfi/split-items-ready-to-load [q-c-z q-c-w]) => [[q-c-z] [q-c-w]]
(dfi/split-items-ready-to-load [q-c-w]) => [[q-c-w] []]
"defers loading when any key conflicts, preserving order where possible"
(dfi/split-items-ready-to-load
[q-a-x q-a-y q-a-z
q-b-x
q-c-x q-c-y q-c-z]) => [[q-a-x q-b-x q-c-x] [q-a-y q-a-z q-c-y q-c-z]]
"defers loading when join keys partially conflict, preserving order where possible"
(dfi/split-items-ready-to-load [q-ab-x q-bc-x q-cd-x q-de-x]) => [[q-ab-x q-cd-x] [q-bc-x q-de-x]]
(dfi/split-items-ready-to-load [q-bc-x q-de-x]) => [[q-bc-x q-de-x] []])))
|
[
{
"context": " for multiple dispatch alternatives.\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2017-12-15\"}\n \n (:require [palisa",
"end": 287,
"score": 0.7936733365058899,
"start": 251,
"tag": "EMAIL",
"value": "palisades dot lakes at gmail dot com"
}
] | src/scripts/clojure/palisades/lakes/collex/scripts/defs.clj | palisades-lakes/collection-experiments | 0 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.collex.scripts.defs
{:doc "Benchmarks for multiple dispatch alternatives."
:author "palisades dot lakes at gmail dot com"
:version "2017-12-15"}
(:require [palisades.lakes.bench.prng :as prng]
[palisades.lakes.fm.iterator :as iterator]
[palisades.lakes.collex.arrays :as arrays]
[palisades.lakes.collex.transduce :as tr]))
;;----------------------------------------------------------------
;; element generators
;;----------------------------------------------------------------
(let [urp (prng/uniform-random-provider
"seeds/Well44497b-2017-07-25.edn")
umin -1024
umax 1024
uint0 (prng/uniform-int umin umax urp)
ufloat0 (prng/uniform-float (float umin) (float umax) urp)]
(defn uint ^Integer [] (Integer/valueOf (int (uint0))))
(defn ufloat ^Float [] (Float/valueOf (float (ufloat0)))))
;;----------------------------------------------------------------
;; reducers
;;----------------------------------------------------------------
;; sum the squares of the even values
;; idiomatic clojure here, not faster accumulators (yet)
(defn- sq ^long [^long i] (* i i))
(defn- non-negative? [^long i] (<= (long 0) i))
(def composed (tr/composed + sq non-negative?))
(def reduce-map-filter (tr/reduce-map-filter + sq non-negative?))
(def transducer (tr/transducer + sq non-negative?))
(def manual (tr/manual + sq non-negative?))
;;----------------------------------------------------------------
| 107556 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.collex.scripts.defs
{:doc "Benchmarks for multiple dispatch alternatives."
:author "<EMAIL>"
:version "2017-12-15"}
(:require [palisades.lakes.bench.prng :as prng]
[palisades.lakes.fm.iterator :as iterator]
[palisades.lakes.collex.arrays :as arrays]
[palisades.lakes.collex.transduce :as tr]))
;;----------------------------------------------------------------
;; element generators
;;----------------------------------------------------------------
(let [urp (prng/uniform-random-provider
"seeds/Well44497b-2017-07-25.edn")
umin -1024
umax 1024
uint0 (prng/uniform-int umin umax urp)
ufloat0 (prng/uniform-float (float umin) (float umax) urp)]
(defn uint ^Integer [] (Integer/valueOf (int (uint0))))
(defn ufloat ^Float [] (Float/valueOf (float (ufloat0)))))
;;----------------------------------------------------------------
;; reducers
;;----------------------------------------------------------------
;; sum the squares of the even values
;; idiomatic clojure here, not faster accumulators (yet)
(defn- sq ^long [^long i] (* i i))
(defn- non-negative? [^long i] (<= (long 0) i))
(def composed (tr/composed + sq non-negative?))
(def reduce-map-filter (tr/reduce-map-filter + sq non-negative?))
(def transducer (tr/transducer + sq non-negative?))
(def manual (tr/manual + sq non-negative?))
;;----------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.collex.scripts.defs
{:doc "Benchmarks for multiple dispatch alternatives."
:author "PI:EMAIL:<EMAIL>END_PI"
:version "2017-12-15"}
(:require [palisades.lakes.bench.prng :as prng]
[palisades.lakes.fm.iterator :as iterator]
[palisades.lakes.collex.arrays :as arrays]
[palisades.lakes.collex.transduce :as tr]))
;;----------------------------------------------------------------
;; element generators
;;----------------------------------------------------------------
(let [urp (prng/uniform-random-provider
"seeds/Well44497b-2017-07-25.edn")
umin -1024
umax 1024
uint0 (prng/uniform-int umin umax urp)
ufloat0 (prng/uniform-float (float umin) (float umax) urp)]
(defn uint ^Integer [] (Integer/valueOf (int (uint0))))
(defn ufloat ^Float [] (Float/valueOf (float (ufloat0)))))
;;----------------------------------------------------------------
;; reducers
;;----------------------------------------------------------------
;; sum the squares of the even values
;; idiomatic clojure here, not faster accumulators (yet)
(defn- sq ^long [^long i] (* i i))
(defn- non-negative? [^long i] (<= (long 0) i))
(def composed (tr/composed + sq non-negative?))
(def reduce-map-filter (tr/reduce-map-filter + sq non-negative?))
(def transducer (tr/transducer + sq non-negative?))
(def manual (tr/manual + sq non-negative?))
;;----------------------------------------------------------------
|
[
{
"context": "re :as r]\n ))\n\n(defonce r-node-address (r/atom \"3.80.184.123:26657\"))\n(defonce r-node-status (r/atom {}))\n\n(de",
"end": 344,
"score": 0.9997124075889587,
"start": 332,
"tag": "IP_ADDRESS",
"value": "3.80.184.123"
}
] | src/tenderflow/core.cljs | kevlubkcm/tenderflow | 6 | (ns ^:figwheel-hooks tenderflow.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require
[goog.dom :as gdom]
[cljsjs.d3]
[cljs-http.client :as http]
[cljs.core.async :refer [<!]]
[wscljs.client :as ws]
[wscljs.format :as fmt]
[reagent.core :as r]
))
(defonce r-node-address (r/atom "3.80.184.123:26657"))
(defonce r-node-status (r/atom {}))
(defonce app-state (atom {}))
(defonce websocket (atom nil))
(defn atom-input [value]
[:input {:type "text"
:value @value
:on-change #(reset! value (-> % .-target .-value))}])
(defn parse-consensus-dump [msg]
(let [s (get-in msg [:result :round_state])
{:keys [height round step]} s
val-info (:validators s)
validators (map #(select-keys % [:address :voting_power]) (:validators val-info))]
{:height height
:first-height height
:round round
:step step
:validators validators}))
(defn get-consensus-dump
[node-address]
(go (let [url (str "http://" node-address "/dump_consensus_state")
resp (<! (http/get url {:with-credentials? false}))
d (parse-consensus-dump (:body resp))]
(reset! app-state d))))
(defn get-node-status
[node-address]
(go (let [url (str "http://" node-address "/status")
resp (<! (http/get url {:with-credentials? false}))
info (get-in resp [:body :result :node_info])
{:keys [id network moniker]} info]
(reset! r-node-status {:id id :network network :moniker moniker}))))
(defn get-app-element []
(gdom/getElement "app"))
(defn append-svg [div-id height width]
(-> js/d3
(.select div-id)
(.append "svg")
(.attr "height" height)
(.attr "width" width)))
(defn compute-locations
[[x y] n r]
(vec (for [i (range n)
:let [o (* (/ i n) 2 Math/PI)]]
[(+ x (* r (Math/cos o)))
(+ y (* r (Math/sin o)))])))
(def val-radius 300)
(def vote-radius 20)
(def center [500 500])
(def blocks-max 10)
(def blocks-head [900 700])
(def block-space 50)
(def vote-styles
{:proposal [30 "red"]
:pre-vote [3 "blue"]
:pre-commit [2 "green"]})
(defn block-locations
[head spacing n]
(let [[x head-y] head
dys (range n)
dys (map #(* % spacing) dys)]
(map #(vector x (- head-y %)) dys)))
(defn draw-blockchain
[svg heights [prop-x prop-y]]
(let [locs (block-locations blocks-head block-space (count heights))
data (into-array (map vector heights locs))
[r _] (:proposal vote-styles)
s (/ r 2)
fill "green"
svg (-> svg
(.selectAll "rect")
(.data data (fn [[h _]] h)))]
(-> svg
(.enter)
(.append "rect")
(.attr "x" (- prop-x s))
(.attr "y" (- prop-y s))
(.attr "width" r)
(.attr "height" r)
(.attr "fill" fill)
(.transition)
(.attr "x" (fn [[_ [x _]]] x))
(.attr "y" (fn [[_ [_ y]]] y)))
(-> svg
(.transition)
(.attr "x" (fn [[_ [x _]]] x))
(.attr "y" (fn [[_ [_ y]]] y)))
(-> svg
(.exit)
(.remove))))
(defn draw-validators
[svg-base validators proposer-idx locs]
(let [zipped (map vector validators locs)
data (into-array zipped)
attrs (fn [s]
(-> s
(.attr "r" 10)
(.attr "cx" (fn [[_ [x _]]] x))
(.attr "cy" (fn [[_ [_ y]]] y))
(.attr "fill" (fn [_ i] (if (= i proposer-idx) "green" "red")))))
svg (-> svg-base
(.selectAll "circle")
(.data data (fn [[v _]] (:address v))))]
(-> svg
(.exit)
(.remove))
(-> svg
(.enter)
(.append "circle")
(attrs)
(.on "mouseover"
(fn [[d [x y]]]
(-> svg-base
(.append "text")
(.attr "id" (str "t-" (:address d)))
(.attr "x" x)
(.attr "y" y)
(.text (:address d)))))
(.on "mouseout"
(fn [[d _]]
(-> svg-base
(.select (str "#t-" (:address d)))
(.remove)))))
(-> svg
(.transition)
(attrs))))
(defn draw-proposal
[svg prop height round idx locs [vote-x vote-y]]
(let [[val-x val-y] (nth locs idx)
[r fill] (:proposal vote-styles)
s (/ r 2)
data (if (nil? prop) [] [(str height "#" round)])
data (into-array data)
svg (-> svg
(.selectAll "rect")
(.data data (fn [h] h)))]
(-> svg
(.enter)
(.append "rect")
(.attr "x" (- val-x s))
(.attr "y" (- val-y s))
(.attr "width" r)
(.attr "height" r)
(.attr "fill" fill)
(.transition)
(.attr "x" (- vote-x s))
(.attr "y" (- vote-y s)))
(-> svg
(.exit)
(.remove))))
(defn vote-id
[idx height vote-type]
(str height "#" idx "#" vote-type))
(defn draw-votes
[svg pre-votes pre-commits val-locs vote-locs height]
(let [locs (vec (map vector val-locs vote-locs))
pre-votes (for [i pre-votes] [(vote-id i height 0) (locs i) (:pre-vote vote-styles)])
pre-commits (for [i pre-commits] [(vote-id i height 1) (locs i) (:pre-commit vote-styles)])
data (into-array (concat pre-votes pre-commits))
svg (-> svg
(.selectAll "circle")
(.data data (fn [[d _ _]] d)))]
(-> svg
(.enter)
(.append "circle")
(.attr "cx" (fn [[_ [[x _] _] _]] x))
(.attr "cy" (fn [[_ [[_ y] _] _]] y))
(.attr "r" (fn [[_ _ [r _]]] r))
(.attr "fill" (fn [[_ _ [_ f]]] f))
(.transition)
(.attr "cx" (fn [[_ [_ [x _]] _]] x))
(.attr "cy" (fn [[_ [_ [_ y]] _]] y)))
(-> svg
(.exit)
(.remove))))
(defn update-graphics
[svg-groups _ _ _ new-state]
(let [current-validators (:validators new-state)
n (count current-validators)
proposer-idx (:proposer-idx new-state)
val-locs (compute-locations center n val-radius)
vote-locs (compute-locations center n vote-radius)
{:keys [height round step pre-votes pre-commits proposal first-height]} new-state
complete-blocks (take blocks-max (range height first-height -1))]
(draw-validators (:validators svg-groups) current-validators proposer-idx val-locs)
(draw-blockchain (:blockchain svg-groups) complete-blocks center)
(if (some? proposer-idx)
(draw-proposal (:proposal svg-groups) proposal height round proposer-idx val-locs center))
(draw-votes (:votes svg-groups) pre-votes pre-commits val-locs vote-locs height)))
(defn subscribe-msg
[id evt]
{:jsonrpc "2.0"
:method "subscribe"
:id id
:params {:query (str "tm.event='" evt "'")}})
(defn subscribe
[socket id evt]
(let [msg (subscribe-msg id evt)]
(prn (str "Subscribing: " msg))
(ws/send socket msg fmt/json)))
(defn subscribe-all
[socket]
(subscribe socket "0" "CompleteProposal")
(subscribe socket "1" "Vote")
(subscribe socket "2" "NewRound")
(subscribe socket "3" "ValidatorSetUpdates"))
(defn handle-new-round
[d]
(let [{:keys [height round step]} d
proposer-idx (get-in d [:proposer :index])
proposer-idx (js/parseInt proposer-idx)
height (js/parseInt height)
round (js/parseInt round)]
(swap! app-state assoc
:height height
:round round
:step step
:proposer-idx proposer-idx
:proposal nil
:pre-votes []
:pre-commits [])))
(defn handle-complete-proposal
[d]
(let [proposal (get-in d [:block_id :hash])]
; TODO: check that height and round match
(swap! app-state assoc :proposal proposal)))
(def vote-type-map
{1 :pre-votes
2 :pre-commits})
(defn add-vote
[state vote-type idx]
(let [old-votes (vote-type state)
new-votes (conj old-votes idx)]
(assoc state vote-type new-votes)))
(defn handle-vote
[d]
(let [d (:Vote d)
idx (:validator_index d)
idx (js/parseInt idx)
vote-type (get vote-type-map (:type d))]
(swap! app-state #(add-vote % vote-type idx))))
(defn handle-validator-set-updates
[d]
(prn d))
(def event-handlers
{"tendermint/event/NewRound" handle-new-round
"tendermint/event/CompleteProposal" handle-complete-proposal
"tendermint/event/Vote" handle-vote
"tendermint/event/ValidatorSetUpdates" handle-validator-set-updates})
(defn handle-message
[e]
(let [data (.-data e)
data (.parse js/JSON data)
data (js->clj data :keywordize-keys true)
data (get-in data [:result :data])
event-type (:type data)
handler (get event-handlers event-type)
data (:value data)]
(if (some? event-type)
(handler data))))
(def handlers {:on-message handle-message
:on-open #(subscribe-all @websocket)
:on-close #(reset! websocket nil)})
(defn connect-to-websocket
[host]
(reset! websocket (ws/create (str "ws://" host "/websocket") handlers)))
(defn connect-to-node
[node-address]
(get-node-status node-address)
(get-consensus-dump node-address)
(connect-to-websocket node-address))
(defn connect-to-node-component []
[:div
"Node Address: " [atom-input r-node-address]
[:input {:type "button" :value "Connect" :on-click #(connect-to-node @r-node-address)}]])
(defn node-info-component []
(let [info @r-node-status]
(if-not (empty? info)
(let [address @r-node-address
{:keys [id network moniker]} info]
[:div (str "Connected to Network: " network " via " moniker " (" id "@" address ")")])
[:div (str "Not connected")])))
(defn header []
[:div
[connect-to-node-component]
[node-info-component]])
(defn ^:export main []
(let [svg-main (append-svg "#app" 1000 1500)
svg-groups {:proposal (.append svg-main "g")
:votes (.append svg-main "g")
:blockchain (.append svg-main "g")
:validators (.append svg-main "g")}
]
(add-watch app-state :state-update (partial update-graphics svg-groups))
(r/render [header] (js/document.getElementById "header"))
))
(defn ^:after-load on-reload []
;; (swap! app-state update-in [:__figwheel_counter] inc)
)
| 76261 | (ns ^:figwheel-hooks tenderflow.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require
[goog.dom :as gdom]
[cljsjs.d3]
[cljs-http.client :as http]
[cljs.core.async :refer [<!]]
[wscljs.client :as ws]
[wscljs.format :as fmt]
[reagent.core :as r]
))
(defonce r-node-address (r/atom "172.16.17.32:26657"))
(defonce r-node-status (r/atom {}))
(defonce app-state (atom {}))
(defonce websocket (atom nil))
(defn atom-input [value]
[:input {:type "text"
:value @value
:on-change #(reset! value (-> % .-target .-value))}])
(defn parse-consensus-dump [msg]
(let [s (get-in msg [:result :round_state])
{:keys [height round step]} s
val-info (:validators s)
validators (map #(select-keys % [:address :voting_power]) (:validators val-info))]
{:height height
:first-height height
:round round
:step step
:validators validators}))
(defn get-consensus-dump
[node-address]
(go (let [url (str "http://" node-address "/dump_consensus_state")
resp (<! (http/get url {:with-credentials? false}))
d (parse-consensus-dump (:body resp))]
(reset! app-state d))))
(defn get-node-status
[node-address]
(go (let [url (str "http://" node-address "/status")
resp (<! (http/get url {:with-credentials? false}))
info (get-in resp [:body :result :node_info])
{:keys [id network moniker]} info]
(reset! r-node-status {:id id :network network :moniker moniker}))))
(defn get-app-element []
(gdom/getElement "app"))
(defn append-svg [div-id height width]
(-> js/d3
(.select div-id)
(.append "svg")
(.attr "height" height)
(.attr "width" width)))
(defn compute-locations
[[x y] n r]
(vec (for [i (range n)
:let [o (* (/ i n) 2 Math/PI)]]
[(+ x (* r (Math/cos o)))
(+ y (* r (Math/sin o)))])))
(def val-radius 300)
(def vote-radius 20)
(def center [500 500])
(def blocks-max 10)
(def blocks-head [900 700])
(def block-space 50)
(def vote-styles
{:proposal [30 "red"]
:pre-vote [3 "blue"]
:pre-commit [2 "green"]})
(defn block-locations
[head spacing n]
(let [[x head-y] head
dys (range n)
dys (map #(* % spacing) dys)]
(map #(vector x (- head-y %)) dys)))
(defn draw-blockchain
[svg heights [prop-x prop-y]]
(let [locs (block-locations blocks-head block-space (count heights))
data (into-array (map vector heights locs))
[r _] (:proposal vote-styles)
s (/ r 2)
fill "green"
svg (-> svg
(.selectAll "rect")
(.data data (fn [[h _]] h)))]
(-> svg
(.enter)
(.append "rect")
(.attr "x" (- prop-x s))
(.attr "y" (- prop-y s))
(.attr "width" r)
(.attr "height" r)
(.attr "fill" fill)
(.transition)
(.attr "x" (fn [[_ [x _]]] x))
(.attr "y" (fn [[_ [_ y]]] y)))
(-> svg
(.transition)
(.attr "x" (fn [[_ [x _]]] x))
(.attr "y" (fn [[_ [_ y]]] y)))
(-> svg
(.exit)
(.remove))))
(defn draw-validators
[svg-base validators proposer-idx locs]
(let [zipped (map vector validators locs)
data (into-array zipped)
attrs (fn [s]
(-> s
(.attr "r" 10)
(.attr "cx" (fn [[_ [x _]]] x))
(.attr "cy" (fn [[_ [_ y]]] y))
(.attr "fill" (fn [_ i] (if (= i proposer-idx) "green" "red")))))
svg (-> svg-base
(.selectAll "circle")
(.data data (fn [[v _]] (:address v))))]
(-> svg
(.exit)
(.remove))
(-> svg
(.enter)
(.append "circle")
(attrs)
(.on "mouseover"
(fn [[d [x y]]]
(-> svg-base
(.append "text")
(.attr "id" (str "t-" (:address d)))
(.attr "x" x)
(.attr "y" y)
(.text (:address d)))))
(.on "mouseout"
(fn [[d _]]
(-> svg-base
(.select (str "#t-" (:address d)))
(.remove)))))
(-> svg
(.transition)
(attrs))))
(defn draw-proposal
[svg prop height round idx locs [vote-x vote-y]]
(let [[val-x val-y] (nth locs idx)
[r fill] (:proposal vote-styles)
s (/ r 2)
data (if (nil? prop) [] [(str height "#" round)])
data (into-array data)
svg (-> svg
(.selectAll "rect")
(.data data (fn [h] h)))]
(-> svg
(.enter)
(.append "rect")
(.attr "x" (- val-x s))
(.attr "y" (- val-y s))
(.attr "width" r)
(.attr "height" r)
(.attr "fill" fill)
(.transition)
(.attr "x" (- vote-x s))
(.attr "y" (- vote-y s)))
(-> svg
(.exit)
(.remove))))
(defn vote-id
[idx height vote-type]
(str height "#" idx "#" vote-type))
(defn draw-votes
[svg pre-votes pre-commits val-locs vote-locs height]
(let [locs (vec (map vector val-locs vote-locs))
pre-votes (for [i pre-votes] [(vote-id i height 0) (locs i) (:pre-vote vote-styles)])
pre-commits (for [i pre-commits] [(vote-id i height 1) (locs i) (:pre-commit vote-styles)])
data (into-array (concat pre-votes pre-commits))
svg (-> svg
(.selectAll "circle")
(.data data (fn [[d _ _]] d)))]
(-> svg
(.enter)
(.append "circle")
(.attr "cx" (fn [[_ [[x _] _] _]] x))
(.attr "cy" (fn [[_ [[_ y] _] _]] y))
(.attr "r" (fn [[_ _ [r _]]] r))
(.attr "fill" (fn [[_ _ [_ f]]] f))
(.transition)
(.attr "cx" (fn [[_ [_ [x _]] _]] x))
(.attr "cy" (fn [[_ [_ [_ y]] _]] y)))
(-> svg
(.exit)
(.remove))))
(defn update-graphics
[svg-groups _ _ _ new-state]
(let [current-validators (:validators new-state)
n (count current-validators)
proposer-idx (:proposer-idx new-state)
val-locs (compute-locations center n val-radius)
vote-locs (compute-locations center n vote-radius)
{:keys [height round step pre-votes pre-commits proposal first-height]} new-state
complete-blocks (take blocks-max (range height first-height -1))]
(draw-validators (:validators svg-groups) current-validators proposer-idx val-locs)
(draw-blockchain (:blockchain svg-groups) complete-blocks center)
(if (some? proposer-idx)
(draw-proposal (:proposal svg-groups) proposal height round proposer-idx val-locs center))
(draw-votes (:votes svg-groups) pre-votes pre-commits val-locs vote-locs height)))
(defn subscribe-msg
[id evt]
{:jsonrpc "2.0"
:method "subscribe"
:id id
:params {:query (str "tm.event='" evt "'")}})
(defn subscribe
[socket id evt]
(let [msg (subscribe-msg id evt)]
(prn (str "Subscribing: " msg))
(ws/send socket msg fmt/json)))
(defn subscribe-all
[socket]
(subscribe socket "0" "CompleteProposal")
(subscribe socket "1" "Vote")
(subscribe socket "2" "NewRound")
(subscribe socket "3" "ValidatorSetUpdates"))
(defn handle-new-round
[d]
(let [{:keys [height round step]} d
proposer-idx (get-in d [:proposer :index])
proposer-idx (js/parseInt proposer-idx)
height (js/parseInt height)
round (js/parseInt round)]
(swap! app-state assoc
:height height
:round round
:step step
:proposer-idx proposer-idx
:proposal nil
:pre-votes []
:pre-commits [])))
(defn handle-complete-proposal
[d]
(let [proposal (get-in d [:block_id :hash])]
; TODO: check that height and round match
(swap! app-state assoc :proposal proposal)))
(def vote-type-map
{1 :pre-votes
2 :pre-commits})
(defn add-vote
[state vote-type idx]
(let [old-votes (vote-type state)
new-votes (conj old-votes idx)]
(assoc state vote-type new-votes)))
(defn handle-vote
[d]
(let [d (:Vote d)
idx (:validator_index d)
idx (js/parseInt idx)
vote-type (get vote-type-map (:type d))]
(swap! app-state #(add-vote % vote-type idx))))
(defn handle-validator-set-updates
[d]
(prn d))
(def event-handlers
{"tendermint/event/NewRound" handle-new-round
"tendermint/event/CompleteProposal" handle-complete-proposal
"tendermint/event/Vote" handle-vote
"tendermint/event/ValidatorSetUpdates" handle-validator-set-updates})
(defn handle-message
[e]
(let [data (.-data e)
data (.parse js/JSON data)
data (js->clj data :keywordize-keys true)
data (get-in data [:result :data])
event-type (:type data)
handler (get event-handlers event-type)
data (:value data)]
(if (some? event-type)
(handler data))))
(def handlers {:on-message handle-message
:on-open #(subscribe-all @websocket)
:on-close #(reset! websocket nil)})
(defn connect-to-websocket
[host]
(reset! websocket (ws/create (str "ws://" host "/websocket") handlers)))
(defn connect-to-node
[node-address]
(get-node-status node-address)
(get-consensus-dump node-address)
(connect-to-websocket node-address))
(defn connect-to-node-component []
[:div
"Node Address: " [atom-input r-node-address]
[:input {:type "button" :value "Connect" :on-click #(connect-to-node @r-node-address)}]])
(defn node-info-component []
(let [info @r-node-status]
(if-not (empty? info)
(let [address @r-node-address
{:keys [id network moniker]} info]
[:div (str "Connected to Network: " network " via " moniker " (" id "@" address ")")])
[:div (str "Not connected")])))
(defn header []
[:div
[connect-to-node-component]
[node-info-component]])
(defn ^:export main []
(let [svg-main (append-svg "#app" 1000 1500)
svg-groups {:proposal (.append svg-main "g")
:votes (.append svg-main "g")
:blockchain (.append svg-main "g")
:validators (.append svg-main "g")}
]
(add-watch app-state :state-update (partial update-graphics svg-groups))
(r/render [header] (js/document.getElementById "header"))
))
(defn ^:after-load on-reload []
;; (swap! app-state update-in [:__figwheel_counter] inc)
)
| true | (ns ^:figwheel-hooks tenderflow.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require
[goog.dom :as gdom]
[cljsjs.d3]
[cljs-http.client :as http]
[cljs.core.async :refer [<!]]
[wscljs.client :as ws]
[wscljs.format :as fmt]
[reagent.core :as r]
))
(defonce r-node-address (r/atom "PI:IP_ADDRESS:172.16.17.32END_PI:26657"))
(defonce r-node-status (r/atom {}))
(defonce app-state (atom {}))
(defonce websocket (atom nil))
(defn atom-input [value]
[:input {:type "text"
:value @value
:on-change #(reset! value (-> % .-target .-value))}])
(defn parse-consensus-dump [msg]
(let [s (get-in msg [:result :round_state])
{:keys [height round step]} s
val-info (:validators s)
validators (map #(select-keys % [:address :voting_power]) (:validators val-info))]
{:height height
:first-height height
:round round
:step step
:validators validators}))
(defn get-consensus-dump
[node-address]
(go (let [url (str "http://" node-address "/dump_consensus_state")
resp (<! (http/get url {:with-credentials? false}))
d (parse-consensus-dump (:body resp))]
(reset! app-state d))))
(defn get-node-status
[node-address]
(go (let [url (str "http://" node-address "/status")
resp (<! (http/get url {:with-credentials? false}))
info (get-in resp [:body :result :node_info])
{:keys [id network moniker]} info]
(reset! r-node-status {:id id :network network :moniker moniker}))))
(defn get-app-element []
(gdom/getElement "app"))
(defn append-svg [div-id height width]
(-> js/d3
(.select div-id)
(.append "svg")
(.attr "height" height)
(.attr "width" width)))
(defn compute-locations
[[x y] n r]
(vec (for [i (range n)
:let [o (* (/ i n) 2 Math/PI)]]
[(+ x (* r (Math/cos o)))
(+ y (* r (Math/sin o)))])))
(def val-radius 300)
(def vote-radius 20)
(def center [500 500])
(def blocks-max 10)
(def blocks-head [900 700])
(def block-space 50)
(def vote-styles
{:proposal [30 "red"]
:pre-vote [3 "blue"]
:pre-commit [2 "green"]})
(defn block-locations
[head spacing n]
(let [[x head-y] head
dys (range n)
dys (map #(* % spacing) dys)]
(map #(vector x (- head-y %)) dys)))
(defn draw-blockchain
[svg heights [prop-x prop-y]]
(let [locs (block-locations blocks-head block-space (count heights))
data (into-array (map vector heights locs))
[r _] (:proposal vote-styles)
s (/ r 2)
fill "green"
svg (-> svg
(.selectAll "rect")
(.data data (fn [[h _]] h)))]
(-> svg
(.enter)
(.append "rect")
(.attr "x" (- prop-x s))
(.attr "y" (- prop-y s))
(.attr "width" r)
(.attr "height" r)
(.attr "fill" fill)
(.transition)
(.attr "x" (fn [[_ [x _]]] x))
(.attr "y" (fn [[_ [_ y]]] y)))
(-> svg
(.transition)
(.attr "x" (fn [[_ [x _]]] x))
(.attr "y" (fn [[_ [_ y]]] y)))
(-> svg
(.exit)
(.remove))))
(defn draw-validators
[svg-base validators proposer-idx locs]
(let [zipped (map vector validators locs)
data (into-array zipped)
attrs (fn [s]
(-> s
(.attr "r" 10)
(.attr "cx" (fn [[_ [x _]]] x))
(.attr "cy" (fn [[_ [_ y]]] y))
(.attr "fill" (fn [_ i] (if (= i proposer-idx) "green" "red")))))
svg (-> svg-base
(.selectAll "circle")
(.data data (fn [[v _]] (:address v))))]
(-> svg
(.exit)
(.remove))
(-> svg
(.enter)
(.append "circle")
(attrs)
(.on "mouseover"
(fn [[d [x y]]]
(-> svg-base
(.append "text")
(.attr "id" (str "t-" (:address d)))
(.attr "x" x)
(.attr "y" y)
(.text (:address d)))))
(.on "mouseout"
(fn [[d _]]
(-> svg-base
(.select (str "#t-" (:address d)))
(.remove)))))
(-> svg
(.transition)
(attrs))))
(defn draw-proposal
[svg prop height round idx locs [vote-x vote-y]]
(let [[val-x val-y] (nth locs idx)
[r fill] (:proposal vote-styles)
s (/ r 2)
data (if (nil? prop) [] [(str height "#" round)])
data (into-array data)
svg (-> svg
(.selectAll "rect")
(.data data (fn [h] h)))]
(-> svg
(.enter)
(.append "rect")
(.attr "x" (- val-x s))
(.attr "y" (- val-y s))
(.attr "width" r)
(.attr "height" r)
(.attr "fill" fill)
(.transition)
(.attr "x" (- vote-x s))
(.attr "y" (- vote-y s)))
(-> svg
(.exit)
(.remove))))
(defn vote-id
[idx height vote-type]
(str height "#" idx "#" vote-type))
(defn draw-votes
[svg pre-votes pre-commits val-locs vote-locs height]
(let [locs (vec (map vector val-locs vote-locs))
pre-votes (for [i pre-votes] [(vote-id i height 0) (locs i) (:pre-vote vote-styles)])
pre-commits (for [i pre-commits] [(vote-id i height 1) (locs i) (:pre-commit vote-styles)])
data (into-array (concat pre-votes pre-commits))
svg (-> svg
(.selectAll "circle")
(.data data (fn [[d _ _]] d)))]
(-> svg
(.enter)
(.append "circle")
(.attr "cx" (fn [[_ [[x _] _] _]] x))
(.attr "cy" (fn [[_ [[_ y] _] _]] y))
(.attr "r" (fn [[_ _ [r _]]] r))
(.attr "fill" (fn [[_ _ [_ f]]] f))
(.transition)
(.attr "cx" (fn [[_ [_ [x _]] _]] x))
(.attr "cy" (fn [[_ [_ [_ y]] _]] y)))
(-> svg
(.exit)
(.remove))))
(defn update-graphics
[svg-groups _ _ _ new-state]
(let [current-validators (:validators new-state)
n (count current-validators)
proposer-idx (:proposer-idx new-state)
val-locs (compute-locations center n val-radius)
vote-locs (compute-locations center n vote-radius)
{:keys [height round step pre-votes pre-commits proposal first-height]} new-state
complete-blocks (take blocks-max (range height first-height -1))]
(draw-validators (:validators svg-groups) current-validators proposer-idx val-locs)
(draw-blockchain (:blockchain svg-groups) complete-blocks center)
(if (some? proposer-idx)
(draw-proposal (:proposal svg-groups) proposal height round proposer-idx val-locs center))
(draw-votes (:votes svg-groups) pre-votes pre-commits val-locs vote-locs height)))
(defn subscribe-msg
[id evt]
{:jsonrpc "2.0"
:method "subscribe"
:id id
:params {:query (str "tm.event='" evt "'")}})
(defn subscribe
[socket id evt]
(let [msg (subscribe-msg id evt)]
(prn (str "Subscribing: " msg))
(ws/send socket msg fmt/json)))
(defn subscribe-all
[socket]
(subscribe socket "0" "CompleteProposal")
(subscribe socket "1" "Vote")
(subscribe socket "2" "NewRound")
(subscribe socket "3" "ValidatorSetUpdates"))
(defn handle-new-round
[d]
(let [{:keys [height round step]} d
proposer-idx (get-in d [:proposer :index])
proposer-idx (js/parseInt proposer-idx)
height (js/parseInt height)
round (js/parseInt round)]
(swap! app-state assoc
:height height
:round round
:step step
:proposer-idx proposer-idx
:proposal nil
:pre-votes []
:pre-commits [])))
(defn handle-complete-proposal
[d]
(let [proposal (get-in d [:block_id :hash])]
; TODO: check that height and round match
(swap! app-state assoc :proposal proposal)))
(def vote-type-map
{1 :pre-votes
2 :pre-commits})
(defn add-vote
[state vote-type idx]
(let [old-votes (vote-type state)
new-votes (conj old-votes idx)]
(assoc state vote-type new-votes)))
(defn handle-vote
[d]
(let [d (:Vote d)
idx (:validator_index d)
idx (js/parseInt idx)
vote-type (get vote-type-map (:type d))]
(swap! app-state #(add-vote % vote-type idx))))
(defn handle-validator-set-updates
[d]
(prn d))
(def event-handlers
{"tendermint/event/NewRound" handle-new-round
"tendermint/event/CompleteProposal" handle-complete-proposal
"tendermint/event/Vote" handle-vote
"tendermint/event/ValidatorSetUpdates" handle-validator-set-updates})
(defn handle-message
[e]
(let [data (.-data e)
data (.parse js/JSON data)
data (js->clj data :keywordize-keys true)
data (get-in data [:result :data])
event-type (:type data)
handler (get event-handlers event-type)
data (:value data)]
(if (some? event-type)
(handler data))))
(def handlers {:on-message handle-message
:on-open #(subscribe-all @websocket)
:on-close #(reset! websocket nil)})
(defn connect-to-websocket
[host]
(reset! websocket (ws/create (str "ws://" host "/websocket") handlers)))
(defn connect-to-node
[node-address]
(get-node-status node-address)
(get-consensus-dump node-address)
(connect-to-websocket node-address))
(defn connect-to-node-component []
[:div
"Node Address: " [atom-input r-node-address]
[:input {:type "button" :value "Connect" :on-click #(connect-to-node @r-node-address)}]])
(defn node-info-component []
(let [info @r-node-status]
(if-not (empty? info)
(let [address @r-node-address
{:keys [id network moniker]} info]
[:div (str "Connected to Network: " network " via " moniker " (" id "@" address ")")])
[:div (str "Not connected")])))
(defn header []
[:div
[connect-to-node-component]
[node-info-component]])
(defn ^:export main []
(let [svg-main (append-svg "#app" 1000 1500)
svg-groups {:proposal (.append svg-main "g")
:votes (.append svg-main "g")
:blockchain (.append svg-main "g")
:validators (.append svg-main "g")}
]
(add-watch app-state :state-update (partial update-graphics svg-groups))
(r/render [header] (js/document.getElementById "header"))
))
(defn ^:after-load on-reload []
;; (swap! app-state update-in [:__figwheel_counter] inc)
)
|
[
{
"context": "l://localhost/inviteyoself?user=postgres&password=password\"}\n :plugins\n [[lein-ring \"0.8.10\"]\n [lein-env",
"end": 388,
"score": 0.9994731545448303,
"start": 380,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " true :db-user-name \"postgres\" :db-user-password \"password\" :db-host \"localhost\" :db-name \"inviteyoself\"}}}\n",
"end": 988,
"score": 0.999599039554596,
"start": 980,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "e \"1.6.0\"]\n [environ \"1.0.0\"]\n [ring-server \"0.3.1\"]\n [postgresql/postgresql \"9.1-901-1.jdbc4\"]",
"end": 1507,
"score": 0.5763602256774902,
"start": 1507,
"tag": "IP_ADDRESS",
"value": ""
},
{
"context": "\"1.6.0\"]\n [environ \"1.0.0\"]\n [ring-server \"0.3.1\"]\n [postgresql/postgresql \"9.1-901-1.jdbc4\"]\n ",
"end": 1509,
"score": 0.5456923842430115,
"start": 1509,
"tag": "IP_ADDRESS",
"value": ""
}
] | project.clj | Lance0312/inviteyoself | 23 | (defproject
inviteyoself
"0.1.0-SNAPSHOT"
:description
"Allow people to invite themselves to your slack team."
:ring
{:handler inviteyoself.handler/app,
:init inviteyoself.handler/init,
:destroy inviteyoself.handler/destroy}
:ragtime
{:migrations ragtime.sql.files/migrations,
:database
"jdbc:postgresql://localhost/inviteyoself?user=postgres&password=password"}
:plugins
[[lein-ring "0.8.10"]
[lein-environ "0.5.0"]
[lein-ancient "0.5.5"]
[ragtime/ragtime.lein "0.3.6"]]
:url
"http://example.com/FIXME"
:profiles
{:uberjar {:aot :all},
:production
{:ring
{:open-browser? false, :stacktraces? false, :auto-reload? false}},
:dev
{:dependencies
[[ring-mock "0.1.5"]
[ring/ring-devel "1.3.1"]
[pjstadig/humane-test-output "0.6.0"]],
:injections
[(require 'pjstadig.humane-test-output)
(pjstadig.humane-test-output/activate!)],
:env {:dev true :db-user-name "postgres" :db-user-password "password" :db-host "localhost" :db-name "inviteyoself"}}}
:main
inviteyoself.core
:jvm-opts
["-server"]
:dependencies
[[lib-noir "0.8.9"]
[log4j
"1.2.17"
:exclusions
[javax.mail/mail
javax.jms/jms
com.sun.jdmk/jmxtools
com.sun.jmx/jmxri]]
[http-kit "2.1.18"]
[prone "0.6.0"]
[noir-exception "0.2.2"]
[com.taoensso/timbre "3.3.1"]
[com.taoensso/tower "3.0.1"]
[korma "0.4.0"]
[selmer "0.7.1"]
[org.clojure/clojure "1.6.0"]
[environ "1.0.0"]
[ring-server "0.3.1"]
[postgresql/postgresql "9.1-901-1.jdbc4"]
[ragtime "0.3.6"]
[red-tape "1.0.0"]
[commons-validator "1.4.0"]
[slingshot "0.10.3"]]
:repl-options
{:init-ns inviteyoself.repl}
:min-lein-version "2.0.0"
:aliases {"start-production-server" ["with-profile" "production" "trampoline" "ring" "server"]
"send-invites" ["trampoline" "run" "-m" "inviteyoself.tasks.send-invites"]
})
| 90106 | (defproject
inviteyoself
"0.1.0-SNAPSHOT"
:description
"Allow people to invite themselves to your slack team."
:ring
{:handler inviteyoself.handler/app,
:init inviteyoself.handler/init,
:destroy inviteyoself.handler/destroy}
:ragtime
{:migrations ragtime.sql.files/migrations,
:database
"jdbc:postgresql://localhost/inviteyoself?user=postgres&password=<PASSWORD>"}
:plugins
[[lein-ring "0.8.10"]
[lein-environ "0.5.0"]
[lein-ancient "0.5.5"]
[ragtime/ragtime.lein "0.3.6"]]
:url
"http://example.com/FIXME"
:profiles
{:uberjar {:aot :all},
:production
{:ring
{:open-browser? false, :stacktraces? false, :auto-reload? false}},
:dev
{:dependencies
[[ring-mock "0.1.5"]
[ring/ring-devel "1.3.1"]
[pjstadig/humane-test-output "0.6.0"]],
:injections
[(require 'pjstadig.humane-test-output)
(pjstadig.humane-test-output/activate!)],
:env {:dev true :db-user-name "postgres" :db-user-password "<PASSWORD>" :db-host "localhost" :db-name "inviteyoself"}}}
:main
inviteyoself.core
:jvm-opts
["-server"]
:dependencies
[[lib-noir "0.8.9"]
[log4j
"1.2.17"
:exclusions
[javax.mail/mail
javax.jms/jms
com.sun.jdmk/jmxtools
com.sun.jmx/jmxri]]
[http-kit "2.1.18"]
[prone "0.6.0"]
[noir-exception "0.2.2"]
[com.taoensso/timbre "3.3.1"]
[com.taoensso/tower "3.0.1"]
[korma "0.4.0"]
[selmer "0.7.1"]
[org.clojure/clojure "1.6.0"]
[environ "1.0.0"]
[ring-server "0.3.1"]
[postgresql/postgresql "9.1-901-1.jdbc4"]
[ragtime "0.3.6"]
[red-tape "1.0.0"]
[commons-validator "1.4.0"]
[slingshot "0.10.3"]]
:repl-options
{:init-ns inviteyoself.repl}
:min-lein-version "2.0.0"
:aliases {"start-production-server" ["with-profile" "production" "trampoline" "ring" "server"]
"send-invites" ["trampoline" "run" "-m" "inviteyoself.tasks.send-invites"]
})
| true | (defproject
inviteyoself
"0.1.0-SNAPSHOT"
:description
"Allow people to invite themselves to your slack team."
:ring
{:handler inviteyoself.handler/app,
:init inviteyoself.handler/init,
:destroy inviteyoself.handler/destroy}
:ragtime
{:migrations ragtime.sql.files/migrations,
:database
"jdbc:postgresql://localhost/inviteyoself?user=postgres&password=PI:PASSWORD:<PASSWORD>END_PI"}
:plugins
[[lein-ring "0.8.10"]
[lein-environ "0.5.0"]
[lein-ancient "0.5.5"]
[ragtime/ragtime.lein "0.3.6"]]
:url
"http://example.com/FIXME"
:profiles
{:uberjar {:aot :all},
:production
{:ring
{:open-browser? false, :stacktraces? false, :auto-reload? false}},
:dev
{:dependencies
[[ring-mock "0.1.5"]
[ring/ring-devel "1.3.1"]
[pjstadig/humane-test-output "0.6.0"]],
:injections
[(require 'pjstadig.humane-test-output)
(pjstadig.humane-test-output/activate!)],
:env {:dev true :db-user-name "postgres" :db-user-password "PI:PASSWORD:<PASSWORD>END_PI" :db-host "localhost" :db-name "inviteyoself"}}}
:main
inviteyoself.core
:jvm-opts
["-server"]
:dependencies
[[lib-noir "0.8.9"]
[log4j
"1.2.17"
:exclusions
[javax.mail/mail
javax.jms/jms
com.sun.jdmk/jmxtools
com.sun.jmx/jmxri]]
[http-kit "2.1.18"]
[prone "0.6.0"]
[noir-exception "0.2.2"]
[com.taoensso/timbre "3.3.1"]
[com.taoensso/tower "3.0.1"]
[korma "0.4.0"]
[selmer "0.7.1"]
[org.clojure/clojure "1.6.0"]
[environ "1.0.0"]
[ring-server "0.3.1"]
[postgresql/postgresql "9.1-901-1.jdbc4"]
[ragtime "0.3.6"]
[red-tape "1.0.0"]
[commons-validator "1.4.0"]
[slingshot "0.10.3"]]
:repl-options
{:init-ns inviteyoself.repl}
:min-lein-version "2.0.0"
:aliases {"start-production-server" ["with-profile" "production" "trampoline" "ring" "server"]
"send-invites" ["trampoline" "run" "-m" "inviteyoself.tasks.send-invites"]
})
|
[
{
"context": "gned data cell.\n \n Uses Ed25519.\"\n\n {:author \"Adam Helinski\"}\n\n (:import (convex.core.crypto AKeyPair\n ",
"end": 269,
"score": 0.9989038705825806,
"start": 256,
"tag": "NAME",
"value": "Adam Helinski"
}
] | project/net/src/clj/main/convex/sign.clj | rosejn/convex.cljc | 30 | (ns convex.sign
"Signing cells using public key cryptography, most notably transactions as required prior to submission.
More precisely, is signed the hash of the encoding of the cell, producing a signed data cell.
Uses Ed25519."
{:author "Adam Helinski"}
(:import (convex.core.crypto AKeyPair
Ed25519KeyPair)
(convex.core.data AccountKey
ACell
Blob
SignedData)
(java.security PrivateKey
PublicKey)))
(set! *warn-on-reflection*
true)
;;;;;;;;;; Creating key pairs
(defn ed25519
"Creates an Ed25519 key pair.
It is generated from a [[seed]], a 32-byte blob. If not given, one is generated randomly.
Alternatively, a [[public-key]] and a [[private-key]] retrieved from an existing key pair can
be provided."
(^AKeyPair []
(Ed25519KeyPair/generate))
(^AKeyPair [^Blob seed]
(Ed25519KeyPair/create seed))
(^AKeyPair [^PublicKey key-public ^PrivateKey key-private]
(Ed25519KeyPair/create key-public
key-private)))
;;;;;;;;;; Retrieving keys from key pairs
(defn account-key
"Returns the account key of the given `key-pair`.
This is effectively the public key presented as a cell."
^AccountKey
[^AKeyPair key-pair]
(.getAccountKey key-pair))
(defn hex-string
"Returns the public key of the given `key-pair` as a hex-string (64-char string where each pair of
chars represents a byte in hexadecimal)."
[^AKeyPair key-pair]
(-> key-pair
account-key
.toHexString))
(defn key-private
"Returns the `java.security.PrivateKey` of the given `key-pair`."
^PrivateKey
[^AKeyPair key-pair]
(.getPrivate key-pair))
(defn key-public
"Returns the `java.security.PublicKey` of the given `key-pair`."
^PublicKey
[^AKeyPair key-pair]
(.getPublic key-pair))
(defn seed
"Returns the seed of"
^Blob
[^Ed25519KeyPair key-pair]
(.getSeed key-pair))
;;;;;;;;;; Using key pairs
(defn signed
"Returns the given `cell` signed by `key-pair`."
^SignedData
[^AKeyPair key-pair ^ACell cell]
(.signData key-pair
cell))
| 122500 | (ns convex.sign
"Signing cells using public key cryptography, most notably transactions as required prior to submission.
More precisely, is signed the hash of the encoding of the cell, producing a signed data cell.
Uses Ed25519."
{:author "<NAME>"}
(:import (convex.core.crypto AKeyPair
Ed25519KeyPair)
(convex.core.data AccountKey
ACell
Blob
SignedData)
(java.security PrivateKey
PublicKey)))
(set! *warn-on-reflection*
true)
;;;;;;;;;; Creating key pairs
(defn ed25519
"Creates an Ed25519 key pair.
It is generated from a [[seed]], a 32-byte blob. If not given, one is generated randomly.
Alternatively, a [[public-key]] and a [[private-key]] retrieved from an existing key pair can
be provided."
(^AKeyPair []
(Ed25519KeyPair/generate))
(^AKeyPair [^Blob seed]
(Ed25519KeyPair/create seed))
(^AKeyPair [^PublicKey key-public ^PrivateKey key-private]
(Ed25519KeyPair/create key-public
key-private)))
;;;;;;;;;; Retrieving keys from key pairs
(defn account-key
"Returns the account key of the given `key-pair`.
This is effectively the public key presented as a cell."
^AccountKey
[^AKeyPair key-pair]
(.getAccountKey key-pair))
(defn hex-string
"Returns the public key of the given `key-pair` as a hex-string (64-char string where each pair of
chars represents a byte in hexadecimal)."
[^AKeyPair key-pair]
(-> key-pair
account-key
.toHexString))
(defn key-private
"Returns the `java.security.PrivateKey` of the given `key-pair`."
^PrivateKey
[^AKeyPair key-pair]
(.getPrivate key-pair))
(defn key-public
"Returns the `java.security.PublicKey` of the given `key-pair`."
^PublicKey
[^AKeyPair key-pair]
(.getPublic key-pair))
(defn seed
"Returns the seed of"
^Blob
[^Ed25519KeyPair key-pair]
(.getSeed key-pair))
;;;;;;;;;; Using key pairs
(defn signed
"Returns the given `cell` signed by `key-pair`."
^SignedData
[^AKeyPair key-pair ^ACell cell]
(.signData key-pair
cell))
| true | (ns convex.sign
"Signing cells using public key cryptography, most notably transactions as required prior to submission.
More precisely, is signed the hash of the encoding of the cell, producing a signed data cell.
Uses Ed25519."
{:author "PI:NAME:<NAME>END_PI"}
(:import (convex.core.crypto AKeyPair
Ed25519KeyPair)
(convex.core.data AccountKey
ACell
Blob
SignedData)
(java.security PrivateKey
PublicKey)))
(set! *warn-on-reflection*
true)
;;;;;;;;;; Creating key pairs
(defn ed25519
"Creates an Ed25519 key pair.
It is generated from a [[seed]], a 32-byte blob. If not given, one is generated randomly.
Alternatively, a [[public-key]] and a [[private-key]] retrieved from an existing key pair can
be provided."
(^AKeyPair []
(Ed25519KeyPair/generate))
(^AKeyPair [^Blob seed]
(Ed25519KeyPair/create seed))
(^AKeyPair [^PublicKey key-public ^PrivateKey key-private]
(Ed25519KeyPair/create key-public
key-private)))
;;;;;;;;;; Retrieving keys from key pairs
(defn account-key
"Returns the account key of the given `key-pair`.
This is effectively the public key presented as a cell."
^AccountKey
[^AKeyPair key-pair]
(.getAccountKey key-pair))
(defn hex-string
"Returns the public key of the given `key-pair` as a hex-string (64-char string where each pair of
chars represents a byte in hexadecimal)."
[^AKeyPair key-pair]
(-> key-pair
account-key
.toHexString))
(defn key-private
"Returns the `java.security.PrivateKey` of the given `key-pair`."
^PrivateKey
[^AKeyPair key-pair]
(.getPrivate key-pair))
(defn key-public
"Returns the `java.security.PublicKey` of the given `key-pair`."
^PublicKey
[^AKeyPair key-pair]
(.getPublic key-pair))
(defn seed
"Returns the seed of"
^Blob
[^Ed25519KeyPair key-pair]
(.getSeed key-pair))
;;;;;;;;;; Using key pairs
(defn signed
"Returns the given `cell` signed by `key-pair`."
^SignedData
[^AKeyPair key-pair ^ACell cell]
(.signData key-pair
cell))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9998584985733032,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "es.clj: unit tests for fixtures in test.clj\n\n;; by Stuart Sierra\n;; March 28, 2009\n\n(ns clojure.test-clojure.test-",
"end": 544,
"score": 0.9998663663864136,
"start": 531,
"tag": "NAME",
"value": "Stuart Sierra"
}
] | ThirdParty/clojure-1.1.0/test/clojure/test_clojure/test_fixtures.clj | allertonm/Couverjure | 3 | ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;
;;; test_fixtures.clj: unit tests for fixtures in test.clj
;; by Stuart Sierra
;; March 28, 2009
(ns clojure.test-clojure.test-fixtures
(:use clojure.test))
(declare *a* *b* *c* *d*)
(def *n* 0)
(defn fixture-a [f]
(binding [*a* 3] (f)))
(defn fixture-b [f]
(binding [*b* 5] (f)))
(defn fixture-c [f]
(binding [*c* 7] (f)))
(defn fixture-d [f]
(binding [*d* 11] (f)))
(defn inc-n-fixture [f]
(binding [*n* (inc *n*)] (f)))
(use-fixtures :once fixture-a fixture-b)
(use-fixtures :each fixture-c fixture-d inc-n-fixture)
(use-fixtures :each fixture-c fixture-d inc-n-fixture)
(deftest can-use-once-fixtures
(is (= 3 *a*))
(is (= 5 *b*)))
(deftest can-use-each-fixtures
(is (= 7 *c*))
(is (= 11 *d*)))
(deftest use-fixtures-replaces
(is (= *n* 1))) | 5875 | ; Copyright (c) <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;
;;; test_fixtures.clj: unit tests for fixtures in test.clj
;; by <NAME>
;; March 28, 2009
(ns clojure.test-clojure.test-fixtures
(:use clojure.test))
(declare *a* *b* *c* *d*)
(def *n* 0)
(defn fixture-a [f]
(binding [*a* 3] (f)))
(defn fixture-b [f]
(binding [*b* 5] (f)))
(defn fixture-c [f]
(binding [*c* 7] (f)))
(defn fixture-d [f]
(binding [*d* 11] (f)))
(defn inc-n-fixture [f]
(binding [*n* (inc *n*)] (f)))
(use-fixtures :once fixture-a fixture-b)
(use-fixtures :each fixture-c fixture-d inc-n-fixture)
(use-fixtures :each fixture-c fixture-d inc-n-fixture)
(deftest can-use-once-fixtures
(is (= 3 *a*))
(is (= 5 *b*)))
(deftest can-use-each-fixtures
(is (= 7 *c*))
(is (= 11 *d*)))
(deftest use-fixtures-replaces
(is (= *n* 1))) | true | ; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;
;;; test_fixtures.clj: unit tests for fixtures in test.clj
;; by PI:NAME:<NAME>END_PI
;; March 28, 2009
(ns clojure.test-clojure.test-fixtures
(:use clojure.test))
(declare *a* *b* *c* *d*)
(def *n* 0)
(defn fixture-a [f]
(binding [*a* 3] (f)))
(defn fixture-b [f]
(binding [*b* 5] (f)))
(defn fixture-c [f]
(binding [*c* 7] (f)))
(defn fixture-d [f]
(binding [*d* 11] (f)))
(defn inc-n-fixture [f]
(binding [*n* (inc *n*)] (f)))
(use-fixtures :once fixture-a fixture-b)
(use-fixtures :each fixture-c fixture-d inc-n-fixture)
(use-fixtures :each fixture-c fixture-d inc-n-fixture)
(deftest can-use-once-fixtures
(is (= 3 *a*))
(is (= 5 *b*)))
(deftest can-use-each-fixtures
(is (= 7 *c*))
(is (= 11 *d*)))
(deftest use-fixtures-replaces
(is (= *n* 1))) |
[
{
"context": "-machine\n {:initial :a\n :context {:first-name \"Peter\"\n :last-name \"Muys\"}\n :entry [:e",
"end": 250,
"score": 0.999566912651062,
"start": 245,
"tag": "NAME",
"value": "Peter"
},
{
"context": "xt {:first-name \"Peter\"\n :last-name \"Muys\"}\n :entry [:entry-a (sl/assign (fn [c e]\n ",
"end": 282,
"score": 0.9995326399803162,
"start": 278,
"tag": "NAME",
"value": "Muys"
}
] | test/glasgolia/glas_state/service_test.cljc | glasgolia/glas-state | 5 | (ns glasgolia.glas-state.service-test
(:require [clojure.test :refer :all]
[glasgolia.glas-state.stateless :as sl]
[glasgolia.glas-state.service :refer :all]))
(def the-machine
{:initial :a
:context {:first-name "Peter"
:last-name "Muys"}
:entry [:entry-a (sl/assign (fn [c e]
(-> c
(assoc :we-where-in-a true)
(dissoc :first-name)
(dissoc :last-name))))]
:states {:a {:entry :entry-a
:on {:switch :b}
:invoke {:id :child-service-start
:src (fn [context event]
(let []
(fn [callback on-event]
(println "Child Service Invoked")
(println "Context=" context)
(println "event=" event)
(fn [] (println "Child Service Cleanup Invoked")))
))
:on-done {:target :b}
}
:initial :on
:states {:on {:entry (fn [c e]
(println "Light a is on"))
:on {:switch :off}}
:off {:entry (sl/assign :turn-light-off)}}}
:b {:entry :entry-b
:on {:switch :a}}}})
(deftest ^:test-refresh/focus-not interpreter-test
(testing create-service
"Testing transitions"
(let [state (atom {})
inst (-> (create-service the-machine {:state-atom state
:change-listener service-logger
:actions {:turn-light-off (fn [c _]
(assoc c :the-a-light-was-off true))}})
#_(start))
]
(is (= @state
{:value {:a :on} :context {:we-where-in-a true}}))
(dispatch inst :hello :child-service-start )
(dispatch-and-wait inst :switch)
(is (= @state
{:value {:a :off} :context {:we-where-in-a true :the-a-light-was-off true}}))
(dispatch-and-wait inst :switch)
(is (= @state
{:value :b :context {:we-where-in-a true :the-a-light-was-off true}}))
(stop inst))))
(def example-cmp-machine
{:id :examples-component
:initial :please-select-example
:states
{:please-select-example {:on
{:select-example
{:target :show-example
:actions (sl/assign (fn [c e]
(assoc c :selected (:example-id e))))}}}
:show-example {}}
:context {:list []
:selected nil}})
(deftest ^:test-refresh/focus_not reactions-test
(let [state (atom {})
reactions-result (atom {})
inst (-> (create-service {:id test
:initial :idle
:states {:idle {:on {:next :start}}
:start {:on {:next :stop}}
:stop {}}}
{:state-atom state
:change-listener service-logger})
(start))
remove-reactor1 (add-value-reaction inst (fn [old new]
(println "GOT REACTION" old new)
(reset! reactions-result {:old old :new new})))
remove-reactor2 (add-context-reaction inst (fn [old new]))
_ (println "VALUE:" (service-value inst))
_ (dispatch-and-wait inst :next)
_ (is (= @reactions-result {:old :idle :new :start}))
_ (remove-reactor1)
_ (dispatch-and-wait inst :next)
_ (is (= @reactions-result {:old :idle :new :start}))
]))
(deftest ^:test-refresh/focus-not on-with-actions-test
(let [state (atom {})
inst (-> (create-service example-cmp-machine {:state-atom state
:change-listener service-logger})
#_(start))]
(dispatch-and-wait inst {:type :select-example :example-id "blabla"})
(is (= @state {:value :show-example :context {:list [] :selected "blabla"}}))))
#_(def delay-test-machine (sl/machine {:initial :red
:states {:red {:on {:timer :green}
:entry (sl/send-event :timer {:delay 1000 :id :to-green-timer})}
:green {:on {:timer :orange}}
:orange {:on {:timer :red}}}}))
#_(deftest delayed-events-test
(testing create-service
"Testing delay send"
(let [inst (-> (create-service delay-test-machine {:change-listener service-logger})
(start))]
(dispatch inst :dummy)
(is inst)))) ; TODO
(deftest ^:test-refresh/focus_not child-machines
(let [inst (create-service {:id :invoke-test
:initial :a
:states {:a {:invoke [{:id :child-machine
:src {:id :child-machine
:entry (fn [c e] (println "Child-machine entry..."))
:initial :child-a
:states {:child-a {:entry (fn [c e] (println "child-machine: in :child-a"))
:on {:next :child-done}}
:child-done {:type :final
:entry (fn [c e] (println "Child-machine in :child-done"))}}}
:on-done {:target :b
:actions (fn [c e] (println "Child-machine on-done -> send target b"))}}]}
:b {:entry (fn [c e] (println "Parent-machine entry :b"))
:type :final}
}} {:change-listener service-logger})
_ (start inst)
_ (dispatch inst :next {:to :child-machine})
;_ (dispatch inst :dummy)
_ (Thread/sleep 1000)
])
)
| 70310 | (ns glasgolia.glas-state.service-test
(:require [clojure.test :refer :all]
[glasgolia.glas-state.stateless :as sl]
[glasgolia.glas-state.service :refer :all]))
(def the-machine
{:initial :a
:context {:first-name "<NAME>"
:last-name "<NAME>"}
:entry [:entry-a (sl/assign (fn [c e]
(-> c
(assoc :we-where-in-a true)
(dissoc :first-name)
(dissoc :last-name))))]
:states {:a {:entry :entry-a
:on {:switch :b}
:invoke {:id :child-service-start
:src (fn [context event]
(let []
(fn [callback on-event]
(println "Child Service Invoked")
(println "Context=" context)
(println "event=" event)
(fn [] (println "Child Service Cleanup Invoked")))
))
:on-done {:target :b}
}
:initial :on
:states {:on {:entry (fn [c e]
(println "Light a is on"))
:on {:switch :off}}
:off {:entry (sl/assign :turn-light-off)}}}
:b {:entry :entry-b
:on {:switch :a}}}})
(deftest ^:test-refresh/focus-not interpreter-test
(testing create-service
"Testing transitions"
(let [state (atom {})
inst (-> (create-service the-machine {:state-atom state
:change-listener service-logger
:actions {:turn-light-off (fn [c _]
(assoc c :the-a-light-was-off true))}})
#_(start))
]
(is (= @state
{:value {:a :on} :context {:we-where-in-a true}}))
(dispatch inst :hello :child-service-start )
(dispatch-and-wait inst :switch)
(is (= @state
{:value {:a :off} :context {:we-where-in-a true :the-a-light-was-off true}}))
(dispatch-and-wait inst :switch)
(is (= @state
{:value :b :context {:we-where-in-a true :the-a-light-was-off true}}))
(stop inst))))
(def example-cmp-machine
{:id :examples-component
:initial :please-select-example
:states
{:please-select-example {:on
{:select-example
{:target :show-example
:actions (sl/assign (fn [c e]
(assoc c :selected (:example-id e))))}}}
:show-example {}}
:context {:list []
:selected nil}})
(deftest ^:test-refresh/focus_not reactions-test
(let [state (atom {})
reactions-result (atom {})
inst (-> (create-service {:id test
:initial :idle
:states {:idle {:on {:next :start}}
:start {:on {:next :stop}}
:stop {}}}
{:state-atom state
:change-listener service-logger})
(start))
remove-reactor1 (add-value-reaction inst (fn [old new]
(println "GOT REACTION" old new)
(reset! reactions-result {:old old :new new})))
remove-reactor2 (add-context-reaction inst (fn [old new]))
_ (println "VALUE:" (service-value inst))
_ (dispatch-and-wait inst :next)
_ (is (= @reactions-result {:old :idle :new :start}))
_ (remove-reactor1)
_ (dispatch-and-wait inst :next)
_ (is (= @reactions-result {:old :idle :new :start}))
]))
(deftest ^:test-refresh/focus-not on-with-actions-test
(let [state (atom {})
inst (-> (create-service example-cmp-machine {:state-atom state
:change-listener service-logger})
#_(start))]
(dispatch-and-wait inst {:type :select-example :example-id "blabla"})
(is (= @state {:value :show-example :context {:list [] :selected "blabla"}}))))
#_(def delay-test-machine (sl/machine {:initial :red
:states {:red {:on {:timer :green}
:entry (sl/send-event :timer {:delay 1000 :id :to-green-timer})}
:green {:on {:timer :orange}}
:orange {:on {:timer :red}}}}))
#_(deftest delayed-events-test
(testing create-service
"Testing delay send"
(let [inst (-> (create-service delay-test-machine {:change-listener service-logger})
(start))]
(dispatch inst :dummy)
(is inst)))) ; TODO
(deftest ^:test-refresh/focus_not child-machines
(let [inst (create-service {:id :invoke-test
:initial :a
:states {:a {:invoke [{:id :child-machine
:src {:id :child-machine
:entry (fn [c e] (println "Child-machine entry..."))
:initial :child-a
:states {:child-a {:entry (fn [c e] (println "child-machine: in :child-a"))
:on {:next :child-done}}
:child-done {:type :final
:entry (fn [c e] (println "Child-machine in :child-done"))}}}
:on-done {:target :b
:actions (fn [c e] (println "Child-machine on-done -> send target b"))}}]}
:b {:entry (fn [c e] (println "Parent-machine entry :b"))
:type :final}
}} {:change-listener service-logger})
_ (start inst)
_ (dispatch inst :next {:to :child-machine})
;_ (dispatch inst :dummy)
_ (Thread/sleep 1000)
])
)
| true | (ns glasgolia.glas-state.service-test
(:require [clojure.test :refer :all]
[glasgolia.glas-state.stateless :as sl]
[glasgolia.glas-state.service :refer :all]))
(def the-machine
{:initial :a
:context {:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"}
:entry [:entry-a (sl/assign (fn [c e]
(-> c
(assoc :we-where-in-a true)
(dissoc :first-name)
(dissoc :last-name))))]
:states {:a {:entry :entry-a
:on {:switch :b}
:invoke {:id :child-service-start
:src (fn [context event]
(let []
(fn [callback on-event]
(println "Child Service Invoked")
(println "Context=" context)
(println "event=" event)
(fn [] (println "Child Service Cleanup Invoked")))
))
:on-done {:target :b}
}
:initial :on
:states {:on {:entry (fn [c e]
(println "Light a is on"))
:on {:switch :off}}
:off {:entry (sl/assign :turn-light-off)}}}
:b {:entry :entry-b
:on {:switch :a}}}})
(deftest ^:test-refresh/focus-not interpreter-test
(testing create-service
"Testing transitions"
(let [state (atom {})
inst (-> (create-service the-machine {:state-atom state
:change-listener service-logger
:actions {:turn-light-off (fn [c _]
(assoc c :the-a-light-was-off true))}})
#_(start))
]
(is (= @state
{:value {:a :on} :context {:we-where-in-a true}}))
(dispatch inst :hello :child-service-start )
(dispatch-and-wait inst :switch)
(is (= @state
{:value {:a :off} :context {:we-where-in-a true :the-a-light-was-off true}}))
(dispatch-and-wait inst :switch)
(is (= @state
{:value :b :context {:we-where-in-a true :the-a-light-was-off true}}))
(stop inst))))
(def example-cmp-machine
{:id :examples-component
:initial :please-select-example
:states
{:please-select-example {:on
{:select-example
{:target :show-example
:actions (sl/assign (fn [c e]
(assoc c :selected (:example-id e))))}}}
:show-example {}}
:context {:list []
:selected nil}})
(deftest ^:test-refresh/focus_not reactions-test
(let [state (atom {})
reactions-result (atom {})
inst (-> (create-service {:id test
:initial :idle
:states {:idle {:on {:next :start}}
:start {:on {:next :stop}}
:stop {}}}
{:state-atom state
:change-listener service-logger})
(start))
remove-reactor1 (add-value-reaction inst (fn [old new]
(println "GOT REACTION" old new)
(reset! reactions-result {:old old :new new})))
remove-reactor2 (add-context-reaction inst (fn [old new]))
_ (println "VALUE:" (service-value inst))
_ (dispatch-and-wait inst :next)
_ (is (= @reactions-result {:old :idle :new :start}))
_ (remove-reactor1)
_ (dispatch-and-wait inst :next)
_ (is (= @reactions-result {:old :idle :new :start}))
]))
(deftest ^:test-refresh/focus-not on-with-actions-test
(let [state (atom {})
inst (-> (create-service example-cmp-machine {:state-atom state
:change-listener service-logger})
#_(start))]
(dispatch-and-wait inst {:type :select-example :example-id "blabla"})
(is (= @state {:value :show-example :context {:list [] :selected "blabla"}}))))
#_(def delay-test-machine (sl/machine {:initial :red
:states {:red {:on {:timer :green}
:entry (sl/send-event :timer {:delay 1000 :id :to-green-timer})}
:green {:on {:timer :orange}}
:orange {:on {:timer :red}}}}))
#_(deftest delayed-events-test
(testing create-service
"Testing delay send"
(let [inst (-> (create-service delay-test-machine {:change-listener service-logger})
(start))]
(dispatch inst :dummy)
(is inst)))) ; TODO
(deftest ^:test-refresh/focus_not child-machines
(let [inst (create-service {:id :invoke-test
:initial :a
:states {:a {:invoke [{:id :child-machine
:src {:id :child-machine
:entry (fn [c e] (println "Child-machine entry..."))
:initial :child-a
:states {:child-a {:entry (fn [c e] (println "child-machine: in :child-a"))
:on {:next :child-done}}
:child-done {:type :final
:entry (fn [c e] (println "Child-machine in :child-done"))}}}
:on-done {:target :b
:actions (fn [c e] (println "Child-machine on-done -> send target b"))}}]}
:b {:entry (fn [c e] (println "Parent-machine entry :b"))
:type :final}
}} {:change-listener service-logger})
_ (start inst)
_ (dispatch inst :next {:to :child-machine})
;_ (dispatch inst :dummy)
_ (Thread/sleep 1000)
])
)
|
[
{
"context": ";; The MIT License (MIT)\n;;\n;; Copyright (c) 2015 Richard Hull\n;;\n;; Permission is hereby granted, free of charg",
"end": 62,
"score": 0.9997876286506653,
"start": 50,
"tag": "NAME",
"value": "Richard Hull"
},
{
"context": "ake-context)\n (assoc :trace true)\n (query \"father(R, henry)\")\n (program \"father(richard, henry)\")\n s/",
"end": 10432,
"score": 0.8113023042678833,
"start": 10431,
"tag": "NAME",
"value": "R"
},
{
"context": "e-context)\n (assoc :trace true)\n (query \"father(R, henry)\")\n (program \"father(richard, henry)\")\n s/diag\n (",
"end": 10439,
"score": 0.998974084854126,
"start": 10434,
"tag": "NAME",
"value": "henry"
},
{
"context": "ue)\n (query \"father(R, henry)\")\n (program \"father(richard, henry)\")\n s/diag\n (tee #(println \"R\" (resolve-st",
"end": 10468,
"score": 0.9995394945144653,
"start": 10461,
"tag": "NAME",
"value": "richard"
},
{
"context": "ery \"father(R, henry)\")\n (program \"father(richard, henry)\")\n s/diag\n (tee #(println \"R\" (resolve-struct % ",
"end": 10475,
"score": 0.9973986744880676,
"start": 10470,
"tag": "NAME",
"value": "henry"
},
{
"context": "\n; │ 7 ╎ richard|0 │\n; └─────┴───────────┘\n;\n; R richard\n; {:fail false, :mode :read, :pointer {:h 8, :s 2",
"end": 11359,
"score": 0.9989678859710693,
"start": 11352,
"tag": "NAME",
"value": "richard"
},
{
"context": "e-context)\n (assoc :trace true)\n (query \"father(R, henry)\")\n (program \"father(henry, richard)\")\n s/diag\n (",
"end": 11665,
"score": 0.9991536736488342,
"start": 11660,
"tag": "NAME",
"value": "henry"
},
{
"context": "ue)\n (query \"father(R, henry)\")\n (program \"father(henry, richard)\")\n s/diag\n (tee #(println \"R\" (resolve-",
"end": 11692,
"score": 0.9988800287246704,
"start": 11687,
"tag": "NAME",
"value": "henry"
},
{
"context": "query \"father(R, henry)\")\n (program \"father(henry, richard)\")\n s/diag\n (tee #(println \"R\" (resolve-struct % ",
"end": 11701,
"score": 0.9993252754211426,
"start": 11694,
"tag": "NAME",
"value": "richard"
},
{
"context": " │\n; │ 7 ╎ henry|0 │\n; └─────┴──────────┘\n;\n; R henry\n; {:fail true, :mode :write, :pointer {:h 8, :s 6",
"end": 12569,
"score": 0.995982825756073,
"start": 12564,
"tag": "NAME",
"value": "henry"
},
{
"context": "ake-context)\n (assoc :trace true)\n (query \"father(richard, J)\")\n (program \"father(W, K)\")\n s/diag\n ;(tee #",
"end": 12872,
"score": 0.9986572861671448,
"start": 12865,
"tag": "NAME",
"value": "richard"
}
] | test/wam/compiler_test.clj | rm-hull/wam | 23 | ;; The MIT License (MIT)
;;
;; Copyright (c) 2015 Richard Hull
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns wam.compiler-test
(:require
[clojure.test :refer :all]
[jasentaa.parser :refer [parse-all]]
[wam.assert-helpers :refer :all]
[wam.anciliary :refer [unify resolve-struct]]
[wam.compiler :refer :all]
[wam.instruction-set :refer :all]
[wam.grammar :refer [structure]]
[wam.store :as s]))
(deftest check-register-allocation
(testing "Register allocation"
(is (tbl= (register-allocation (parse-all structure "p(Z, h(Z, W), f(W))"))
"+------------------+-------+
| key | value |
+------------------+-------+
| p(Z h(Z W) f(W)) | X1 |
| Z | X2 |
| h(Z W) | X3 |
| f(W) | X4 |
| W | X5 |
+------------------+-------+"))
(is (tbl= (register-allocation (parse-all structure "p(f(X), h(Y, f(a)), Y)"))
"+---------------------+-------+
| key | value |
+---------------------+-------+
| p(f(X) h(Y f(a)) Y) | X1 |
| f(X) | X2 |
| h(Y f(a)) | X3 |
| Y | X4 |
| X | X5 |
| f(a) | X6 |
| a | X7 |
+---------------------+-------+"))
(is (tbl= (register-allocation (parse-all structure "f(X, g(X,a))"))
"+-------------+-------+
| key | value |
+-------------+-------+
| f(X g(X a)) | X1 |
| X | X2 |
| g(X a) | X3 |
| a | X4 |
+-------------+-------+"))))
(deftest check-query-builder
(testing "Query builder"
(let [term (parse-all structure "f(X, g(X,a))")
register-allocation (register-allocation term)]
(is (instr= (emit-instructions query-builder term register-allocation)
"+---------------+------+------+
| instr | arg1 | arg2 |
+---------------+------+------+
| put_structure | a|0 | X4 |
| put_structure | g|2 | X3 |
| set_variable | X2 | |
| set_value | X4 | |
| put_structure | f|2 | X1 |
| set_value | X2 | |
| set_value | X3 | |
+---------------+------+------+")))
(let [term (parse-all structure "p(Z, h(Z, W), f(W))")
register-allocation (register-allocation term)]
(is (instr= (emit-instructions query-builder term register-allocation)
"+---------------+------+------+
| instr | arg1 | arg2 |
+---------------+------+------+
| put_structure | h|2 | X3 |
| set_variable | X2 | |
| set_variable | X5 | |
| put_structure | f|1 | X4 |
| set_value | X5 | |
| put_structure | p|3 | X1 |
| set_value | X2 | |
| set_value | X3 | |
| set_value | X4 | |
+---------------+------+------+")))))
(deftest check-program-builder
(testing "Program builder"
(let [term (parse-all structure "p(f(X), h(Y, f(a)), Y)")
register-allocation (register-allocation term)]
(is (instr= (emit-instructions program-builder term register-allocation)
"+----------------+------+------+
| instr | arg1 | arg2 |
+----------------+------+------+
| get_structure | p|3 | X1 |
| unify_variable | X2 | |
| unify_variable | X3 | |
| unify_variable | X4 | |
| get_structure | f|1 | X2 |
| unify_variable | X5 | |
| get_structure | h|2 | X3 |
| unify_value | X4 | |
| unify_variable | X6 | |
| get_structure | f|1 | X6 |
| unify_variable | X7 | |
| get_structure | a|0 | X7 |
+----------------+------+------+")))))
(deftest check-compile
(testing "Query compilation"
(let [q (->>
"p(Z, h(Z, W), f(W))"
(parse-all structure)
(compile-term query-builder))]
(is (tbl= (-> (s/make-context) q s/heap)
"+------+------------+
| key | value |
+------+------------+
| 1000 | [STR 1001] |
| 1001 | h|2 |
| 1002 | [REF 1002] |
| 1003 | [REF 1003] |
| 1004 | [STR 1005] |
| 1005 | f|1 |
| 1006 | [REF 1003] |
| 1007 | [STR 1008] |
| 1008 | p|3 |
| 1009 | [REF 1002] |
| 1010 | [STR 1001] |
| 1011 | [STR 1005] |
+------+------------+"))))
(testing "Sequential queries"
(is (tbl=
(->
(s/make-context)
(query "f(X, g(X, a))")
(query "f(b, Y)")
s/heap)
"+------+------------+
| key | value |
+------+------------+
| 1000 | [STR 1001] |
| 1001 | a|0 |
| 1002 | [STR 1003] |
| 1003 | g|2 |
| 1004 | [REF 1004] |
| 1005 | [STR 1001] |
| 1006 | [STR 1007] |
| 1007 | f|2 |
| 1008 | [REF 1004] |
| 1009 | [STR 1003] |
| 1010 | [STR 1011] |
| 1011 | b|0 |
| 1012 | [STR 1013] |
| 1013 | f|2 |
| 1014 | [STR 1011] |
| 1015 | [REF 1015] |
+------+------------+")))
(testing "Unification"
(is (tbl=
(->
(s/make-context)
(query "f(X, g(X, a))")
(query "f(b, Y)")
(unify (heap 6) (heap 12))
s/heap)
"+------+------------+
| key | value |
+------+------------+
| 1000 | [STR 1001] |
| 1001 | a|0 |
| 1002 | [STR 1003] |
| 1003 | g|2 |
| 1004 | [STR 1011] |
| 1005 | [STR 1001] |
| 1006 | [STR 1007] |
| 1007 | f|2 |
| 1008 | [REF 1004] |
| 1009 | [STR 1003] |
| 1010 | [STR 1011] |
| 1011 | b|0 |
| 1012 | [STR 1013] |
| 1013 | f|2 |
| 1014 | [STR 1011] |
| 1015 | [STR 1003] |
+------+------------+"))))
(deftest ex2.2
(let [ctx (->
(s/make-context)
(query "f(X, g(X, a))")
(query "f(b, Y)")
(unify (heap 12) (heap 6)))]
(is (= (resolve-struct ctx (s/register-address 'X2)) "b"))
(is (= (resolve-struct ctx (s/register-address 'X3)) "g(b, a)"))))
(deftest ex2.3
(let [ctx (->
(s/make-context)
; fig 2.3: compiled code for ℒ₀ query ?- p(Z, h(Z, W), f(W)).
(put-structure 'h|2, 'X3)
(set-variable 'X2)
(set-variable 'X5)
(put-structure 'f|1, 'X4)
(set-value 'X5)
(put-structure 'p|3, 'X1)
(set-value 'X2)
(set-value 'X3)
(set-value 'X4)
; fig 2.4: compiled code for ℒ₀ query ?- p(f(X), h(Y, f(a)), Y).
(get-structure 'p|3, 'X1)
(unify-variable 'X2)
(unify-variable 'X3)
(unify-variable 'X4)
(get-structure 'f|1, 'X2)
(unify-variable 'X5)
(get-structure 'h|2, 'X3)
(unify-value 'X4)
(unify-variable 'X6)
(get-structure 'f|1, 'X6)
(unify-variable 'X7)
(get-structure 'a|0, 'X7))
W (resolve-struct ctx (s/register-address 'X5))
X (resolve-struct ctx (s/register-address 'X5))
Y (resolve-struct ctx (s/register-address 'X4))
Z (resolve-struct ctx (s/register-address 'X2))]
(is (= W "f(a)"))
(is (= X "f(a)"))
(is (= Y "f(f(a))"))
(is (= Z "f(f(a))"))))
(deftest ex2.5
(let [ctx (->
(s/make-context)
(query "p(Z, h(Z, W), f(W))")
(program "p(f(X), h(Y, f(a)), Y)"))
W (resolve-struct ctx (s/register-address 'X5))
X (resolve-struct ctx (s/register-address 'X5))
Y (resolve-struct ctx (s/register-address 'X4))
Z (resolve-struct ctx (s/register-address 'X2))]
(is (= W "f(a)"))
(is (= X "f(a)"))
(is (= Y "f(f(a))"))
(is (= Z "f(f(a))"))))
(defn tee [v func]
(func v)
v)
(->
(s/make-context)
(assoc :trace true)
(query "father(R, henry)")
(program "father(richard, henry)")
s/diag
(tee #(println "R" (resolve-struct % 1002))))
; put_structure henry|0, X3
; put_structure father|2, X1
; set_variable X2
; set_value X3
; get_structure father|2, X1
; unify_variable X2
; unify_variable X3
; get_structure richard|0, X2
; get_structure henry|0, X3
;
; Heap Registers Variables
; -------------------------------------------------------
; ┌─────┬───────────┐ ┌─────┬─────────┐ ┌─────┬───────┐
; │ key │ value │ │ key │ value │ │ key │ value │
; ├─────┼───────────┤ ├─────┼─────────┤ ├─────┼───────┤
; │ 0 ╎ [STR 1] │ │ X1 ╎ [STR 3] │ │ R ╎ X2 │
; │ 1 ╎ henry|0 │ │ X2 ╎ [REF 4] │ └─────┴───────┘
; │ 2 ╎ [STR 3] │ │ X3 ╎ [STR 1] │
; │ 3 ╎ father|2 │ └─────┴─────────┘
; │ 4 ╎ [STR 7] │
; │ 5 ╎ [STR 1] │
; │ 6 ╎ [STR 7] │
; │ 7 ╎ richard|0 │
; └─────┴───────────┘
;
; R richard
; {:fail false, :mode :read, :pointer {:h 8, :s 2, :x 1000}, :store {0 [STR 1], 7 richard|0, 1001 [STR 3], 1 henry|0, 4 [STR 7], 1002 [REF 4], 1003 [STR 1], 6 [STR 7], 3 father|2, 2 [STR 3], 5 [STR 1]}, :trace true, :variables ([R X2])}
(->
(s/make-context)
(assoc :trace true)
(query "father(R, henry)")
(program "father(henry, richard)")
s/diag
(tee #(println "R" (resolve-struct % 1002))))
; put_structure henry|0, X3
; put_structure father|2, X1
; set_variable X2
; set_value X3
; get_structure father|2, X1
; unify_variable X2
; unify_variable X3
; get_structure henry|0, X2
; get_structure richard|0, X3
;
; Heap Registers Variables
; ------------------------------------------------------
; ┌─────┬──────────┐ ┌─────┬─────────┐ ┌─────┬───────┐
; │ key │ value │ │ key │ value │ │ key │ value │
; ├─────┼──────────┤ ├─────┼─────────┤ ├─────┼───────┤
; │ 0 ╎ [STR 1] │ │ X1 ╎ [STR 3] │ │ R ╎ X2 │
; │ 1 ╎ henry|0 │ │ X2 ╎ [REF 4] │ └─────┴───────┘
; │ 2 ╎ [STR 3] │ │ X3 ╎ [STR 1] │
; │ 3 ╎ father|2 │ └─────┴─────────┘
; │ 4 ╎ [STR 7] │
; │ 5 ╎ [STR 1] │
; │ 6 ╎ [STR 7] │
; │ 7 ╎ henry|0 │
; └─────┴──────────┘
;
; R henry
; {:fail true, :mode :write, :pointer {:h 8, :s 6, :x 1000}, :store {0 [STR 1], 7 henry|0, 1001 [STR 3], 1 henry|0, 4 [STR 7], 1002 [REF 4], 1003 [STR 1], 6 [STR 7], 3 father|2, 2 [STR 3], 5 [STR 1]}, :trace true, :variables ([R X2])}
(->
(s/make-context)
(assoc :trace true)
(query "father(richard, J)")
(program "father(W, K)")
s/diag
;(tee #(println "J" (resolve-struct % 1003)))
;(tee #(println "K" (resolve-struct % 1003)))
;(tee #(println "W" (resolve-struct % 1002)))
)
| 91355 | ;; The MIT License (MIT)
;;
;; Copyright (c) 2015 <NAME>
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns wam.compiler-test
(:require
[clojure.test :refer :all]
[jasentaa.parser :refer [parse-all]]
[wam.assert-helpers :refer :all]
[wam.anciliary :refer [unify resolve-struct]]
[wam.compiler :refer :all]
[wam.instruction-set :refer :all]
[wam.grammar :refer [structure]]
[wam.store :as s]))
(deftest check-register-allocation
(testing "Register allocation"
(is (tbl= (register-allocation (parse-all structure "p(Z, h(Z, W), f(W))"))
"+------------------+-------+
| key | value |
+------------------+-------+
| p(Z h(Z W) f(W)) | X1 |
| Z | X2 |
| h(Z W) | X3 |
| f(W) | X4 |
| W | X5 |
+------------------+-------+"))
(is (tbl= (register-allocation (parse-all structure "p(f(X), h(Y, f(a)), Y)"))
"+---------------------+-------+
| key | value |
+---------------------+-------+
| p(f(X) h(Y f(a)) Y) | X1 |
| f(X) | X2 |
| h(Y f(a)) | X3 |
| Y | X4 |
| X | X5 |
| f(a) | X6 |
| a | X7 |
+---------------------+-------+"))
(is (tbl= (register-allocation (parse-all structure "f(X, g(X,a))"))
"+-------------+-------+
| key | value |
+-------------+-------+
| f(X g(X a)) | X1 |
| X | X2 |
| g(X a) | X3 |
| a | X4 |
+-------------+-------+"))))
(deftest check-query-builder
(testing "Query builder"
(let [term (parse-all structure "f(X, g(X,a))")
register-allocation (register-allocation term)]
(is (instr= (emit-instructions query-builder term register-allocation)
"+---------------+------+------+
| instr | arg1 | arg2 |
+---------------+------+------+
| put_structure | a|0 | X4 |
| put_structure | g|2 | X3 |
| set_variable | X2 | |
| set_value | X4 | |
| put_structure | f|2 | X1 |
| set_value | X2 | |
| set_value | X3 | |
+---------------+------+------+")))
(let [term (parse-all structure "p(Z, h(Z, W), f(W))")
register-allocation (register-allocation term)]
(is (instr= (emit-instructions query-builder term register-allocation)
"+---------------+------+------+
| instr | arg1 | arg2 |
+---------------+------+------+
| put_structure | h|2 | X3 |
| set_variable | X2 | |
| set_variable | X5 | |
| put_structure | f|1 | X4 |
| set_value | X5 | |
| put_structure | p|3 | X1 |
| set_value | X2 | |
| set_value | X3 | |
| set_value | X4 | |
+---------------+------+------+")))))
(deftest check-program-builder
(testing "Program builder"
(let [term (parse-all structure "p(f(X), h(Y, f(a)), Y)")
register-allocation (register-allocation term)]
(is (instr= (emit-instructions program-builder term register-allocation)
"+----------------+------+------+
| instr | arg1 | arg2 |
+----------------+------+------+
| get_structure | p|3 | X1 |
| unify_variable | X2 | |
| unify_variable | X3 | |
| unify_variable | X4 | |
| get_structure | f|1 | X2 |
| unify_variable | X5 | |
| get_structure | h|2 | X3 |
| unify_value | X4 | |
| unify_variable | X6 | |
| get_structure | f|1 | X6 |
| unify_variable | X7 | |
| get_structure | a|0 | X7 |
+----------------+------+------+")))))
(deftest check-compile
(testing "Query compilation"
(let [q (->>
"p(Z, h(Z, W), f(W))"
(parse-all structure)
(compile-term query-builder))]
(is (tbl= (-> (s/make-context) q s/heap)
"+------+------------+
| key | value |
+------+------------+
| 1000 | [STR 1001] |
| 1001 | h|2 |
| 1002 | [REF 1002] |
| 1003 | [REF 1003] |
| 1004 | [STR 1005] |
| 1005 | f|1 |
| 1006 | [REF 1003] |
| 1007 | [STR 1008] |
| 1008 | p|3 |
| 1009 | [REF 1002] |
| 1010 | [STR 1001] |
| 1011 | [STR 1005] |
+------+------------+"))))
(testing "Sequential queries"
(is (tbl=
(->
(s/make-context)
(query "f(X, g(X, a))")
(query "f(b, Y)")
s/heap)
"+------+------------+
| key | value |
+------+------------+
| 1000 | [STR 1001] |
| 1001 | a|0 |
| 1002 | [STR 1003] |
| 1003 | g|2 |
| 1004 | [REF 1004] |
| 1005 | [STR 1001] |
| 1006 | [STR 1007] |
| 1007 | f|2 |
| 1008 | [REF 1004] |
| 1009 | [STR 1003] |
| 1010 | [STR 1011] |
| 1011 | b|0 |
| 1012 | [STR 1013] |
| 1013 | f|2 |
| 1014 | [STR 1011] |
| 1015 | [REF 1015] |
+------+------------+")))
(testing "Unification"
(is (tbl=
(->
(s/make-context)
(query "f(X, g(X, a))")
(query "f(b, Y)")
(unify (heap 6) (heap 12))
s/heap)
"+------+------------+
| key | value |
+------+------------+
| 1000 | [STR 1001] |
| 1001 | a|0 |
| 1002 | [STR 1003] |
| 1003 | g|2 |
| 1004 | [STR 1011] |
| 1005 | [STR 1001] |
| 1006 | [STR 1007] |
| 1007 | f|2 |
| 1008 | [REF 1004] |
| 1009 | [STR 1003] |
| 1010 | [STR 1011] |
| 1011 | b|0 |
| 1012 | [STR 1013] |
| 1013 | f|2 |
| 1014 | [STR 1011] |
| 1015 | [STR 1003] |
+------+------------+"))))
(deftest ex2.2
(let [ctx (->
(s/make-context)
(query "f(X, g(X, a))")
(query "f(b, Y)")
(unify (heap 12) (heap 6)))]
(is (= (resolve-struct ctx (s/register-address 'X2)) "b"))
(is (= (resolve-struct ctx (s/register-address 'X3)) "g(b, a)"))))
(deftest ex2.3
(let [ctx (->
(s/make-context)
; fig 2.3: compiled code for ℒ₀ query ?- p(Z, h(Z, W), f(W)).
(put-structure 'h|2, 'X3)
(set-variable 'X2)
(set-variable 'X5)
(put-structure 'f|1, 'X4)
(set-value 'X5)
(put-structure 'p|3, 'X1)
(set-value 'X2)
(set-value 'X3)
(set-value 'X4)
; fig 2.4: compiled code for ℒ₀ query ?- p(f(X), h(Y, f(a)), Y).
(get-structure 'p|3, 'X1)
(unify-variable 'X2)
(unify-variable 'X3)
(unify-variable 'X4)
(get-structure 'f|1, 'X2)
(unify-variable 'X5)
(get-structure 'h|2, 'X3)
(unify-value 'X4)
(unify-variable 'X6)
(get-structure 'f|1, 'X6)
(unify-variable 'X7)
(get-structure 'a|0, 'X7))
W (resolve-struct ctx (s/register-address 'X5))
X (resolve-struct ctx (s/register-address 'X5))
Y (resolve-struct ctx (s/register-address 'X4))
Z (resolve-struct ctx (s/register-address 'X2))]
(is (= W "f(a)"))
(is (= X "f(a)"))
(is (= Y "f(f(a))"))
(is (= Z "f(f(a))"))))
(deftest ex2.5
(let [ctx (->
(s/make-context)
(query "p(Z, h(Z, W), f(W))")
(program "p(f(X), h(Y, f(a)), Y)"))
W (resolve-struct ctx (s/register-address 'X5))
X (resolve-struct ctx (s/register-address 'X5))
Y (resolve-struct ctx (s/register-address 'X4))
Z (resolve-struct ctx (s/register-address 'X2))]
(is (= W "f(a)"))
(is (= X "f(a)"))
(is (= Y "f(f(a))"))
(is (= Z "f(f(a))"))))
(defn tee [v func]
(func v)
v)
(->
(s/make-context)
(assoc :trace true)
(query "father(<NAME>, <NAME>)")
(program "father(<NAME>, <NAME>)")
s/diag
(tee #(println "R" (resolve-struct % 1002))))
; put_structure henry|0, X3
; put_structure father|2, X1
; set_variable X2
; set_value X3
; get_structure father|2, X1
; unify_variable X2
; unify_variable X3
; get_structure richard|0, X2
; get_structure henry|0, X3
;
; Heap Registers Variables
; -------------------------------------------------------
; ┌─────┬───────────┐ ┌─────┬─────────┐ ┌─────┬───────┐
; │ key │ value │ │ key │ value │ │ key │ value │
; ├─────┼───────────┤ ├─────┼─────────┤ ├─────┼───────┤
; │ 0 ╎ [STR 1] │ │ X1 ╎ [STR 3] │ │ R ╎ X2 │
; │ 1 ╎ henry|0 │ │ X2 ╎ [REF 4] │ └─────┴───────┘
; │ 2 ╎ [STR 3] │ │ X3 ╎ [STR 1] │
; │ 3 ╎ father|2 │ └─────┴─────────┘
; │ 4 ╎ [STR 7] │
; │ 5 ╎ [STR 1] │
; │ 6 ╎ [STR 7] │
; │ 7 ╎ richard|0 │
; └─────┴───────────┘
;
; R <NAME>
; {:fail false, :mode :read, :pointer {:h 8, :s 2, :x 1000}, :store {0 [STR 1], 7 richard|0, 1001 [STR 3], 1 henry|0, 4 [STR 7], 1002 [REF 4], 1003 [STR 1], 6 [STR 7], 3 father|2, 2 [STR 3], 5 [STR 1]}, :trace true, :variables ([R X2])}
(->
(s/make-context)
(assoc :trace true)
(query "father(R, <NAME>)")
(program "father(<NAME>, <NAME>)")
s/diag
(tee #(println "R" (resolve-struct % 1002))))
; put_structure henry|0, X3
; put_structure father|2, X1
; set_variable X2
; set_value X3
; get_structure father|2, X1
; unify_variable X2
; unify_variable X3
; get_structure henry|0, X2
; get_structure richard|0, X3
;
; Heap Registers Variables
; ------------------------------------------------------
; ┌─────┬──────────┐ ┌─────┬─────────┐ ┌─────┬───────┐
; │ key │ value │ │ key │ value │ │ key │ value │
; ├─────┼──────────┤ ├─────┼─────────┤ ├─────┼───────┤
; │ 0 ╎ [STR 1] │ │ X1 ╎ [STR 3] │ │ R ╎ X2 │
; │ 1 ╎ henry|0 │ │ X2 ╎ [REF 4] │ └─────┴───────┘
; │ 2 ╎ [STR 3] │ │ X3 ╎ [STR 1] │
; │ 3 ╎ father|2 │ └─────┴─────────┘
; │ 4 ╎ [STR 7] │
; │ 5 ╎ [STR 1] │
; │ 6 ╎ [STR 7] │
; │ 7 ╎ henry|0 │
; └─────┴──────────┘
;
; R <NAME>
; {:fail true, :mode :write, :pointer {:h 8, :s 6, :x 1000}, :store {0 [STR 1], 7 henry|0, 1001 [STR 3], 1 henry|0, 4 [STR 7], 1002 [REF 4], 1003 [STR 1], 6 [STR 7], 3 father|2, 2 [STR 3], 5 [STR 1]}, :trace true, :variables ([R X2])}
(->
(s/make-context)
(assoc :trace true)
(query "father(<NAME>, J)")
(program "father(W, K)")
s/diag
;(tee #(println "J" (resolve-struct % 1003)))
;(tee #(println "K" (resolve-struct % 1003)))
;(tee #(println "W" (resolve-struct % 1002)))
)
| true | ;; The MIT License (MIT)
;;
;; Copyright (c) 2015 PI:NAME:<NAME>END_PI
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns wam.compiler-test
(:require
[clojure.test :refer :all]
[jasentaa.parser :refer [parse-all]]
[wam.assert-helpers :refer :all]
[wam.anciliary :refer [unify resolve-struct]]
[wam.compiler :refer :all]
[wam.instruction-set :refer :all]
[wam.grammar :refer [structure]]
[wam.store :as s]))
(deftest check-register-allocation
(testing "Register allocation"
(is (tbl= (register-allocation (parse-all structure "p(Z, h(Z, W), f(W))"))
"+------------------+-------+
| key | value |
+------------------+-------+
| p(Z h(Z W) f(W)) | X1 |
| Z | X2 |
| h(Z W) | X3 |
| f(W) | X4 |
| W | X5 |
+------------------+-------+"))
(is (tbl= (register-allocation (parse-all structure "p(f(X), h(Y, f(a)), Y)"))
"+---------------------+-------+
| key | value |
+---------------------+-------+
| p(f(X) h(Y f(a)) Y) | X1 |
| f(X) | X2 |
| h(Y f(a)) | X3 |
| Y | X4 |
| X | X5 |
| f(a) | X6 |
| a | X7 |
+---------------------+-------+"))
(is (tbl= (register-allocation (parse-all structure "f(X, g(X,a))"))
"+-------------+-------+
| key | value |
+-------------+-------+
| f(X g(X a)) | X1 |
| X | X2 |
| g(X a) | X3 |
| a | X4 |
+-------------+-------+"))))
(deftest check-query-builder
(testing "Query builder"
(let [term (parse-all structure "f(X, g(X,a))")
register-allocation (register-allocation term)]
(is (instr= (emit-instructions query-builder term register-allocation)
"+---------------+------+------+
| instr | arg1 | arg2 |
+---------------+------+------+
| put_structure | a|0 | X4 |
| put_structure | g|2 | X3 |
| set_variable | X2 | |
| set_value | X4 | |
| put_structure | f|2 | X1 |
| set_value | X2 | |
| set_value | X3 | |
+---------------+------+------+")))
(let [term (parse-all structure "p(Z, h(Z, W), f(W))")
register-allocation (register-allocation term)]
(is (instr= (emit-instructions query-builder term register-allocation)
"+---------------+------+------+
| instr | arg1 | arg2 |
+---------------+------+------+
| put_structure | h|2 | X3 |
| set_variable | X2 | |
| set_variable | X5 | |
| put_structure | f|1 | X4 |
| set_value | X5 | |
| put_structure | p|3 | X1 |
| set_value | X2 | |
| set_value | X3 | |
| set_value | X4 | |
+---------------+------+------+")))))
(deftest check-program-builder
(testing "Program builder"
(let [term (parse-all structure "p(f(X), h(Y, f(a)), Y)")
register-allocation (register-allocation term)]
(is (instr= (emit-instructions program-builder term register-allocation)
"+----------------+------+------+
| instr | arg1 | arg2 |
+----------------+------+------+
| get_structure | p|3 | X1 |
| unify_variable | X2 | |
| unify_variable | X3 | |
| unify_variable | X4 | |
| get_structure | f|1 | X2 |
| unify_variable | X5 | |
| get_structure | h|2 | X3 |
| unify_value | X4 | |
| unify_variable | X6 | |
| get_structure | f|1 | X6 |
| unify_variable | X7 | |
| get_structure | a|0 | X7 |
+----------------+------+------+")))))
(deftest check-compile
(testing "Query compilation"
(let [q (->>
"p(Z, h(Z, W), f(W))"
(parse-all structure)
(compile-term query-builder))]
(is (tbl= (-> (s/make-context) q s/heap)
"+------+------------+
| key | value |
+------+------------+
| 1000 | [STR 1001] |
| 1001 | h|2 |
| 1002 | [REF 1002] |
| 1003 | [REF 1003] |
| 1004 | [STR 1005] |
| 1005 | f|1 |
| 1006 | [REF 1003] |
| 1007 | [STR 1008] |
| 1008 | p|3 |
| 1009 | [REF 1002] |
| 1010 | [STR 1001] |
| 1011 | [STR 1005] |
+------+------------+"))))
(testing "Sequential queries"
(is (tbl=
(->
(s/make-context)
(query "f(X, g(X, a))")
(query "f(b, Y)")
s/heap)
"+------+------------+
| key | value |
+------+------------+
| 1000 | [STR 1001] |
| 1001 | a|0 |
| 1002 | [STR 1003] |
| 1003 | g|2 |
| 1004 | [REF 1004] |
| 1005 | [STR 1001] |
| 1006 | [STR 1007] |
| 1007 | f|2 |
| 1008 | [REF 1004] |
| 1009 | [STR 1003] |
| 1010 | [STR 1011] |
| 1011 | b|0 |
| 1012 | [STR 1013] |
| 1013 | f|2 |
| 1014 | [STR 1011] |
| 1015 | [REF 1015] |
+------+------------+")))
(testing "Unification"
(is (tbl=
(->
(s/make-context)
(query "f(X, g(X, a))")
(query "f(b, Y)")
(unify (heap 6) (heap 12))
s/heap)
"+------+------------+
| key | value |
+------+------------+
| 1000 | [STR 1001] |
| 1001 | a|0 |
| 1002 | [STR 1003] |
| 1003 | g|2 |
| 1004 | [STR 1011] |
| 1005 | [STR 1001] |
| 1006 | [STR 1007] |
| 1007 | f|2 |
| 1008 | [REF 1004] |
| 1009 | [STR 1003] |
| 1010 | [STR 1011] |
| 1011 | b|0 |
| 1012 | [STR 1013] |
| 1013 | f|2 |
| 1014 | [STR 1011] |
| 1015 | [STR 1003] |
+------+------------+"))))
(deftest ex2.2
(let [ctx (->
(s/make-context)
(query "f(X, g(X, a))")
(query "f(b, Y)")
(unify (heap 12) (heap 6)))]
(is (= (resolve-struct ctx (s/register-address 'X2)) "b"))
(is (= (resolve-struct ctx (s/register-address 'X3)) "g(b, a)"))))
(deftest ex2.3
(let [ctx (->
(s/make-context)
; fig 2.3: compiled code for ℒ₀ query ?- p(Z, h(Z, W), f(W)).
(put-structure 'h|2, 'X3)
(set-variable 'X2)
(set-variable 'X5)
(put-structure 'f|1, 'X4)
(set-value 'X5)
(put-structure 'p|3, 'X1)
(set-value 'X2)
(set-value 'X3)
(set-value 'X4)
; fig 2.4: compiled code for ℒ₀ query ?- p(f(X), h(Y, f(a)), Y).
(get-structure 'p|3, 'X1)
(unify-variable 'X2)
(unify-variable 'X3)
(unify-variable 'X4)
(get-structure 'f|1, 'X2)
(unify-variable 'X5)
(get-structure 'h|2, 'X3)
(unify-value 'X4)
(unify-variable 'X6)
(get-structure 'f|1, 'X6)
(unify-variable 'X7)
(get-structure 'a|0, 'X7))
W (resolve-struct ctx (s/register-address 'X5))
X (resolve-struct ctx (s/register-address 'X5))
Y (resolve-struct ctx (s/register-address 'X4))
Z (resolve-struct ctx (s/register-address 'X2))]
(is (= W "f(a)"))
(is (= X "f(a)"))
(is (= Y "f(f(a))"))
(is (= Z "f(f(a))"))))
(deftest ex2.5
(let [ctx (->
(s/make-context)
(query "p(Z, h(Z, W), f(W))")
(program "p(f(X), h(Y, f(a)), Y)"))
W (resolve-struct ctx (s/register-address 'X5))
X (resolve-struct ctx (s/register-address 'X5))
Y (resolve-struct ctx (s/register-address 'X4))
Z (resolve-struct ctx (s/register-address 'X2))]
(is (= W "f(a)"))
(is (= X "f(a)"))
(is (= Y "f(f(a))"))
(is (= Z "f(f(a))"))))
(defn tee [v func]
(func v)
v)
(->
(s/make-context)
(assoc :trace true)
(query "father(PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI)")
(program "father(PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI)")
s/diag
(tee #(println "R" (resolve-struct % 1002))))
; put_structure henry|0, X3
; put_structure father|2, X1
; set_variable X2
; set_value X3
; get_structure father|2, X1
; unify_variable X2
; unify_variable X3
; get_structure richard|0, X2
; get_structure henry|0, X3
;
; Heap Registers Variables
; -------------------------------------------------------
; ┌─────┬───────────┐ ┌─────┬─────────┐ ┌─────┬───────┐
; │ key │ value │ │ key │ value │ │ key │ value │
; ├─────┼───────────┤ ├─────┼─────────┤ ├─────┼───────┤
; │ 0 ╎ [STR 1] │ │ X1 ╎ [STR 3] │ │ R ╎ X2 │
; │ 1 ╎ henry|0 │ │ X2 ╎ [REF 4] │ └─────┴───────┘
; │ 2 ╎ [STR 3] │ │ X3 ╎ [STR 1] │
; │ 3 ╎ father|2 │ └─────┴─────────┘
; │ 4 ╎ [STR 7] │
; │ 5 ╎ [STR 1] │
; │ 6 ╎ [STR 7] │
; │ 7 ╎ richard|0 │
; └─────┴───────────┘
;
; R PI:NAME:<NAME>END_PI
; {:fail false, :mode :read, :pointer {:h 8, :s 2, :x 1000}, :store {0 [STR 1], 7 richard|0, 1001 [STR 3], 1 henry|0, 4 [STR 7], 1002 [REF 4], 1003 [STR 1], 6 [STR 7], 3 father|2, 2 [STR 3], 5 [STR 1]}, :trace true, :variables ([R X2])}
(->
(s/make-context)
(assoc :trace true)
(query "father(R, PI:NAME:<NAME>END_PI)")
(program "father(PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI)")
s/diag
(tee #(println "R" (resolve-struct % 1002))))
; put_structure henry|0, X3
; put_structure father|2, X1
; set_variable X2
; set_value X3
; get_structure father|2, X1
; unify_variable X2
; unify_variable X3
; get_structure henry|0, X2
; get_structure richard|0, X3
;
; Heap Registers Variables
; ------------------------------------------------------
; ┌─────┬──────────┐ ┌─────┬─────────┐ ┌─────┬───────┐
; │ key │ value │ │ key │ value │ │ key │ value │
; ├─────┼──────────┤ ├─────┼─────────┤ ├─────┼───────┤
; │ 0 ╎ [STR 1] │ │ X1 ╎ [STR 3] │ │ R ╎ X2 │
; │ 1 ╎ henry|0 │ │ X2 ╎ [REF 4] │ └─────┴───────┘
; │ 2 ╎ [STR 3] │ │ X3 ╎ [STR 1] │
; │ 3 ╎ father|2 │ └─────┴─────────┘
; │ 4 ╎ [STR 7] │
; │ 5 ╎ [STR 1] │
; │ 6 ╎ [STR 7] │
; │ 7 ╎ henry|0 │
; └─────┴──────────┘
;
; R PI:NAME:<NAME>END_PI
; {:fail true, :mode :write, :pointer {:h 8, :s 6, :x 1000}, :store {0 [STR 1], 7 henry|0, 1001 [STR 3], 1 henry|0, 4 [STR 7], 1002 [REF 4], 1003 [STR 1], 6 [STR 7], 3 father|2, 2 [STR 3], 5 [STR 1]}, :trace true, :variables ([R X2])}
(->
(s/make-context)
(assoc :trace true)
(query "father(PI:NAME:<NAME>END_PI, J)")
(program "father(W, K)")
s/diag
;(tee #(println "J" (resolve-struct % 1003)))
;(tee #(println "K" (resolve-struct % 1003)))
;(tee #(println "W" (resolve-struct % 1002)))
)
|
[
{
"context": ": Add this boost to your gauge.\"]\n :ryu-tatsu [\"Tatsumaki Senpukyaku\"\n \"Special\n Speed 3.\n",
"end": 1838,
"score": 0.9569891691207886,
"start": 1818,
"tag": "NAME",
"value": "Tatsumaki Senpukyaku"
},
{
"context": " Power and +1 Speed.\"]\n :ryu-metsu-hadoken [\"Metsu Hadoken\"\n \"Ultra (3 Gauge)\n ",
"end": 2197,
"score": 0.6319105625152588,
"start": 2187,
"tag": "NAME",
"value": "su Hadoken"
},
{
"context": "+2 Power and +2 Speed\"]\n :ryu-metsu-shoryuken [\"Metsu Shoryuken\"\n \"Ultra (4 Gauge)\n ",
"end": 2560,
"score": 0.9041511416435242,
"start": 2545,
"tag": "NAME",
"value": "Metsu Shoryuken"
}
] | src/cljs/exceed/cards/season_three.cljs | Jungorend/gekiha | 2 | (ns exceed.cards.season-three)
(def ryu
"Contains the names and descriptions for
Ryu's cards. Each is a tuple of `name` and
then the card `description`"
{:ryu ["Ryu"
"As an action, you may Move 1.\nExceed Cost: 1"]
:ryu-donkey-kick ["Donkey Kick"
"Special
Speed 4.
Power 6.
Range 1~2.
Guard 4.
Hit: Push 2 and Gain Advantage.
Boost: Ki Charge
Add this card to your Gauge."]
:ryu-hadoken ["Hadoken"
"Special
Speed 4.
Power 4.
Range 3~6.
Critical: +2 Speed
After: If you hit, you may return this card to your deck.
If you do, add the top card of your discard to your gauge.
Boost: Defensive (+)
+2 Power and +1 Armor."]
:ryu-one-inch-punch ["One Inch Punch"
"Special
Speed 3.
Power 5.
Range 1.
Guard 6.
Critical: +2 Armor
Ignore Armor
Hit: Push 3.
Boost: Quick Step
Move 1. Take another action."]
:ryu-shoryuken ["Shoryuken"
"Special
Speed 5.
Power 4.
Range 1.
+2 Speed if the opponent initiated this Strike.
Critical, Before: Close 1.
Boost: Overhead (+)
Ignore Armor.
Now: Strike
Hit: Add this boost to your gauge."]
:ryu-tatsu ["Tatsumaki Senpukyaku"
"Special
Speed 3.
Power 5.
Range 1~2.
Guard 4.
Before: Advance 2.
Hit: If you advanced past your opponent during this Strike, gain Advantage.
Boost: Swift (+)
+1 Power and +1 Speed."]
:ryu-metsu-hadoken ["Metsu Hadoken"
"Ultra (3 Gauge)
Speed 5.
Power 7.
Range 3~5.
After: Move up to 2.
Boost: Way of the Warrior (+)
1 Force Cost.
+2 Power and +2 Speed"]
:ryu-metsu-shoryuken ["Metsu Shoryuken"
"Ultra (4 Gauge)
5 Speed.
7 Power.
Range 1.
+3 Speed if the opponent initiated this Strike.
Boost: Lighting Reflexes
1 Force Cost
Move 2 then Strike."]}) | 49918 | (ns exceed.cards.season-three)
(def ryu
"Contains the names and descriptions for
Ryu's cards. Each is a tuple of `name` and
then the card `description`"
{:ryu ["Ryu"
"As an action, you may Move 1.\nExceed Cost: 1"]
:ryu-donkey-kick ["Donkey Kick"
"Special
Speed 4.
Power 6.
Range 1~2.
Guard 4.
Hit: Push 2 and Gain Advantage.
Boost: Ki Charge
Add this card to your Gauge."]
:ryu-hadoken ["Hadoken"
"Special
Speed 4.
Power 4.
Range 3~6.
Critical: +2 Speed
After: If you hit, you may return this card to your deck.
If you do, add the top card of your discard to your gauge.
Boost: Defensive (+)
+2 Power and +1 Armor."]
:ryu-one-inch-punch ["One Inch Punch"
"Special
Speed 3.
Power 5.
Range 1.
Guard 6.
Critical: +2 Armor
Ignore Armor
Hit: Push 3.
Boost: Quick Step
Move 1. Take another action."]
:ryu-shoryuken ["Shoryuken"
"Special
Speed 5.
Power 4.
Range 1.
+2 Speed if the opponent initiated this Strike.
Critical, Before: Close 1.
Boost: Overhead (+)
Ignore Armor.
Now: Strike
Hit: Add this boost to your gauge."]
:ryu-tatsu ["<NAME>"
"Special
Speed 3.
Power 5.
Range 1~2.
Guard 4.
Before: Advance 2.
Hit: If you advanced past your opponent during this Strike, gain Advantage.
Boost: Swift (+)
+1 Power and +1 Speed."]
:ryu-metsu-hadoken ["Met<NAME>"
"Ultra (3 Gauge)
Speed 5.
Power 7.
Range 3~5.
After: Move up to 2.
Boost: Way of the Warrior (+)
1 Force Cost.
+2 Power and +2 Speed"]
:ryu-metsu-shoryuken ["<NAME>"
"Ultra (4 Gauge)
5 Speed.
7 Power.
Range 1.
+3 Speed if the opponent initiated this Strike.
Boost: Lighting Reflexes
1 Force Cost
Move 2 then Strike."]}) | true | (ns exceed.cards.season-three)
(def ryu
"Contains the names and descriptions for
Ryu's cards. Each is a tuple of `name` and
then the card `description`"
{:ryu ["Ryu"
"As an action, you may Move 1.\nExceed Cost: 1"]
:ryu-donkey-kick ["Donkey Kick"
"Special
Speed 4.
Power 6.
Range 1~2.
Guard 4.
Hit: Push 2 and Gain Advantage.
Boost: Ki Charge
Add this card to your Gauge."]
:ryu-hadoken ["Hadoken"
"Special
Speed 4.
Power 4.
Range 3~6.
Critical: +2 Speed
After: If you hit, you may return this card to your deck.
If you do, add the top card of your discard to your gauge.
Boost: Defensive (+)
+2 Power and +1 Armor."]
:ryu-one-inch-punch ["One Inch Punch"
"Special
Speed 3.
Power 5.
Range 1.
Guard 6.
Critical: +2 Armor
Ignore Armor
Hit: Push 3.
Boost: Quick Step
Move 1. Take another action."]
:ryu-shoryuken ["Shoryuken"
"Special
Speed 5.
Power 4.
Range 1.
+2 Speed if the opponent initiated this Strike.
Critical, Before: Close 1.
Boost: Overhead (+)
Ignore Armor.
Now: Strike
Hit: Add this boost to your gauge."]
:ryu-tatsu ["PI:NAME:<NAME>END_PI"
"Special
Speed 3.
Power 5.
Range 1~2.
Guard 4.
Before: Advance 2.
Hit: If you advanced past your opponent during this Strike, gain Advantage.
Boost: Swift (+)
+1 Power and +1 Speed."]
:ryu-metsu-hadoken ["MetPI:NAME:<NAME>END_PI"
"Ultra (3 Gauge)
Speed 5.
Power 7.
Range 3~5.
After: Move up to 2.
Boost: Way of the Warrior (+)
1 Force Cost.
+2 Power and +2 Speed"]
:ryu-metsu-shoryuken ["PI:NAME:<NAME>END_PI"
"Ultra (4 Gauge)
5 Speed.
7 Power.
Range 1.
+3 Speed if the opponent initiated this Strike.
Boost: Lighting Reflexes
1 Force Cost
Move 2 then Strike."]}) |
[
{
"context": " Dexterity Vest\", :sell-in 9, :quality 0} {:name \"Aged Brie\", :sell-in 1, :quality 1} {:name \"Elixir of the M",
"end": 352,
"score": 0.907465398311615,
"start": 343,
"tag": "NAME",
"value": "Aged Brie"
}
] | clojure/spec/gilded_rose/core_spec.clj | santosh79/gilded-rose | 0 | (ns gilded-rose.core-spec
(:require [speclj.core :refer :all]
[clojure.test :refer :all]
[gilded-rose.core :refer [update-quality]]))
(deftest a-test
(testing "base case"
(let [
result '({:name "+5 Dexterity Vest", :sell-in 9, :quality 19} {:name "+6 Dexterity Vest", :sell-in 9, :quality 0} {:name "Aged Brie", :sell-in 1, :quality 1} {:name "Elixir of the Mongoose", :sell-in 4, :quality 6} {:name "Sulfuras, Hand Of Ragnaros", :sell-in -1, :quality 80} {:name "Backstage passes to a TAFKAL80ETC concert", :sell-in 14, :quality 21} {:name "Conjured", :sell-in 14, :quality 16})
]
(is (= (gilded-rose.core/update-current-inventory) result))))
)
| 78415 | (ns gilded-rose.core-spec
(:require [speclj.core :refer :all]
[clojure.test :refer :all]
[gilded-rose.core :refer [update-quality]]))
(deftest a-test
(testing "base case"
(let [
result '({:name "+5 Dexterity Vest", :sell-in 9, :quality 19} {:name "+6 Dexterity Vest", :sell-in 9, :quality 0} {:name "<NAME>", :sell-in 1, :quality 1} {:name "Elixir of the Mongoose", :sell-in 4, :quality 6} {:name "Sulfuras, Hand Of Ragnaros", :sell-in -1, :quality 80} {:name "Backstage passes to a TAFKAL80ETC concert", :sell-in 14, :quality 21} {:name "Conjured", :sell-in 14, :quality 16})
]
(is (= (gilded-rose.core/update-current-inventory) result))))
)
| true | (ns gilded-rose.core-spec
(:require [speclj.core :refer :all]
[clojure.test :refer :all]
[gilded-rose.core :refer [update-quality]]))
(deftest a-test
(testing "base case"
(let [
result '({:name "+5 Dexterity Vest", :sell-in 9, :quality 19} {:name "+6 Dexterity Vest", :sell-in 9, :quality 0} {:name "PI:NAME:<NAME>END_PI", :sell-in 1, :quality 1} {:name "Elixir of the Mongoose", :sell-in 4, :quality 6} {:name "Sulfuras, Hand Of Ragnaros", :sell-in -1, :quality 80} {:name "Backstage passes to a TAFKAL80ETC concert", :sell-in 14, :quality 21} {:name "Conjured", :sell-in 14, :quality 16})
]
(is (= (gilded-rose.core/update-current-inventory) result))))
)
|
[
{
"context": " of the templated target project.\"\n :author \"Paul Landes\"}\n zensols.mkproj.make-project\n (:require [cl",
"end": 115,
"score": 0.9998815655708313,
"start": 104,
"tag": "NAME",
"value": "Paul Landes"
}
] | src/clojure/zensols/mkproj/make_project.clj | plandes/clj-mkproj | 0 | (ns ^{:doc "The library that orchestrates the creation of the templated target project."
:author "Paul Landes"}
zensols.mkproj.make-project
(:require [clojure.java.io :as io]
[clojure.tools.logging :as log]
[clj-yaml.core :as yaml])
(:require [zensols.mkproj.velocity :as v]
[zensols.mkproj.config :as c]))
(def ^{:dynamic true :private true}
*generate-config*
"Top level template configuration")
(defn- write-template-reader
"Apply and write to the file system the template contents found in
**reader**. The template context (parameters) come
from [[*generate-context*]]. Write the output to **dst-file**. The **name**
parameter is usually useless for our usecase."
[reader name dst-file]
(let [{:keys [template-context]} *generate-config*]
(with-open [writer (io/writer dst-file)]
(binding [*out* writer]
(log/debugf "template context: %s" template-context)
(->> reader
(v/create-template-from-reader name)
(v/apply-template template-context)
print)))))
(defn- write-template-file
"Read a template from **src-file**, apply using
context [[*generate-context*]] and write it to **dst-file**.
See [[write-template-reader]]."
[src-file dst-file]
(with-open [reader (io/reader src-file)]
(write-template-reader reader (.getName src-file) dst-file)))
(defn- write-project-config
"Write the project configuration, **project-config** to the target templated
project in **dst-dir**. The file name comes from [[c/project-file-yaml]]."
[project-config dst-dir]
(let [dst-file (->> (c/project-file-yaml) (io/file dst-dir))]
(with-open [writer (io/writer dst-file)]
(binding [*out* writer]
(->> (yaml/generate-string project-config
:dumper-options {:flow-style :block})
println)))
(log/infof "wrote project config file: %s" dst-file)))
(defn- process-file
"Process a source file (**src-file**), optionally apply the template if not
an exclude file, and write it to the target templated
project (**dst-file**)."
[src-file dst-file]
(let [{:keys [generate]} *generate-config*
to-match (.getPath src-file)
exclude-tempify? (->> (:excludes generate)
(map #(re-find (re-pattern %) to-match))
(remove nil?)
first)
_ (log/debugf "processing file: %s -> %s (exclude=%s)"
to-match dst-file (not (nil? exclude-tempify?)))
dst-dir (.getParentFile dst-file)]
(log/tracef "exclude on %s: %s" to-match exclude-tempify?)
(if exclude-tempify?
(io/copy src-file dst-file)
(write-template-file src-file dst-file))
(log/infof "wrote %s %s -> %s"
(if exclude-tempify? "file" "template")
(.getPath src-file) dst-file)))
(defn- unfold-dirs
"Create a nested `java.io.File` by composition (constructor) from a
front-slash delimited path string. The current directory is given by
**cur-dir** and the destination path string is given in **dst-dir**."
[cur-dir dst-dir]
(if-not dst-dir
cur-dir
(let [[_ next-dir rest-dir] (re-find #"([^/]+)(\/.+)?" dst-dir)]
(unfold-dirs (io/file cur-dir next-dir) rest-dir))))
(declare process-directory)
(defn- process-files
"Process files **src-file** by optionally applying a template and writing
them to the **dst-dir** destination directory."
[template-context src-dir dst-dir src-files]
(let [file-mappings (c/file-mappings template-context src-dir)]
(log/debugf "file mappings: <%s>" (pr-str file-mappings))
(->> src-files
(map (fn [src-file]
(let [src-name (.getName src-file)
dst-name (or (get file-mappings src-name) src-name)
dst-file (io/file dst-dir dst-name)]
(log/tracef "%s, %s, %s, %s"
(get file-mappings src-name) src-name
dst-name dst-file)
(cond (.isFile src-file)
(process-file src-file dst-file)
(.isDirectory src-file)
(process-directory src-file dst-file)))))
doall)))
(defn- process-directory
"Process a source directory **src-dir** by copying or templating and then
copying files to destination directory **dst-dir**. Then apply recursively
to all directories."
[src-dir dst-dir]
(log/debugf "processing dir: %s -> %s" src-dir dst-dir)
(if (not (.exists src-dir))
(throw (ex-info (format "Directory not found: %s" src-dir)
{:src-dir src-dir})))
(log/infof "creating directory: %s" dst-dir)
(.mkdirs dst-dir)
(let [{:keys [template-context]} *generate-config*
confs (->> (c/directory-mappings template-context src-dir)
(map (fn [{:keys [source] :as m}]
(if m
{(name source) (dissoc m :source)})))
(apply merge))
dir-entries (.listFiles src-dir)]
(log/debugf "dir confs: %s" (pr-str confs))
(->> dir-entries
(remove (fn [file]
(or (and (.isFile file)
(= (.getName file) (c/project-dir-config)))
(contains? confs (.getName file)))))
(process-files template-context src-dir dst-dir))
(->> confs
(map (fn [[src {:keys [destination]}]]
(let [dst-dir (unfold-dirs dst-dir destination)
src-dir (io/file src-dir src)]
(log/debugf "dir interpolate: %s -> %s" src-dir dst-dir)
(process-directory src-dir dst-dir))))
doall)))
(defn make-project
"Create the project templated target found in **src-dir**. This directory
needs a [[project-file-yaml]] file and a directory
called [[c/project-file-name]].
You can change a parameter from what's given in the [[project-file-yaml]] by
providing **override-fn**. This function takes a key and a map with
`description`, `example` and `default` keys from the project file and returns
a value to use for that parameter."
[src-dir override-fn]
(log/infof "making project from %s" src-dir)
(let [env (c/project-environment src-dir :override-fn override-fn)
{template-directory :template-directory
template-context :context} env
{project "project"} template-context
dst-dir (io/file (.getParentFile (io/file template-directory)) project)
dst-project-file (io/file dst-dir (c/project-file-yaml))]
(assert project)
(log/infof "creating new project %s -> %s" src-dir dst-dir)
(.mkdirs dst-dir)
(binding [*generate-config* (merge (dissoc env :template-context)
{:template-context template-context})]
(process-directory (io/file src-dir c/project-file-name) dst-dir))))
(defn create-mapped-override-fn
"Default override function for [[make-project]]."
[map]
(fn [key def]
(get map key)))
| 84837 | (ns ^{:doc "The library that orchestrates the creation of the templated target project."
:author "<NAME>"}
zensols.mkproj.make-project
(:require [clojure.java.io :as io]
[clojure.tools.logging :as log]
[clj-yaml.core :as yaml])
(:require [zensols.mkproj.velocity :as v]
[zensols.mkproj.config :as c]))
(def ^{:dynamic true :private true}
*generate-config*
"Top level template configuration")
(defn- write-template-reader
"Apply and write to the file system the template contents found in
**reader**. The template context (parameters) come
from [[*generate-context*]]. Write the output to **dst-file**. The **name**
parameter is usually useless for our usecase."
[reader name dst-file]
(let [{:keys [template-context]} *generate-config*]
(with-open [writer (io/writer dst-file)]
(binding [*out* writer]
(log/debugf "template context: %s" template-context)
(->> reader
(v/create-template-from-reader name)
(v/apply-template template-context)
print)))))
(defn- write-template-file
"Read a template from **src-file**, apply using
context [[*generate-context*]] and write it to **dst-file**.
See [[write-template-reader]]."
[src-file dst-file]
(with-open [reader (io/reader src-file)]
(write-template-reader reader (.getName src-file) dst-file)))
(defn- write-project-config
"Write the project configuration, **project-config** to the target templated
project in **dst-dir**. The file name comes from [[c/project-file-yaml]]."
[project-config dst-dir]
(let [dst-file (->> (c/project-file-yaml) (io/file dst-dir))]
(with-open [writer (io/writer dst-file)]
(binding [*out* writer]
(->> (yaml/generate-string project-config
:dumper-options {:flow-style :block})
println)))
(log/infof "wrote project config file: %s" dst-file)))
(defn- process-file
"Process a source file (**src-file**), optionally apply the template if not
an exclude file, and write it to the target templated
project (**dst-file**)."
[src-file dst-file]
(let [{:keys [generate]} *generate-config*
to-match (.getPath src-file)
exclude-tempify? (->> (:excludes generate)
(map #(re-find (re-pattern %) to-match))
(remove nil?)
first)
_ (log/debugf "processing file: %s -> %s (exclude=%s)"
to-match dst-file (not (nil? exclude-tempify?)))
dst-dir (.getParentFile dst-file)]
(log/tracef "exclude on %s: %s" to-match exclude-tempify?)
(if exclude-tempify?
(io/copy src-file dst-file)
(write-template-file src-file dst-file))
(log/infof "wrote %s %s -> %s"
(if exclude-tempify? "file" "template")
(.getPath src-file) dst-file)))
(defn- unfold-dirs
"Create a nested `java.io.File` by composition (constructor) from a
front-slash delimited path string. The current directory is given by
**cur-dir** and the destination path string is given in **dst-dir**."
[cur-dir dst-dir]
(if-not dst-dir
cur-dir
(let [[_ next-dir rest-dir] (re-find #"([^/]+)(\/.+)?" dst-dir)]
(unfold-dirs (io/file cur-dir next-dir) rest-dir))))
(declare process-directory)
(defn- process-files
"Process files **src-file** by optionally applying a template and writing
them to the **dst-dir** destination directory."
[template-context src-dir dst-dir src-files]
(let [file-mappings (c/file-mappings template-context src-dir)]
(log/debugf "file mappings: <%s>" (pr-str file-mappings))
(->> src-files
(map (fn [src-file]
(let [src-name (.getName src-file)
dst-name (or (get file-mappings src-name) src-name)
dst-file (io/file dst-dir dst-name)]
(log/tracef "%s, %s, %s, %s"
(get file-mappings src-name) src-name
dst-name dst-file)
(cond (.isFile src-file)
(process-file src-file dst-file)
(.isDirectory src-file)
(process-directory src-file dst-file)))))
doall)))
(defn- process-directory
"Process a source directory **src-dir** by copying or templating and then
copying files to destination directory **dst-dir**. Then apply recursively
to all directories."
[src-dir dst-dir]
(log/debugf "processing dir: %s -> %s" src-dir dst-dir)
(if (not (.exists src-dir))
(throw (ex-info (format "Directory not found: %s" src-dir)
{:src-dir src-dir})))
(log/infof "creating directory: %s" dst-dir)
(.mkdirs dst-dir)
(let [{:keys [template-context]} *generate-config*
confs (->> (c/directory-mappings template-context src-dir)
(map (fn [{:keys [source] :as m}]
(if m
{(name source) (dissoc m :source)})))
(apply merge))
dir-entries (.listFiles src-dir)]
(log/debugf "dir confs: %s" (pr-str confs))
(->> dir-entries
(remove (fn [file]
(or (and (.isFile file)
(= (.getName file) (c/project-dir-config)))
(contains? confs (.getName file)))))
(process-files template-context src-dir dst-dir))
(->> confs
(map (fn [[src {:keys [destination]}]]
(let [dst-dir (unfold-dirs dst-dir destination)
src-dir (io/file src-dir src)]
(log/debugf "dir interpolate: %s -> %s" src-dir dst-dir)
(process-directory src-dir dst-dir))))
doall)))
(defn make-project
"Create the project templated target found in **src-dir**. This directory
needs a [[project-file-yaml]] file and a directory
called [[c/project-file-name]].
You can change a parameter from what's given in the [[project-file-yaml]] by
providing **override-fn**. This function takes a key and a map with
`description`, `example` and `default` keys from the project file and returns
a value to use for that parameter."
[src-dir override-fn]
(log/infof "making project from %s" src-dir)
(let [env (c/project-environment src-dir :override-fn override-fn)
{template-directory :template-directory
template-context :context} env
{project "project"} template-context
dst-dir (io/file (.getParentFile (io/file template-directory)) project)
dst-project-file (io/file dst-dir (c/project-file-yaml))]
(assert project)
(log/infof "creating new project %s -> %s" src-dir dst-dir)
(.mkdirs dst-dir)
(binding [*generate-config* (merge (dissoc env :template-context)
{:template-context template-context})]
(process-directory (io/file src-dir c/project-file-name) dst-dir))))
(defn create-mapped-override-fn
"Default override function for [[make-project]]."
[map]
(fn [key def]
(get map key)))
| true | (ns ^{:doc "The library that orchestrates the creation of the templated target project."
:author "PI:NAME:<NAME>END_PI"}
zensols.mkproj.make-project
(:require [clojure.java.io :as io]
[clojure.tools.logging :as log]
[clj-yaml.core :as yaml])
(:require [zensols.mkproj.velocity :as v]
[zensols.mkproj.config :as c]))
(def ^{:dynamic true :private true}
*generate-config*
"Top level template configuration")
(defn- write-template-reader
"Apply and write to the file system the template contents found in
**reader**. The template context (parameters) come
from [[*generate-context*]]. Write the output to **dst-file**. The **name**
parameter is usually useless for our usecase."
[reader name dst-file]
(let [{:keys [template-context]} *generate-config*]
(with-open [writer (io/writer dst-file)]
(binding [*out* writer]
(log/debugf "template context: %s" template-context)
(->> reader
(v/create-template-from-reader name)
(v/apply-template template-context)
print)))))
(defn- write-template-file
"Read a template from **src-file**, apply using
context [[*generate-context*]] and write it to **dst-file**.
See [[write-template-reader]]."
[src-file dst-file]
(with-open [reader (io/reader src-file)]
(write-template-reader reader (.getName src-file) dst-file)))
(defn- write-project-config
"Write the project configuration, **project-config** to the target templated
project in **dst-dir**. The file name comes from [[c/project-file-yaml]]."
[project-config dst-dir]
(let [dst-file (->> (c/project-file-yaml) (io/file dst-dir))]
(with-open [writer (io/writer dst-file)]
(binding [*out* writer]
(->> (yaml/generate-string project-config
:dumper-options {:flow-style :block})
println)))
(log/infof "wrote project config file: %s" dst-file)))
(defn- process-file
"Process a source file (**src-file**), optionally apply the template if not
an exclude file, and write it to the target templated
project (**dst-file**)."
[src-file dst-file]
(let [{:keys [generate]} *generate-config*
to-match (.getPath src-file)
exclude-tempify? (->> (:excludes generate)
(map #(re-find (re-pattern %) to-match))
(remove nil?)
first)
_ (log/debugf "processing file: %s -> %s (exclude=%s)"
to-match dst-file (not (nil? exclude-tempify?)))
dst-dir (.getParentFile dst-file)]
(log/tracef "exclude on %s: %s" to-match exclude-tempify?)
(if exclude-tempify?
(io/copy src-file dst-file)
(write-template-file src-file dst-file))
(log/infof "wrote %s %s -> %s"
(if exclude-tempify? "file" "template")
(.getPath src-file) dst-file)))
(defn- unfold-dirs
"Create a nested `java.io.File` by composition (constructor) from a
front-slash delimited path string. The current directory is given by
**cur-dir** and the destination path string is given in **dst-dir**."
[cur-dir dst-dir]
(if-not dst-dir
cur-dir
(let [[_ next-dir rest-dir] (re-find #"([^/]+)(\/.+)?" dst-dir)]
(unfold-dirs (io/file cur-dir next-dir) rest-dir))))
(declare process-directory)
(defn- process-files
"Process files **src-file** by optionally applying a template and writing
them to the **dst-dir** destination directory."
[template-context src-dir dst-dir src-files]
(let [file-mappings (c/file-mappings template-context src-dir)]
(log/debugf "file mappings: <%s>" (pr-str file-mappings))
(->> src-files
(map (fn [src-file]
(let [src-name (.getName src-file)
dst-name (or (get file-mappings src-name) src-name)
dst-file (io/file dst-dir dst-name)]
(log/tracef "%s, %s, %s, %s"
(get file-mappings src-name) src-name
dst-name dst-file)
(cond (.isFile src-file)
(process-file src-file dst-file)
(.isDirectory src-file)
(process-directory src-file dst-file)))))
doall)))
(defn- process-directory
"Process a source directory **src-dir** by copying or templating and then
copying files to destination directory **dst-dir**. Then apply recursively
to all directories."
[src-dir dst-dir]
(log/debugf "processing dir: %s -> %s" src-dir dst-dir)
(if (not (.exists src-dir))
(throw (ex-info (format "Directory not found: %s" src-dir)
{:src-dir src-dir})))
(log/infof "creating directory: %s" dst-dir)
(.mkdirs dst-dir)
(let [{:keys [template-context]} *generate-config*
confs (->> (c/directory-mappings template-context src-dir)
(map (fn [{:keys [source] :as m}]
(if m
{(name source) (dissoc m :source)})))
(apply merge))
dir-entries (.listFiles src-dir)]
(log/debugf "dir confs: %s" (pr-str confs))
(->> dir-entries
(remove (fn [file]
(or (and (.isFile file)
(= (.getName file) (c/project-dir-config)))
(contains? confs (.getName file)))))
(process-files template-context src-dir dst-dir))
(->> confs
(map (fn [[src {:keys [destination]}]]
(let [dst-dir (unfold-dirs dst-dir destination)
src-dir (io/file src-dir src)]
(log/debugf "dir interpolate: %s -> %s" src-dir dst-dir)
(process-directory src-dir dst-dir))))
doall)))
(defn make-project
"Create the project templated target found in **src-dir**. This directory
needs a [[project-file-yaml]] file and a directory
called [[c/project-file-name]].
You can change a parameter from what's given in the [[project-file-yaml]] by
providing **override-fn**. This function takes a key and a map with
`description`, `example` and `default` keys from the project file and returns
a value to use for that parameter."
[src-dir override-fn]
(log/infof "making project from %s" src-dir)
(let [env (c/project-environment src-dir :override-fn override-fn)
{template-directory :template-directory
template-context :context} env
{project "project"} template-context
dst-dir (io/file (.getParentFile (io/file template-directory)) project)
dst-project-file (io/file dst-dir (c/project-file-yaml))]
(assert project)
(log/infof "creating new project %s -> %s" src-dir dst-dir)
(.mkdirs dst-dir)
(binding [*generate-config* (merge (dissoc env :template-context)
{:template-context template-context})]
(process-directory (io/file src-dir c/project-file-name) dst-dir))))
(defn create-mapped-override-fn
"Default override function for [[make-project]]."
[map]
(fn [key def]
(get map key)))
|
[
{
"context": " api-endpoint \"/api\")\n(def csrf-token-header-key \"X-TEST-HELPER-CSRF\")\n\n;; fulcro doesn't append charset=UTF-8 to tran",
"end": 321,
"score": 0.9681361317634583,
"start": 303,
"tag": "KEY",
"value": "X-TEST-HELPER-CSRF"
}
] | test/server/com/grzm/sorty/server/test/api_helpers.clj | grzm/sorty | 0 | (ns com.grzm.sorty.server.test.api-helpers
(:require
[clojure.test :refer [is]]
[cognitect.transit :as ct]
[com.grzm.sorty.server.fulcro-util :as fu]
[fulcro.server :as fs]
[io.pedestal.log :as log]
[peridot.core :as p]))
(def api-endpoint "/api")
(def csrf-token-header-key "X-TEST-HELPER-CSRF")
;; fulcro doesn't append charset=UTF-8 to transit+json
(def transit+json "application/transit+json")
;; transit helpers
(defn edn->body [edn] (fu/write-transit edn))
(def body->edn fu/read-transit)
(defn response-csrf-token
"Extracts CSRF token from server response"
[response]
(get-in response [:headers csrf-token-header-key]))
(defn api-request
"Helper function to make Fulco Api requests"
[{:keys [response] :as state} edn]
(-> state
(p/request api-endpoint
:request-method :post
:body (edn->body edn)
:headers {"x-csrf-token" (response-csrf-token response)}
:content-type transit+json)))
(defn test-api-request
[state request-edn response-edn]
(-> state (api-request request-edn)
(doto ((fn [{:keys [response]}]
(let [{:keys [body status headers]} response]
(is (= transit+json (get headers "Content-Type")))
(is (= 200 status))
(is (= response-edn (body->edn body))))))))) | 18835 | (ns com.grzm.sorty.server.test.api-helpers
(:require
[clojure.test :refer [is]]
[cognitect.transit :as ct]
[com.grzm.sorty.server.fulcro-util :as fu]
[fulcro.server :as fs]
[io.pedestal.log :as log]
[peridot.core :as p]))
(def api-endpoint "/api")
(def csrf-token-header-key "<KEY>")
;; fulcro doesn't append charset=UTF-8 to transit+json
(def transit+json "application/transit+json")
;; transit helpers
(defn edn->body [edn] (fu/write-transit edn))
(def body->edn fu/read-transit)
(defn response-csrf-token
"Extracts CSRF token from server response"
[response]
(get-in response [:headers csrf-token-header-key]))
(defn api-request
"Helper function to make Fulco Api requests"
[{:keys [response] :as state} edn]
(-> state
(p/request api-endpoint
:request-method :post
:body (edn->body edn)
:headers {"x-csrf-token" (response-csrf-token response)}
:content-type transit+json)))
(defn test-api-request
[state request-edn response-edn]
(-> state (api-request request-edn)
(doto ((fn [{:keys [response]}]
(let [{:keys [body status headers]} response]
(is (= transit+json (get headers "Content-Type")))
(is (= 200 status))
(is (= response-edn (body->edn body))))))))) | true | (ns com.grzm.sorty.server.test.api-helpers
(:require
[clojure.test :refer [is]]
[cognitect.transit :as ct]
[com.grzm.sorty.server.fulcro-util :as fu]
[fulcro.server :as fs]
[io.pedestal.log :as log]
[peridot.core :as p]))
(def api-endpoint "/api")
(def csrf-token-header-key "PI:KEY:<KEY>END_PI")
;; fulcro doesn't append charset=UTF-8 to transit+json
(def transit+json "application/transit+json")
;; transit helpers
(defn edn->body [edn] (fu/write-transit edn))
(def body->edn fu/read-transit)
(defn response-csrf-token
"Extracts CSRF token from server response"
[response]
(get-in response [:headers csrf-token-header-key]))
(defn api-request
"Helper function to make Fulco Api requests"
[{:keys [response] :as state} edn]
(-> state
(p/request api-endpoint
:request-method :post
:body (edn->body edn)
:headers {"x-csrf-token" (response-csrf-token response)}
:content-type transit+json)))
(defn test-api-request
[state request-edn response-edn]
(-> state (api-request request-edn)
(doto ((fn [{:keys [response]}]
(let [{:keys [body status headers]} response]
(is (= transit+json (get headers "Content-Type")))
(is (= 200 status))
(is (= response-edn (body->edn body))))))))) |
[
{
"context": "ions date-opts\n :initiator {:name \"My epic name\"\n :email \"me@example.c",
"end": 2380,
"score": 0.9977262020111084,
"start": 2368,
"tag": "NAME",
"value": "My epic name"
},
{
"context": "My epic name\"\n :email \"me@example.com\"}}))\n\n [])\n",
"end": 2432,
"score": 0.999891459941864,
"start": 2418,
"tag": "EMAIL",
"value": "me@example.com"
}
] | src/doodlebot/api.clj | Akeboshiwind/tg-doodlebot | 0 | (ns doodlebot.api
(:require [org.httpkit.client :as http]
[cheshire.core :refer [generate-string parse-string]]
[clj-time.core :as t]
[clj-time.coerce :as c]
[clj-time.periodic :as p]
[doodlebot.utils :refer :all])
(:import [javax.net.ssl
SSLEngine
SSLParameters
SNIHostName]
[java.net URI]
[java.util Date]))
;;;; --- Private API --- ;;;;
(def ^:dynamic doodle-base-url "https://doodle.com/api/v2.0")
(defn- sni-configure
[^SSLEngine ssl-engine ^URI uri]
(let [^SSLParameters ssl-params (.getSSLParameters ssl-engine)]
(.setServerNames ssl-params [(SNIHostName. (.getHost uri))])
(.setSSLParameters ssl-engine ssl-params)))
(def ^:dynamic client (http/make-client {:ssl-configurer sni-configure}))
(defn- make-address
[endpoint]
(str doodle-base-url endpoint))
(defn- post
[endpoint payload]
(let [response @(http/post (make-address endpoint)
{:client client
:keep-alive 3000
:headers {"content-type" "application/json"}
:body payload})]
(when (= (:status response) 200)
response)))
(defn- post-json
[endpoint payload-str]
(-> (post endpoint (generate-string payload-str))
:body
(parse-string true)))
;;;; --- Public API --- ;;;;
(defn date->opt
"Given a joda time returns a correctly formatted option for doodle."
[date]
{:allday true
:start (c/to-long date)
:end nil})
(def default-opts
{:initiator {:notify true
:timeZone "Etc/GMT+12"}
:participants []
:comments []
:type "DATE"
:description ""
:preferencesType "YESNOIFNEEDBE"
:hidden false
:askAddress false
:askEmail false
:askPhone false
:locale "en"})
(defn make-poll
"Makes a new doodle poll."
[opts]
(let [opts (deep-merge default-opts opts)]
(post-json "/polls" (deep-merge default-opts opts))))
(defn poll-url
[id]
(str "https://doodle.com/poll/" id))
(comment
(def start-date (t/local-date 2019 4 22))
(def date-opts
(->> (p/periodic-seq start-date (t/days 1))
(map date->opt)
(take 7)))
(def d
(make-poll {:title "Dnd wen"
:options date-opts
:initiator {:name "My epic name"
:email "me@example.com"}}))
[])
| 36143 | (ns doodlebot.api
(:require [org.httpkit.client :as http]
[cheshire.core :refer [generate-string parse-string]]
[clj-time.core :as t]
[clj-time.coerce :as c]
[clj-time.periodic :as p]
[doodlebot.utils :refer :all])
(:import [javax.net.ssl
SSLEngine
SSLParameters
SNIHostName]
[java.net URI]
[java.util Date]))
;;;; --- Private API --- ;;;;
(def ^:dynamic doodle-base-url "https://doodle.com/api/v2.0")
(defn- sni-configure
[^SSLEngine ssl-engine ^URI uri]
(let [^SSLParameters ssl-params (.getSSLParameters ssl-engine)]
(.setServerNames ssl-params [(SNIHostName. (.getHost uri))])
(.setSSLParameters ssl-engine ssl-params)))
(def ^:dynamic client (http/make-client {:ssl-configurer sni-configure}))
(defn- make-address
[endpoint]
(str doodle-base-url endpoint))
(defn- post
[endpoint payload]
(let [response @(http/post (make-address endpoint)
{:client client
:keep-alive 3000
:headers {"content-type" "application/json"}
:body payload})]
(when (= (:status response) 200)
response)))
(defn- post-json
[endpoint payload-str]
(-> (post endpoint (generate-string payload-str))
:body
(parse-string true)))
;;;; --- Public API --- ;;;;
(defn date->opt
"Given a joda time returns a correctly formatted option for doodle."
[date]
{:allday true
:start (c/to-long date)
:end nil})
(def default-opts
{:initiator {:notify true
:timeZone "Etc/GMT+12"}
:participants []
:comments []
:type "DATE"
:description ""
:preferencesType "YESNOIFNEEDBE"
:hidden false
:askAddress false
:askEmail false
:askPhone false
:locale "en"})
(defn make-poll
"Makes a new doodle poll."
[opts]
(let [opts (deep-merge default-opts opts)]
(post-json "/polls" (deep-merge default-opts opts))))
(defn poll-url
[id]
(str "https://doodle.com/poll/" id))
(comment
(def start-date (t/local-date 2019 4 22))
(def date-opts
(->> (p/periodic-seq start-date (t/days 1))
(map date->opt)
(take 7)))
(def d
(make-poll {:title "Dnd wen"
:options date-opts
:initiator {:name "<NAME>"
:email "<EMAIL>"}}))
[])
| true | (ns doodlebot.api
(:require [org.httpkit.client :as http]
[cheshire.core :refer [generate-string parse-string]]
[clj-time.core :as t]
[clj-time.coerce :as c]
[clj-time.periodic :as p]
[doodlebot.utils :refer :all])
(:import [javax.net.ssl
SSLEngine
SSLParameters
SNIHostName]
[java.net URI]
[java.util Date]))
;;;; --- Private API --- ;;;;
(def ^:dynamic doodle-base-url "https://doodle.com/api/v2.0")
(defn- sni-configure
[^SSLEngine ssl-engine ^URI uri]
(let [^SSLParameters ssl-params (.getSSLParameters ssl-engine)]
(.setServerNames ssl-params [(SNIHostName. (.getHost uri))])
(.setSSLParameters ssl-engine ssl-params)))
(def ^:dynamic client (http/make-client {:ssl-configurer sni-configure}))
(defn- make-address
[endpoint]
(str doodle-base-url endpoint))
(defn- post
[endpoint payload]
(let [response @(http/post (make-address endpoint)
{:client client
:keep-alive 3000
:headers {"content-type" "application/json"}
:body payload})]
(when (= (:status response) 200)
response)))
(defn- post-json
[endpoint payload-str]
(-> (post endpoint (generate-string payload-str))
:body
(parse-string true)))
;;;; --- Public API --- ;;;;
(defn date->opt
"Given a joda time returns a correctly formatted option for doodle."
[date]
{:allday true
:start (c/to-long date)
:end nil})
(def default-opts
{:initiator {:notify true
:timeZone "Etc/GMT+12"}
:participants []
:comments []
:type "DATE"
:description ""
:preferencesType "YESNOIFNEEDBE"
:hidden false
:askAddress false
:askEmail false
:askPhone false
:locale "en"})
(defn make-poll
"Makes a new doodle poll."
[opts]
(let [opts (deep-merge default-opts opts)]
(post-json "/polls" (deep-merge default-opts opts))))
(defn poll-url
[id]
(str "https://doodle.com/poll/" id))
(comment
(def start-date (t/local-date 2019 4 22))
(def date-opts
(->> (p/periodic-seq start-date (t/days 1))
(map date->opt)
(take 7)))
(def d
(make-poll {:title "Dnd wen"
:options date-opts
:initiator {:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}}))
[])
|
[
{
"context": "ame\\\"\n :password \\\"a_bad_password\\\"}))\"\n [spec]\n (assoc spec\n :subprotoco",
"end": 621,
"score": 0.9994848370552063,
"start": 607,
"tag": "PASSWORD",
"value": "a_bad_password"
}
] | src/bedquilt/core.clj | BedquiltDB/clj-bedquilt | 7 | (ns bedquilt.core
(:require [clojure.java.jdbc :as j]
[cheshire.core :as json]
[bedquilt.utils :as utils])
(:refer-clojure :exclude [find count remove distinct]))
(defn make-db-spec
"Build a connection spec, same as a clojure.java.jdbc spec.
This function will add the appropriate PostgreSQL bits to the supplied
spec map.
See http://clojure.github.io/java.jdbc/#clojure.java.jdbc/get-connection.
Example:
(def spec (bq/make-db-spec {:subname \"//localhost/some_db\"
:user \"a_username\"
:password \"a_bad_password\"}))"
[spec]
(assoc spec
:subprotocol "postgresql"
:classname "org.postgresql.Driver"))
(defmacro with-connection
"Evaluates body expressions in the context of a single db connection.
Example:
(bq/with-connection [conn spec]
(bq/insert conn \"things\" {:a 1})
(bq/insert conn \"things\" {:a 2}))"
[binding & body]
`(j/with-db-connection ~binding ~@body))
(defn- query [spec query-vec]
(j/query spec query-vec))
(defn list-collections
"Get a list of collections on the server.
Returns a sequence of strings"
[spec]
(map :bq_result
(query spec ["select bq_list_collections() as bq_result;"])))
;; Collection Ops
(defn create-collection
"Create a collection if it does not already exist.
Returns boolean indicating whether the collection was created by this command."
[spec collection-name]
(first
(map :bq_result
(query spec ["select bq_create_collection(?) as bq_result"
collection-name]))))
(defn delete-collection
"Delete a collection if it exists.
Returns boolean indicating whether the collection was deleted by this command."
[spec collection-name]
(first
(map :bq_result
(query spec ["select bq_delete_collection(?) as bq_result"
collection-name]))))
(defn collection-exists?
"Check if a collection exists currently.
Returns boolean."
[spec collection-name]
(first
(map :bq_result
(query spec ["select bq_collection_exists(?) as bq_result"
collection-name]))))
;; Constraints
(defn add-constraints
"Add a set of constraints to the collection.
Returns true if any constraints were added by this command"
[spec collection-name constraints]
(first
(map :bq_result
(query spec ["select bq_add_constraints(?, ?::jsonb) as bq_result"
collection-name
(json/encode constraints)]))))
(defn remove-constraints
"Remove a set of constraints from the collection.
Returns true if any constraints were removed by this command"
[spec collection-name constraints]
(first
(map :bq_result
(query spec ["select bq_remove_constraints(?, ?::jsonb) as bq_result"
collection-name
(json/encode constraints)]))))
(defn list-constraints
"Get a list of constraints on this collection."
[spec collection-name]
(map :bq_result
(query spec ["select bq_list_constraints(?) as bq_result"
collection-name])))
;; TODO: various arities
;; Query Ops
(defn find
"Find documents from the collection matching a given query."
([spec collection-name]
(find spec collection-name {} {}))
([spec collection-name query-doc]
(find spec collection-name query-doc {}))
([spec collection-name query-doc {:keys [skip limit sort] :as options}]
(map :bq_result
(query spec
["select bq_find(?, ?::jsonb, ?::int, ?::int, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)
(or skip 0)
limit
(if sort (json/encode sort) nil)]))))
(defn find-one
"Find a single document from the collection matching a given query.
Returns a map, or nil if not found."
([spec collection-name]
(find-one spec collection-name {} {}))
([spec collection-name query-doc]
(find-one spec collection-name query-doc {}))
([spec collection-name query-doc {:keys [skip sort] :as options}]
(first
(map :bq_result
(query spec
["select bq_find_one(?, ?::jsonb, ?::int, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)
(or skip 0)
(if sort (json/encode sort) nil)])))))
(defn find-one-by-id
"Find a single document which has a _id equal to the supplied doc-id.
Returns a map, or nil if not found."
[spec collection-name doc-id]
(first
(map :bq_result
(query spec ["select bq_find_one_by_id(?, ?) as bq_result"
collection-name
doc-id]))))
(defn find-many-by-ids
"Find documents which have _id in the supplied sequence of doc-ids.
Returns a potentially empty sequence of docs."
[spec collection-name doc-ids]
(map :bq_result
(query spec ["select bq_find_many_by_ids(?, ?::jsonb) as bq_result"
collection-name
(json/encode doc-ids)])))
(defn count
"Get a count of documents in the collection."
([spec collection-name]
(count spec collection-name {}))
([spec collection-name query-doc]
(first
(map :bq_result
(query spec ["select bq_count(?, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)])))))
(defn distinct
"Get a sequence of unique values at the given dotted-path.
Example: (bq/distinct db \"people\" \"address.city\")"
[spec collection-name dotted-path]
(map :bq_result
(query spec ["select bq_distinct(?, ?) as bq_result"
collection-name
dotted-path])))
;; Write Ops
(defn insert
"Insert a document (map) into the collection"
[spec collection-name doc]
(first
(map :bq_result
(query spec ["select bq_insert(?, ?::jsonb) as bq_result"
collection-name
(json/encode doc)]))))
(defn save
"Save a document (map) to the collection, overwriting any existing
doc with the same _id value."
[spec collection-name doc]
(first
(map :bq_result
(query spec ["select bq_save(?, ?::jsonb) as bq_result"
collection-name
(json/encode doc)]))))
(defn remove
"Remove documunts matching the supplied query-doc."
[spec collection-name query-doc]
(first
(map :bq_result
(query spec ["select bq_remove(?, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)]))))
(defn remove-one
"Remove a single document matching the supplied query-doc."
[spec collection-name query-doc]
(first
(map :bq_result
(query spec ["select bq_remove_one(?, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)]))))
(defn remove-one-by-id
"Remove a single document which has a _id value matching the supplied doc-id."
[spec collection-name doc-id]
(first
(map :bq_result
(query spec ["select bq_remove_one_by_id(?, ?) as bq_result"
collection-name
doc-id]))))
(defn remove-many-by-ids
"Remove many documents, by their _id fields"
[spec collection-name doc-ids]
(first
(map :bq_result
(query spec ["select bq_remove_many_by_ids(?, ?::jsonb) as bq_result"
collection-name
(json/encode doc-ids)]))))
| 104491 | (ns bedquilt.core
(:require [clojure.java.jdbc :as j]
[cheshire.core :as json]
[bedquilt.utils :as utils])
(:refer-clojure :exclude [find count remove distinct]))
(defn make-db-spec
"Build a connection spec, same as a clojure.java.jdbc spec.
This function will add the appropriate PostgreSQL bits to the supplied
spec map.
See http://clojure.github.io/java.jdbc/#clojure.java.jdbc/get-connection.
Example:
(def spec (bq/make-db-spec {:subname \"//localhost/some_db\"
:user \"a_username\"
:password \"<PASSWORD>\"}))"
[spec]
(assoc spec
:subprotocol "postgresql"
:classname "org.postgresql.Driver"))
(defmacro with-connection
"Evaluates body expressions in the context of a single db connection.
Example:
(bq/with-connection [conn spec]
(bq/insert conn \"things\" {:a 1})
(bq/insert conn \"things\" {:a 2}))"
[binding & body]
`(j/with-db-connection ~binding ~@body))
(defn- query [spec query-vec]
(j/query spec query-vec))
(defn list-collections
"Get a list of collections on the server.
Returns a sequence of strings"
[spec]
(map :bq_result
(query spec ["select bq_list_collections() as bq_result;"])))
;; Collection Ops
(defn create-collection
"Create a collection if it does not already exist.
Returns boolean indicating whether the collection was created by this command."
[spec collection-name]
(first
(map :bq_result
(query spec ["select bq_create_collection(?) as bq_result"
collection-name]))))
(defn delete-collection
"Delete a collection if it exists.
Returns boolean indicating whether the collection was deleted by this command."
[spec collection-name]
(first
(map :bq_result
(query spec ["select bq_delete_collection(?) as bq_result"
collection-name]))))
(defn collection-exists?
"Check if a collection exists currently.
Returns boolean."
[spec collection-name]
(first
(map :bq_result
(query spec ["select bq_collection_exists(?) as bq_result"
collection-name]))))
;; Constraints
(defn add-constraints
"Add a set of constraints to the collection.
Returns true if any constraints were added by this command"
[spec collection-name constraints]
(first
(map :bq_result
(query spec ["select bq_add_constraints(?, ?::jsonb) as bq_result"
collection-name
(json/encode constraints)]))))
(defn remove-constraints
"Remove a set of constraints from the collection.
Returns true if any constraints were removed by this command"
[spec collection-name constraints]
(first
(map :bq_result
(query spec ["select bq_remove_constraints(?, ?::jsonb) as bq_result"
collection-name
(json/encode constraints)]))))
(defn list-constraints
"Get a list of constraints on this collection."
[spec collection-name]
(map :bq_result
(query spec ["select bq_list_constraints(?) as bq_result"
collection-name])))
;; TODO: various arities
;; Query Ops
(defn find
"Find documents from the collection matching a given query."
([spec collection-name]
(find spec collection-name {} {}))
([spec collection-name query-doc]
(find spec collection-name query-doc {}))
([spec collection-name query-doc {:keys [skip limit sort] :as options}]
(map :bq_result
(query spec
["select bq_find(?, ?::jsonb, ?::int, ?::int, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)
(or skip 0)
limit
(if sort (json/encode sort) nil)]))))
(defn find-one
"Find a single document from the collection matching a given query.
Returns a map, or nil if not found."
([spec collection-name]
(find-one spec collection-name {} {}))
([spec collection-name query-doc]
(find-one spec collection-name query-doc {}))
([spec collection-name query-doc {:keys [skip sort] :as options}]
(first
(map :bq_result
(query spec
["select bq_find_one(?, ?::jsonb, ?::int, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)
(or skip 0)
(if sort (json/encode sort) nil)])))))
(defn find-one-by-id
"Find a single document which has a _id equal to the supplied doc-id.
Returns a map, or nil if not found."
[spec collection-name doc-id]
(first
(map :bq_result
(query spec ["select bq_find_one_by_id(?, ?) as bq_result"
collection-name
doc-id]))))
(defn find-many-by-ids
"Find documents which have _id in the supplied sequence of doc-ids.
Returns a potentially empty sequence of docs."
[spec collection-name doc-ids]
(map :bq_result
(query spec ["select bq_find_many_by_ids(?, ?::jsonb) as bq_result"
collection-name
(json/encode doc-ids)])))
(defn count
"Get a count of documents in the collection."
([spec collection-name]
(count spec collection-name {}))
([spec collection-name query-doc]
(first
(map :bq_result
(query spec ["select bq_count(?, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)])))))
(defn distinct
"Get a sequence of unique values at the given dotted-path.
Example: (bq/distinct db \"people\" \"address.city\")"
[spec collection-name dotted-path]
(map :bq_result
(query spec ["select bq_distinct(?, ?) as bq_result"
collection-name
dotted-path])))
;; Write Ops
(defn insert
"Insert a document (map) into the collection"
[spec collection-name doc]
(first
(map :bq_result
(query spec ["select bq_insert(?, ?::jsonb) as bq_result"
collection-name
(json/encode doc)]))))
(defn save
"Save a document (map) to the collection, overwriting any existing
doc with the same _id value."
[spec collection-name doc]
(first
(map :bq_result
(query spec ["select bq_save(?, ?::jsonb) as bq_result"
collection-name
(json/encode doc)]))))
(defn remove
"Remove documunts matching the supplied query-doc."
[spec collection-name query-doc]
(first
(map :bq_result
(query spec ["select bq_remove(?, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)]))))
(defn remove-one
"Remove a single document matching the supplied query-doc."
[spec collection-name query-doc]
(first
(map :bq_result
(query spec ["select bq_remove_one(?, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)]))))
(defn remove-one-by-id
"Remove a single document which has a _id value matching the supplied doc-id."
[spec collection-name doc-id]
(first
(map :bq_result
(query spec ["select bq_remove_one_by_id(?, ?) as bq_result"
collection-name
doc-id]))))
(defn remove-many-by-ids
"Remove many documents, by their _id fields"
[spec collection-name doc-ids]
(first
(map :bq_result
(query spec ["select bq_remove_many_by_ids(?, ?::jsonb) as bq_result"
collection-name
(json/encode doc-ids)]))))
| true | (ns bedquilt.core
(:require [clojure.java.jdbc :as j]
[cheshire.core :as json]
[bedquilt.utils :as utils])
(:refer-clojure :exclude [find count remove distinct]))
(defn make-db-spec
"Build a connection spec, same as a clojure.java.jdbc spec.
This function will add the appropriate PostgreSQL bits to the supplied
spec map.
See http://clojure.github.io/java.jdbc/#clojure.java.jdbc/get-connection.
Example:
(def spec (bq/make-db-spec {:subname \"//localhost/some_db\"
:user \"a_username\"
:password \"PI:PASSWORD:<PASSWORD>END_PI\"}))"
[spec]
(assoc spec
:subprotocol "postgresql"
:classname "org.postgresql.Driver"))
(defmacro with-connection
"Evaluates body expressions in the context of a single db connection.
Example:
(bq/with-connection [conn spec]
(bq/insert conn \"things\" {:a 1})
(bq/insert conn \"things\" {:a 2}))"
[binding & body]
`(j/with-db-connection ~binding ~@body))
(defn- query [spec query-vec]
(j/query spec query-vec))
(defn list-collections
"Get a list of collections on the server.
Returns a sequence of strings"
[spec]
(map :bq_result
(query spec ["select bq_list_collections() as bq_result;"])))
;; Collection Ops
(defn create-collection
"Create a collection if it does not already exist.
Returns boolean indicating whether the collection was created by this command."
[spec collection-name]
(first
(map :bq_result
(query spec ["select bq_create_collection(?) as bq_result"
collection-name]))))
(defn delete-collection
"Delete a collection if it exists.
Returns boolean indicating whether the collection was deleted by this command."
[spec collection-name]
(first
(map :bq_result
(query spec ["select bq_delete_collection(?) as bq_result"
collection-name]))))
(defn collection-exists?
"Check if a collection exists currently.
Returns boolean."
[spec collection-name]
(first
(map :bq_result
(query spec ["select bq_collection_exists(?) as bq_result"
collection-name]))))
;; Constraints
(defn add-constraints
"Add a set of constraints to the collection.
Returns true if any constraints were added by this command"
[spec collection-name constraints]
(first
(map :bq_result
(query spec ["select bq_add_constraints(?, ?::jsonb) as bq_result"
collection-name
(json/encode constraints)]))))
(defn remove-constraints
"Remove a set of constraints from the collection.
Returns true if any constraints were removed by this command"
[spec collection-name constraints]
(first
(map :bq_result
(query spec ["select bq_remove_constraints(?, ?::jsonb) as bq_result"
collection-name
(json/encode constraints)]))))
(defn list-constraints
"Get a list of constraints on this collection."
[spec collection-name]
(map :bq_result
(query spec ["select bq_list_constraints(?) as bq_result"
collection-name])))
;; TODO: various arities
;; Query Ops
(defn find
"Find documents from the collection matching a given query."
([spec collection-name]
(find spec collection-name {} {}))
([spec collection-name query-doc]
(find spec collection-name query-doc {}))
([spec collection-name query-doc {:keys [skip limit sort] :as options}]
(map :bq_result
(query spec
["select bq_find(?, ?::jsonb, ?::int, ?::int, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)
(or skip 0)
limit
(if sort (json/encode sort) nil)]))))
(defn find-one
"Find a single document from the collection matching a given query.
Returns a map, or nil if not found."
([spec collection-name]
(find-one spec collection-name {} {}))
([spec collection-name query-doc]
(find-one spec collection-name query-doc {}))
([spec collection-name query-doc {:keys [skip sort] :as options}]
(first
(map :bq_result
(query spec
["select bq_find_one(?, ?::jsonb, ?::int, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)
(or skip 0)
(if sort (json/encode sort) nil)])))))
(defn find-one-by-id
"Find a single document which has a _id equal to the supplied doc-id.
Returns a map, or nil if not found."
[spec collection-name doc-id]
(first
(map :bq_result
(query spec ["select bq_find_one_by_id(?, ?) as bq_result"
collection-name
doc-id]))))
(defn find-many-by-ids
"Find documents which have _id in the supplied sequence of doc-ids.
Returns a potentially empty sequence of docs."
[spec collection-name doc-ids]
(map :bq_result
(query spec ["select bq_find_many_by_ids(?, ?::jsonb) as bq_result"
collection-name
(json/encode doc-ids)])))
(defn count
"Get a count of documents in the collection."
([spec collection-name]
(count spec collection-name {}))
([spec collection-name query-doc]
(first
(map :bq_result
(query spec ["select bq_count(?, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)])))))
(defn distinct
"Get a sequence of unique values at the given dotted-path.
Example: (bq/distinct db \"people\" \"address.city\")"
[spec collection-name dotted-path]
(map :bq_result
(query spec ["select bq_distinct(?, ?) as bq_result"
collection-name
dotted-path])))
;; Write Ops
(defn insert
"Insert a document (map) into the collection"
[spec collection-name doc]
(first
(map :bq_result
(query spec ["select bq_insert(?, ?::jsonb) as bq_result"
collection-name
(json/encode doc)]))))
(defn save
"Save a document (map) to the collection, overwriting any existing
doc with the same _id value."
[spec collection-name doc]
(first
(map :bq_result
(query spec ["select bq_save(?, ?::jsonb) as bq_result"
collection-name
(json/encode doc)]))))
(defn remove
"Remove documunts matching the supplied query-doc."
[spec collection-name query-doc]
(first
(map :bq_result
(query spec ["select bq_remove(?, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)]))))
(defn remove-one
"Remove a single document matching the supplied query-doc."
[spec collection-name query-doc]
(first
(map :bq_result
(query spec ["select bq_remove_one(?, ?::jsonb) as bq_result"
collection-name
(json/encode query-doc)]))))
(defn remove-one-by-id
"Remove a single document which has a _id value matching the supplied doc-id."
[spec collection-name doc-id]
(first
(map :bq_result
(query spec ["select bq_remove_one_by_id(?, ?) as bq_result"
collection-name
doc-id]))))
(defn remove-many-by-ids
"Remove many documents, by their _id fields"
[spec collection-name doc-ids]
(first
(map :bq_result
(query spec ["select bq_remove_many_by_ids(?, ?::jsonb) as bq_result"
collection-name
(json/encode doc-ids)]))))
|
[
{
"context": "figuration\n [user-domain-config]\n (let [{:keys [hashed-password clear-password gpg ssh-authorized-keys s",
"end": 1965,
"score": 0.9809753894805908,
"start": 1959,
"tag": "PASSWORD",
"value": "hashed"
},
{
"context": "ion\n [user-domain-config]\n (let [{:keys [hashed-password clear-password gpg ssh-authorized-keys ssh-key se",
"end": 1974,
"score": 0.5209448337554932,
"start": 1966,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ser-domain-config]\n (let [{:keys [hashed-password clear-password gpg ssh-authorized-keys ssh-key settings",
"end": 1980,
"score": 0.8813753128051758,
"start": 1975,
"tag": "PASSWORD",
"value": "clear"
},
{
"context": "-config :hashed-password)\n {:hashed-password hashed-password})\n (when (contains? user-domain-conf",
"end": 2154,
"score": 0.7805215716362,
"start": 2148,
"tag": "PASSWORD",
"value": "hashed"
},
{
"context": "in-config :clear-password)\n {:clear-password clear-password})\n (when (contains? user-domain-conf",
"end": 2253,
"score": 0.735004186630249,
"start": 2248,
"tag": "PASSWORD",
"value": "clear"
}
] | main/src/dda/pallet/dda_user_crate/convention.clj | DomainDrivenArchitecture/dda-user-crate | 3 | ; Licensed to the Apache Software Foundation (ASF) under one
; or more contributor license agreements. See the NOTICE file
; distributed with this work for additional information
; regarding copyright ownership. The ASF licenses this file
; to you 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.
(ns dda.pallet.dda-user-crate.convention
(:require
[schema.core :as s]
[dda.config.commons.ssh-key :as ssh-commons]
[dda.config.commons.gpg-key :as gpg-commons]
[dda.config.commons.map-utils :as mu]
[dda.pallet.commons.secret :as secret]
[clojure.tools.logging :as logging]
[dda.pallet.dda-user-crate.convention.ssh :as ssh]
[dda.pallet.dda-user-crate.infra :as infra]))
(def GpgKey {:public-key secret/Secret
(s/optional-key :passphrase) secret/Secret
(s/optional-key :private-key) secret/Secret})
(def Gpg
{(s/optional-key :gpg) {:trusted-key GpgKey}})
(def Ssh ssh/Ssh)
(def SshResolved ssh/SshResolved)
(def Settings {(s/optional-key :settings)
(hash-set (s/enum :sudo :bashrc-d))})
(def User
(s/either
(merge {:hashed-password secret/Secret}
Gpg Ssh Settings)
(merge {:clear-password secret/Secret}
Gpg Ssh Settings)))
(def UserDomainConfig {s/Keyword User})
(def UserDomainConfigResolved (secret/create-resolved-schema UserDomainConfig))
(def InfraResult {infra/facility infra/UserCrateConfig})
(defn-
user-infra-configuration
[user-domain-config]
(let [{:keys [hashed-password clear-password gpg ssh-authorized-keys ssh-key settings]} user-domain-config]
(merge
(when (contains? user-domain-config :hashed-password)
{:hashed-password hashed-password})
(when (contains? user-domain-config :clear-password)
{:clear-password clear-password})
(when (contains? user-domain-config :gpg)
{:gpg (mu/deep-merge gpg
{:trusted-key {:public-key-id (gpg-commons/hex-id (get-in gpg [:trusted-key :public-key]))}})})
(when (contains? user-domain-config :ssh-authorized-keys)
{:ssh-authorized-keys (ssh/authorized-keys-infra-configuration ssh-authorized-keys)})
(when (contains? user-domain-config :ssh-key)
{:ssh-key (ssh/key-pair-infra-configuration ssh-key)})
(when (contains? user-domain-config :settings)
{:settings settings}))))
(s/defn ^:always-validate
infra-configuration :- InfraResult
[domain-config :- UserDomainConfigResolved]
{infra/facility
(apply merge (map (fn [[k v]] {k (user-infra-configuration v)}) domain-config))})
| 102185 | ; Licensed to the Apache Software Foundation (ASF) under one
; or more contributor license agreements. See the NOTICE file
; distributed with this work for additional information
; regarding copyright ownership. The ASF licenses this file
; to you 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.
(ns dda.pallet.dda-user-crate.convention
(:require
[schema.core :as s]
[dda.config.commons.ssh-key :as ssh-commons]
[dda.config.commons.gpg-key :as gpg-commons]
[dda.config.commons.map-utils :as mu]
[dda.pallet.commons.secret :as secret]
[clojure.tools.logging :as logging]
[dda.pallet.dda-user-crate.convention.ssh :as ssh]
[dda.pallet.dda-user-crate.infra :as infra]))
(def GpgKey {:public-key secret/Secret
(s/optional-key :passphrase) secret/Secret
(s/optional-key :private-key) secret/Secret})
(def Gpg
{(s/optional-key :gpg) {:trusted-key GpgKey}})
(def Ssh ssh/Ssh)
(def SshResolved ssh/SshResolved)
(def Settings {(s/optional-key :settings)
(hash-set (s/enum :sudo :bashrc-d))})
(def User
(s/either
(merge {:hashed-password secret/Secret}
Gpg Ssh Settings)
(merge {:clear-password secret/Secret}
Gpg Ssh Settings)))
(def UserDomainConfig {s/Keyword User})
(def UserDomainConfigResolved (secret/create-resolved-schema UserDomainConfig))
(def InfraResult {infra/facility infra/UserCrateConfig})
(defn-
user-infra-configuration
[user-domain-config]
(let [{:keys [<PASSWORD>-<PASSWORD> <PASSWORD>-password gpg ssh-authorized-keys ssh-key settings]} user-domain-config]
(merge
(when (contains? user-domain-config :hashed-password)
{:hashed-password <PASSWORD>-password})
(when (contains? user-domain-config :clear-password)
{:clear-password <PASSWORD>-password})
(when (contains? user-domain-config :gpg)
{:gpg (mu/deep-merge gpg
{:trusted-key {:public-key-id (gpg-commons/hex-id (get-in gpg [:trusted-key :public-key]))}})})
(when (contains? user-domain-config :ssh-authorized-keys)
{:ssh-authorized-keys (ssh/authorized-keys-infra-configuration ssh-authorized-keys)})
(when (contains? user-domain-config :ssh-key)
{:ssh-key (ssh/key-pair-infra-configuration ssh-key)})
(when (contains? user-domain-config :settings)
{:settings settings}))))
(s/defn ^:always-validate
infra-configuration :- InfraResult
[domain-config :- UserDomainConfigResolved]
{infra/facility
(apply merge (map (fn [[k v]] {k (user-infra-configuration v)}) domain-config))})
| true | ; Licensed to the Apache Software Foundation (ASF) under one
; or more contributor license agreements. See the NOTICE file
; distributed with this work for additional information
; regarding copyright ownership. The ASF licenses this file
; to you 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.
(ns dda.pallet.dda-user-crate.convention
(:require
[schema.core :as s]
[dda.config.commons.ssh-key :as ssh-commons]
[dda.config.commons.gpg-key :as gpg-commons]
[dda.config.commons.map-utils :as mu]
[dda.pallet.commons.secret :as secret]
[clojure.tools.logging :as logging]
[dda.pallet.dda-user-crate.convention.ssh :as ssh]
[dda.pallet.dda-user-crate.infra :as infra]))
(def GpgKey {:public-key secret/Secret
(s/optional-key :passphrase) secret/Secret
(s/optional-key :private-key) secret/Secret})
(def Gpg
{(s/optional-key :gpg) {:trusted-key GpgKey}})
(def Ssh ssh/Ssh)
(def SshResolved ssh/SshResolved)
(def Settings {(s/optional-key :settings)
(hash-set (s/enum :sudo :bashrc-d))})
(def User
(s/either
(merge {:hashed-password secret/Secret}
Gpg Ssh Settings)
(merge {:clear-password secret/Secret}
Gpg Ssh Settings)))
(def UserDomainConfig {s/Keyword User})
(def UserDomainConfigResolved (secret/create-resolved-schema UserDomainConfig))
(def InfraResult {infra/facility infra/UserCrateConfig})
(defn-
user-infra-configuration
[user-domain-config]
(let [{:keys [PI:PASSWORD:<PASSWORD>END_PI-PI:PASSWORD:<PASSWORD>END_PI PI:PASSWORD:<PASSWORD>END_PI-password gpg ssh-authorized-keys ssh-key settings]} user-domain-config]
(merge
(when (contains? user-domain-config :hashed-password)
{:hashed-password PI:PASSWORD:<PASSWORD>END_PI-password})
(when (contains? user-domain-config :clear-password)
{:clear-password PI:PASSWORD:<PASSWORD>END_PI-password})
(when (contains? user-domain-config :gpg)
{:gpg (mu/deep-merge gpg
{:trusted-key {:public-key-id (gpg-commons/hex-id (get-in gpg [:trusted-key :public-key]))}})})
(when (contains? user-domain-config :ssh-authorized-keys)
{:ssh-authorized-keys (ssh/authorized-keys-infra-configuration ssh-authorized-keys)})
(when (contains? user-domain-config :ssh-key)
{:ssh-key (ssh/key-pair-infra-configuration ssh-key)})
(when (contains? user-domain-config :settings)
{:settings settings}))))
(s/defn ^:always-validate
infra-configuration :- InfraResult
[domain-config :- UserDomainConfigResolved]
{infra/facility
(apply merge (map (fn [[k v]] {k (user-infra-configuration v)}) domain-config))})
|
[
{
"context": "ogether form the well-known `eval`.\"\n\n {:author \"Adam Helinski\"}\n\n (:require [convex.cell :as $.cell]\n ",
"end": 558,
"score": 0.9996340274810791,
"start": 545,
"tag": "NAME",
"value": "Adam Helinski"
}
] | project/recipe/src/clj/main/convex/recipe/cvm.clj | rosejn/convex.cljc | 30 | (ns convex.recipe.cvm
"The CVM (Convex Virtual Machine) is the execution engine of the Convex network.
Whenever a query or a transaction is submitted to a peer, as seen in `convex.recipe.client`, peers
execute code given as a cell using the CVM.
This example provides an overview to get an idea of what is going on.
In essence, code undergoes the 3 steps that any true Lisp follows:
- Expansion, executing macros
- Compilation
- Execution
Those steps combined together form the well-known `eval`."
{:author "Adam Helinski"}
(:require [convex.cell :as $.cell]
[convex.cvm :as $.cvm]))
;;;;;;;;;;
(def ctx
"A `context` holds a state and allows executing operations. It is the heart of the CVM.
The state is effectively the network state that is composed of many things such as all accounts on the network.
However, when created as such, context holds a minimal state: a few required accounts, official Convex libraries and utilities."
($.cvm/ctx))
(def code
"Code to execute is a cell.
We use the star macro to convert the following Clojure data to an actual cell.
See `convex.recipe.cell` for more information about cells."
($.cell/* (if (< 1 50)
:lesser
:greater)))
;;;;;;;;;;
(comment
;; EVAL
;;
;; Executing code straightaway.
;; We get the result and stringify it so it is easier to read.
;;
(-> ($.cvm/eval ctx
code)
$.cvm/result)
;; EXPANSION
;;
;; In Convex, `if` is a macro that expands to low-level operation `cond`.
;;
(def expanded
(-> ($.cvm/expand ctx
code)
$.cvm/result))
expanded
;; COMPILATION
;;
;; We can see that our expanded code compiles indeed to the `cond` low-level operation.
;;
(def compiled
(-> ($.cvm/compile ctx
expanded)
$.cvm/result))
(class compiled)
;; EXECUTION
;;
;; Compile code is ready for execution.
;;
(-> ($.cvm/exec ctx
compiled)
$.cvm/result)
;;
;; Hence, Convex is (very probably) the first decentralized Lisp ever.
;;
;; Lisp has been mentioned in a couple of projects, even Ethereum, but it most often about s-expression.
;; Not a full language with lambdas, macros, and eval!
;;
;; This is useful for cutting on cost.
;;
;; When possible, it is best to compile code ahead before submitting it as a transaction. Otherwise
;; peers have to compile it themselves and overall execution is simply more expensive.
;;
(-> ($.cvm/expand-compile ctx
code)
$.cvm/result)
;; Preparing and executing code in any way uses 'juice'.
;;
;; Juice is a computational unit. More complex operations require more 'juice'. This is how the cost of
;; a transaction is computed.
;;
;; Hence, when using a context directly, it must be refilled once in a while otherwise we will get
;; an `OutOfJuiceException`.
;;
($.cvm/juice-refill ctx)
)
| 118711 | (ns convex.recipe.cvm
"The CVM (Convex Virtual Machine) is the execution engine of the Convex network.
Whenever a query or a transaction is submitted to a peer, as seen in `convex.recipe.client`, peers
execute code given as a cell using the CVM.
This example provides an overview to get an idea of what is going on.
In essence, code undergoes the 3 steps that any true Lisp follows:
- Expansion, executing macros
- Compilation
- Execution
Those steps combined together form the well-known `eval`."
{:author "<NAME>"}
(:require [convex.cell :as $.cell]
[convex.cvm :as $.cvm]))
;;;;;;;;;;
(def ctx
"A `context` holds a state and allows executing operations. It is the heart of the CVM.
The state is effectively the network state that is composed of many things such as all accounts on the network.
However, when created as such, context holds a minimal state: a few required accounts, official Convex libraries and utilities."
($.cvm/ctx))
(def code
"Code to execute is a cell.
We use the star macro to convert the following Clojure data to an actual cell.
See `convex.recipe.cell` for more information about cells."
($.cell/* (if (< 1 50)
:lesser
:greater)))
;;;;;;;;;;
(comment
;; EVAL
;;
;; Executing code straightaway.
;; We get the result and stringify it so it is easier to read.
;;
(-> ($.cvm/eval ctx
code)
$.cvm/result)
;; EXPANSION
;;
;; In Convex, `if` is a macro that expands to low-level operation `cond`.
;;
(def expanded
(-> ($.cvm/expand ctx
code)
$.cvm/result))
expanded
;; COMPILATION
;;
;; We can see that our expanded code compiles indeed to the `cond` low-level operation.
;;
(def compiled
(-> ($.cvm/compile ctx
expanded)
$.cvm/result))
(class compiled)
;; EXECUTION
;;
;; Compile code is ready for execution.
;;
(-> ($.cvm/exec ctx
compiled)
$.cvm/result)
;;
;; Hence, Convex is (very probably) the first decentralized Lisp ever.
;;
;; Lisp has been mentioned in a couple of projects, even Ethereum, but it most often about s-expression.
;; Not a full language with lambdas, macros, and eval!
;;
;; This is useful for cutting on cost.
;;
;; When possible, it is best to compile code ahead before submitting it as a transaction. Otherwise
;; peers have to compile it themselves and overall execution is simply more expensive.
;;
(-> ($.cvm/expand-compile ctx
code)
$.cvm/result)
;; Preparing and executing code in any way uses 'juice'.
;;
;; Juice is a computational unit. More complex operations require more 'juice'. This is how the cost of
;; a transaction is computed.
;;
;; Hence, when using a context directly, it must be refilled once in a while otherwise we will get
;; an `OutOfJuiceException`.
;;
($.cvm/juice-refill ctx)
)
| true | (ns convex.recipe.cvm
"The CVM (Convex Virtual Machine) is the execution engine of the Convex network.
Whenever a query or a transaction is submitted to a peer, as seen in `convex.recipe.client`, peers
execute code given as a cell using the CVM.
This example provides an overview to get an idea of what is going on.
In essence, code undergoes the 3 steps that any true Lisp follows:
- Expansion, executing macros
- Compilation
- Execution
Those steps combined together form the well-known `eval`."
{:author "PI:NAME:<NAME>END_PI"}
(:require [convex.cell :as $.cell]
[convex.cvm :as $.cvm]))
;;;;;;;;;;
(def ctx
"A `context` holds a state and allows executing operations. It is the heart of the CVM.
The state is effectively the network state that is composed of many things such as all accounts on the network.
However, when created as such, context holds a minimal state: a few required accounts, official Convex libraries and utilities."
($.cvm/ctx))
(def code
"Code to execute is a cell.
We use the star macro to convert the following Clojure data to an actual cell.
See `convex.recipe.cell` for more information about cells."
($.cell/* (if (< 1 50)
:lesser
:greater)))
;;;;;;;;;;
(comment
;; EVAL
;;
;; Executing code straightaway.
;; We get the result and stringify it so it is easier to read.
;;
(-> ($.cvm/eval ctx
code)
$.cvm/result)
;; EXPANSION
;;
;; In Convex, `if` is a macro that expands to low-level operation `cond`.
;;
(def expanded
(-> ($.cvm/expand ctx
code)
$.cvm/result))
expanded
;; COMPILATION
;;
;; We can see that our expanded code compiles indeed to the `cond` low-level operation.
;;
(def compiled
(-> ($.cvm/compile ctx
expanded)
$.cvm/result))
(class compiled)
;; EXECUTION
;;
;; Compile code is ready for execution.
;;
(-> ($.cvm/exec ctx
compiled)
$.cvm/result)
;;
;; Hence, Convex is (very probably) the first decentralized Lisp ever.
;;
;; Lisp has been mentioned in a couple of projects, even Ethereum, but it most often about s-expression.
;; Not a full language with lambdas, macros, and eval!
;;
;; This is useful for cutting on cost.
;;
;; When possible, it is best to compile code ahead before submitting it as a transaction. Otherwise
;; peers have to compile it themselves and overall execution is simply more expensive.
;;
(-> ($.cvm/expand-compile ctx
code)
$.cvm/result)
;; Preparing and executing code in any way uses 'juice'.
;;
;; Juice is a computational unit. More complex operations require more 'juice'. This is how the cost of
;; a transaction is computed.
;;
;; Hence, when using a context directly, it must be refilled once in a while otherwise we will get
;; an `OutOfJuiceException`.
;;
($.cvm/juice-refill ctx)
)
|
[
{
"context": ":div \"Password:\" [:br]\n (form/password-field \"password\")]\n [:div (form/submit-button \"Log in\")]\n [",
"end": 4463,
"score": 0.9937905669212341,
"start": 4455,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "rification!\n [user-id email]\n (let [token (util/generate-uuid)\n expires-at (jt/plus (jt/local-date-time)",
"end": 7334,
"score": 0.6424760818481445,
"start": 7321,
"tag": "KEY",
"value": "generate-uuid"
}
] | src/auth_template/service.clj | cjbarre/auth-template | 51 | (ns auth-template.service
(:require [io.pedestal.http :as http]
[io.pedestal.http.body-params :refer [body-params]]
[io.pedestal.http.secure-headers :as sec-headers]
[io.pedestal.http.csrf :as csrf]
[clojure.string :as str]
[ring.util.response :as ring-response]
[io.pedestal.interceptor.chain :as int-chain]
[auth-template.config :as config]
[hiccup.page :as page]
[hiccup.form :as form]
[clojure.spec.alpha :as s]
[buddy.hashers :as hashers]
[auth-template.db :as db]
[java-time :as jt]
[auth-template.email :refer [send-email-verification-email!
send-account-exists-email!
send-password-reset-email!
send-dummy-password-reset-email!]]
[auth-template.util :as util]
[auth-template.db-session-store :refer [->DbSessionStore]]))
;;;; Helpers
(defn response
([status body]
(response status body {}))
([status body headers]
{:status status :body body :headers headers}))
(def ok (partial response 200))
(def bad-request (partial response 400))
(def unauthorized (partial response 401))
(defn ok-html
[html]
(ok html {"Content-Type" "text/html"}))
(defn get-anti-forgery-token
[request]
;; Pulls from session if token exists there, otherwise pulls from request
(or (csrf/existing-token request)
(::csrf/anti-forgery-token request)))
(defn new-session
([request]
(new-session request nil))
([request user-id]
{:user-id user-id ;; If nil, it's an anonymous session
:user-agent (get-in request [:headers "user-agent"])
:ip-address (or (get-in request [:headers "x-real-ip"])
(:remote-addr request))
csrf/anti-forgery-token-str (::csrf/anti-forgery-token request)
:expires-at (jt/plus (jt/local-date-time)
(jt/minutes config/session-valid-minutes))}))
;;;; Validation
(def email-regex #"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$")
(s/def ::email (s/and string? #(re-matches email-regex %) #(<= (count %) 254)))
(defn validate-email
[email]
(when-not (s/valid? ::email email)
"Invalid email"))
(defn validate-password
[password]
(cond
(> (count password) 64) "Password cannot be more than 64 characters"
(< (count password) 8) "Password must be at least 8 characters"))
;;;; Views
(defn create-page
[title & content]
(page/html5
{:lang "en"}
[:head
[:meta {:charset "utf-8"}]
[:title title]
[:meta {:name "description" :content "Your description here"}]]
(apply conj [:body] content)))
(defn signup-page
[{:keys [anti-forgery-token email password password-repeated email-error password-error]}]
(create-page
"Sign up"
(form/form-to
[:post "/signup"]
(form/text-field {:type "hidden"} csrf/anti-forgery-token-str anti-forgery-token)
[:div
"Email:" [:br]
(form/text-field "email" email)
[:div email-error]]
[:div
"Password:" [:br]
(form/password-field "password" password)]
[:div
"Repeat password:" [:br]
(form/password-field "password-repeated" password-repeated)
[:div password-error]]
[:div
(form/submit-button "Sign up")]
[:div [:a {:href "/login"} "Have an account? Log in!"]])))
(defn email-verification-sent-page
[email]
(create-page
"Verify email"
[:div (format "Please check your email, %s, and click the link to verify your email address and begin using your account." email)]))
(defn email-verified-page
[]
(create-page
"Email verified"
[:div "Your email has been verified! "
[:a {:href (str config/root-app-url "/login")} "Click here"]
" to log in."]))
(defn email-verification-error-page
[]
(create-page
"Error verifying email"
[:div "There was an error verifying your email address. Please "
[:a {:href (str config/root-app-url "/login")} "click here"]
" to log in and have a new verification email sent to you."]))
(defn login-page
[{:keys [anti-forgery-token email error]}]
(create-page
"Log in"
(form/form-to
[:post "/login"]
(form/hidden-field csrf/anti-forgery-token-str anti-forgery-token)
[:div error]
[:div "Email:" [:br]
(form/text-field "email" email)]
[:div "Password:" [:br]
(form/password-field "password")]
[:div (form/submit-button "Log in")]
[:div [:a {:href "/forgotpassword"} "Forgot password?"]]
[:div [:a {:href "/signup"} "New user? Sign up!"]])))
(defn forgot-password-page
[{:keys [anti-forgery-token email email-error]}]
(create-page
"Forgot password"
(form/form-to
[:post "/forgotpassword"]
(form/hidden-field csrf/anti-forgery-token-str anti-forgery-token)
[:div "Enter the email you signed up with:" [:br]
(form/text-field "email" email)
[:div email-error]]
[:div (form/submit-button "Email password reset link")])))
(defn password-reset-email-sent-page
[email]
(create-page
"Password reset email sent"
[:div (format "If an account exists with that email address (%s), an email was sent with a link to reset the password." email)]))
(defn password-reset-page
[{:keys [anti-forgery-token reset-token error]}]
(create-page
"Reset password"
(form/form-to
[:post "/resetpassword"]
(form/hidden-field csrf/anti-forgery-token-str anti-forgery-token)
(form/hidden-field "reset-token" reset-token)
[:h3 "Reset your password"]
[:div "New password:" [:br]
(form/password-field "password")]
[:div "Repeat new password:" [:br]
(form/password-field "password-repeated")]
[:div error]
[:div (form/submit-button "Reset password")])))
(defn password-reset-error-page
[]
(create-page
"Password reset error"
[:div "The token for resetting your password has expired or does not exist. Please "
[:a {:href "/forgotpassword"} "click here"] " and enter your email to have another reset link sent to you."]))
(defn landing-page
[]
(create-page
"auth-template"
[:a {:href "/login"} "Log in"] " "
[:a {:href "/signup"} "Sign up"]
[:h1 "auth-template"]
[:p "App description and other content go here."]))
(defn app-page
[]
(create-page
"auth-template"
[:a {:href "/logout"} "Log out"]
[:br] [:br]
[:iframe {:width 560 :height 315
:src "https://www.youtube.com/embed/dQw4w9WgXcQ?controls=0&autoplay=true"
:frameborder 0}]
[:script {:src "/js/main.js" :type "text/javascript"}]))
;;;; Interceptors and handlers
(def anonymous-session
{:name ::anonymous-session
:leave
(fn [context]
(let [response (:response context)
session-key (:session/key response)
session (:session response)]
;; Checking if session is empty here allows handlers to set custom session data (this will not overwrite it)
(if (and (nil? session-key) (empty? session))
(assoc-in context [:response :session] (new-session (:request context)))
context)))})
(defn signup
[request]
(ok-html (signup-page {:anti-forgery-token (get-anti-forgery-token request)})))
(defn create-new-email-verification!
[user-id email]
(let [token (util/generate-uuid)
expires-at (jt/plus (jt/local-date-time)
(jt/minutes config/email-verification-token-valid-minutes))]
(db/insert-email-verification! user-id email token expires-at)
(send-email-verification-email! email token)))
(defn signup-submit
[request]
(let [email (get-in request [:form-params :email])
password (get-in request [:form-params :password])
password-repeated (get-in request [:form-params :password-repeated])
email-error (validate-email email)
password-error (if (= password password-repeated)
(validate-password password)
"Passwords did not match")]
(if (or email-error password-error)
(ok-html (signup-page {:email email
:email-error email-error
:password-error password-error
:anti-forgery-token (get-anti-forgery-token request)}))
(let [password-hash (hashers/derive password)]
(if (db/get-user-by-email email)
(do
(send-account-exists-email! email)
(ok-html (email-verification-sent-page email)))
(do
(db/insert-user! email password-hash)
(let [{user-id :users/id} (db/get-user-by-email email)]
(create-new-email-verification! user-id email)
(ok-html (email-verification-sent-page email)))))))))
(defn verify-email
[request]
(let [token (-> request :query-params :token)]
(if-let [verification (db/get-email-verification-by-token token)]
(let [expires-at (-> verification :email_verifications/expires_at (jt/local-date-time))
id (-> verification :email_verifications/id)]
(if (jt/before? (jt/local-date-time) expires-at)
(do
(db/set-email-verification-to-verified! id)
(ok-html (email-verified-page)))
(ok-html (email-verification-error-page))))
(ok-html (email-verification-error-page)))))
(defn login
[request]
(ok-html (login-page {:anti-forgery-token (get-anti-forgery-token request)})))
(defn login-submit
[request]
(let [email (get-in request [:form-params :email])
password (get-in request [:form-params :password])
email-error (validate-email email)
password-error (validate-password password)
email-or-password-incorrect-response
(ok-html (login-page {:anti-forgery-token (get-anti-forgery-token request)
:email email
:error "Email or password is incorrect"}))]
(if (or email-error password-error)
email-or-password-incorrect-response
(let [user (db/get-user-by-email email)
user-id (:users/id user)]
(if (and user (hashers/check password (:users/password_hash user)))
(if-let [email-verification (db/get-email-verification-for-user user-id email)]
(if (:email_verifications/verified email-verification)
(-> (ring-response/redirect "/")
(assoc :session (with-meta (new-session request user-id) {:recreate true})))
(let [expires-at (-> email-verification :email_verifications/expires_at (jt/local-date-time))]
(if (jt/before? (jt/local-date-time) expires-at)
(ok-html (email-verification-sent-page email))
(do
(create-new-email-verification! user-id email)
(ok-html (email-verification-sent-page email))))))
(do
(create-new-email-verification! user-id email)
(ok-html (email-verification-sent-page email))))
email-or-password-incorrect-response)))))
(defn logout
[_]
(-> (ring-response/redirect "/")
(assoc :session nil)))
(defn forgot-password
[request]
(ok-html (forgot-password-page {:anti-forgery-token (get-anti-forgery-token request)})))
(defn forgot-password-submit
[request]
(let [email (get-in request [:form-params :email])
email-error (validate-email email)]
(if email-error
(ok-html (forgot-password-page
{:anti-forgery-token (get-anti-forgery-token request)
:email email
:email-error email-error}))
(do
(if-let [user (db/get-user-by-email email)]
(let [token (util/generate-uuid)]
(db/insert-password-reset-token!
{:user-id (:users/id user)
:reset-token token
:expires-at (jt/plus (jt/local-date-time)
(jt/minutes config/password-reset-token-valid-minutes))})
(send-password-reset-email! email token))
;; Send an email either way to prevent time-based attacks
(send-dummy-password-reset-email! email))
(ok-html (password-reset-email-sent-page email))))))
(defn reset-password
[request]
(let [reset-token (-> request :query-params :token)]
(ok-html (password-reset-page
{:anti-forgery-token (get-anti-forgery-token request)
:reset-token reset-token}))))
(defn reset-password-submit
[request]
(let [password (get-in request [:form-params :password])
password-repeated (get-in request [:form-params :password-repeated])
reset-token (get-in request [:form-params :reset-token])
error (cond
(not= password password-repeated) "Passwords did not match"
:else (validate-password password))]
(if error
(ok-html (password-reset-page {:anti-forgery-token (get-anti-forgery-token request)
:error error
:reset-token reset-token}))
(if-let [{token-id :password_reset_tokens/id
user-id :password_reset_tokens/user_id}
(db/get-valid-password-reset-token reset-token)]
(let [password-hash (hashers/derive password)]
(db/set-password-reset-token-to-used! token-id)
(db/invalidate-user-sessions! user-id)
(db/set-password-hash-for-user! password-hash user-id)
(-> (ring-response/redirect "/")
(assoc :session (with-meta (new-session request user-id) {:recreate true}))))
(ok-html (password-reset-error-page))))))
(defn authenticated?
[request]
(boolean (get-in request [:session :identity])))
(def authenticate
{:name ::authenticate
:enter
(fn [context]
(let [request (:request context)]
(if (authenticated? request)
context
(int-chain/terminate (assoc context :response (ring-response/redirect "/"))))))})
(defn landing-or-app
[request]
(if (authenticated? request)
(ok-html (app-page))
(ok-html (landing-page))))
(def routes
#{["/" :get [anonymous-session landing-or-app] :route-name :landing-or-app]
["/signup" :get [anonymous-session signup] :route-name :signup]
["/signup" :post signup-submit :route-name :signup-submit]
["/verifyemail" :get [anonymous-session verify-email] :route-name :verify-email]
["/login" :get [anonymous-session login] :route-name :login]
["/login" :post [(body-params) login-submit] :route-name :login-submit]
["/logout" :get [logout] :route-name :logout]
["/forgotpassword" :get [anonymous-session forgot-password] :route-name :forgot-password]
["/forgotpassword" :post forgot-password-submit :route-name :forgot-password-submit]
["/resetpassword" :get [anonymous-session reset-password] :route-name :reset-password]
["/resetpassword" :post reset-password-submit :route-name :reset-password-submit]})
(def service {:env :prod
::http/routes routes
::http/resource-path "/public"
::http/type :jetty
::http/port config/service-port
::http/host "0.0.0.0"
::http/enable-session {:cookie-name config/session-cookie-name
:cookie-attrs {:http-only true
:secure true
:same-site :lax}
:store (->DbSessionStore)}
::http/enable-csrf {}
::http/secure-headers
{:content-security-policy-settings
;; This removes the default 'strict-dynamic' that pedestal adds to the CSP header script-src,
;; which requires a nonce or hash in the script tag.
;; You probably should modify this to how you see fit for your app, or use a nonce/hash.
;; See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
(sec-headers/content-security-policy-header
{:object-src "'none'"
:script-src "'unsafe-inline' 'unsafe-eval' https: http:"})}})
| 74392 | (ns auth-template.service
(:require [io.pedestal.http :as http]
[io.pedestal.http.body-params :refer [body-params]]
[io.pedestal.http.secure-headers :as sec-headers]
[io.pedestal.http.csrf :as csrf]
[clojure.string :as str]
[ring.util.response :as ring-response]
[io.pedestal.interceptor.chain :as int-chain]
[auth-template.config :as config]
[hiccup.page :as page]
[hiccup.form :as form]
[clojure.spec.alpha :as s]
[buddy.hashers :as hashers]
[auth-template.db :as db]
[java-time :as jt]
[auth-template.email :refer [send-email-verification-email!
send-account-exists-email!
send-password-reset-email!
send-dummy-password-reset-email!]]
[auth-template.util :as util]
[auth-template.db-session-store :refer [->DbSessionStore]]))
;;;; Helpers
(defn response
([status body]
(response status body {}))
([status body headers]
{:status status :body body :headers headers}))
(def ok (partial response 200))
(def bad-request (partial response 400))
(def unauthorized (partial response 401))
(defn ok-html
[html]
(ok html {"Content-Type" "text/html"}))
(defn get-anti-forgery-token
[request]
;; Pulls from session if token exists there, otherwise pulls from request
(or (csrf/existing-token request)
(::csrf/anti-forgery-token request)))
(defn new-session
([request]
(new-session request nil))
([request user-id]
{:user-id user-id ;; If nil, it's an anonymous session
:user-agent (get-in request [:headers "user-agent"])
:ip-address (or (get-in request [:headers "x-real-ip"])
(:remote-addr request))
csrf/anti-forgery-token-str (::csrf/anti-forgery-token request)
:expires-at (jt/plus (jt/local-date-time)
(jt/minutes config/session-valid-minutes))}))
;;;; Validation
(def email-regex #"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$")
(s/def ::email (s/and string? #(re-matches email-regex %) #(<= (count %) 254)))
(defn validate-email
[email]
(when-not (s/valid? ::email email)
"Invalid email"))
(defn validate-password
[password]
(cond
(> (count password) 64) "Password cannot be more than 64 characters"
(< (count password) 8) "Password must be at least 8 characters"))
;;;; Views
(defn create-page
[title & content]
(page/html5
{:lang "en"}
[:head
[:meta {:charset "utf-8"}]
[:title title]
[:meta {:name "description" :content "Your description here"}]]
(apply conj [:body] content)))
(defn signup-page
[{:keys [anti-forgery-token email password password-repeated email-error password-error]}]
(create-page
"Sign up"
(form/form-to
[:post "/signup"]
(form/text-field {:type "hidden"} csrf/anti-forgery-token-str anti-forgery-token)
[:div
"Email:" [:br]
(form/text-field "email" email)
[:div email-error]]
[:div
"Password:" [:br]
(form/password-field "password" password)]
[:div
"Repeat password:" [:br]
(form/password-field "password-repeated" password-repeated)
[:div password-error]]
[:div
(form/submit-button "Sign up")]
[:div [:a {:href "/login"} "Have an account? Log in!"]])))
(defn email-verification-sent-page
[email]
(create-page
"Verify email"
[:div (format "Please check your email, %s, and click the link to verify your email address and begin using your account." email)]))
(defn email-verified-page
[]
(create-page
"Email verified"
[:div "Your email has been verified! "
[:a {:href (str config/root-app-url "/login")} "Click here"]
" to log in."]))
(defn email-verification-error-page
[]
(create-page
"Error verifying email"
[:div "There was an error verifying your email address. Please "
[:a {:href (str config/root-app-url "/login")} "click here"]
" to log in and have a new verification email sent to you."]))
(defn login-page
[{:keys [anti-forgery-token email error]}]
(create-page
"Log in"
(form/form-to
[:post "/login"]
(form/hidden-field csrf/anti-forgery-token-str anti-forgery-token)
[:div error]
[:div "Email:" [:br]
(form/text-field "email" email)]
[:div "Password:" [:br]
(form/password-field "<PASSWORD>")]
[:div (form/submit-button "Log in")]
[:div [:a {:href "/forgotpassword"} "Forgot password?"]]
[:div [:a {:href "/signup"} "New user? Sign up!"]])))
(defn forgot-password-page
[{:keys [anti-forgery-token email email-error]}]
(create-page
"Forgot password"
(form/form-to
[:post "/forgotpassword"]
(form/hidden-field csrf/anti-forgery-token-str anti-forgery-token)
[:div "Enter the email you signed up with:" [:br]
(form/text-field "email" email)
[:div email-error]]
[:div (form/submit-button "Email password reset link")])))
(defn password-reset-email-sent-page
[email]
(create-page
"Password reset email sent"
[:div (format "If an account exists with that email address (%s), an email was sent with a link to reset the password." email)]))
(defn password-reset-page
[{:keys [anti-forgery-token reset-token error]}]
(create-page
"Reset password"
(form/form-to
[:post "/resetpassword"]
(form/hidden-field csrf/anti-forgery-token-str anti-forgery-token)
(form/hidden-field "reset-token" reset-token)
[:h3 "Reset your password"]
[:div "New password:" [:br]
(form/password-field "password")]
[:div "Repeat new password:" [:br]
(form/password-field "password-repeated")]
[:div error]
[:div (form/submit-button "Reset password")])))
(defn password-reset-error-page
[]
(create-page
"Password reset error"
[:div "The token for resetting your password has expired or does not exist. Please "
[:a {:href "/forgotpassword"} "click here"] " and enter your email to have another reset link sent to you."]))
(defn landing-page
[]
(create-page
"auth-template"
[:a {:href "/login"} "Log in"] " "
[:a {:href "/signup"} "Sign up"]
[:h1 "auth-template"]
[:p "App description and other content go here."]))
(defn app-page
[]
(create-page
"auth-template"
[:a {:href "/logout"} "Log out"]
[:br] [:br]
[:iframe {:width 560 :height 315
:src "https://www.youtube.com/embed/dQw4w9WgXcQ?controls=0&autoplay=true"
:frameborder 0}]
[:script {:src "/js/main.js" :type "text/javascript"}]))
;;;; Interceptors and handlers
(def anonymous-session
{:name ::anonymous-session
:leave
(fn [context]
(let [response (:response context)
session-key (:session/key response)
session (:session response)]
;; Checking if session is empty here allows handlers to set custom session data (this will not overwrite it)
(if (and (nil? session-key) (empty? session))
(assoc-in context [:response :session] (new-session (:request context)))
context)))})
(defn signup
[request]
(ok-html (signup-page {:anti-forgery-token (get-anti-forgery-token request)})))
(defn create-new-email-verification!
[user-id email]
(let [token (util/<KEY>)
expires-at (jt/plus (jt/local-date-time)
(jt/minutes config/email-verification-token-valid-minutes))]
(db/insert-email-verification! user-id email token expires-at)
(send-email-verification-email! email token)))
(defn signup-submit
[request]
(let [email (get-in request [:form-params :email])
password (get-in request [:form-params :password])
password-repeated (get-in request [:form-params :password-repeated])
email-error (validate-email email)
password-error (if (= password password-repeated)
(validate-password password)
"Passwords did not match")]
(if (or email-error password-error)
(ok-html (signup-page {:email email
:email-error email-error
:password-error password-error
:anti-forgery-token (get-anti-forgery-token request)}))
(let [password-hash (hashers/derive password)]
(if (db/get-user-by-email email)
(do
(send-account-exists-email! email)
(ok-html (email-verification-sent-page email)))
(do
(db/insert-user! email password-hash)
(let [{user-id :users/id} (db/get-user-by-email email)]
(create-new-email-verification! user-id email)
(ok-html (email-verification-sent-page email)))))))))
(defn verify-email
[request]
(let [token (-> request :query-params :token)]
(if-let [verification (db/get-email-verification-by-token token)]
(let [expires-at (-> verification :email_verifications/expires_at (jt/local-date-time))
id (-> verification :email_verifications/id)]
(if (jt/before? (jt/local-date-time) expires-at)
(do
(db/set-email-verification-to-verified! id)
(ok-html (email-verified-page)))
(ok-html (email-verification-error-page))))
(ok-html (email-verification-error-page)))))
(defn login
[request]
(ok-html (login-page {:anti-forgery-token (get-anti-forgery-token request)})))
(defn login-submit
[request]
(let [email (get-in request [:form-params :email])
password (get-in request [:form-params :password])
email-error (validate-email email)
password-error (validate-password password)
email-or-password-incorrect-response
(ok-html (login-page {:anti-forgery-token (get-anti-forgery-token request)
:email email
:error "Email or password is incorrect"}))]
(if (or email-error password-error)
email-or-password-incorrect-response
(let [user (db/get-user-by-email email)
user-id (:users/id user)]
(if (and user (hashers/check password (:users/password_hash user)))
(if-let [email-verification (db/get-email-verification-for-user user-id email)]
(if (:email_verifications/verified email-verification)
(-> (ring-response/redirect "/")
(assoc :session (with-meta (new-session request user-id) {:recreate true})))
(let [expires-at (-> email-verification :email_verifications/expires_at (jt/local-date-time))]
(if (jt/before? (jt/local-date-time) expires-at)
(ok-html (email-verification-sent-page email))
(do
(create-new-email-verification! user-id email)
(ok-html (email-verification-sent-page email))))))
(do
(create-new-email-verification! user-id email)
(ok-html (email-verification-sent-page email))))
email-or-password-incorrect-response)))))
(defn logout
[_]
(-> (ring-response/redirect "/")
(assoc :session nil)))
(defn forgot-password
[request]
(ok-html (forgot-password-page {:anti-forgery-token (get-anti-forgery-token request)})))
(defn forgot-password-submit
[request]
(let [email (get-in request [:form-params :email])
email-error (validate-email email)]
(if email-error
(ok-html (forgot-password-page
{:anti-forgery-token (get-anti-forgery-token request)
:email email
:email-error email-error}))
(do
(if-let [user (db/get-user-by-email email)]
(let [token (util/generate-uuid)]
(db/insert-password-reset-token!
{:user-id (:users/id user)
:reset-token token
:expires-at (jt/plus (jt/local-date-time)
(jt/minutes config/password-reset-token-valid-minutes))})
(send-password-reset-email! email token))
;; Send an email either way to prevent time-based attacks
(send-dummy-password-reset-email! email))
(ok-html (password-reset-email-sent-page email))))))
(defn reset-password
[request]
(let [reset-token (-> request :query-params :token)]
(ok-html (password-reset-page
{:anti-forgery-token (get-anti-forgery-token request)
:reset-token reset-token}))))
(defn reset-password-submit
[request]
(let [password (get-in request [:form-params :password])
password-repeated (get-in request [:form-params :password-repeated])
reset-token (get-in request [:form-params :reset-token])
error (cond
(not= password password-repeated) "Passwords did not match"
:else (validate-password password))]
(if error
(ok-html (password-reset-page {:anti-forgery-token (get-anti-forgery-token request)
:error error
:reset-token reset-token}))
(if-let [{token-id :password_reset_tokens/id
user-id :password_reset_tokens/user_id}
(db/get-valid-password-reset-token reset-token)]
(let [password-hash (hashers/derive password)]
(db/set-password-reset-token-to-used! token-id)
(db/invalidate-user-sessions! user-id)
(db/set-password-hash-for-user! password-hash user-id)
(-> (ring-response/redirect "/")
(assoc :session (with-meta (new-session request user-id) {:recreate true}))))
(ok-html (password-reset-error-page))))))
(defn authenticated?
[request]
(boolean (get-in request [:session :identity])))
(def authenticate
{:name ::authenticate
:enter
(fn [context]
(let [request (:request context)]
(if (authenticated? request)
context
(int-chain/terminate (assoc context :response (ring-response/redirect "/"))))))})
(defn landing-or-app
[request]
(if (authenticated? request)
(ok-html (app-page))
(ok-html (landing-page))))
(def routes
#{["/" :get [anonymous-session landing-or-app] :route-name :landing-or-app]
["/signup" :get [anonymous-session signup] :route-name :signup]
["/signup" :post signup-submit :route-name :signup-submit]
["/verifyemail" :get [anonymous-session verify-email] :route-name :verify-email]
["/login" :get [anonymous-session login] :route-name :login]
["/login" :post [(body-params) login-submit] :route-name :login-submit]
["/logout" :get [logout] :route-name :logout]
["/forgotpassword" :get [anonymous-session forgot-password] :route-name :forgot-password]
["/forgotpassword" :post forgot-password-submit :route-name :forgot-password-submit]
["/resetpassword" :get [anonymous-session reset-password] :route-name :reset-password]
["/resetpassword" :post reset-password-submit :route-name :reset-password-submit]})
(def service {:env :prod
::http/routes routes
::http/resource-path "/public"
::http/type :jetty
::http/port config/service-port
::http/host "0.0.0.0"
::http/enable-session {:cookie-name config/session-cookie-name
:cookie-attrs {:http-only true
:secure true
:same-site :lax}
:store (->DbSessionStore)}
::http/enable-csrf {}
::http/secure-headers
{:content-security-policy-settings
;; This removes the default 'strict-dynamic' that pedestal adds to the CSP header script-src,
;; which requires a nonce or hash in the script tag.
;; You probably should modify this to how you see fit for your app, or use a nonce/hash.
;; See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
(sec-headers/content-security-policy-header
{:object-src "'none'"
:script-src "'unsafe-inline' 'unsafe-eval' https: http:"})}})
| true | (ns auth-template.service
(:require [io.pedestal.http :as http]
[io.pedestal.http.body-params :refer [body-params]]
[io.pedestal.http.secure-headers :as sec-headers]
[io.pedestal.http.csrf :as csrf]
[clojure.string :as str]
[ring.util.response :as ring-response]
[io.pedestal.interceptor.chain :as int-chain]
[auth-template.config :as config]
[hiccup.page :as page]
[hiccup.form :as form]
[clojure.spec.alpha :as s]
[buddy.hashers :as hashers]
[auth-template.db :as db]
[java-time :as jt]
[auth-template.email :refer [send-email-verification-email!
send-account-exists-email!
send-password-reset-email!
send-dummy-password-reset-email!]]
[auth-template.util :as util]
[auth-template.db-session-store :refer [->DbSessionStore]]))
;;;; Helpers
(defn response
([status body]
(response status body {}))
([status body headers]
{:status status :body body :headers headers}))
(def ok (partial response 200))
(def bad-request (partial response 400))
(def unauthorized (partial response 401))
(defn ok-html
[html]
(ok html {"Content-Type" "text/html"}))
(defn get-anti-forgery-token
[request]
;; Pulls from session if token exists there, otherwise pulls from request
(or (csrf/existing-token request)
(::csrf/anti-forgery-token request)))
(defn new-session
([request]
(new-session request nil))
([request user-id]
{:user-id user-id ;; If nil, it's an anonymous session
:user-agent (get-in request [:headers "user-agent"])
:ip-address (or (get-in request [:headers "x-real-ip"])
(:remote-addr request))
csrf/anti-forgery-token-str (::csrf/anti-forgery-token request)
:expires-at (jt/plus (jt/local-date-time)
(jt/minutes config/session-valid-minutes))}))
;;;; Validation
(def email-regex #"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$")
(s/def ::email (s/and string? #(re-matches email-regex %) #(<= (count %) 254)))
(defn validate-email
[email]
(when-not (s/valid? ::email email)
"Invalid email"))
(defn validate-password
[password]
(cond
(> (count password) 64) "Password cannot be more than 64 characters"
(< (count password) 8) "Password must be at least 8 characters"))
;;;; Views
(defn create-page
[title & content]
(page/html5
{:lang "en"}
[:head
[:meta {:charset "utf-8"}]
[:title title]
[:meta {:name "description" :content "Your description here"}]]
(apply conj [:body] content)))
(defn signup-page
[{:keys [anti-forgery-token email password password-repeated email-error password-error]}]
(create-page
"Sign up"
(form/form-to
[:post "/signup"]
(form/text-field {:type "hidden"} csrf/anti-forgery-token-str anti-forgery-token)
[:div
"Email:" [:br]
(form/text-field "email" email)
[:div email-error]]
[:div
"Password:" [:br]
(form/password-field "password" password)]
[:div
"Repeat password:" [:br]
(form/password-field "password-repeated" password-repeated)
[:div password-error]]
[:div
(form/submit-button "Sign up")]
[:div [:a {:href "/login"} "Have an account? Log in!"]])))
(defn email-verification-sent-page
[email]
(create-page
"Verify email"
[:div (format "Please check your email, %s, and click the link to verify your email address and begin using your account." email)]))
(defn email-verified-page
[]
(create-page
"Email verified"
[:div "Your email has been verified! "
[:a {:href (str config/root-app-url "/login")} "Click here"]
" to log in."]))
(defn email-verification-error-page
[]
(create-page
"Error verifying email"
[:div "There was an error verifying your email address. Please "
[:a {:href (str config/root-app-url "/login")} "click here"]
" to log in and have a new verification email sent to you."]))
(defn login-page
[{:keys [anti-forgery-token email error]}]
(create-page
"Log in"
(form/form-to
[:post "/login"]
(form/hidden-field csrf/anti-forgery-token-str anti-forgery-token)
[:div error]
[:div "Email:" [:br]
(form/text-field "email" email)]
[:div "Password:" [:br]
(form/password-field "PI:PASSWORD:<PASSWORD>END_PI")]
[:div (form/submit-button "Log in")]
[:div [:a {:href "/forgotpassword"} "Forgot password?"]]
[:div [:a {:href "/signup"} "New user? Sign up!"]])))
(defn forgot-password-page
[{:keys [anti-forgery-token email email-error]}]
(create-page
"Forgot password"
(form/form-to
[:post "/forgotpassword"]
(form/hidden-field csrf/anti-forgery-token-str anti-forgery-token)
[:div "Enter the email you signed up with:" [:br]
(form/text-field "email" email)
[:div email-error]]
[:div (form/submit-button "Email password reset link")])))
(defn password-reset-email-sent-page
[email]
(create-page
"Password reset email sent"
[:div (format "If an account exists with that email address (%s), an email was sent with a link to reset the password." email)]))
(defn password-reset-page
[{:keys [anti-forgery-token reset-token error]}]
(create-page
"Reset password"
(form/form-to
[:post "/resetpassword"]
(form/hidden-field csrf/anti-forgery-token-str anti-forgery-token)
(form/hidden-field "reset-token" reset-token)
[:h3 "Reset your password"]
[:div "New password:" [:br]
(form/password-field "password")]
[:div "Repeat new password:" [:br]
(form/password-field "password-repeated")]
[:div error]
[:div (form/submit-button "Reset password")])))
(defn password-reset-error-page
[]
(create-page
"Password reset error"
[:div "The token for resetting your password has expired or does not exist. Please "
[:a {:href "/forgotpassword"} "click here"] " and enter your email to have another reset link sent to you."]))
(defn landing-page
[]
(create-page
"auth-template"
[:a {:href "/login"} "Log in"] " "
[:a {:href "/signup"} "Sign up"]
[:h1 "auth-template"]
[:p "App description and other content go here."]))
(defn app-page
[]
(create-page
"auth-template"
[:a {:href "/logout"} "Log out"]
[:br] [:br]
[:iframe {:width 560 :height 315
:src "https://www.youtube.com/embed/dQw4w9WgXcQ?controls=0&autoplay=true"
:frameborder 0}]
[:script {:src "/js/main.js" :type "text/javascript"}]))
;;;; Interceptors and handlers
(def anonymous-session
{:name ::anonymous-session
:leave
(fn [context]
(let [response (:response context)
session-key (:session/key response)
session (:session response)]
;; Checking if session is empty here allows handlers to set custom session data (this will not overwrite it)
(if (and (nil? session-key) (empty? session))
(assoc-in context [:response :session] (new-session (:request context)))
context)))})
(defn signup
[request]
(ok-html (signup-page {:anti-forgery-token (get-anti-forgery-token request)})))
(defn create-new-email-verification!
[user-id email]
(let [token (util/PI:KEY:<KEY>END_PI)
expires-at (jt/plus (jt/local-date-time)
(jt/minutes config/email-verification-token-valid-minutes))]
(db/insert-email-verification! user-id email token expires-at)
(send-email-verification-email! email token)))
(defn signup-submit
[request]
(let [email (get-in request [:form-params :email])
password (get-in request [:form-params :password])
password-repeated (get-in request [:form-params :password-repeated])
email-error (validate-email email)
password-error (if (= password password-repeated)
(validate-password password)
"Passwords did not match")]
(if (or email-error password-error)
(ok-html (signup-page {:email email
:email-error email-error
:password-error password-error
:anti-forgery-token (get-anti-forgery-token request)}))
(let [password-hash (hashers/derive password)]
(if (db/get-user-by-email email)
(do
(send-account-exists-email! email)
(ok-html (email-verification-sent-page email)))
(do
(db/insert-user! email password-hash)
(let [{user-id :users/id} (db/get-user-by-email email)]
(create-new-email-verification! user-id email)
(ok-html (email-verification-sent-page email)))))))))
(defn verify-email
[request]
(let [token (-> request :query-params :token)]
(if-let [verification (db/get-email-verification-by-token token)]
(let [expires-at (-> verification :email_verifications/expires_at (jt/local-date-time))
id (-> verification :email_verifications/id)]
(if (jt/before? (jt/local-date-time) expires-at)
(do
(db/set-email-verification-to-verified! id)
(ok-html (email-verified-page)))
(ok-html (email-verification-error-page))))
(ok-html (email-verification-error-page)))))
(defn login
[request]
(ok-html (login-page {:anti-forgery-token (get-anti-forgery-token request)})))
(defn login-submit
[request]
(let [email (get-in request [:form-params :email])
password (get-in request [:form-params :password])
email-error (validate-email email)
password-error (validate-password password)
email-or-password-incorrect-response
(ok-html (login-page {:anti-forgery-token (get-anti-forgery-token request)
:email email
:error "Email or password is incorrect"}))]
(if (or email-error password-error)
email-or-password-incorrect-response
(let [user (db/get-user-by-email email)
user-id (:users/id user)]
(if (and user (hashers/check password (:users/password_hash user)))
(if-let [email-verification (db/get-email-verification-for-user user-id email)]
(if (:email_verifications/verified email-verification)
(-> (ring-response/redirect "/")
(assoc :session (with-meta (new-session request user-id) {:recreate true})))
(let [expires-at (-> email-verification :email_verifications/expires_at (jt/local-date-time))]
(if (jt/before? (jt/local-date-time) expires-at)
(ok-html (email-verification-sent-page email))
(do
(create-new-email-verification! user-id email)
(ok-html (email-verification-sent-page email))))))
(do
(create-new-email-verification! user-id email)
(ok-html (email-verification-sent-page email))))
email-or-password-incorrect-response)))))
(defn logout
[_]
(-> (ring-response/redirect "/")
(assoc :session nil)))
(defn forgot-password
[request]
(ok-html (forgot-password-page {:anti-forgery-token (get-anti-forgery-token request)})))
(defn forgot-password-submit
[request]
(let [email (get-in request [:form-params :email])
email-error (validate-email email)]
(if email-error
(ok-html (forgot-password-page
{:anti-forgery-token (get-anti-forgery-token request)
:email email
:email-error email-error}))
(do
(if-let [user (db/get-user-by-email email)]
(let [token (util/generate-uuid)]
(db/insert-password-reset-token!
{:user-id (:users/id user)
:reset-token token
:expires-at (jt/plus (jt/local-date-time)
(jt/minutes config/password-reset-token-valid-minutes))})
(send-password-reset-email! email token))
;; Send an email either way to prevent time-based attacks
(send-dummy-password-reset-email! email))
(ok-html (password-reset-email-sent-page email))))))
(defn reset-password
[request]
(let [reset-token (-> request :query-params :token)]
(ok-html (password-reset-page
{:anti-forgery-token (get-anti-forgery-token request)
:reset-token reset-token}))))
(defn reset-password-submit
[request]
(let [password (get-in request [:form-params :password])
password-repeated (get-in request [:form-params :password-repeated])
reset-token (get-in request [:form-params :reset-token])
error (cond
(not= password password-repeated) "Passwords did not match"
:else (validate-password password))]
(if error
(ok-html (password-reset-page {:anti-forgery-token (get-anti-forgery-token request)
:error error
:reset-token reset-token}))
(if-let [{token-id :password_reset_tokens/id
user-id :password_reset_tokens/user_id}
(db/get-valid-password-reset-token reset-token)]
(let [password-hash (hashers/derive password)]
(db/set-password-reset-token-to-used! token-id)
(db/invalidate-user-sessions! user-id)
(db/set-password-hash-for-user! password-hash user-id)
(-> (ring-response/redirect "/")
(assoc :session (with-meta (new-session request user-id) {:recreate true}))))
(ok-html (password-reset-error-page))))))
(defn authenticated?
[request]
(boolean (get-in request [:session :identity])))
(def authenticate
{:name ::authenticate
:enter
(fn [context]
(let [request (:request context)]
(if (authenticated? request)
context
(int-chain/terminate (assoc context :response (ring-response/redirect "/"))))))})
(defn landing-or-app
[request]
(if (authenticated? request)
(ok-html (app-page))
(ok-html (landing-page))))
(def routes
#{["/" :get [anonymous-session landing-or-app] :route-name :landing-or-app]
["/signup" :get [anonymous-session signup] :route-name :signup]
["/signup" :post signup-submit :route-name :signup-submit]
["/verifyemail" :get [anonymous-session verify-email] :route-name :verify-email]
["/login" :get [anonymous-session login] :route-name :login]
["/login" :post [(body-params) login-submit] :route-name :login-submit]
["/logout" :get [logout] :route-name :logout]
["/forgotpassword" :get [anonymous-session forgot-password] :route-name :forgot-password]
["/forgotpassword" :post forgot-password-submit :route-name :forgot-password-submit]
["/resetpassword" :get [anonymous-session reset-password] :route-name :reset-password]
["/resetpassword" :post reset-password-submit :route-name :reset-password-submit]})
(def service {:env :prod
::http/routes routes
::http/resource-path "/public"
::http/type :jetty
::http/port config/service-port
::http/host "0.0.0.0"
::http/enable-session {:cookie-name config/session-cookie-name
:cookie-attrs {:http-only true
:secure true
:same-site :lax}
:store (->DbSessionStore)}
::http/enable-csrf {}
::http/secure-headers
{:content-security-policy-settings
;; This removes the default 'strict-dynamic' that pedestal adds to the CSP header script-src,
;; which requires a nonce or hash in the script tag.
;; You probably should modify this to how you see fit for your app, or use a nonce/hash.
;; See https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
(sec-headers/content-security-policy-header
{:object-src "'none'"
:script-src "'unsafe-inline' 'unsafe-eval' https: http:"})}})
|
[
{
"context": "supplied TSV files\n;; interactively in emacs using Jack Rusher's tsv-to-sexp lisp function:\n;;\n;;;; (defun tsv",
"end": 176,
"score": 0.735090434551239,
"start": 167,
"tag": "NAME",
"value": "Jack Rush"
}
] | src/vdquil/chapter4/ch4data.clj | Jjunior130/vdquil | 33 | ;; Data for exercises in Chapter 4
(ns vdquil.chapter4.ch4data)
;; Data (locations, names) was extracted from the supplied TSV files
;; interactively in emacs using Jack Rusher's tsv-to-sexp lisp function:
;;
;;;; (defun tsv-to-sexp (tsv)
;;;; "Parses the string `tsv` as a tab-separated-value file,
;;;; returning a sexp containing the values with strings converted to
;;;; numbers where appropriate."
;;;; (-map (lambda (s) (-map 'reformat-field (s-split "\t" s))) (s-lines tsv)))
(def milk-tea-coffee-data
'(("Year" "Milk" "Tea" "Coffee")
(1910 32.2 9.6 21.7)
(1911 31.3 10.2 19.7)
(1912 34.4 9.6 25.5)
(1913 33.1 8.5 21.2)
(1914 31.1 8.9 21.8)
(1915 29 9.6 25)
(1916 28 9.6 27.1)
(1917 29.7 11.3 28.6)
(1918 34 11.3 23.7)
(1919 30.4 5.8 27.9)
(1920 34 7.7 27.6)
(1921 33.2 6.5 28.4)
(1922 33.5 8 27.8)
(1923 32.5 8.5 29.9)
(1924 32.7 7.5 28.9)
(1925 33.6 8.1 25)
(1926 33.5 7.6 29.3)
(1927 33.2 6.9 28.7)
(1928 33.2 6.9 28.2)
(1929 33.4 6.8 28.7)
(1930 33.2 6.4 29.5)
(1931 33.2 6.5 30.7)
(1932 33.8 7.1 29.4)
(1933 33.7 7.2 30.1)
(1934 32.5 5.5 29.1)
(1935 33 6 31.7)
(1936 33.3 6 32.4)
(1937 33.5 6.4 31.4)
(1938 33.5 6.3 35.2)
(1939 34 6.6 35.2)
(1940 34 6.2 36.6)
(1941 34.4 7.3 38)
(1942 37 5.2 36.2)
(1943 41 5.7 33.1)
(1944 43.6 5.1 41.8)
(1945 44.7 5.2 44.4)
(1946 42.1 5.2 46.4)
(1947 39.9 5.4 40.8)
(1948 38.1 5.4 43.5)
(1949 37.5 5.7 45.1)
(1950 37.2 5.7 38.6)
(1951 37.5 6.1 39.5)
(1952 37.6 5.9 38)
(1953 37 6.2 37.3)
(1954 36.2 6.4 30.5)
(1955 36.2 6 32)
(1956 36.3 5.9 31.6)
(1957 35.9 5.5 30.6)
(1958 35.2 5.5 30.4)
(1959 34.4 5.5 30.9)
(1960 33.9 5.6 30.7)
(1961 33 5.8 31)
(1962 32.9 6 31)
(1963 33 6.2 30.8)
(1964 33 6.3 30.5)
(1965 32.9 6.4 29.4)
(1966 33 6.5 28.9)
(1967 31.4 6.6 29)
(1968 31.3 6.8 29.1)
(1969 31.1 6.8 27.6)
(1970 31.3 6.8 27.4)
(1971 31.3 7.2 25.7)
(1972 31 7.3 26.8)
(1973 30.5 7.4 25.8)
(1974 29.5 7.5 24.2)
(1975 29.5 7.5 23.3)
(1976 29.3 7.7 23.7)
(1977 29 7.5 17.2)
(1978 28.6 7.2 19.9)
(1979 28.2 6.9 21.7)
(1980 27.6 7.3 19.2)
(1981 27.1 7.2 18.7)
(1982 26.4 6.9 18.3)
(1983 26.3 7 18.5)
(1984 26.4 7.1 18.9)
(1985 26.7 7.1 19.3)
(1986 26.5 7.1 19.4)
(1987 26.1 6.9 18.8)
(1988 26.1 7 18.2)
(1989 26 6.9 18.8)
(1990 25.7 6.9 19.4)
(1991 25.5 7.4 19.5)
(1992 25.1 8 18.9)
(1993 24.4 8.3 17.2)
(1994 24.3 8.1 15.6)
(1995 23.9 7.9 15.3)
(1996 23.8 7.6 16.8)
(1997 23.4 7.2 17.9)
(1998 23 8.3 18.3)
(1999 22.9 8.2 19.3)
(2000 22.5 7.8 20)
(2001 22 8.2 18.5)
(2002 21.9 7.8 18.1)
(2003 21.6 7.5 18.5)
(2004 21.2 7.3 18.8)))
| 11739 | ;; Data for exercises in Chapter 4
(ns vdquil.chapter4.ch4data)
;; Data (locations, names) was extracted from the supplied TSV files
;; interactively in emacs using <NAME>er's tsv-to-sexp lisp function:
;;
;;;; (defun tsv-to-sexp (tsv)
;;;; "Parses the string `tsv` as a tab-separated-value file,
;;;; returning a sexp containing the values with strings converted to
;;;; numbers where appropriate."
;;;; (-map (lambda (s) (-map 'reformat-field (s-split "\t" s))) (s-lines tsv)))
(def milk-tea-coffee-data
'(("Year" "Milk" "Tea" "Coffee")
(1910 32.2 9.6 21.7)
(1911 31.3 10.2 19.7)
(1912 34.4 9.6 25.5)
(1913 33.1 8.5 21.2)
(1914 31.1 8.9 21.8)
(1915 29 9.6 25)
(1916 28 9.6 27.1)
(1917 29.7 11.3 28.6)
(1918 34 11.3 23.7)
(1919 30.4 5.8 27.9)
(1920 34 7.7 27.6)
(1921 33.2 6.5 28.4)
(1922 33.5 8 27.8)
(1923 32.5 8.5 29.9)
(1924 32.7 7.5 28.9)
(1925 33.6 8.1 25)
(1926 33.5 7.6 29.3)
(1927 33.2 6.9 28.7)
(1928 33.2 6.9 28.2)
(1929 33.4 6.8 28.7)
(1930 33.2 6.4 29.5)
(1931 33.2 6.5 30.7)
(1932 33.8 7.1 29.4)
(1933 33.7 7.2 30.1)
(1934 32.5 5.5 29.1)
(1935 33 6 31.7)
(1936 33.3 6 32.4)
(1937 33.5 6.4 31.4)
(1938 33.5 6.3 35.2)
(1939 34 6.6 35.2)
(1940 34 6.2 36.6)
(1941 34.4 7.3 38)
(1942 37 5.2 36.2)
(1943 41 5.7 33.1)
(1944 43.6 5.1 41.8)
(1945 44.7 5.2 44.4)
(1946 42.1 5.2 46.4)
(1947 39.9 5.4 40.8)
(1948 38.1 5.4 43.5)
(1949 37.5 5.7 45.1)
(1950 37.2 5.7 38.6)
(1951 37.5 6.1 39.5)
(1952 37.6 5.9 38)
(1953 37 6.2 37.3)
(1954 36.2 6.4 30.5)
(1955 36.2 6 32)
(1956 36.3 5.9 31.6)
(1957 35.9 5.5 30.6)
(1958 35.2 5.5 30.4)
(1959 34.4 5.5 30.9)
(1960 33.9 5.6 30.7)
(1961 33 5.8 31)
(1962 32.9 6 31)
(1963 33 6.2 30.8)
(1964 33 6.3 30.5)
(1965 32.9 6.4 29.4)
(1966 33 6.5 28.9)
(1967 31.4 6.6 29)
(1968 31.3 6.8 29.1)
(1969 31.1 6.8 27.6)
(1970 31.3 6.8 27.4)
(1971 31.3 7.2 25.7)
(1972 31 7.3 26.8)
(1973 30.5 7.4 25.8)
(1974 29.5 7.5 24.2)
(1975 29.5 7.5 23.3)
(1976 29.3 7.7 23.7)
(1977 29 7.5 17.2)
(1978 28.6 7.2 19.9)
(1979 28.2 6.9 21.7)
(1980 27.6 7.3 19.2)
(1981 27.1 7.2 18.7)
(1982 26.4 6.9 18.3)
(1983 26.3 7 18.5)
(1984 26.4 7.1 18.9)
(1985 26.7 7.1 19.3)
(1986 26.5 7.1 19.4)
(1987 26.1 6.9 18.8)
(1988 26.1 7 18.2)
(1989 26 6.9 18.8)
(1990 25.7 6.9 19.4)
(1991 25.5 7.4 19.5)
(1992 25.1 8 18.9)
(1993 24.4 8.3 17.2)
(1994 24.3 8.1 15.6)
(1995 23.9 7.9 15.3)
(1996 23.8 7.6 16.8)
(1997 23.4 7.2 17.9)
(1998 23 8.3 18.3)
(1999 22.9 8.2 19.3)
(2000 22.5 7.8 20)
(2001 22 8.2 18.5)
(2002 21.9 7.8 18.1)
(2003 21.6 7.5 18.5)
(2004 21.2 7.3 18.8)))
| true | ;; Data for exercises in Chapter 4
(ns vdquil.chapter4.ch4data)
;; Data (locations, names) was extracted from the supplied TSV files
;; interactively in emacs using PI:NAME:<NAME>END_PIer's tsv-to-sexp lisp function:
;;
;;;; (defun tsv-to-sexp (tsv)
;;;; "Parses the string `tsv` as a tab-separated-value file,
;;;; returning a sexp containing the values with strings converted to
;;;; numbers where appropriate."
;;;; (-map (lambda (s) (-map 'reformat-field (s-split "\t" s))) (s-lines tsv)))
(def milk-tea-coffee-data
'(("Year" "Milk" "Tea" "Coffee")
(1910 32.2 9.6 21.7)
(1911 31.3 10.2 19.7)
(1912 34.4 9.6 25.5)
(1913 33.1 8.5 21.2)
(1914 31.1 8.9 21.8)
(1915 29 9.6 25)
(1916 28 9.6 27.1)
(1917 29.7 11.3 28.6)
(1918 34 11.3 23.7)
(1919 30.4 5.8 27.9)
(1920 34 7.7 27.6)
(1921 33.2 6.5 28.4)
(1922 33.5 8 27.8)
(1923 32.5 8.5 29.9)
(1924 32.7 7.5 28.9)
(1925 33.6 8.1 25)
(1926 33.5 7.6 29.3)
(1927 33.2 6.9 28.7)
(1928 33.2 6.9 28.2)
(1929 33.4 6.8 28.7)
(1930 33.2 6.4 29.5)
(1931 33.2 6.5 30.7)
(1932 33.8 7.1 29.4)
(1933 33.7 7.2 30.1)
(1934 32.5 5.5 29.1)
(1935 33 6 31.7)
(1936 33.3 6 32.4)
(1937 33.5 6.4 31.4)
(1938 33.5 6.3 35.2)
(1939 34 6.6 35.2)
(1940 34 6.2 36.6)
(1941 34.4 7.3 38)
(1942 37 5.2 36.2)
(1943 41 5.7 33.1)
(1944 43.6 5.1 41.8)
(1945 44.7 5.2 44.4)
(1946 42.1 5.2 46.4)
(1947 39.9 5.4 40.8)
(1948 38.1 5.4 43.5)
(1949 37.5 5.7 45.1)
(1950 37.2 5.7 38.6)
(1951 37.5 6.1 39.5)
(1952 37.6 5.9 38)
(1953 37 6.2 37.3)
(1954 36.2 6.4 30.5)
(1955 36.2 6 32)
(1956 36.3 5.9 31.6)
(1957 35.9 5.5 30.6)
(1958 35.2 5.5 30.4)
(1959 34.4 5.5 30.9)
(1960 33.9 5.6 30.7)
(1961 33 5.8 31)
(1962 32.9 6 31)
(1963 33 6.2 30.8)
(1964 33 6.3 30.5)
(1965 32.9 6.4 29.4)
(1966 33 6.5 28.9)
(1967 31.4 6.6 29)
(1968 31.3 6.8 29.1)
(1969 31.1 6.8 27.6)
(1970 31.3 6.8 27.4)
(1971 31.3 7.2 25.7)
(1972 31 7.3 26.8)
(1973 30.5 7.4 25.8)
(1974 29.5 7.5 24.2)
(1975 29.5 7.5 23.3)
(1976 29.3 7.7 23.7)
(1977 29 7.5 17.2)
(1978 28.6 7.2 19.9)
(1979 28.2 6.9 21.7)
(1980 27.6 7.3 19.2)
(1981 27.1 7.2 18.7)
(1982 26.4 6.9 18.3)
(1983 26.3 7 18.5)
(1984 26.4 7.1 18.9)
(1985 26.7 7.1 19.3)
(1986 26.5 7.1 19.4)
(1987 26.1 6.9 18.8)
(1988 26.1 7 18.2)
(1989 26 6.9 18.8)
(1990 25.7 6.9 19.4)
(1991 25.5 7.4 19.5)
(1992 25.1 8 18.9)
(1993 24.4 8.3 17.2)
(1994 24.3 8.1 15.6)
(1995 23.9 7.9 15.3)
(1996 23.8 7.6 16.8)
(1997 23.4 7.2 17.9)
(1998 23 8.3 18.3)
(1999 22.9 8.2 19.3)
(2000 22.5 7.8 20)
(2001 22 8.2 18.5)
(2002 21.9 7.8 18.1)
(2003 21.6 7.5 18.5)
(2004 21.2 7.3 18.8)))
|
[
{
"context": "; Copyright 2020 Mark Wardle and Eldrix Ltd\n;\n; Licensed under the Apache Li",
"end": 28,
"score": 0.9998632669448853,
"start": 17,
"tag": "NAME",
"value": "Mark Wardle"
}
] | src/com/eldrix/hermes/core.clj | sidharthramesh/hermes | 0 | ; Copyright 2020 Mark Wardle and Eldrix Ltd
;
; 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.
;;;;
(ns com.eldrix.hermes.core
(:gen-class)
(:require [clojure.pprint :as pp]
[clojure.string :as str]
[clojure.tools.cli :as cli]
[clojure.tools.logging :as log]
[com.eldrix.hermes.config :as config]
[com.eldrix.hermes.import :as import]
[com.eldrix.hermes.terminology :as terminology]
[integrant.core :as ig]))
(defn import-from [{:keys [db]} args]
(if db
(let [dirs (if (= 0 (count args)) ["."] args)]
(terminology/import-snomed db dirs))
(log/error "no database directory specified")))
(defn list-from [_ args]
(let [dirs (if (= 0 (count args)) ["."] args)
metadata (map #(select-keys % [:name :effectiveTime :deltaFromDate :deltaToDate]) (mapcat import/all-metadata dirs))]
(pp/print-table metadata)
(doseq [dir dirs]
(let [files (import/importable-files dir)
heading (str "| Distribution files in " dir ":" (count files) " |")
banner (apply str (repeat (count heading) "="))]
(println "\n" banner "\n" heading "\n" banner)
(pp/print-table (map #(select-keys % [:filename :component :version-date :format :content-subtype :content-type]) files))))))
(defn build-indices [{:keys [db]} _]
(if db
(do (terminology/build-indices db)
(terminology/build-search-index db))
(log/error "no database directory specified")))
(defn compact [{:keys [db]} _]
(if db
(terminology/compact db)
(log/error "no database directory specified")))
(defn status [{:keys [db]} _]
(if db
(pp/pprint (terminology/get-status db))
(log/error "no database directory specified")))
(defn serve [{:keys [db port]} _]
(if db
(let [conf (-> (:ig/system (config/config :live))
(assoc-in [:terminology/service :path] db)
(assoc-in [:http/server :port] port)
(assoc-in [:http/server :join?] true))]
(log/info "starting terminology server " conf)
(ig/init conf))
(log/error "no database directory specified")))
(def cli-options
[["-p" "--port PORT" "Port number"
:default 8080
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]]
["-d" "--db PATH" "Path to database directory"
:validate [string? "Missing database path"]]
["-h" "--help"]])
(defn usage [options-summary]
(->> ["Usage: hermes [options] command [parameters]"
""
"Options:"
options-summary
""
"Commands:"
" import [paths] Import SNOMED distribution files from paths specified."
" list [paths] List importable files from the paths specified."
" index Build indexes"
" compact Compact database"
" serve Start a terminology server"
" status Displays status information"]
(str/join \newline)))
(def commands
{"import" {:fn import-from}
"list" {:fn list-from}
"index" {:fn build-indices}
"compact" {:fn compact}
"serve" {:fn serve}
"status" {:fn status}})
(defn exit [status msg]
(println msg)
(System/exit status))
(defn invoke-command [cmd opts args]
(if-let [f (:fn cmd)]
(f opts args)
(exit 1 "error: not implemented")))
(defn -main [& args]
(let [{:keys [options arguments summary errors]} (cli/parse-opts args cli-options)
command (get commands ((fnil str/lower-case "") (first arguments)))]
(cond
;; asking for help?
(:help options)
(println (usage summary))
;; if we have any errors, exit with error message(s)
errors
(exit 1 (str/join \newline errors))
;; if we have no command, exit with error message
(not command)
(exit 1 (str "invalid command\n" (usage summary)))
;; invoke command
:else (invoke-command command options (rest arguments)))))
(comment
) | 84857 | ; Copyright 2020 <NAME> and Eldrix Ltd
;
; 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.
;;;;
(ns com.eldrix.hermes.core
(:gen-class)
(:require [clojure.pprint :as pp]
[clojure.string :as str]
[clojure.tools.cli :as cli]
[clojure.tools.logging :as log]
[com.eldrix.hermes.config :as config]
[com.eldrix.hermes.import :as import]
[com.eldrix.hermes.terminology :as terminology]
[integrant.core :as ig]))
(defn import-from [{:keys [db]} args]
(if db
(let [dirs (if (= 0 (count args)) ["."] args)]
(terminology/import-snomed db dirs))
(log/error "no database directory specified")))
(defn list-from [_ args]
(let [dirs (if (= 0 (count args)) ["."] args)
metadata (map #(select-keys % [:name :effectiveTime :deltaFromDate :deltaToDate]) (mapcat import/all-metadata dirs))]
(pp/print-table metadata)
(doseq [dir dirs]
(let [files (import/importable-files dir)
heading (str "| Distribution files in " dir ":" (count files) " |")
banner (apply str (repeat (count heading) "="))]
(println "\n" banner "\n" heading "\n" banner)
(pp/print-table (map #(select-keys % [:filename :component :version-date :format :content-subtype :content-type]) files))))))
(defn build-indices [{:keys [db]} _]
(if db
(do (terminology/build-indices db)
(terminology/build-search-index db))
(log/error "no database directory specified")))
(defn compact [{:keys [db]} _]
(if db
(terminology/compact db)
(log/error "no database directory specified")))
(defn status [{:keys [db]} _]
(if db
(pp/pprint (terminology/get-status db))
(log/error "no database directory specified")))
(defn serve [{:keys [db port]} _]
(if db
(let [conf (-> (:ig/system (config/config :live))
(assoc-in [:terminology/service :path] db)
(assoc-in [:http/server :port] port)
(assoc-in [:http/server :join?] true))]
(log/info "starting terminology server " conf)
(ig/init conf))
(log/error "no database directory specified")))
(def cli-options
[["-p" "--port PORT" "Port number"
:default 8080
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]]
["-d" "--db PATH" "Path to database directory"
:validate [string? "Missing database path"]]
["-h" "--help"]])
(defn usage [options-summary]
(->> ["Usage: hermes [options] command [parameters]"
""
"Options:"
options-summary
""
"Commands:"
" import [paths] Import SNOMED distribution files from paths specified."
" list [paths] List importable files from the paths specified."
" index Build indexes"
" compact Compact database"
" serve Start a terminology server"
" status Displays status information"]
(str/join \newline)))
(def commands
{"import" {:fn import-from}
"list" {:fn list-from}
"index" {:fn build-indices}
"compact" {:fn compact}
"serve" {:fn serve}
"status" {:fn status}})
(defn exit [status msg]
(println msg)
(System/exit status))
(defn invoke-command [cmd opts args]
(if-let [f (:fn cmd)]
(f opts args)
(exit 1 "error: not implemented")))
(defn -main [& args]
(let [{:keys [options arguments summary errors]} (cli/parse-opts args cli-options)
command (get commands ((fnil str/lower-case "") (first arguments)))]
(cond
;; asking for help?
(:help options)
(println (usage summary))
;; if we have any errors, exit with error message(s)
errors
(exit 1 (str/join \newline errors))
;; if we have no command, exit with error message
(not command)
(exit 1 (str "invalid command\n" (usage summary)))
;; invoke command
:else (invoke-command command options (rest arguments)))))
(comment
) | true | ; Copyright 2020 PI:NAME:<NAME>END_PI and Eldrix Ltd
;
; 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.
;;;;
(ns com.eldrix.hermes.core
(:gen-class)
(:require [clojure.pprint :as pp]
[clojure.string :as str]
[clojure.tools.cli :as cli]
[clojure.tools.logging :as log]
[com.eldrix.hermes.config :as config]
[com.eldrix.hermes.import :as import]
[com.eldrix.hermes.terminology :as terminology]
[integrant.core :as ig]))
(defn import-from [{:keys [db]} args]
(if db
(let [dirs (if (= 0 (count args)) ["."] args)]
(terminology/import-snomed db dirs))
(log/error "no database directory specified")))
(defn list-from [_ args]
(let [dirs (if (= 0 (count args)) ["."] args)
metadata (map #(select-keys % [:name :effectiveTime :deltaFromDate :deltaToDate]) (mapcat import/all-metadata dirs))]
(pp/print-table metadata)
(doseq [dir dirs]
(let [files (import/importable-files dir)
heading (str "| Distribution files in " dir ":" (count files) " |")
banner (apply str (repeat (count heading) "="))]
(println "\n" banner "\n" heading "\n" banner)
(pp/print-table (map #(select-keys % [:filename :component :version-date :format :content-subtype :content-type]) files))))))
(defn build-indices [{:keys [db]} _]
(if db
(do (terminology/build-indices db)
(terminology/build-search-index db))
(log/error "no database directory specified")))
(defn compact [{:keys [db]} _]
(if db
(terminology/compact db)
(log/error "no database directory specified")))
(defn status [{:keys [db]} _]
(if db
(pp/pprint (terminology/get-status db))
(log/error "no database directory specified")))
(defn serve [{:keys [db port]} _]
(if db
(let [conf (-> (:ig/system (config/config :live))
(assoc-in [:terminology/service :path] db)
(assoc-in [:http/server :port] port)
(assoc-in [:http/server :join?] true))]
(log/info "starting terminology server " conf)
(ig/init conf))
(log/error "no database directory specified")))
(def cli-options
[["-p" "--port PORT" "Port number"
:default 8080
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]]
["-d" "--db PATH" "Path to database directory"
:validate [string? "Missing database path"]]
["-h" "--help"]])
(defn usage [options-summary]
(->> ["Usage: hermes [options] command [parameters]"
""
"Options:"
options-summary
""
"Commands:"
" import [paths] Import SNOMED distribution files from paths specified."
" list [paths] List importable files from the paths specified."
" index Build indexes"
" compact Compact database"
" serve Start a terminology server"
" status Displays status information"]
(str/join \newline)))
(def commands
{"import" {:fn import-from}
"list" {:fn list-from}
"index" {:fn build-indices}
"compact" {:fn compact}
"serve" {:fn serve}
"status" {:fn status}})
(defn exit [status msg]
(println msg)
(System/exit status))
(defn invoke-command [cmd opts args]
(if-let [f (:fn cmd)]
(f opts args)
(exit 1 "error: not implemented")))
(defn -main [& args]
(let [{:keys [options arguments summary errors]} (cli/parse-opts args cli-options)
command (get commands ((fnil str/lower-case "") (first arguments)))]
(cond
;; asking for help?
(:help options)
(println (usage summary))
;; if we have any errors, exit with error message(s)
errors
(exit 1 (str/join \newline errors))
;; if we have no command, exit with error message
(not command)
(exit 1 (str "invalid command\n" (usage summary)))
;; invoke command
:else (invoke-command command options (rest arguments)))))
(comment
) |
[
{
"context": "(let [s \"Hello, World\"]\n (println s))\n",
"end": 21,
"score": 0.7204849720001221,
"start": 16,
"tag": "NAME",
"value": "World"
}
] | clojure/hello-world.clj | AnselAtoms/blog-snippets | 0 | (let [s "Hello, World"]
(println s))
| 45913 | (let [s "Hello, <NAME>"]
(println s))
| true | (let [s "Hello, PI:NAME:<NAME>END_PI"]
(println s))
|
[
{
"context": ";;;; Copyright © 2011 Paul Stadig\n;;;;\n;;;; Licensed under the Apache License, Vers",
"end": 33,
"score": 0.9998817443847656,
"start": 22,
"tag": "NAME",
"value": "Paul Stadig"
}
] | test/migratus/test/core.clj | aclaimant/migratus | 0 | ;;;; Copyright © 2011 Paul Stadig
;;;;
;;;; 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.
(ns migratus.test.core
(:require [migratus.protocols :as proto]
[migratus.mock :as mock]
[clojure.test :refer :all]
[migratus.core :refer :all]
migratus.logger
[migratus.migrations :as mig]
[migratus.utils :as utils]
[clojure.java.io :as io])
(:import [migratus.mock MockStore MockMigration]))
(defn migrations [ups downs]
(for [n (range 4)]
(mock/make-migration
{:id (inc n) :name (str "id-" (inc n)) :ups ups :downs downs})))
(deftest test-migrate
(let [ups (atom [])
downs (atom [])
config {:store :mock
:completed-ids (atom #{1 3})}]
(with-redefs [mig/list-migrations (constantly (migrations ups downs))]
(migrate config))
(is (= [2 4] @ups))
(is (empty? @downs))))
(deftest test-up
(let [ups (atom [])
downs (atom [])
config {:store :mock
:completed-ids (atom #{1 3})}]
(with-redefs [mig/list-migrations (constantly (migrations ups downs))]
(testing "should bring up an uncompleted migration"
(up config 4 2)
(is (= [2 4] @ups))
(is (empty? @downs)))
(reset! ups [])
(reset! downs [])
(testing "should do nothing for a completed migration"
(up config 1)
(is (empty? @ups))
(is (empty? @downs))))))
(deftest test-down
(let [ups (atom [])
downs (atom [])
config {:store :mock
:completed-ids (atom #{1 3})}]
(with-redefs [mig/list-migrations (constantly (migrations ups downs))]
(testing "should bring down a completed migration"
(down config 1 3)
(is (empty? @ups))
(is (= [3 1] @downs)))
(reset! ups [])
(reset! downs [])
(testing "should do nothing for an uncompleted migration"
(down config 2)
(is (empty? @ups))
(is (empty? @downs))))))
(defn- migration-exists? [name & [dir]]
(when-let [migrations-dir (utils/find-migration-dir (or dir "migrations"))]
(->> (file-seq migrations-dir)
(map #(.getName %))
(filter #(.contains % name))
(not-empty))))
(deftest test-create-and-destroy
(let [migration "create-user"
migration-up "create-user.up.sql"
migration-down "create-user.down.sql"]
(testing "should create two migrations"
(create nil migration)
(is (migration-exists? migration-up))
(is (migration-exists? migration-down)))
(testing "should delete two migrations"
(destroy nil migration)
(is (empty? (migration-exists? migration-up)))
(is (empty? (migration-exists? migration-down))))))
(deftest test-create-and-destroy-edn
(let [migration "create-other-user"
migration-edn "create-other-user.edn"]
(testing "should create the migration"
(create nil migration :edn)
(is (migration-exists? migration-edn)))
(testing "should delete the migration"
(destroy nil migration)
(is (empty? (migration-exists? migration-edn))))))
(deftest test-create-missing-directory
(let [migration-dir "doesnt_exist"
config {:parent-migration-dir "test"
:migration-dir migration-dir}
migration "create-user"
migration-up "create-user.up.sql"
migration-down "create-user.down.sql"]
;; Make sure the directory doesn't exist before we start the test
(when (.exists (io/file "test" migration-dir))
(io/delete-file (io/file "test" migration-dir)))
(testing "when migration dir doesn't exist, it is created"
(is (nil? (utils/find-migration-dir migration-dir)))
(create config migration)
(is (not (nil? (utils/find-migration-dir migration-dir))))
(is (migration-exists? migration-up migration-dir))
(is (migration-exists? migration-down migration-dir)))
;; Clean up after ourselves
(when (.exists (io/file "test" migration-dir))
(destroy config migration)
(io/delete-file (io/file "test" migration-dir)))))
(deftest test-pending-list
(let [ups (atom [])
downs (atom [])
config {:store :mock
:completed-ids (atom #{1})}]
(with-redefs [mig/list-migrations (constantly (migrations ups downs))]
(testing "should return the list of pending migrations"
(is (= ["id-2" "id-3" "id-4"]
(migratus.core/pending-list config)))))))
(deftest supported-extensions
(testing "All supported extensions show up.
NOTE: when you add a protocol, to migratus core, update this test")
(is (= '("sql" "edn")
(proto/get-all-supported-extensions))))
| 110462 | ;;;; Copyright © 2011 <NAME>
;;;;
;;;; 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.
(ns migratus.test.core
(:require [migratus.protocols :as proto]
[migratus.mock :as mock]
[clojure.test :refer :all]
[migratus.core :refer :all]
migratus.logger
[migratus.migrations :as mig]
[migratus.utils :as utils]
[clojure.java.io :as io])
(:import [migratus.mock MockStore MockMigration]))
(defn migrations [ups downs]
(for [n (range 4)]
(mock/make-migration
{:id (inc n) :name (str "id-" (inc n)) :ups ups :downs downs})))
(deftest test-migrate
(let [ups (atom [])
downs (atom [])
config {:store :mock
:completed-ids (atom #{1 3})}]
(with-redefs [mig/list-migrations (constantly (migrations ups downs))]
(migrate config))
(is (= [2 4] @ups))
(is (empty? @downs))))
(deftest test-up
(let [ups (atom [])
downs (atom [])
config {:store :mock
:completed-ids (atom #{1 3})}]
(with-redefs [mig/list-migrations (constantly (migrations ups downs))]
(testing "should bring up an uncompleted migration"
(up config 4 2)
(is (= [2 4] @ups))
(is (empty? @downs)))
(reset! ups [])
(reset! downs [])
(testing "should do nothing for a completed migration"
(up config 1)
(is (empty? @ups))
(is (empty? @downs))))))
(deftest test-down
(let [ups (atom [])
downs (atom [])
config {:store :mock
:completed-ids (atom #{1 3})}]
(with-redefs [mig/list-migrations (constantly (migrations ups downs))]
(testing "should bring down a completed migration"
(down config 1 3)
(is (empty? @ups))
(is (= [3 1] @downs)))
(reset! ups [])
(reset! downs [])
(testing "should do nothing for an uncompleted migration"
(down config 2)
(is (empty? @ups))
(is (empty? @downs))))))
(defn- migration-exists? [name & [dir]]
(when-let [migrations-dir (utils/find-migration-dir (or dir "migrations"))]
(->> (file-seq migrations-dir)
(map #(.getName %))
(filter #(.contains % name))
(not-empty))))
(deftest test-create-and-destroy
(let [migration "create-user"
migration-up "create-user.up.sql"
migration-down "create-user.down.sql"]
(testing "should create two migrations"
(create nil migration)
(is (migration-exists? migration-up))
(is (migration-exists? migration-down)))
(testing "should delete two migrations"
(destroy nil migration)
(is (empty? (migration-exists? migration-up)))
(is (empty? (migration-exists? migration-down))))))
(deftest test-create-and-destroy-edn
(let [migration "create-other-user"
migration-edn "create-other-user.edn"]
(testing "should create the migration"
(create nil migration :edn)
(is (migration-exists? migration-edn)))
(testing "should delete the migration"
(destroy nil migration)
(is (empty? (migration-exists? migration-edn))))))
(deftest test-create-missing-directory
(let [migration-dir "doesnt_exist"
config {:parent-migration-dir "test"
:migration-dir migration-dir}
migration "create-user"
migration-up "create-user.up.sql"
migration-down "create-user.down.sql"]
;; Make sure the directory doesn't exist before we start the test
(when (.exists (io/file "test" migration-dir))
(io/delete-file (io/file "test" migration-dir)))
(testing "when migration dir doesn't exist, it is created"
(is (nil? (utils/find-migration-dir migration-dir)))
(create config migration)
(is (not (nil? (utils/find-migration-dir migration-dir))))
(is (migration-exists? migration-up migration-dir))
(is (migration-exists? migration-down migration-dir)))
;; Clean up after ourselves
(when (.exists (io/file "test" migration-dir))
(destroy config migration)
(io/delete-file (io/file "test" migration-dir)))))
(deftest test-pending-list
(let [ups (atom [])
downs (atom [])
config {:store :mock
:completed-ids (atom #{1})}]
(with-redefs [mig/list-migrations (constantly (migrations ups downs))]
(testing "should return the list of pending migrations"
(is (= ["id-2" "id-3" "id-4"]
(migratus.core/pending-list config)))))))
(deftest supported-extensions
(testing "All supported extensions show up.
NOTE: when you add a protocol, to migratus core, update this test")
(is (= '("sql" "edn")
(proto/get-all-supported-extensions))))
| true | ;;;; Copyright © 2011 PI:NAME:<NAME>END_PI
;;;;
;;;; 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.
(ns migratus.test.core
(:require [migratus.protocols :as proto]
[migratus.mock :as mock]
[clojure.test :refer :all]
[migratus.core :refer :all]
migratus.logger
[migratus.migrations :as mig]
[migratus.utils :as utils]
[clojure.java.io :as io])
(:import [migratus.mock MockStore MockMigration]))
(defn migrations [ups downs]
(for [n (range 4)]
(mock/make-migration
{:id (inc n) :name (str "id-" (inc n)) :ups ups :downs downs})))
(deftest test-migrate
(let [ups (atom [])
downs (atom [])
config {:store :mock
:completed-ids (atom #{1 3})}]
(with-redefs [mig/list-migrations (constantly (migrations ups downs))]
(migrate config))
(is (= [2 4] @ups))
(is (empty? @downs))))
(deftest test-up
(let [ups (atom [])
downs (atom [])
config {:store :mock
:completed-ids (atom #{1 3})}]
(with-redefs [mig/list-migrations (constantly (migrations ups downs))]
(testing "should bring up an uncompleted migration"
(up config 4 2)
(is (= [2 4] @ups))
(is (empty? @downs)))
(reset! ups [])
(reset! downs [])
(testing "should do nothing for a completed migration"
(up config 1)
(is (empty? @ups))
(is (empty? @downs))))))
(deftest test-down
(let [ups (atom [])
downs (atom [])
config {:store :mock
:completed-ids (atom #{1 3})}]
(with-redefs [mig/list-migrations (constantly (migrations ups downs))]
(testing "should bring down a completed migration"
(down config 1 3)
(is (empty? @ups))
(is (= [3 1] @downs)))
(reset! ups [])
(reset! downs [])
(testing "should do nothing for an uncompleted migration"
(down config 2)
(is (empty? @ups))
(is (empty? @downs))))))
(defn- migration-exists? [name & [dir]]
(when-let [migrations-dir (utils/find-migration-dir (or dir "migrations"))]
(->> (file-seq migrations-dir)
(map #(.getName %))
(filter #(.contains % name))
(not-empty))))
(deftest test-create-and-destroy
(let [migration "create-user"
migration-up "create-user.up.sql"
migration-down "create-user.down.sql"]
(testing "should create two migrations"
(create nil migration)
(is (migration-exists? migration-up))
(is (migration-exists? migration-down)))
(testing "should delete two migrations"
(destroy nil migration)
(is (empty? (migration-exists? migration-up)))
(is (empty? (migration-exists? migration-down))))))
(deftest test-create-and-destroy-edn
(let [migration "create-other-user"
migration-edn "create-other-user.edn"]
(testing "should create the migration"
(create nil migration :edn)
(is (migration-exists? migration-edn)))
(testing "should delete the migration"
(destroy nil migration)
(is (empty? (migration-exists? migration-edn))))))
(deftest test-create-missing-directory
(let [migration-dir "doesnt_exist"
config {:parent-migration-dir "test"
:migration-dir migration-dir}
migration "create-user"
migration-up "create-user.up.sql"
migration-down "create-user.down.sql"]
;; Make sure the directory doesn't exist before we start the test
(when (.exists (io/file "test" migration-dir))
(io/delete-file (io/file "test" migration-dir)))
(testing "when migration dir doesn't exist, it is created"
(is (nil? (utils/find-migration-dir migration-dir)))
(create config migration)
(is (not (nil? (utils/find-migration-dir migration-dir))))
(is (migration-exists? migration-up migration-dir))
(is (migration-exists? migration-down migration-dir)))
;; Clean up after ourselves
(when (.exists (io/file "test" migration-dir))
(destroy config migration)
(io/delete-file (io/file "test" migration-dir)))))
(deftest test-pending-list
(let [ups (atom [])
downs (atom [])
config {:store :mock
:completed-ids (atom #{1})}]
(with-redefs [mig/list-migrations (constantly (migrations ups downs))]
(testing "should return the list of pending migrations"
(is (= ["id-2" "id-3" "id-4"]
(migratus.core/pending-list config)))))))
(deftest supported-extensions
(testing "All supported extensions show up.
NOTE: when you add a protocol, to migratus core, update this test")
(is (= '("sql" "edn")
(proto/get-all-supported-extensions))))
|
[
{
"context": " #{}))\n #{\"County Cork\" \"County Laois\" \"Leinster\" \"Ulster\" \"County Waterford\" \"County Meath\"\n ",
"end": 1959,
"score": 0.9784228801727295,
"start": 1951,
"tag": "NAME",
"value": "Leinster"
},
{
"context": " #{\"County Cork\" \"County Laois\" \"Leinster\" \"Ulster\" \"County Waterford\" \"County Meath\"\n \"",
"end": 1968,
"score": 0.8320846557617188,
"start": 1962,
"tag": "NAME",
"value": "Ulster"
},
{
"context": " Meath\"\n \"County Longford\" \"County Tipperary\" \"County Donegal\" \"County Louth\" \"Munster\"\n ",
"end": 2049,
"score": 0.8425079584121704,
"start": 2046,
"tag": "NAME",
"value": "per"
},
{
"context": "nty Louth\" \"Munster\"\n \"County Clare\" \"Connacht\" \"County Cavan\" \"County Limerick\" \"County Leitrim",
"end": 2133,
"score": 0.8223825097084045,
"start": 2125,
"tag": "NAME",
"value": "Connacht"
},
{
"context": "exford\" \"County Kilkenny\"\n \"County Carlow\" \"County Dublin\" \"County Roscommon\" \"County Galwa",
"end": 2327,
"score": 0.6283411383628845,
"start": 2324,
"tag": "NAME",
"value": "low"
}
] | test/mundaneum/core_test.clj | den1k/mundaneum | 0 | (ns mundaneum.core-test
(:require [clojure.test :refer :all]
[mundaneum.query :refer [property entity describe query]]
[backtick :refer [template]]))
(deftest property-and-entity-tests
(testing "Property lookups"
(is (= (property :instance-of) "P31"))
(is (= (property :part-of) "P361")))
(testing "Entity lookup/description"
(is (= (entity "U2") "Q396"))
(is (= (describe (entity "U2")) "Irish rock band"))
(is (= (entity "Berlin U-Bahn") "Q68646"))
(is (= (entity "U2" :part-of (entity "Berlin U-Bahn")) "Q99697"))
(is (= (describe (entity "U2" :part-of (entity "Berlin U-Bahn")))
"underground line in Berlin"))))
(deftest queries
(testing "Example queries"
;; all stations on the U1 line in Berlin, with lat/long
(let [u1 (entity "U1" :part-of (entity "Berlin U-Bahn"))]
(is (= (->> (query
(template
[:select ?stationLabel ?coord
:where [[?station (wdt :connecting-line) (wd ~u1)
_ (wdt :coordinate-location) ?coord]]]))
(map :stationLabel)
(into #{}))
#{"Kurfürstenstraße metro station" "Möckernbrücke" "Uhlandstraße metro station"
"Schlesisches Tor" "Hallesches Tor" "Wittenbergplatz metro station"
"Kurfürstendamm metro station" "Warschauer Straße metro station" "Görlitzer Bahnhof"
"Kottbusser Tor station" "Gleisdreieck" "Nollendorfplatz metro station" "Prinzenstraße"})))
;; administrative districts of Ireland
(is (= (->> (query '[:select ?biggerLabel ?smallerLabel
:where [[?bigger (wdt :contains-administrative-territorial-entity) ?smaller]
:filter [?bigger = (entity "Ireland")]]])
(map :smallerLabel)
(into #{}))
#{"County Cork" "County Laois" "Leinster" "Ulster" "County Waterford" "County Meath"
"County Longford" "County Tipperary" "County Donegal" "County Louth" "Munster"
"County Clare" "Connacht" "County Cavan" "County Limerick" "County Leitrim" "County Offaly"
"County Westmeath" "County Wicklow" "County Kerry" "County Wexford" "County Kilkenny"
"County Carlow" "County Dublin" "County Roscommon" "County Galway" "County Monaghan"
"County Sligo" "County Mayo" "County Kildare"}))))
| 11350 | (ns mundaneum.core-test
(:require [clojure.test :refer :all]
[mundaneum.query :refer [property entity describe query]]
[backtick :refer [template]]))
(deftest property-and-entity-tests
(testing "Property lookups"
(is (= (property :instance-of) "P31"))
(is (= (property :part-of) "P361")))
(testing "Entity lookup/description"
(is (= (entity "U2") "Q396"))
(is (= (describe (entity "U2")) "Irish rock band"))
(is (= (entity "Berlin U-Bahn") "Q68646"))
(is (= (entity "U2" :part-of (entity "Berlin U-Bahn")) "Q99697"))
(is (= (describe (entity "U2" :part-of (entity "Berlin U-Bahn")))
"underground line in Berlin"))))
(deftest queries
(testing "Example queries"
;; all stations on the U1 line in Berlin, with lat/long
(let [u1 (entity "U1" :part-of (entity "Berlin U-Bahn"))]
(is (= (->> (query
(template
[:select ?stationLabel ?coord
:where [[?station (wdt :connecting-line) (wd ~u1)
_ (wdt :coordinate-location) ?coord]]]))
(map :stationLabel)
(into #{}))
#{"Kurfürstenstraße metro station" "Möckernbrücke" "Uhlandstraße metro station"
"Schlesisches Tor" "Hallesches Tor" "Wittenbergplatz metro station"
"Kurfürstendamm metro station" "Warschauer Straße metro station" "Görlitzer Bahnhof"
"Kottbusser Tor station" "Gleisdreieck" "Nollendorfplatz metro station" "Prinzenstraße"})))
;; administrative districts of Ireland
(is (= (->> (query '[:select ?biggerLabel ?smallerLabel
:where [[?bigger (wdt :contains-administrative-territorial-entity) ?smaller]
:filter [?bigger = (entity "Ireland")]]])
(map :smallerLabel)
(into #{}))
#{"County Cork" "County Laois" "<NAME>" "<NAME>" "County Waterford" "County Meath"
"County Longford" "County Tip<NAME>ary" "County Donegal" "County Louth" "Munster"
"County Clare" "<NAME>" "County Cavan" "County Limerick" "County Leitrim" "County Offaly"
"County Westmeath" "County Wicklow" "County Kerry" "County Wexford" "County Kilkenny"
"County Car<NAME>" "County Dublin" "County Roscommon" "County Galway" "County Monaghan"
"County Sligo" "County Mayo" "County Kildare"}))))
| true | (ns mundaneum.core-test
(:require [clojure.test :refer :all]
[mundaneum.query :refer [property entity describe query]]
[backtick :refer [template]]))
(deftest property-and-entity-tests
(testing "Property lookups"
(is (= (property :instance-of) "P31"))
(is (= (property :part-of) "P361")))
(testing "Entity lookup/description"
(is (= (entity "U2") "Q396"))
(is (= (describe (entity "U2")) "Irish rock band"))
(is (= (entity "Berlin U-Bahn") "Q68646"))
(is (= (entity "U2" :part-of (entity "Berlin U-Bahn")) "Q99697"))
(is (= (describe (entity "U2" :part-of (entity "Berlin U-Bahn")))
"underground line in Berlin"))))
(deftest queries
(testing "Example queries"
;; all stations on the U1 line in Berlin, with lat/long
(let [u1 (entity "U1" :part-of (entity "Berlin U-Bahn"))]
(is (= (->> (query
(template
[:select ?stationLabel ?coord
:where [[?station (wdt :connecting-line) (wd ~u1)
_ (wdt :coordinate-location) ?coord]]]))
(map :stationLabel)
(into #{}))
#{"Kurfürstenstraße metro station" "Möckernbrücke" "Uhlandstraße metro station"
"Schlesisches Tor" "Hallesches Tor" "Wittenbergplatz metro station"
"Kurfürstendamm metro station" "Warschauer Straße metro station" "Görlitzer Bahnhof"
"Kottbusser Tor station" "Gleisdreieck" "Nollendorfplatz metro station" "Prinzenstraße"})))
;; administrative districts of Ireland
(is (= (->> (query '[:select ?biggerLabel ?smallerLabel
:where [[?bigger (wdt :contains-administrative-territorial-entity) ?smaller]
:filter [?bigger = (entity "Ireland")]]])
(map :smallerLabel)
(into #{}))
#{"County Cork" "County Laois" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "County Waterford" "County Meath"
"County Longford" "County TipPI:NAME:<NAME>END_PIary" "County Donegal" "County Louth" "Munster"
"County Clare" "PI:NAME:<NAME>END_PI" "County Cavan" "County Limerick" "County Leitrim" "County Offaly"
"County Westmeath" "County Wicklow" "County Kerry" "County Wexford" "County Kilkenny"
"County CarPI:NAME:<NAME>END_PI" "County Dublin" "County Roscommon" "County Galway" "County Monaghan"
"County Sligo" "County Mayo" "County Kildare"}))))
|
[
{
"context": "0] (encode nil [100.00])))\n (is (= [\"{\\\"name\\\":\\\"Bruce\\\"}\"] (encode nil [{:name \"Bruce\"}])))\n (is (= [[",
"end": 825,
"score": 0.9929302334785461,
"start": 820,
"tag": "NAME",
"value": "Bruce"
},
{
"context": " (= [\"{\\\"name\\\":\\\"Bruce\\\"}\"] (encode nil [{:name \"Bruce\"}])))\n (is (= [[\"{\\\"name\\\":\\\"Bruce\\\"}\"] [\"{\\\"nam",
"end": 857,
"score": 0.9923774600028992,
"start": 852,
"tag": "NAME",
"value": "Bruce"
},
{
"context": " nil [{:name \"Bruce\"}])))\n (is (= [[\"{\\\"name\\\":\\\"Bruce\\\"}\"] [\"{\\\"name\\\":\\\"Lex\\\"}\"]] (encode nil [[{:name",
"end": 893,
"score": 0.9973282217979431,
"start": 888,
"tag": "NAME",
"value": "Bruce"
},
{
"context": "\n (is (= [[\"{\\\"name\\\":\\\"Bruce\\\"}\"] [\"{\\\"name\\\":\\\"Lex\\\"}\"]] (encode nil [[{:name \"Bruce\"}] [{:name \"Lex",
"end": 916,
"score": 0.9974048733711243,
"start": 913,
"tag": "NAME",
"value": "Lex"
},
{
"context": "}\"] [\"{\\\"name\\\":\\\"Lex\\\"}\"]] (encode nil [[{:name \"Bruce\"}] [{:name \"Lex\"}]])))\n (is (nil? (encode nil ni",
"end": 950,
"score": 0.982658863067627,
"start": 945,
"tag": "NAME",
"value": "Bruce"
},
{
"context": "Lex\\\"}\"]] (encode nil [[{:name \"Bruce\"}] [{:name \"Lex\"}]])))\n (is (nil? (encode nil nil))))\n\n",
"end": 966,
"score": 0.9974164962768555,
"start": 963,
"tag": "NAME",
"value": "Lex"
}
] | test/unit/restql/core/encoders/core_test.clj | caiorcferreira/restQL-clojure | 0 | (ns restql.core.encoders.core-test
(:require [slingshot.slingshot :refer [try+]]
[clojure.test :refer [deftest is]])
(:use restql.core.encoders.core))
(deftest test-simple-values
(is (= 10 (encode base-encoders 10)))
(is (= true (encode base-encoders true)))
(is (= "[\"a\",\"b\"]" (encode base-encoders ^{:encoder :json} ["a" "b"])))
(is (= "[1,2]" (encode base-encoders ^{:encoder :json} [1 2])))
(is (nil? (encode base-encoders nil)))
(is (= [[] []] (encode base-encoders [[] []])))
(is (vector? (encode base-encoders [[] []]))))
(deftest test-simple-values-whithout-encoders
(is (= 10 (encode nil 10)))
(is (= true (encode nil true)))
(is (= "a" (encode nil "a")))
(is (= ["a" "b"] (encode nil ["a" "b"])))
(is (= [100.00] (encode nil [100.00])))
(is (= ["{\"name\":\"Bruce\"}"] (encode nil [{:name "Bruce"}])))
(is (= [["{\"name\":\"Bruce\"}"] ["{\"name\":\"Lex\"}"]] (encode nil [[{:name "Bruce"}] [{:name "Lex"}]])))
(is (nil? (encode nil nil))))
| 41308 | (ns restql.core.encoders.core-test
(:require [slingshot.slingshot :refer [try+]]
[clojure.test :refer [deftest is]])
(:use restql.core.encoders.core))
(deftest test-simple-values
(is (= 10 (encode base-encoders 10)))
(is (= true (encode base-encoders true)))
(is (= "[\"a\",\"b\"]" (encode base-encoders ^{:encoder :json} ["a" "b"])))
(is (= "[1,2]" (encode base-encoders ^{:encoder :json} [1 2])))
(is (nil? (encode base-encoders nil)))
(is (= [[] []] (encode base-encoders [[] []])))
(is (vector? (encode base-encoders [[] []]))))
(deftest test-simple-values-whithout-encoders
(is (= 10 (encode nil 10)))
(is (= true (encode nil true)))
(is (= "a" (encode nil "a")))
(is (= ["a" "b"] (encode nil ["a" "b"])))
(is (= [100.00] (encode nil [100.00])))
(is (= ["{\"name\":\"<NAME>\"}"] (encode nil [{:name "<NAME>"}])))
(is (= [["{\"name\":\"<NAME>\"}"] ["{\"name\":\"<NAME>\"}"]] (encode nil [[{:name "<NAME>"}] [{:name "<NAME>"}]])))
(is (nil? (encode nil nil))))
| true | (ns restql.core.encoders.core-test
(:require [slingshot.slingshot :refer [try+]]
[clojure.test :refer [deftest is]])
(:use restql.core.encoders.core))
(deftest test-simple-values
(is (= 10 (encode base-encoders 10)))
(is (= true (encode base-encoders true)))
(is (= "[\"a\",\"b\"]" (encode base-encoders ^{:encoder :json} ["a" "b"])))
(is (= "[1,2]" (encode base-encoders ^{:encoder :json} [1 2])))
(is (nil? (encode base-encoders nil)))
(is (= [[] []] (encode base-encoders [[] []])))
(is (vector? (encode base-encoders [[] []]))))
(deftest test-simple-values-whithout-encoders
(is (= 10 (encode nil 10)))
(is (= true (encode nil true)))
(is (= "a" (encode nil "a")))
(is (= ["a" "b"] (encode nil ["a" "b"])))
(is (= [100.00] (encode nil [100.00])))
(is (= ["{\"name\":\"PI:NAME:<NAME>END_PI\"}"] (encode nil [{:name "PI:NAME:<NAME>END_PI"}])))
(is (= [["{\"name\":\"PI:NAME:<NAME>END_PI\"}"] ["{\"name\":\"PI:NAME:<NAME>END_PI\"}"]] (encode nil [[{:name "PI:NAME:<NAME>END_PI"}] [{:name "PI:NAME:<NAME>END_PI"}]])))
(is (nil? (encode nil nil))))
|
[
{
"context": "ring-serialization\n (testing \"v0\"\n (let [b58 \"Qmd8kgzaFLGYtTS1zfF37qKGgYQd5yKcQMyBeSa8UkUz4W\"\n ",
"end": 3994,
"score": 0.57588791847229,
"start": 3990,
"tag": "KEY",
"value": "Qmd8"
},
{
"context": "erialization\n (testing \"v0\"\n (let [b58 \"Qmd8kgzaFLGYtTS1zfF37qKGgYQd5yKcQMyBeSa8UkUz4W\"\n ",
"end": 3998,
"score": 0.544765830039978,
"start": 3996,
"tag": "KEY",
"value": "za"
},
{
"context": "ation\n (testing \"v0\"\n (let [b58 \"Qmd8kgzaFLGYtTS1zfF37qKGgYQd5yKcQMyBeSa8UkUz4W\"\n mh (mha",
"end": 4005,
"score": 0.5284466743469238,
"start": 4003,
"tag": "KEY",
"value": "TS"
},
{
"context": "\n (testing \"v0\"\n (let [b58 \"Qmd8kgzaFLGYtTS1zfF37qKGgYQd5yKcQMyBeSa8UkUz4W\"\n mh (mhash/sh",
"end": 4010,
"score": 0.5295618772506714,
"start": 4008,
"tag": "KEY",
"value": "F3"
},
{
"context": "sting \"v0\"\n (let [b58 \"Qmd8kgzaFLGYtTS1zfF37qKGgYQd5yKcQMyBeSa8UkUz4W\"\n mh (mhash/sha2-256 ",
"end": 4017,
"score": 0.5297859907150269,
"start": 4014,
"tag": "KEY",
"value": "gYQ"
},
{
"context": " \"v0\"\n (let [b58 \"Qmd8kgzaFLGYtTS1zfF37qKGgYQd5yKcQMyBeSa8UkUz4W\"\n mh (mhash/sha2-256 \"foo bar",
"end": 4025,
"score": 0.5923693180084229,
"start": 4019,
"tag": "KEY",
"value": "yKcQMy"
},
{
"context": "spect b58)))))\n (testing \"v1\"\n (let [b58 \"zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA\"\n ",
"end": 5033,
"score": 0.5444527268409729,
"start": 5029,
"tag": "KEY",
"value": "he5P"
},
{
"context": ")))\n (testing \"v1\"\n (let [b58 \"zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA\"\n b32 \"b",
"end": 5042,
"score": 0.541921079158783,
"start": 5040,
"tag": "KEY",
"value": "vA"
},
{
"context": "\n (testing \"v1\"\n (let [b58 \"zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA\"\n b32 \"baf",
"end": 5044,
"score": 0.5269923806190491,
"start": 5043,
"tag": "KEY",
"value": "e"
},
{
"context": "(testing \"v1\"\n (let [b58 \"zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA\"\n b32 \"bafkre",
"end": 5047,
"score": 0.5423093438148499,
"start": 5046,
"tag": "KEY",
"value": "5"
},
{
"context": "sting \"v1\"\n (let [b58 \"zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA\"\n b32 \"bafkreidon",
"end": 5051,
"score": 0.5184379816055298,
"start": 5049,
"tag": "KEY",
"value": "ws"
},
{
"context": "g \"v1\"\n (let [b58 \"zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA\"\n b32 \"bafkreidon73zkcrwdb5iaf",
"end": 5064,
"score": 0.5322551131248474,
"start": 5053,
"tag": "KEY",
"value": "2owDyS9sKaQ"
},
{
"context": "et [b58 \"zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA\"\n b32 \"bafkreidon73zkcrwdb5iafqtijxil",
"end": 5071,
"score": 0.5341458916664124,
"start": 5066,
"tag": "KEY",
"value": "VQPn9"
},
{
"context": "8 \"zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA\"\n b32 \"bafkreidon73zkcrwdb5iafqtijxildoo",
"end": 5074,
"score": 0.5108358263969421,
"start": 5072,
"tag": "KEY",
"value": "bA"
}
] | test/multiformats/cid_test.cljc | aria42/clj-multiformats | 0 | (ns multiformats.cid-test
(:require
[alphabase.bytes :as b :refer [bytes=]]
[clojure.string :as str]
#?(:clj [clojure.test :refer [deftest testing is]]
:cljs [cljs.test :refer-macros [deftest testing is]])
[multiformats.cid :as cid]
[multiformats.hash :as mhash])
#?(:clj
(:import
clojure.lang.ExceptionInfo)))
(deftest constructor-validation
(is (thrown? #?(:clj ExceptionInfo, :cljs js/Error)
(cid/create true (mhash/sha1 "hello world")))
"Unknown codec type should be rejected")
(is (thrown? #?(:clj ExceptionInfo, :cljs js/Error)
(cid/create :no-such-codec (mhash/create :sha1 "0beec7b8")))
"Unknown algorithm keyword should be rejected")
(is (thrown? #?(:clj ExceptionInfo, :cljs js/Error)
(cid/create -1 (mhash/sha1 "hello world")))
"Negative codec code should be rejected")
(is (thrown? #?(:clj ExceptionInfo, :cljs js/Error)
(cid/create :cbor nil))
"Nil hash should be rejected"))
(deftest value-semantics
(let [mh (mhash/sha1 "hello world")
a (cid/create :raw mh)
b (cid/create 0x51 mh)
b' (cid/create :cbor mh)]
(is (= a a) "identical values are equal")
(is (= b b') "values with same code and digest are equal")
(is (integer? (hash a)) "hash code returns an integer")
(is (= (hash b) (hash b')) "equivalent objects return same hashcode")))
(deftest cid-properties
(let [mh (mhash/sha2-256 "test input")
cid (cid/create :cbor mh)]
(is (= 36 (:length cid)))
(is (= 1 (:version cid)))
(is (= :cbor (:codec cid)))
(is (= 0x51 (:code cid)))
(is (= :sha2-256 (get-in cid [:hash :algorithm])))
(is (nil? (:foo cid)))
(is (= {:length 36
:version 1
:codec :cbor
:code 0x51
:hash mh}
(cid/inspect cid)))
(is (nil? (cid/inspect nil)))))
(deftest cid-rendering
(is (= "cidv1:raw:sha1:0beec7b5ea3f0fdb"
(str (cid/create :raw (mhash/create :sha1 "0beec7b5ea3f0fdb")))))
(is (= "cidv1:cbor:sha2-256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
(str (cid/create :cbor (mhash/create :sha2-256 "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"))))))
(deftest exercise-metadata
(let [a (cid/create :raw (mhash/sha2-256 "abc123"))
a' (vary-meta a assoc :foo :bar/baz)]
(is (empty? (meta a)) "values start with empty metadata")
(is (= :bar/baz (:foo (meta a'))) "metadata can be associated with value")
(is (= a a') "metadata does not affect equality")))
(deftest binary-serialization
(testing "v0"
(let [mh (mhash/sha2-256 "hello world")
encoded (mhash/encode mh)
cid (cid/decode encoded)]
(is (= 0 (:version cid)))
(is (= :raw (:codec cid)))
(is (= mh (:hash cid)))
(is (bytes= encoded (cid/encode cid)))
(let [buffer (b/byte-array (+ 4 (:length cid)))]
(is (= (:length cid) (cid/write-bytes cid buffer 2)))
(is (= [0x00 0x00 0x12 0x20]
(take 4 (b/byte-seq buffer)))))))
(testing "v1"
(let [mh (mhash/sha2-256 "hello world")
cid (cid/create :cbor mh)]
(is (= 1 (:version cid)))
(is (= :cbor (:codec cid)))
(is (= mh (:hash cid)))
(let [encoded (cid/encode cid)]
(is (= (alength encoded) (:length cid)))
(is (= cid (cid/decode encoded))))
(let [buffer (b/byte-array (+ 4 (:length cid)))]
(is (= (:length cid) (cid/write-bytes cid buffer 1)))
(is (= [0x00 0x01 0x51 0x12 0x20]
(take 5 (b/byte-seq buffer)))))))
(testing "bad input"
(let [encoded (doto (b/byte-array 34)
(b/set-byte 0 0x02))]
(is (thrown-with-msg? #?(:clj ExceptionInfo, :cljs js/Error)
#"Unable to decode CID version 2"
(cid/decode encoded))))))
(deftest string-serialization
(testing "v0"
(let [b58 "Qmd8kgzaFLGYtTS1zfF37qKGgYQd5yKcQMyBeSa8UkUz4W"
mh (mhash/sha2-256 "foo bar baz")
encoded (mhash/encode mh)
cid (cid/decode encoded)]
(is (= 34 (:length cid)))
(is (= 0 (:version cid)))
(is (= :raw (:codec cid)))
(is (= b58 (cid/format cid)))
(is (= cid (cid/parse b58)))
(is (thrown-with-msg? #?(:clj ExceptionInfo, :cljs js/Error)
#"v0 CID values cannot be formatted in alternative bases"
(cid/format :base32 cid)))
(is (= {:length 34
:version 0
:codec :raw
:code 0x55
:hash mh}
(cid/inspect cid)))
(is (= {:length 34
:version 0
:codec :raw
:code 0x55
:hash mh}
(cid/inspect encoded)))
(is (= {:length 34
:version 0
:codec :raw
:code 0x55
:hash mh}
(cid/inspect b58)))))
(testing "v1"
(let [b58 "zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA"
b32 "bafkreidon73zkcrwdb5iafqtijxildoonbwnpv7dyd6ef3qdgads2jc4su"
cid (cid/parse b58)
mh (:hash cid)]
(is (= 36 (:length cid)))
(is (= 1 (:version cid)))
(is (= :raw (:codec cid)))
(is (= b58 (cid/format :base58btc cid)))
(is (= b32 (cid/format cid)))
(is (= cid (cid/parse b32)))
(is (= {:length 36
:version 1
:codec :raw
:code 0x55
:hash mh
:prefix "b"
:base :base32}
(cid/inspect b32)))
(is (= {:length 36
:version 1
:codec :raw
:code 0x55
:hash mh
:prefix "z"
:base :base58btc}
(cid/inspect b58))))))
| 108780 | (ns multiformats.cid-test
(:require
[alphabase.bytes :as b :refer [bytes=]]
[clojure.string :as str]
#?(:clj [clojure.test :refer [deftest testing is]]
:cljs [cljs.test :refer-macros [deftest testing is]])
[multiformats.cid :as cid]
[multiformats.hash :as mhash])
#?(:clj
(:import
clojure.lang.ExceptionInfo)))
(deftest constructor-validation
(is (thrown? #?(:clj ExceptionInfo, :cljs js/Error)
(cid/create true (mhash/sha1 "hello world")))
"Unknown codec type should be rejected")
(is (thrown? #?(:clj ExceptionInfo, :cljs js/Error)
(cid/create :no-such-codec (mhash/create :sha1 "0beec7b8")))
"Unknown algorithm keyword should be rejected")
(is (thrown? #?(:clj ExceptionInfo, :cljs js/Error)
(cid/create -1 (mhash/sha1 "hello world")))
"Negative codec code should be rejected")
(is (thrown? #?(:clj ExceptionInfo, :cljs js/Error)
(cid/create :cbor nil))
"Nil hash should be rejected"))
(deftest value-semantics
(let [mh (mhash/sha1 "hello world")
a (cid/create :raw mh)
b (cid/create 0x51 mh)
b' (cid/create :cbor mh)]
(is (= a a) "identical values are equal")
(is (= b b') "values with same code and digest are equal")
(is (integer? (hash a)) "hash code returns an integer")
(is (= (hash b) (hash b')) "equivalent objects return same hashcode")))
(deftest cid-properties
(let [mh (mhash/sha2-256 "test input")
cid (cid/create :cbor mh)]
(is (= 36 (:length cid)))
(is (= 1 (:version cid)))
(is (= :cbor (:codec cid)))
(is (= 0x51 (:code cid)))
(is (= :sha2-256 (get-in cid [:hash :algorithm])))
(is (nil? (:foo cid)))
(is (= {:length 36
:version 1
:codec :cbor
:code 0x51
:hash mh}
(cid/inspect cid)))
(is (nil? (cid/inspect nil)))))
(deftest cid-rendering
(is (= "cidv1:raw:sha1:0beec7b5ea3f0fdb"
(str (cid/create :raw (mhash/create :sha1 "0beec7b5ea3f0fdb")))))
(is (= "cidv1:cbor:sha2-256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
(str (cid/create :cbor (mhash/create :sha2-256 "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"))))))
(deftest exercise-metadata
(let [a (cid/create :raw (mhash/sha2-256 "abc123"))
a' (vary-meta a assoc :foo :bar/baz)]
(is (empty? (meta a)) "values start with empty metadata")
(is (= :bar/baz (:foo (meta a'))) "metadata can be associated with value")
(is (= a a') "metadata does not affect equality")))
(deftest binary-serialization
(testing "v0"
(let [mh (mhash/sha2-256 "hello world")
encoded (mhash/encode mh)
cid (cid/decode encoded)]
(is (= 0 (:version cid)))
(is (= :raw (:codec cid)))
(is (= mh (:hash cid)))
(is (bytes= encoded (cid/encode cid)))
(let [buffer (b/byte-array (+ 4 (:length cid)))]
(is (= (:length cid) (cid/write-bytes cid buffer 2)))
(is (= [0x00 0x00 0x12 0x20]
(take 4 (b/byte-seq buffer)))))))
(testing "v1"
(let [mh (mhash/sha2-256 "hello world")
cid (cid/create :cbor mh)]
(is (= 1 (:version cid)))
(is (= :cbor (:codec cid)))
(is (= mh (:hash cid)))
(let [encoded (cid/encode cid)]
(is (= (alength encoded) (:length cid)))
(is (= cid (cid/decode encoded))))
(let [buffer (b/byte-array (+ 4 (:length cid)))]
(is (= (:length cid) (cid/write-bytes cid buffer 1)))
(is (= [0x00 0x01 0x51 0x12 0x20]
(take 5 (b/byte-seq buffer)))))))
(testing "bad input"
(let [encoded (doto (b/byte-array 34)
(b/set-byte 0 0x02))]
(is (thrown-with-msg? #?(:clj ExceptionInfo, :cljs js/Error)
#"Unable to decode CID version 2"
(cid/decode encoded))))))
(deftest string-serialization
(testing "v0"
(let [b58 "<KEY>kg<KEY>FLGYt<KEY>1zf<KEY>7qKG<KEY>d5<KEY>BeSa8UkUz4W"
mh (mhash/sha2-256 "foo bar baz")
encoded (mhash/encode mh)
cid (cid/decode encoded)]
(is (= 34 (:length cid)))
(is (= 0 (:version cid)))
(is (= :raw (:codec cid)))
(is (= b58 (cid/format cid)))
(is (= cid (cid/parse b58)))
(is (thrown-with-msg? #?(:clj ExceptionInfo, :cljs js/Error)
#"v0 CID values cannot be formatted in alternative bases"
(cid/format :base32 cid)))
(is (= {:length 34
:version 0
:codec :raw
:code 0x55
:hash mh}
(cid/inspect cid)))
(is (= {:length 34
:version 0
:codec :raw
:code 0x55
:hash mh}
(cid/inspect encoded)))
(is (= {:length 34
:version 0
:codec :raw
:code 0x55
:hash mh}
(cid/inspect b58)))))
(testing "v1"
(let [b58 "zb2r<KEY>4gXftAw<KEY>4<KEY>XQ<KEY>HJ<KEY>ER<KEY>RR<KEY>3<KEY>"
b32 "bafkreidon73zkcrwdb5iafqtijxildoonbwnpv7dyd6ef3qdgads2jc4su"
cid (cid/parse b58)
mh (:hash cid)]
(is (= 36 (:length cid)))
(is (= 1 (:version cid)))
(is (= :raw (:codec cid)))
(is (= b58 (cid/format :base58btc cid)))
(is (= b32 (cid/format cid)))
(is (= cid (cid/parse b32)))
(is (= {:length 36
:version 1
:codec :raw
:code 0x55
:hash mh
:prefix "b"
:base :base32}
(cid/inspect b32)))
(is (= {:length 36
:version 1
:codec :raw
:code 0x55
:hash mh
:prefix "z"
:base :base58btc}
(cid/inspect b58))))))
| true | (ns multiformats.cid-test
(:require
[alphabase.bytes :as b :refer [bytes=]]
[clojure.string :as str]
#?(:clj [clojure.test :refer [deftest testing is]]
:cljs [cljs.test :refer-macros [deftest testing is]])
[multiformats.cid :as cid]
[multiformats.hash :as mhash])
#?(:clj
(:import
clojure.lang.ExceptionInfo)))
(deftest constructor-validation
(is (thrown? #?(:clj ExceptionInfo, :cljs js/Error)
(cid/create true (mhash/sha1 "hello world")))
"Unknown codec type should be rejected")
(is (thrown? #?(:clj ExceptionInfo, :cljs js/Error)
(cid/create :no-such-codec (mhash/create :sha1 "0beec7b8")))
"Unknown algorithm keyword should be rejected")
(is (thrown? #?(:clj ExceptionInfo, :cljs js/Error)
(cid/create -1 (mhash/sha1 "hello world")))
"Negative codec code should be rejected")
(is (thrown? #?(:clj ExceptionInfo, :cljs js/Error)
(cid/create :cbor nil))
"Nil hash should be rejected"))
(deftest value-semantics
(let [mh (mhash/sha1 "hello world")
a (cid/create :raw mh)
b (cid/create 0x51 mh)
b' (cid/create :cbor mh)]
(is (= a a) "identical values are equal")
(is (= b b') "values with same code and digest are equal")
(is (integer? (hash a)) "hash code returns an integer")
(is (= (hash b) (hash b')) "equivalent objects return same hashcode")))
(deftest cid-properties
(let [mh (mhash/sha2-256 "test input")
cid (cid/create :cbor mh)]
(is (= 36 (:length cid)))
(is (= 1 (:version cid)))
(is (= :cbor (:codec cid)))
(is (= 0x51 (:code cid)))
(is (= :sha2-256 (get-in cid [:hash :algorithm])))
(is (nil? (:foo cid)))
(is (= {:length 36
:version 1
:codec :cbor
:code 0x51
:hash mh}
(cid/inspect cid)))
(is (nil? (cid/inspect nil)))))
(deftest cid-rendering
(is (= "cidv1:raw:sha1:0beec7b5ea3f0fdb"
(str (cid/create :raw (mhash/create :sha1 "0beec7b5ea3f0fdb")))))
(is (= "cidv1:cbor:sha2-256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
(str (cid/create :cbor (mhash/create :sha2-256 "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"))))))
(deftest exercise-metadata
(let [a (cid/create :raw (mhash/sha2-256 "abc123"))
a' (vary-meta a assoc :foo :bar/baz)]
(is (empty? (meta a)) "values start with empty metadata")
(is (= :bar/baz (:foo (meta a'))) "metadata can be associated with value")
(is (= a a') "metadata does not affect equality")))
(deftest binary-serialization
(testing "v0"
(let [mh (mhash/sha2-256 "hello world")
encoded (mhash/encode mh)
cid (cid/decode encoded)]
(is (= 0 (:version cid)))
(is (= :raw (:codec cid)))
(is (= mh (:hash cid)))
(is (bytes= encoded (cid/encode cid)))
(let [buffer (b/byte-array (+ 4 (:length cid)))]
(is (= (:length cid) (cid/write-bytes cid buffer 2)))
(is (= [0x00 0x00 0x12 0x20]
(take 4 (b/byte-seq buffer)))))))
(testing "v1"
(let [mh (mhash/sha2-256 "hello world")
cid (cid/create :cbor mh)]
(is (= 1 (:version cid)))
(is (= :cbor (:codec cid)))
(is (= mh (:hash cid)))
(let [encoded (cid/encode cid)]
(is (= (alength encoded) (:length cid)))
(is (= cid (cid/decode encoded))))
(let [buffer (b/byte-array (+ 4 (:length cid)))]
(is (= (:length cid) (cid/write-bytes cid buffer 1)))
(is (= [0x00 0x01 0x51 0x12 0x20]
(take 5 (b/byte-seq buffer)))))))
(testing "bad input"
(let [encoded (doto (b/byte-array 34)
(b/set-byte 0 0x02))]
(is (thrown-with-msg? #?(:clj ExceptionInfo, :cljs js/Error)
#"Unable to decode CID version 2"
(cid/decode encoded))))))
(deftest string-serialization
(testing "v0"
(let [b58 "PI:KEY:<KEY>END_PIkgPI:KEY:<KEY>END_PIFLGYtPI:KEY:<KEY>END_PI1zfPI:KEY:<KEY>END_PI7qKGPI:KEY:<KEY>END_PId5PI:KEY:<KEY>END_PIBeSa8UkUz4W"
mh (mhash/sha2-256 "foo bar baz")
encoded (mhash/encode mh)
cid (cid/decode encoded)]
(is (= 34 (:length cid)))
(is (= 0 (:version cid)))
(is (= :raw (:codec cid)))
(is (= b58 (cid/format cid)))
(is (= cid (cid/parse b58)))
(is (thrown-with-msg? #?(:clj ExceptionInfo, :cljs js/Error)
#"v0 CID values cannot be formatted in alternative bases"
(cid/format :base32 cid)))
(is (= {:length 34
:version 0
:codec :raw
:code 0x55
:hash mh}
(cid/inspect cid)))
(is (= {:length 34
:version 0
:codec :raw
:code 0x55
:hash mh}
(cid/inspect encoded)))
(is (= {:length 34
:version 0
:codec :raw
:code 0x55
:hash mh}
(cid/inspect b58)))))
(testing "v1"
(let [b58 "zb2rPI:KEY:<KEY>END_PI4gXftAwPI:KEY:<KEY>END_PI4PI:KEY:<KEY>END_PIXQPI:KEY:<KEY>END_PIHJPI:KEY:<KEY>END_PIERPI:KEY:<KEY>END_PIRRPI:KEY:<KEY>END_PI3PI:KEY:<KEY>END_PI"
b32 "bafkreidon73zkcrwdb5iafqtijxildoonbwnpv7dyd6ef3qdgads2jc4su"
cid (cid/parse b58)
mh (:hash cid)]
(is (= 36 (:length cid)))
(is (= 1 (:version cid)))
(is (= :raw (:codec cid)))
(is (= b58 (cid/format :base58btc cid)))
(is (= b32 (cid/format cid)))
(is (= cid (cid/parse b32)))
(is (= {:length 36
:version 1
:codec :raw
:code 0x55
:hash mh
:prefix "b"
:base :base32}
(cid/inspect b32)))
(is (= {:length 36
:version 1
:codec :raw
:code 0x55
:hash mh
:prefix "z"
:base :base58btc}
(cid/inspect b58))))))
|
[
{
"context": ";;; Copyright 2013 Mitchell Kember. Subject to the MIT License.\n;;; 2010 Canadian Co",
"end": 34,
"score": 0.9998847246170044,
"start": 19,
"tag": "NAME",
"value": "Mitchell Kember"
}
] | src/ccc/y2010/s4_old.clj | mk12/ccc | 0 | ;;; Copyright 2013 Mitchell Kember. Subject to the MIT License.
;;; 2010 Canadian Computing Competition: Senior Division
;;; Problem S4: Animal Farm
(ns ccc.y2010.s4-old
(:require [clojure.set :as s]))
;;; A "node" is an integer representing a point on an undirected graph.
;;; An "edge" is a collection of exactly two nodes, in increasing order.
;;; A "polygon" is a set of edges forming a closed polygon.
;;; The "outside" is a special polygon represented by the empty set #{}. All
;;; otherwise unshared edges of other polygons are shared with the outside.
;;; A "mesh" is a set of polygons.
;;; A "pen" is a collection of nodes that represent a polygon.
;;; (The pen [1 2 3] and the polygon #{[1 2] [2 3] [3 1]} are equivalent.)
;;; A "farm" is a collection of pens.
;;; A "receipt" is a map from edges to integers that represent the cost of
;;; trampling (destroying) that edge.
(defn sort-edge
"Sorts an edge so that the smaller node comes first."
[[a b]]
(if (< a b) [a b] [b a]))
(defn pen->polygon
"Converts a pen (collection of nodes) to a polygon (set of edges)."
[pen]
(let [rotated (take (count pen) (rest (cycle pen)))]
(set (map (comp sort-edge vector) pen rotated))))
(defn farm->mesh
"Converts a farm (collection of pens) to a mesh (set of polygons)."
[farm]
(set (map pen->polygon farm)))
(defn simplify-mesh
"Simplifies a mesh by removing all edges except the least expensive edge
wherever two polygons share multiple edges. If the mesh does not contain the
outside, all unshared edges will be removed."
[mesh receipt]
nil)
(defn sym-difference
"Returns a set of the elements that the sets do not share in common."
[sets]
(s/difference (apply s/union sets)
(apply s/intersection sets)))
(defn trample
"Removes an edge from a mesh. If the edge is shared between multiple polygons
(including the outside, if present), they will be combined into a single
polygon. The returned mesh will always have at least one fewer polygons."
[mesh edge]
(let [border? #(contains? % edge)
sharing (filter border? mesh)
others (remove border? mesh)
combined (sym-difference sharing)]
(conj others combined)))
(defn best-polygon
"Returns the polygon in the mesh that has the most connections to other
polygons. A polygon has a single connection with another if they share one or
more edges. An unshared edge is actually shared with the outside, #{}."
[mesh]
nil)
(defn main
"Determines the minimal cost that will allow all animals to gather in one pen
or outside all the pens given a farm and its receipt."
[farm receipt]
nil)
; no sharer -> remove whole pen
; combines with the outisde -> gone
; done when #pens <= 1
| 122056 | ;;; Copyright 2013 <NAME>. Subject to the MIT License.
;;; 2010 Canadian Computing Competition: Senior Division
;;; Problem S4: Animal Farm
(ns ccc.y2010.s4-old
(:require [clojure.set :as s]))
;;; A "node" is an integer representing a point on an undirected graph.
;;; An "edge" is a collection of exactly two nodes, in increasing order.
;;; A "polygon" is a set of edges forming a closed polygon.
;;; The "outside" is a special polygon represented by the empty set #{}. All
;;; otherwise unshared edges of other polygons are shared with the outside.
;;; A "mesh" is a set of polygons.
;;; A "pen" is a collection of nodes that represent a polygon.
;;; (The pen [1 2 3] and the polygon #{[1 2] [2 3] [3 1]} are equivalent.)
;;; A "farm" is a collection of pens.
;;; A "receipt" is a map from edges to integers that represent the cost of
;;; trampling (destroying) that edge.
(defn sort-edge
"Sorts an edge so that the smaller node comes first."
[[a b]]
(if (< a b) [a b] [b a]))
(defn pen->polygon
"Converts a pen (collection of nodes) to a polygon (set of edges)."
[pen]
(let [rotated (take (count pen) (rest (cycle pen)))]
(set (map (comp sort-edge vector) pen rotated))))
(defn farm->mesh
"Converts a farm (collection of pens) to a mesh (set of polygons)."
[farm]
(set (map pen->polygon farm)))
(defn simplify-mesh
"Simplifies a mesh by removing all edges except the least expensive edge
wherever two polygons share multiple edges. If the mesh does not contain the
outside, all unshared edges will be removed."
[mesh receipt]
nil)
(defn sym-difference
"Returns a set of the elements that the sets do not share in common."
[sets]
(s/difference (apply s/union sets)
(apply s/intersection sets)))
(defn trample
"Removes an edge from a mesh. If the edge is shared between multiple polygons
(including the outside, if present), they will be combined into a single
polygon. The returned mesh will always have at least one fewer polygons."
[mesh edge]
(let [border? #(contains? % edge)
sharing (filter border? mesh)
others (remove border? mesh)
combined (sym-difference sharing)]
(conj others combined)))
(defn best-polygon
"Returns the polygon in the mesh that has the most connections to other
polygons. A polygon has a single connection with another if they share one or
more edges. An unshared edge is actually shared with the outside, #{}."
[mesh]
nil)
(defn main
"Determines the minimal cost that will allow all animals to gather in one pen
or outside all the pens given a farm and its receipt."
[farm receipt]
nil)
; no sharer -> remove whole pen
; combines with the outisde -> gone
; done when #pens <= 1
| true | ;;; Copyright 2013 PI:NAME:<NAME>END_PI. Subject to the MIT License.
;;; 2010 Canadian Computing Competition: Senior Division
;;; Problem S4: Animal Farm
(ns ccc.y2010.s4-old
(:require [clojure.set :as s]))
;;; A "node" is an integer representing a point on an undirected graph.
;;; An "edge" is a collection of exactly two nodes, in increasing order.
;;; A "polygon" is a set of edges forming a closed polygon.
;;; The "outside" is a special polygon represented by the empty set #{}. All
;;; otherwise unshared edges of other polygons are shared with the outside.
;;; A "mesh" is a set of polygons.
;;; A "pen" is a collection of nodes that represent a polygon.
;;; (The pen [1 2 3] and the polygon #{[1 2] [2 3] [3 1]} are equivalent.)
;;; A "farm" is a collection of pens.
;;; A "receipt" is a map from edges to integers that represent the cost of
;;; trampling (destroying) that edge.
(defn sort-edge
"Sorts an edge so that the smaller node comes first."
[[a b]]
(if (< a b) [a b] [b a]))
(defn pen->polygon
"Converts a pen (collection of nodes) to a polygon (set of edges)."
[pen]
(let [rotated (take (count pen) (rest (cycle pen)))]
(set (map (comp sort-edge vector) pen rotated))))
(defn farm->mesh
"Converts a farm (collection of pens) to a mesh (set of polygons)."
[farm]
(set (map pen->polygon farm)))
(defn simplify-mesh
"Simplifies a mesh by removing all edges except the least expensive edge
wherever two polygons share multiple edges. If the mesh does not contain the
outside, all unshared edges will be removed."
[mesh receipt]
nil)
(defn sym-difference
"Returns a set of the elements that the sets do not share in common."
[sets]
(s/difference (apply s/union sets)
(apply s/intersection sets)))
(defn trample
"Removes an edge from a mesh. If the edge is shared between multiple polygons
(including the outside, if present), they will be combined into a single
polygon. The returned mesh will always have at least one fewer polygons."
[mesh edge]
(let [border? #(contains? % edge)
sharing (filter border? mesh)
others (remove border? mesh)
combined (sym-difference sharing)]
(conj others combined)))
(defn best-polygon
"Returns the polygon in the mesh that has the most connections to other
polygons. A polygon has a single connection with another if they share one or
more edges. An unshared edge is actually shared with the outside, #{}."
[mesh]
nil)
(defn main
"Determines the minimal cost that will allow all animals to gather in one pen
or outside all the pens given a farm and its receipt."
[farm receipt]
nil)
; no sharer -> remove whole pen
; combines with the outisde -> gone
; done when #pens <= 1
|
[
{
"context": " ; values with metadata\n(log (Person. \"John Doe\" \"Office 33\\n27 Colmore Row\\nBirmingham\\nEngland\"",
"end": 2821,
"score": 0.9996363520622253,
"start": 2813,
"tag": "NAME",
"value": "John Doe"
}
] | examples/lein/src/demo/devtools_sample/core.cljs | MawiraIke/cljs-devtools | 1,125 | (ns devtools-sample.core
(:require-macros [devtools-sample.logging :refer [log]])
(:require [clojure.string :as string]
[devtools-sample.boot :refer [boot!]]
[devtools.formatters.markup :refer [<standard-body>]]
[devtools.formatters.templating :refer [render-markup]]
[devtools.protocols :refer [IFormat]]))
(boot! "/src/demo/devtools_sample/core.cljs")
; --- MEAT STARTS HERE -->
; note: (log ...) expands to (.log js/console ...)
(defn hello [name]
(str "hello, " name "!"))
(def showcase-value {:number 0
:string "string"
:keyword :keyword
:symbol 'symbol
:vector [0 1 2 3 4 5 6]
:set '#{a b c}
:map '{k1 v1 k2 v2}})
(defprotocol MyProtocol
(-method1 [this])
(-method2
[this param1]
[this param1 param2]))
(deftype MyType [f1 f2]
MyProtocol
(-method1 [this])
(-method2 [this param1])
(-method2 [this param1 param2]))
; custom formatter defined in user code
(deftype Person [name address]
IFormat
(-header [_] (render-markup [["span" "color:white;background-color:#999;padding:0px 4px;"] (str "Person: " name)]))
(-has-body [_] (some? address))
(-body [_] (render-markup (<standard-body> (string/split-lines address)))))
(log nil 42 0.1 :keyword 'symbol "string" #"regexp" [1 2 3] {:k1 1 :k2 2} #{1 2 3}) ; simple values
(log [nil 42 0.1 :keyword 'symbol "string" #"regexp" [1 2 3] {:k1 1 :k2 2} #{1 2 3}]) ; vector of simple values
(log (range 100) (range 101) (range 220) (interleave (repeat :even) (repeat :odd))) ; lists, including infinite ones
(log {:k1 'v1 :k2 'v2 :k3 'v3 :k4 'v4 :k5 'v5 :k6 'v6 :k7 'v7 :k8 'v8 :k9 'v9}) ; maps
(log #{1 2 3 4 5 6 7 8 9 10 11 12 13 14 15}) ; sets
(log hello filter js/document.getElementById) ; functions cljs / native
(log (fn []) (fn [p__gen p123]) #(str %) (js* "function(x) { console.log(x); }")) ; lambda functions
(log [#js {:key "val"} #js [1 2 3] (js-obj "k1" "v1" "k2" :v2) js/window]) ; js interop
(log [1 2 3 [10 20 30 [100 200 300 [1000 2000 3000 :*]]]]) ; nested vectors
(log (with-meta ["has meta data"] {:some "meta-data"})) ; values with metadata
(log (Person. "John Doe" "Office 33\n27 Colmore Row\nBirmingham\nEngland") (Person. "Mr Homeless" nil)) ; custom formatting
(log (atom showcase-value)) ; atoms
(log (MyType. 1 2)) ; types
; <-- MEAT STOPS HERE ---
(def state (atom []))
(defn simple-fn [count]
(let [rng (range count)]
(doseq [item rng]
(let [s (str "item=" item)]
(swap! state conj s))))) ; <- set breakpoint HERE and see Scope variables in DevTools
(defn fn-returns-nil [])
(defn ^:export sanity-test-handler []
((fn-returns-nil) "param")) ; a test of sanity checker
(defn ^:export breakpoint-test-handler []
(simple-fn 10)
(log state))
| 52986 | (ns devtools-sample.core
(:require-macros [devtools-sample.logging :refer [log]])
(:require [clojure.string :as string]
[devtools-sample.boot :refer [boot!]]
[devtools.formatters.markup :refer [<standard-body>]]
[devtools.formatters.templating :refer [render-markup]]
[devtools.protocols :refer [IFormat]]))
(boot! "/src/demo/devtools_sample/core.cljs")
; --- MEAT STARTS HERE -->
; note: (log ...) expands to (.log js/console ...)
(defn hello [name]
(str "hello, " name "!"))
(def showcase-value {:number 0
:string "string"
:keyword :keyword
:symbol 'symbol
:vector [0 1 2 3 4 5 6]
:set '#{a b c}
:map '{k1 v1 k2 v2}})
(defprotocol MyProtocol
(-method1 [this])
(-method2
[this param1]
[this param1 param2]))
(deftype MyType [f1 f2]
MyProtocol
(-method1 [this])
(-method2 [this param1])
(-method2 [this param1 param2]))
; custom formatter defined in user code
(deftype Person [name address]
IFormat
(-header [_] (render-markup [["span" "color:white;background-color:#999;padding:0px 4px;"] (str "Person: " name)]))
(-has-body [_] (some? address))
(-body [_] (render-markup (<standard-body> (string/split-lines address)))))
(log nil 42 0.1 :keyword 'symbol "string" #"regexp" [1 2 3] {:k1 1 :k2 2} #{1 2 3}) ; simple values
(log [nil 42 0.1 :keyword 'symbol "string" #"regexp" [1 2 3] {:k1 1 :k2 2} #{1 2 3}]) ; vector of simple values
(log (range 100) (range 101) (range 220) (interleave (repeat :even) (repeat :odd))) ; lists, including infinite ones
(log {:k1 'v1 :k2 'v2 :k3 'v3 :k4 'v4 :k5 'v5 :k6 'v6 :k7 'v7 :k8 'v8 :k9 'v9}) ; maps
(log #{1 2 3 4 5 6 7 8 9 10 11 12 13 14 15}) ; sets
(log hello filter js/document.getElementById) ; functions cljs / native
(log (fn []) (fn [p__gen p123]) #(str %) (js* "function(x) { console.log(x); }")) ; lambda functions
(log [#js {:key "val"} #js [1 2 3] (js-obj "k1" "v1" "k2" :v2) js/window]) ; js interop
(log [1 2 3 [10 20 30 [100 200 300 [1000 2000 3000 :*]]]]) ; nested vectors
(log (with-meta ["has meta data"] {:some "meta-data"})) ; values with metadata
(log (Person. "<NAME>" "Office 33\n27 Colmore Row\nBirmingham\nEngland") (Person. "Mr Homeless" nil)) ; custom formatting
(log (atom showcase-value)) ; atoms
(log (MyType. 1 2)) ; types
; <-- MEAT STOPS HERE ---
(def state (atom []))
(defn simple-fn [count]
(let [rng (range count)]
(doseq [item rng]
(let [s (str "item=" item)]
(swap! state conj s))))) ; <- set breakpoint HERE and see Scope variables in DevTools
(defn fn-returns-nil [])
(defn ^:export sanity-test-handler []
((fn-returns-nil) "param")) ; a test of sanity checker
(defn ^:export breakpoint-test-handler []
(simple-fn 10)
(log state))
| true | (ns devtools-sample.core
(:require-macros [devtools-sample.logging :refer [log]])
(:require [clojure.string :as string]
[devtools-sample.boot :refer [boot!]]
[devtools.formatters.markup :refer [<standard-body>]]
[devtools.formatters.templating :refer [render-markup]]
[devtools.protocols :refer [IFormat]]))
(boot! "/src/demo/devtools_sample/core.cljs")
; --- MEAT STARTS HERE -->
; note: (log ...) expands to (.log js/console ...)
(defn hello [name]
(str "hello, " name "!"))
(def showcase-value {:number 0
:string "string"
:keyword :keyword
:symbol 'symbol
:vector [0 1 2 3 4 5 6]
:set '#{a b c}
:map '{k1 v1 k2 v2}})
(defprotocol MyProtocol
(-method1 [this])
(-method2
[this param1]
[this param1 param2]))
(deftype MyType [f1 f2]
MyProtocol
(-method1 [this])
(-method2 [this param1])
(-method2 [this param1 param2]))
; custom formatter defined in user code
(deftype Person [name address]
IFormat
(-header [_] (render-markup [["span" "color:white;background-color:#999;padding:0px 4px;"] (str "Person: " name)]))
(-has-body [_] (some? address))
(-body [_] (render-markup (<standard-body> (string/split-lines address)))))
(log nil 42 0.1 :keyword 'symbol "string" #"regexp" [1 2 3] {:k1 1 :k2 2} #{1 2 3}) ; simple values
(log [nil 42 0.1 :keyword 'symbol "string" #"regexp" [1 2 3] {:k1 1 :k2 2} #{1 2 3}]) ; vector of simple values
(log (range 100) (range 101) (range 220) (interleave (repeat :even) (repeat :odd))) ; lists, including infinite ones
(log {:k1 'v1 :k2 'v2 :k3 'v3 :k4 'v4 :k5 'v5 :k6 'v6 :k7 'v7 :k8 'v8 :k9 'v9}) ; maps
(log #{1 2 3 4 5 6 7 8 9 10 11 12 13 14 15}) ; sets
(log hello filter js/document.getElementById) ; functions cljs / native
(log (fn []) (fn [p__gen p123]) #(str %) (js* "function(x) { console.log(x); }")) ; lambda functions
(log [#js {:key "val"} #js [1 2 3] (js-obj "k1" "v1" "k2" :v2) js/window]) ; js interop
(log [1 2 3 [10 20 30 [100 200 300 [1000 2000 3000 :*]]]]) ; nested vectors
(log (with-meta ["has meta data"] {:some "meta-data"})) ; values with metadata
(log (Person. "PI:NAME:<NAME>END_PI" "Office 33\n27 Colmore Row\nBirmingham\nEngland") (Person. "Mr Homeless" nil)) ; custom formatting
(log (atom showcase-value)) ; atoms
(log (MyType. 1 2)) ; types
; <-- MEAT STOPS HERE ---
(def state (atom []))
(defn simple-fn [count]
(let [rng (range count)]
(doseq [item rng]
(let [s (str "item=" item)]
(swap! state conj s))))) ; <- set breakpoint HERE and see Scope variables in DevTools
(defn fn-returns-nil [])
(defn ^:export sanity-test-handler []
((fn-returns-nil) "param")) ; a test of sanity checker
(defn ^:export breakpoint-test-handler []
(simple-fn 10)
(log state))
|
[
{
"context": ";; The MIT License (MIT)\n;;\n;; Copyright (c) 2016 Richard Hull\n;;\n;; Permission is hereby granted, free of charg",
"end": 62,
"score": 0.9998857378959656,
"start": 50,
"tag": "NAME",
"value": "Richard Hull"
},
{
"context": "ented by the Greek letter ρ (rho).\n\n Developed by Karl Pearson from a related idea introduced by Francis Galton\n",
"end": 1390,
"score": 0.9996550679206848,
"start": 1378,
"tag": "NAME",
"value": "Karl Pearson"
},
{
"context": " by Karl Pearson from a related idea introduced by Francis Galton\n in the 1880s, this product-moment correlation c",
"end": 1439,
"score": 0.956912636756897,
"start": 1425,
"tag": "NAME",
"value": "Francis Galton"
},
{
"context": "ample correlation\n coefficient was carried out by Anil Kumar Gain and R. A. Fisher from the\n University of Cambrid",
"end": 1711,
"score": 0.9998992085456848,
"start": 1696,
"tag": "NAME",
"value": "Anil Kumar Gain"
},
{
"context": "coefficient was carried out by Anil Kumar Gain and R. A. Fisher from the\n University of Cambridge.\n\n See: https",
"end": 1728,
"score": 0.9998998641967773,
"start": 1716,
"tag": "NAME",
"value": "R. A. Fisher"
}
] | src/clustering/distance/pearson.cljc | CharlesHD/clustering | 17 | ;; The MIT License (MIT)
;;
;; Copyright (c) 2016 Richard Hull
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns clustering.distance.pearson
"Pearson's correlation coefficient is the covariance of the two variables
divided by the product of their standard deviations, and is commonly
represented by the Greek letter ρ (rho).
Developed by Karl Pearson from a related idea introduced by Francis Galton
in the 1880s, this product-moment correlation coefficient is widely used in
the sciences as a measure of the degree of linear dependence between two
variables. Early work on the distribution of the sample correlation
coefficient was carried out by Anil Kumar Gain and R. A. Fisher from the
University of Cambridge.
See: https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient"
(:require
[clustering.distance.common :refer :all]))
(defn- div0 [x y]
(if (zero? y) 0 (/ x y)))
(defn correlation-coefficient
"Pearson product-moment correlation coefficient is a measure of the linear
correlation between two variables X and Y, giving a value between +1 and −1
inclusive, where 1 is total positive correlation, 0 is no correlation, and
−1 is total negative correlation."
[xs ys]
(let [len (count xs)
sumx (sum xs)
sumy (sum ys)
numer (- (sum-product xs ys) (div0 (* sumx sumy) len))
denom (Math/sqrt (* (- (sum-squares xs) (div0 (sqr sumx) len))
(- (sum-squares ys) (div0 (sqr sumy) len))))]
(div0 numer denom)))
(defn distance
"Pearson's distance can be defined from their correlation coefficient as:
d(X,Y) = 1 - ρ(X,Y)
Considering that the Pearson correlation coefficient falls between [−1, 1],
the Pearson distance lies in [0, 2]."
[xs ys]
(- 1.0 (correlation-coefficient xs ys)))
(defn squared-distance
"The Pearson Squared distance measures the similarity in shape between two
profiles, but can also capture inverse relationships.
While most combinations of clustering algorithm and distance metrics provide
meaningful results, there are a few combinations that are difficult to
interpret. In particular, combining K-Means clustering with the Pearson
Squared distance metric can lead to non-intuitive centroid plots since the
centroid represents the mean of the cluster and Pearson Squared can group
anti-correlated objects. In these cases, visually drilling into clusters to
see the individual members through the use of Cluster Plots produce better
results."
[xs ys]
(- 1.0 (* 2 (correlation-coefficient xs ys))))
| 31198 | ;; The MIT License (MIT)
;;
;; Copyright (c) 2016 <NAME>
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns clustering.distance.pearson
"Pearson's correlation coefficient is the covariance of the two variables
divided by the product of their standard deviations, and is commonly
represented by the Greek letter ρ (rho).
Developed by <NAME> from a related idea introduced by <NAME>
in the 1880s, this product-moment correlation coefficient is widely used in
the sciences as a measure of the degree of linear dependence between two
variables. Early work on the distribution of the sample correlation
coefficient was carried out by <NAME> and <NAME> from the
University of Cambridge.
See: https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient"
(:require
[clustering.distance.common :refer :all]))
(defn- div0 [x y]
(if (zero? y) 0 (/ x y)))
(defn correlation-coefficient
"Pearson product-moment correlation coefficient is a measure of the linear
correlation between two variables X and Y, giving a value between +1 and −1
inclusive, where 1 is total positive correlation, 0 is no correlation, and
−1 is total negative correlation."
[xs ys]
(let [len (count xs)
sumx (sum xs)
sumy (sum ys)
numer (- (sum-product xs ys) (div0 (* sumx sumy) len))
denom (Math/sqrt (* (- (sum-squares xs) (div0 (sqr sumx) len))
(- (sum-squares ys) (div0 (sqr sumy) len))))]
(div0 numer denom)))
(defn distance
"Pearson's distance can be defined from their correlation coefficient as:
d(X,Y) = 1 - ρ(X,Y)
Considering that the Pearson correlation coefficient falls between [−1, 1],
the Pearson distance lies in [0, 2]."
[xs ys]
(- 1.0 (correlation-coefficient xs ys)))
(defn squared-distance
"The Pearson Squared distance measures the similarity in shape between two
profiles, but can also capture inverse relationships.
While most combinations of clustering algorithm and distance metrics provide
meaningful results, there are a few combinations that are difficult to
interpret. In particular, combining K-Means clustering with the Pearson
Squared distance metric can lead to non-intuitive centroid plots since the
centroid represents the mean of the cluster and Pearson Squared can group
anti-correlated objects. In these cases, visually drilling into clusters to
see the individual members through the use of Cluster Plots produce better
results."
[xs ys]
(- 1.0 (* 2 (correlation-coefficient xs ys))))
| true | ;; The MIT License (MIT)
;;
;; Copyright (c) 2016 PI:NAME:<NAME>END_PI
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns clustering.distance.pearson
"Pearson's correlation coefficient is the covariance of the two variables
divided by the product of their standard deviations, and is commonly
represented by the Greek letter ρ (rho).
Developed by PI:NAME:<NAME>END_PI from a related idea introduced by PI:NAME:<NAME>END_PI
in the 1880s, this product-moment correlation coefficient is widely used in
the sciences as a measure of the degree of linear dependence between two
variables. Early work on the distribution of the sample correlation
coefficient was carried out by PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI from the
University of Cambridge.
See: https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient"
(:require
[clustering.distance.common :refer :all]))
(defn- div0 [x y]
(if (zero? y) 0 (/ x y)))
(defn correlation-coefficient
"Pearson product-moment correlation coefficient is a measure of the linear
correlation between two variables X and Y, giving a value between +1 and −1
inclusive, where 1 is total positive correlation, 0 is no correlation, and
−1 is total negative correlation."
[xs ys]
(let [len (count xs)
sumx (sum xs)
sumy (sum ys)
numer (- (sum-product xs ys) (div0 (* sumx sumy) len))
denom (Math/sqrt (* (- (sum-squares xs) (div0 (sqr sumx) len))
(- (sum-squares ys) (div0 (sqr sumy) len))))]
(div0 numer denom)))
(defn distance
"Pearson's distance can be defined from their correlation coefficient as:
d(X,Y) = 1 - ρ(X,Y)
Considering that the Pearson correlation coefficient falls between [−1, 1],
the Pearson distance lies in [0, 2]."
[xs ys]
(- 1.0 (correlation-coefficient xs ys)))
(defn squared-distance
"The Pearson Squared distance measures the similarity in shape between two
profiles, but can also capture inverse relationships.
While most combinations of clustering algorithm and distance metrics provide
meaningful results, there are a few combinations that are difficult to
interpret. In particular, combining K-Means clustering with the Pearson
Squared distance metric can lead to non-intuitive centroid plots since the
centroid represents the mean of the cluster and Pearson Squared can group
anti-correlated objects. In these cases, visually drilling into clusters to
see the individual members through the use of Cluster Plots produce better
results."
[xs ys]
(- 1.0 (* 2 (correlation-coefficient xs ys))))
|
[
{
"context": " Based on article \"A data.table and dplyr tour\" by Atrebas dated March 3, 2019\n;; https://atrebas.github.io/",
"end": 394,
"score": 0.992941677570343,
"start": 387,
"tag": "NAME",
"value": "Atrebas"
},
{
"context": "ata.table\n\n;; DT[, V1 := V1^2]\n;; DT\n\n;; TODO (clojisr): another tricky binary operator\n(r '(bra ~DT nil",
"end": 44974,
"score": 0.6064640283584595,
"start": 44970,
"tag": "USERNAME",
"value": "jisr"
}
] | resources/notebooks/datatable_dplyr.clj | pink-gorilla/clojisr-gorilla | 1 | (ns techtest.datatable-dplyr
(:require [tech.ml.dataset :as ds]
[tech.ml.dataset.column :as col]
[tech.v2.datatype.functional :as dfn]
[tech.v2.datatype :as dtype]
[fastmath.core :as m]
[clojure.string :as str]))
;; Comparizon of tech.ml.dataset with datatable and dplyr
;; Based on article "A data.table and dplyr tour" by Atrebas dated March 3, 2019
;; https://atrebas.github.io/post/2019-03-03-datatable-dplyr/
;; Dataset names used:
;;
;; DT - R data.table object
;; DF - R tibble (dplyr) object
;; DS - tech.ml.dataset object
;; # Preparation
;; load R package
(require '[clojisr.v1.r :as r :refer [r r->clj]]
'[clojisr.v1.require :refer [require-r]])
(require-r '[base]
'[utils]
'[stats]
'[tidyr]
'[dplyr :as dpl]
'[data.table :as dt])
(r.base/options :width 160)
(r.base/set-seed 1)
;; HELPER functions
(defn aggregate
([agg-fns-map ds]
(aggregate {} agg-fns-map ds))
([m agg-fns-map-or-vector ds]
(into m (map (fn [[k agg-fn]]
[k (agg-fn ds)]) (if (map? agg-fns-map-or-vector)
agg-fns-map-or-vector
(map-indexed vector agg-fns-map-or-vector))))))
(def aggregate->dataset (comp ds/->dataset vector aggregate))
(defn group-by-columns-or-fn-and-aggregate
[key-fn-or-gr-colls agg-fns-map ds]
(->> (if (fn? key-fn-or-gr-colls)
(ds/group-by key-fn-or-gr-colls ds)
(ds/group-by identity key-fn-or-gr-colls ds))
(map (fn [[group-idx group-ds]]
(let [group-idx-m (if (map? group-idx)
group-idx
{:_fn group-idx})]
(aggregate group-idx-m agg-fns-map group-ds))))
ds/->dataset))
(defn asc-desc-comparator
[orders]
(if (every? #(= % :asc) orders)
compare
(let [mults (map #(if (= % :asc) 1 -1) orders)]
(fn [v1 v2]
(reduce (fn [_ [a b ^long mult]]
(let [c (compare a b)]
(if-not (zero? c)
(reduced (* mult c))
c))) 0 (map vector v1 v2 mults))))))
(defn sort-by-columns-with-orders
([cols ds]
(sort-by-columns-with-orders cols (repeat (count cols) :asc) ds))
([cols orders ds]
(let [sel (apply juxt (map #(fn [ds] (get ds %)) cols))
comp-fn (asc-desc-comparator orders)]
(ds/sort-by sel comp-fn ds))))
(defn map-v [f coll]
(reduce-kv (fn [m k v] (assoc m k (f v))) (empty coll) coll))
(defn filter-by-external-values->indices
[pred values]
(->> values
(map-indexed vector)
(filter (comp pred second))
(map first)))
(defn my-max [xs] (reduce #(if (pos? (compare %1 %2)) %1 %2) xs))
(defn my-min [xs] (reduce #(if (pos? (compare %2 %1)) %1 %2) xs))
(defn- ensure-seq
[v]
(if (seqable? v) v [v]))
(defn apply-to-columns
[f columns ds]
(let [names (ds/column-names ds)
columns (set (if (= :all columns) names columns))
ff (fn [col]
(if (columns (col/column-name col))
(f col)
col))]
(->> names
(map (comp ensure-seq ff ds))
(zipmap names)
(ds/name-values-seq->dataset))))
;; # Create example data
;; ---- data.table
;; DT <- data.table(V1 = rep(c(1L, 2L), 5)[-10],
;; V2 = 1:9,
;; V3 = c(0.5, 1.0, 1.5),
;; V4 = rep(LETTERS[1:3], 3))
;; class(DT)
;; DT
(def DT (dt/data-table :V1 (r/bra (r.base/rep [1 2] 5) -10)
:V2 (r/colon 1 9)
:V3 [0.5 1.0 1.5]
:V4 (r.base/rep (r/bra 'LETTERS (r/colon 1 3)) 3)))
(r.base/class DT)
;; => [1] "data.table" "data.frame"
DT
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 2 8 1.0 B
;; 9: 1 9 1.5 C
;; ---- dplyr
;; DF <- tibble(V1 = rep(c(1L, 2L), 5)[-10],
;; V2 = 1:9,
;; V3 = rep(c(0.5, 1.0, 1.5), 3),
;; V4 = rep(LETTERS[1:3], 3))
;; class(DF)
;; DF
(def DF (dpl/tibble :V1 (r/bra (r.base/rep [1 2] 5) -10)
:V2 (r/colon 1 9)
:V3 (r.base/rep [0.5 1.0 1.5] 3)
:V4 (r.base/rep (r/bra 'LETTERS (r/colon 1 3)) 3)))
(r.base/class DF)
;; => [1] "tbl_df" "tbl" "data.frame"
DF
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; 4 2 4 0.5 A
;; 5 1 5 1 B
;; 6 2 6 1.5 C
;; 7 1 7 0.5 A
;; 8 2 8 1 B
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
(def DS (ds/name-values-seq->dataset {:V1 (take 9 (cycle [1 2]))
:V2 (range 1 10)
:V3 (take 9 (cycle [0.5 1.0 1.5]))
:V4 (take 9 (cycle [\A \B \C]))}))
(class DS)
;; => tech.ml.dataset.impl.dataset.Dataset
DS
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
;; TODO (tech.ml.dataset): char datatype? (now inferred as Object)
(col/metadata (DS :V4))
;; => {:name :V4, :size 9, :datatype :object}
;; # Basic operations
;; ## Filter rows
;; ### Filter rows using indices
;; ---- data.table
;; DT[3:4,]
;; DT[3:4] # same
;; we use symbolic call here since there is a bug about interpreting R empty symbol
(r '(bra ~DT (colon 3 4) nil))
;; => V1 V2 V3 V4
;; 1: 1 3 1.5 C
;; 2: 2 4 0.5 A
(r/bra DT (r/colon 3 4))
;; => V1 V2 V3 V4
;; 1: 1 3 1.5 C
;; 2: 2 4 0.5 A
;; ---- dplyr
;; DF[3:4,]
;; slice(DF, 3:4) # same
(r '(bra ~DF (colon 3 4) nil))
;; => # A tibble: 2 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 3 1.5 C
;; 2 2 4 0.5 A
(dpl/slice DF (r/colon 3 4))
;; => # A tibble: 2 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 3 1.5 C
;; 2 2 4 0.5 A
;; ------ tech.ml.datatable
;; NOTE: row ids start at `0`
(ds/select-rows DS [2 3])
;; => _unnamed [2 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; ### Discard rows using negative indices
;; ---- data.table
;; DT[!3:7,]
;; DT[-(3:7)] # same
(r '(bra ~DT (! (colon 3 7)) nil))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 2 8 1.0 B
;; 4: 1 9 1.5 C
(r/bra DT (r/r- (r/colon 3 7)))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 2 8 1.0 B
;; 4: 1 9 1.5 C
;; ---- dplyr
;; DF[-(3:7),]
;; slice(DF, -(3:7)) # same
;; TODO (clojisr): (symbolic) unary `-` on `colon` doesn't work (workaround below)
(r '(bra ~DF (- [(colon 3 7)]) nil))
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 2 8 1 B
;; 4 1 9 1.5 C
(dpl/slice DF (r/r- (r/colon 3 7)))
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 2 8 1 B
;; 4 1 9 1.5 C
;; ---- tech.ml.dataset
(ds/drop-rows DS (range 2 7))
;; => _unnamed [4 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
;; ### Filter rows using a logical expression
;; ---- data.table
;; DT[V2 > 5]
;; DT[V4 %chin% c("A", "C")] # fast %in% for character
(r/bra DT '(> V2 5))
;; => V1 V2 V3 V4
;; 1: 2 6 1.5 C
;; 2: 1 7 0.5 A
;; 3: 2 8 1.0 B
;; 4: 1 9 1.5 C
;; TODO (clojisr): add %chin% as binary operation
(r/bra DT '((rsymbol "%chin%") V4 ["A" "C"]))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 1 3 1.5 C
;; 3: 2 4 0.5 A
;; 4: 2 6 1.5 C
;; 5: 1 7 0.5 A
;; 6: 1 9 1.5 C
;; ---- dplyr
;; filter(DF, V2 > 5)
;; filter(DF, V4 %in% c("A", "C"))
(dpl/filter DF '(> V2 5))
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 2 6 1.5 C
;; 2 1 7 0.5 A
;; 3 2 8 1 B
;; 4 1 9 1.5 C
(dpl/filter DF '(%in% V4 ["A" "C"]))
;; => # A tibble: 6 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 1 3 1.5 C
;; 3 2 4 0.5 A
;; 4 2 6 1.5 C
;; 5 1 7 0.5 A
;; 6 1 9 1.5 C
;; ---- tech.ml.dataset
(ds/filter-column #(> ^long % 5) :V2 DS)
;; => _unnamed [4 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
(ds/filter-column #{\A \C} :V4 DS)
;; => _unnamed [6 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 1 | 9 | 1.500 | C |
;; ### Filter rows using multiple conditions
;; ---- data.table
;; DT[V1 == 1 & V4 == "A"]
(r/bra DT '(& (== V1 1)
(== V4 "A")))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 1 7 0.5 A
;; ---- dplyr
;; filter(DF, V1 == 1, V4 == "A")
(dpl/filter DF '(== V1 1) '(== V4 "A"))
;; => # A tibble: 2 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 1 7 0.5 A
;; ---- tech.ml.dataset
(ds/filter #(and (= (:V1 %) 1)
(= (:V4 %) \A)) DS)
;; => _unnamed [2 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 1 | 7 | 0.5000 | A |
;; ### Filter unique rows
;; ---- data.table
;; unique(DT)
;; unique(DT, by = c("V1", "V4")) # returns all cols
(r.base/unique DT)
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 2 8 1.0 B
;; 9: 1 9 1.5 C
(r.base/unique DT :by ["V1" "V4"])
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; ---- dplyr
;; distinct(DF) # distinct_all(DF)
;; distinct_at(DF, vars(V1, V4)) # returns selected cols
;; # see also ?distinct_if
(dpl/distinct DF)
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; 4 2 4 0.5 A
;; 5 1 5 1 B
;; 6 2 6 1.5 C
;; 7 1 7 0.5 A
;; 8 2 8 1 B
;; 9 1 9 1.5 C
(dpl/distinct_at DF (dpl/vars 'V1 'V4))
;; => # A tibble: 6 x 2
;; V1 V4
;; <dbl> <chr>
;; 1 1 A
;; 2 2 B
;; 3 1 C
;; 4 2 A
;; 5 1 B
;; 6 2 C
;; ---- tech.ml.dataset
(ds/unique-by identity {:column-name-seq (ds/column-names DS)} DS)
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
(ds/unique-by identity {:column-name-seq [:V1 :V4]} DS)
;; => _unnamed [6 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; ### Discard rows with missing values
;; ---- data.table
;; na.omit(DT, cols = 1:4) # fast S3 method with cols argument
(r.stats/na-omit DT :cols (r/colon 1 4))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 2 8 1.0 B
;; 9: 1 9 1.5 C
;; ---- dplyr
;; tidyr::drop_na(DF, names(DF))
(r.tidyr/drop_na DF (r.base/names DF))
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; 4 2 4 0.5 A
;; 5 1 5 1 B
;; 6 2 6 1.5 C
;; 7 1 7 0.5 A
;; 8 2 8 1 B
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
;; note: missing works on whole dataset, to select columns, first create dataset with selected columns
(ds/drop-rows DS (ds/missing DS))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
;; ### Other filters
;; ---- data.table
;; DT[sample(.N, 3)] # .N = nb of rows in DT
;; DT[sample(.N, .N / 2)]
;; DT[frankv(-V1, ties.method = "dense") < 2]
(r/bra DT '(sample .N 3))
;; => V1 V2 V3 V4
;; 1: 1 7 0.5 A
;; 2: 1 3 1.5 C
;; 3: 2 6 1.5 C
(r/bra DT '(sample .N (/ .N 2)))
;; => V1 V2 V3 V4
;; 1: 2 6 1.5 C
;; 2: 1 7 0.5 A
;; 3: 2 4 0.5 A
;; 4: 2 8 1.0 B
(r/bra DT '(< (frankv (- V1) :ties.method "dense") 2))
;; => V1 V2 V3 V4
;; 1: 2 2 1.0 B
;; 2: 2 4 0.5 A
;; 3: 2 6 1.5 C
;; 4: 2 8 1.0 B
;; ---- dplyr
;; sample_n(DF, 3) # n random rows
;; sample_frac(DF, 0.5) # fraction of random rows
;; top_n(DF, 1, V1) # top n entries (includes equals)
(dpl/sample_n DF 3)
;; => # A tibble: 3 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 5 1 B
(dpl/sample_frac DF 0.5)
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 7 0.5 A
;; 2 1 3 1.5 C
;; 3 2 6 1.5 C
;; 4 2 2 1 B
(dpl/top_n DF 1 'V1)
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 2 2 1 B
;; 2 2 4 0.5 A
;; 3 2 6 1.5 C
;; 4 2 8 1 B
;; ---- tech.ml.dataset
(ds/sample 3 DS)
;; => _unnamed [3 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
(ds/sample (/ (ds/row-count DS) 2) DS)
;; => _unnamed [4 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+-------+-----|
;; | 2 | 8 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; NOTE: Here we use `fastmath` to calculate rank.
;; We need also to translate rank to indices.
(->> (m/rank (map - (DS :V1)) :dense)
(filter-by-external-values->indices #(< ^long % 1))
(ds/select-rows DS))
;; => _unnamed [4 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 2 | 2 | 1.000 | B |
;; | 2 | 4 | 0.5000 | A |
;; | 2 | 6 | 1.500 | C |
;; | 2 | 8 | 1.000 | B |
;; #### Convenience functions
;; ---- data.table
;; DT[V4 %like% "^B"]
;; DT[V2 %between% c(3, 5)]
;; DT[data.table::between(V2, 3, 5, incbounds = FALSE)]
;; DT[V2 %inrange% list(-1:1, 1:3)] # see also ?inrange
(r/bra DT '((rsymbol "%like%") V4 "^B"))
;; => V1 V2 V3 V4
;; 1: 2 2 1 B
;; 2: 1 5 1 B
;; 3: 2 8 1 B
(r/bra DT '((rsymbol "%between%") V2 [3 5]))
;; => V1 V2 V3 V4
;; 1: 1 3 1.5 C
;; 2: 2 4 0.5 A
;; 3: 1 5 1.0 B
(r/bra DT '((rsymbol data.table between) V2 3 5 :incbounds false))
;; => V1 V2 V3 V4
;; 1: 2 4 0.5 A
(r/bra DT '((rsymbol "%inrange%") V2 [:!list (colon -1 1) (colon 1 3)]))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; ---- dplyr
;; filter(DF, grepl("^B", V4))
;; filter(DF, dplyr::between(V2, 3, 5))
;; filter(DF, V2 > 3 & V2 < 5)
;; filter(DF, V2 >= -1:1 & V2 <= 1:3)
(dpl/filter DF '(grepl "^B" V4))
;; => # A tibble: 3 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 2 2 1 B
;; 2 1 5 1 B
;; 3 2 8 1 B
(dpl/filter DF '((rsymbol dplyr between) V2 3 5))
;; => # A tibble: 3 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 3 1.5 C
;; 2 2 4 0.5 A
;; 3 1 5 1 B
(dpl/filter DF '(& (> V2 3) (< V2 5)))
;; => # A tibble: 1 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 2 4 0.5 A
(dpl/filter DF '(& (>= V2 (colon -1 1))
(<= V2 (colon 1 3))))
;; => # A tibble: 3 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; ---- tech.ml.dataset
(ds/filter #(re-matches #"^B" (str (:V4 %))) DS)
;; => _unnamed [3 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+-------+-----|
;; | 2 | 2 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
(ds/filter (comp (partial m/between? 3 5) :V2) DS)
;; => _unnamed [3 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
(ds/filter (comp #(< 3 % 5) :V2) DS)
;; => _unnamed [1 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 2 | 4 | 0.5000 | A |
;; note: there is no range on sequences, I have no idea why to use such
(let [mn (min -1 0 1)
mx (max 1 2 3)]
(ds/filter (comp (partial m/between? mn mx) :V2) DS))
;; => _unnamed [3 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; ## Sort rows
;; ### Sort rows by column
;; ---- data.table
;; DT[order(V3)] # see also setorder
(r/bra DT '(order V3))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 4 0.5 A
;; 3: 1 7 0.5 A
;; 4: 2 2 1.0 B
;; 5: 1 5 1.0 B
;; 6: 2 8 1.0 B
;; 7: 1 3 1.5 C
;; 8: 2 6 1.5 C
;; 9: 1 9 1.5 C
;; ---- dplyr
;; arrange(DF, V3)
(dpl/arrange DF 'V3)
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 4 0.5 A
;; 3 1 7 0.5 A
;; 4 2 2 1 B
;; 5 1 5 1 B
;; 6 2 8 1 B
;; 7 1 3 1.5 C
;; 8 2 6 1.5 C
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
(ds/sort-by-column :V3 DS)
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; alternative use of indices
(ds/select-rows DS (m/order (DS :V3)))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; ### Sort rows in decreasing order
;; ---- data.table
;; DT[order(-V3)]
(r/bra DT '(order (- V3)))
;; => V1 V2 V3 V4
;; 1: 1 3 1.5 C
;; 2: 2 6 1.5 C
;; 3: 1 9 1.5 C
;; 4: 2 2 1.0 B
;; 5: 1 5 1.0 B
;; 6: 2 8 1.0 B
;; 7: 1 1 0.5 A
;; 8: 2 4 0.5 A
;; 9: 1 7 0.5 A
;; ---- dplyr
;; arrange(DF, desc(V3))
(dpl/arrange DF '(desc V3))
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 3 1.5 C
;; 2 2 6 1.5 C
;; 3 1 9 1.5 C
;; 4 2 2 1 B
;; 5 1 5 1 B
;; 6 2 8 1 B
;; 7 1 1 0.5 A
;; 8 2 4 0.5 A
;; 9 1 7 0.5 A
;; ---- tech.ml.dataset
(ds/sort-by-column :V3 (comp - compare) DS)
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 3 | 1.500 | C |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 2 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 1 | 0.5000 | A |
;; using ordering indices
(ds/select-rows DS (m/order (DS :V3) true))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 3 | 1.500 | C |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 7 | 0.5000 | A |
;; ### Sort rows based on several columns
;; ---- data.table
;; DT[order(V1, -V2)]
(r/bra DT '(order V1 (- V2)))
;; => V1 V2 V3 V4
;; 1: 1 9 1.5 C
;; 2: 1 7 0.5 A
;; 3: 1 5 1.0 B
;; 4: 1 3 1.5 C
;; 5: 1 1 0.5 A
;; 6: 2 8 1.0 B
;; 7: 2 6 1.5 C
;; 8: 2 4 0.5 A
;; 9: 2 2 1.0 B
;; ---- dplyr
;; arrange(DF, V1, desc(V2))
(dpl/arrange DF 'V1 '(desc V2))
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 9 1.5 C
;; 2 1 7 0.5 A
;; 3 1 5 1 B
;; 4 1 3 1.5 C
;; 5 1 1 0.5 A
;; 6 2 8 1 B
;; 7 2 6 1.5 C
;; 8 2 4 0.5 A
;; 9 2 2 1 B
;; ---- tech.ml.dataset
;; TODO: improve sorting in general
(sort-by-columns-with-orders [:V1 :V2] [:asc :desc] DS)
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 9 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; ## Select columns
;; ### Select one column using an index (not recommended)
;; ---- data.table
;; DT[[3]] # returns a vector
;; DT[, 3] # returns a data.table
(r/brabra DT 3)
;; => [1] 0.5 1.0 1.5 0.5 1.0 1.5 0.5 1.0 1.5
(r '(bra ~DT nil 3))
;; => V3
;; 1: 0.5
;; 2: 1.0
;; 3: 1.5
;; 4: 0.5
;; 5: 1.0
;; 6: 1.5
;; 7: 0.5
;; 8: 1.0
;; 9: 1.5
;; ---- dplyr
;; DF[[3]] # returns a vector
;; DF[3] # returns a tibble
(r/brabra DF 3)
;; => [1] 0.5 1.0 1.5 0.5 1.0 1.5 0.5 1.0 1.5
(r/bra DF 3)
;; => # A tibble: 9 x 1
;; V3
;; <dbl>
;; 1 0.5
;; 2 1
;; 3 1.5
;; 4 0.5
;; 5 1
;; 6 1.5
;; 7 0.5
;; 8 1
;; 9 1.5
;; ---- tech.ml.dataset
;; NOTE: indices start at 0
(nth (seq DS) 2)
;; => #tech.ml.dataset.column<float64>[9]
;; :V3
;; [0.5000, 1.000, 1.500, 0.5000, 1.000, 1.500, 0.5000, 1.000, 1.500, ]
;; NOTE: column is seqable
(seq (nth (seq DS) 2))
;; => (0.5 1.0 1.5 0.5 1.0 1.5 0.5 1.0 1.5)
(ds/new-dataset [(nth (seq DS) 2)])
;; => _unnamed [9 1]:
;; | :V3 |
;; |--------|
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; ### Select one column using column name
;; DT[, list(V2)] # returns a data.table
;; DT[, .(V2)] # returns a data.table
;; # . is an alias for list
;; DT[, "V2"] # returns a data.table
;; DT[, V2] # returns a vector
;; DT[["V2"]] # returns a vector
;; ---- data.table
(r '(bra ~DT nil [:!list V2]))
;; => V2
;; 1: 1
;; 2: 2
;; 3: 3
;; 4: 4
;; 5: 5
;; 6: 6
;; 7: 7
;; 8: 8
;; 9: 9
(r '(bra ~DT nil (. V2)))
;; => V2
;; 1: 1
;; 2: 2
;; 3: 3
;; 4: 4
;; 5: 5
;; 6: 6
;; 7: 7
;; 8: 8
;; 9: 9
(r '(bra ~DT nil "V2"))
;; => V2
;; 1: 1
;; 2: 2
;; 3: 3
;; 4: 4
;; 5: 5
;; 6: 6
;; 7: 7
;; 8: 8
;; 9: 9
(r '(bra ~DT nil V2))
;; => [1] 1 2 3 4 5 6 7 8 9
(r/brabra DT "V2")
;; => [1] 1 2 3 4 5 6 7 8 9
;; ---- dplyr
;; select(DF, V2) # returns a tibble
;; pull(DF, V2) # returns a vector
;; DF[, "V2"] # returns a tibble
;; DF[["V2"]] # returns a vector
(dpl/select DF 'V2)
;; => # A tibble: 9 x 1
;; V2
;; <int>
;; 1 1
;; 2 2
;; 3 3
;; 4 4
;; 5 5
;; 6 6
;; 7 7
;; 8 8
;; 9 9
(dpl/pull DF 'V2)
;; => [1] 1 2 3 4 5 6 7 8 9
(r '(bra ~DF nil "V2"))
;; => # A tibble: 9 x 1
;; V2
;; <int>
;; 1 1
;; 2 2
;; 3 3
;; 4 4
;; 5 5
;; 6 6
;; 7 7
;; 8 8
;; 9 9
(r/brabra DF "V2")
;; => [1] 1 2 3 4 5 6 7 8 9
;; ---- tech.ml.dataset
;; NOTE: returns dataset
(ds/select-columns DS [:V2])
;; => _unnamed [9 1]:
;; | :V2 |
;; |-----|
;; | 1 |
;; | 2 |
;; | 3 |
;; | 4 |
;; | 5 |
;; | 6 |
;; | 7 |
;; | 8 |
;; | 9 |
;; NOTE: returns dataset
(ds/select DS [:V2] :all)
;; => _unnamed [9 1]:
;; | :V2 |
;; |-----|
;; | 1 |
;; | 2 |
;; | 3 |
;; | 4 |
;; | 5 |
;; | 6 |
;; | 7 |
;; | 8 |
;; | 9 |
;; NOTE: returns column (seqable)
(DS :V2)
;; => #tech.ml.dataset.column<int64>[9]
;; :V2
;; [1, 2, 3, 4, 5, 6, 7, 8, 9, ]
;; NOTE: column as sequence
(seq (DS :V2))
;; => (1 2 3 4 5 6 7 8 9)
;; NOTE: efficient access to data via reader
(dtype/->reader (DS :V2))
;; => [1 2 3 4 5 6 7 8 9]
;; NOTE: returns column
(ds/column DS :V2)
;; => #tech.ml.dataset.column<int64>[9]
;; :V2
;; [1, 2, 3, 4, 5, 6, 7, 8, 9, ]
;; ### Select several columns
;; ---- data.table
;; DT[, .(V2, V3, V4)]
;; DT[, list(V2, V3, V4)]
;; DT[, V2:V4] # select columns between V2 and V4
(r '(bra ~DT nil (. V2 V3 V4)))
;; => V2 V3 V4
;; 1: 1 0.5 A
;; 2: 2 1.0 B
;; 3: 3 1.5 C
;; 4: 4 0.5 A
;; 5: 5 1.0 B
;; 6: 6 1.5 C
;; 7: 7 0.5 A
;; 8: 8 1.0 B
;; 9: 9 1.5 C
(r '(bra ~DT nil (:!list V2 V3 V4)))
;; => V2 V3 V4
;; 1: 1 0.5 A
;; 2: 2 1.0 B
;; 3: 3 1.5 C
;; 4: 4 0.5 A
;; 5: 5 1.0 B
;; 6: 6 1.5 C
;; 7: 7 0.5 A
;; 8: 8 1.0 B
;; 9: 9 1.5 C
(r '(bra ~DT nil (colon V2 V4)))
;; => V2 V3 V4
;; 1: 1 0.5 A
;; 2: 2 1.0 B
;; 3: 3 1.5 C
;; 4: 4 0.5 A
;; 5: 5 1.0 B
;; 6: 6 1.5 C
;; 7: 7 0.5 A
;; 8: 8 1.0 B
;; 9: 9 1.5 C
;; ---- dplyr
;; select(DF, V2, V3, V4)
;; select(DF, V2:V4) # select columns between V2 and V4
(dpl/select DF 'V2 'V3 'V4)
;; => # A tibble: 9 x 3
;; V2 V3 V4
;; <int> <dbl> <chr>
;; 1 1 0.5 A
;; 2 2 1 B
;; 3 3 1.5 C
;; 4 4 0.5 A
;; 5 5 1 B
;; 6 6 1.5 C
;; 7 7 0.5 A
;; 8 8 1 B
;; 9 9 1.5 C
(dpl/select DF '(colon V2 V4))
;; => # A tibble: 9 x 3
;; V2 V3 V4
;; <int> <dbl> <chr>
;; 1 1 0.5 A
;; 2 2 1 B
;; 3 3 1.5 C
;; 4 4 0.5 A
;; 5 5 1 B
;; 6 6 1.5 C
;; 7 7 0.5 A
;; 8 8 1 B
;; 9 9 1.5 C
;; ---- tech.ml.dataset
(ds/select-columns DS [:V2 :V3 :V4])
;; => _unnamed [9 3]:
;; | :V2 | :V3 | :V4 |
;; |-----+--------+-----|
;; | 1 | 0.5000 | A |
;; | 2 | 1.000 | B |
;; | 3 | 1.500 | C |
;; | 4 | 0.5000 | A |
;; | 5 | 1.000 | B |
;; | 6 | 1.500 | C |
;; | 7 | 0.5000 | A |
;; | 8 | 1.000 | B |
;; | 9 | 1.500 | C |
(ds/select DS [:V2 :V3 :V4] :all)
;; => _unnamed [9 3]:
;; | :V2 | :V3 | :V4 |
;; |-----+--------+-----|
;; | 1 | 0.5000 | A |
;; | 2 | 1.000 | B |
;; | 3 | 1.500 | C |
;; | 4 | 0.5000 | A |
;; | 5 | 1.000 | B |
;; | 6 | 1.500 | C |
;; | 7 | 0.5000 | A |
;; | 8 | 1.000 | B |
;; | 9 | 1.500 | C |
;; NOTE: range is not available
;; ### Exclude columns
;; ---- data.table
;; DT[, !c("V2", "V3")]
(r '(bra ~DT nil (! ["V2" "V3"])))
;; => V1 V4
;; 1: 1 A
;; 2: 2 B
;; 3: 1 C
;; 4: 2 A
;; 5: 1 B
;; 6: 2 C
;; 7: 1 A
;; 8: 2 B
;; 9: 1 C
;; ---- dplyr
;; select(DF, -V2, -V3)
(dpl/select DF '(- V2) '(- V3))
;; => # A tibble: 9 x 2
;; V1 V4
;; <dbl> <chr>
;; 1 1 A
;; 2 2 B
;; 3 1 C
;; 4 2 A
;; 5 1 B
;; 6 2 C
;; 7 1 A
;; 8 2 B
;; 9 1 C
;; ---- tech.ml.dataset
(ds/drop-columns DS [:V2 :V3])
;; => _unnamed [9 2]:
;; | :V1 | :V4 |
;; |-----+-----|
;; | 1 | A |
;; | 2 | B |
;; | 1 | C |
;; | 2 | A |
;; | 1 | B |
;; | 2 | C |
;; | 1 | A |
;; | 2 | B |
;; | 1 | C |
;; ### Select/Exclude columns using a character vector
;; ---- data.table
;; cols <- c("V2", "V3")
;; DT[, ..cols] # .. prefix means 'one-level up'
;; DT[, !..cols] # or DT[, -..cols]
(def cols (r.base/<- 'cols ["V2" "V3"]))
(r '(bra ~DT nil ..cols))
;; => V2 V3
;; 1: 1 0.5
;; 2: 2 1.0
;; 3: 3 1.5
;; 4: 4 0.5
;; 5: 5 1.0
;; 6: 6 1.5
;; 7: 7 0.5
;; 8: 8 1.0
;; 9: 9 1.5
(r '(bra ~DT nil !..cols))
;; => V1 V4
;; 1: 1 A
;; 2: 2 B
;; 3: 1 C
;; 4: 2 A
;; 5: 1 B
;; 6: 2 C
;; 7: 1 A
;; 8: 2 B
;; 9: 1 C
(r '(bra ~DT nil -..cols))
;; => V1 V4
;; 1: 1 A
;; 2: 2 B
;; 3: 1 C
;; 4: 2 A
;; 5: 1 B
;; 6: 2 C
;; 7: 1 A
;; 8: 2 B
;; 9: 1 C
;; ---- dplyr
;; cols <- c("V2", "V3")
;; select(DF, !!cols) # unquoting
;; select(DF, -!!cols)
(def cols (r.base/<- 'cols ["V2" "V3"]))
(dpl/select DF '!!cols)
;; => # A tibble: 9 x 2
;; V2 V3
;; <int> <dbl>
;; 1 1 0.5
;; 2 2 1
;; 3 3 1.5
;; 4 4 0.5
;; 5 5 1
;; 6 6 1.5
;; 7 7 0.5
;; 8 8 1
;; 9 9 1.5
(dpl/select DF '-!!cols)
;; => # A tibble: 9 x 2
;; V1 V4
;; <dbl> <chr>
;; 1 1 A
;; 2 2 B
;; 3 1 C
;; 4 2 A
;; 5 1 B
;; 6 2 C
;; 7 1 A
;; 8 2 B
;; 9 1 C
;; ---- tech.ml.dataset
(def cols [:V2 :V3])
(ds/select-columns DS cols)
;; => _unnamed [9 2]:
;; | :V2 | :V3 |
;; |-----+--------|
;; | 1 | 0.5000 |
;; | 2 | 1.000 |
;; | 3 | 1.500 |
;; | 4 | 0.5000 |
;; | 5 | 1.000 |
;; | 6 | 1.500 |
;; | 7 | 0.5000 |
;; | 8 | 1.000 |
;; | 9 | 1.500 |
(ds/drop-columns DS cols)
;; => _unnamed [9 2]:
;; | :V1 | :V4 |
;; |-----+-----|
;; | 1 | A |
;; | 2 | B |
;; | 1 | C |
;; | 2 | A |
;; | 1 | B |
;; | 2 | C |
;; | 1 | A |
;; | 2 | B |
;; | 1 | C |
;; ### Other selections
;; ---- data.table
;; cols <- paste0("V", 1:2)
;; cols <- union("V4", names(DT))
;; cols <- grep("V", names(DT))
;; cols <- grep("3$", names(DT))
;; cols <- grep(".2", names(DT))
;; cols <- grep("^V1|X$", names(DT))
;; cols <- grep("^(?!V2)", names(DT), perl = TRUE)
;; DT[, ..cols]
(r.base/<- 'cols (r.base/paste0 "V" (r/colon 1 2)))
;; => [1] "V1" "V2"
(r '(bra ~DT nil ..cols))
;; => V1 V2
;; 1: 1 1
;; 2: 2 2
;; 3: 1 3
;; 4: 2 4
;; 5: 1 5
;; 6: 2 6
;; 7: 1 7
;; 8: 2 8
;; 9: 1 9
(r.base/<- 'cols (r.base/union "V4" (r.base/names DT)))
;; => [1] "V4" "V1" "V2" "V3"
(r '(bra ~DT nil ..cols))
;; => V4 V1 V2 V3
;; 1: A 1 1 0.5
;; 2: B 2 2 1.0
;; 3: C 1 3 1.5
;; 4: A 2 4 0.5
;; 5: B 1 5 1.0
;; 6: C 2 6 1.5
;; 7: A 1 7 0.5
;; 8: B 2 8 1.0
;; 9: C 1 9 1.5
(r.base/<- 'cols (r.base/grep "V" (r.base/names DT)))
;; => [1] 1 2 3 4
(r '(bra ~DT nil ..cols))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 2 8 1.0 B
;; 9: 1 9 1.5 C
(r.base/<- 'cols (r.base/grep "3$" (r.base/names DT)))
;; => [1] 3
(r '(bra ~DT nil ..cols))
;; => V3
;; 1: 0.5
;; 2: 1.0
;; 3: 1.5
;; 4: 0.5
;; 5: 1.0
;; 6: 1.5
;; 7: 0.5
;; 8: 1.0
;; 9: 1.5
(r.base/<- 'cols (r.base/grep ".2" (r.base/names DT)))
;; => [1] 2
(r '(bra ~DT nil ..cols))
;; => V2
;; 1: 1
;; 2: 2
;; 3: 3
;; 4: 4
;; 5: 5
;; 6: 6
;; 7: 7
;; 8: 8
;; 9: 9
(r.base/<- 'cols (r.base/grep "^V1|X$" (r.base/names DT)))
;; => [1] 1
(r '(bra ~DT nil ..cols))
;; => V1
;; 1: 1
;; 2: 2
;; 3: 1
;; 4: 2
;; 5: 1
;; 6: 2
;; 7: 1
;; 8: 2
;; 9: 1
(r.base/<- 'cols (r.base/grep "^(?!V2)" (r.base/names DT) :perl true))
;; => [1] 1 3 4
(r '(bra ~DT nil ..cols))
;; => V1 V3 V4
;; 1: 1 0.5 A
;; 2: 2 1.0 B
;; 3: 1 1.5 C
;; 4: 2 0.5 A
;; 5: 1 1.0 B
;; 6: 2 1.5 C
;; 7: 1 0.5 A
;; 8: 2 1.0 B
;; 9: 1 1.5 C
;; ---- dplyr
;; select(DF, num_range("V", 1:2))
;; select(DF, V4, everything()) # reorder columns
;; select(DF, contains("V"))
;; select(DF, ends_with("3"))
;; select(DF, matches(".2"))
;; select(DF, one_of(c("V1", "X")))
;; select(DF, -starts_with("V2"))
(dpl/select DF '(num_range "V" (colon 1 2)))
;; => # A tibble: 9 x 2
;; V1 V2
;; <dbl> <int>
;; 1 1 1
;; 2 2 2
;; 3 1 3
;; 4 2 4
;; 5 1 5
;; 6 2 6
;; 7 1 7
;; 8 2 8
;; 9 1 9
(dpl/select DF 'V4 '(everything))
;; => # A tibble: 9 x 4
;; V4 V1 V2 V3
;; <chr> <dbl> <int> <dbl>
;; 1 A 1 1 0.5
;; 2 B 2 2 1
;; 3 C 1 3 1.5
;; 4 A 2 4 0.5
;; 5 B 1 5 1
;; 6 C 2 6 1.5
;; 7 A 1 7 0.5
;; 8 B 2 8 1
;; 9 C 1 9 1.5
(dpl/select DF '(contains "V"))
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; 4 2 4 0.5 A
;; 5 1 5 1 B
;; 6 2 6 1.5 C
;; 7 1 7 0.5 A
;; 8 2 8 1 B
;; 9 1 9 1.5 C
(dpl/select DF '(ends_with "3"))
;; => # A tibble: 9 x 1
;; V3
;; <dbl>
;; 1 0.5
;; 2 1
;; 3 1.5
;; 4 0.5
;; 5 1
;; 6 1.5
;; 7 0.5
;; 8 1
;; 9 1.5
(dpl/select DF '(matches ".2"))
;; => # A tibble: 9 x 1
;; V2
;; <int>
;; 1 1
;; 2 2
;; 3 3
;; 4 4
;; 5 5
;; 6 6
;; 7 7
;; 8 8
;; 9 9
(dpl/select DF '(one_of ["V1" "X"]))
;; => # A tibble: 9 x 1
;; V1
;; <dbl>
;; 1 1
;; 2 2
;; 3 1
;; 4 2
;; 5 1
;; 6 2
;; 7 1
;; 8 2
;; 9 1
(dpl/select DF '(- (starts_with "V2")))
;; => # A tibble: 9 x 3
;; V1 V3 V4
;; <dbl> <dbl> <chr>
;; 1 1 0.5 A
;; 2 2 1 B
;; 3 1 1.5 C
;; 4 2 0.5 A
;; 5 1 1 B
;; 6 2 1.5 C
;; 7 1 0.5 A
;; 8 2 1 B
;; 9 1 1.5 C
;; ---- tech.ml.dataset
;; NOTE: we are using pure Clojure machinery to generate column names
(->> (map (comp keyword str) (repeat "V") (range 1 3))
(ds/select-columns DS))
;; => _unnamed [9 2]:
;; | :V1 | :V2 |
;; |-----+-----|
;; | 1 | 1 |
;; | 2 | 2 |
;; | 1 | 3 |
;; | 2 | 4 |
;; | 1 | 5 |
;; | 2 | 6 |
;; | 1 | 7 |
;; | 2 | 8 |
;; | 1 | 9 |
(->> (distinct (conj (ds/column-names DS) :V4))
(ds/select-columns DS))
;; => _unnamed [9 4]:
;; | :V4 | :V1 | :V2 | :V3 |
;; |-----+-----+-----+--------|
;; | A | 1 | 1 | 0.5000 |
;; | B | 2 | 2 | 1.000 |
;; | C | 1 | 3 | 1.500 |
;; | A | 2 | 4 | 0.5000 |
;; | B | 1 | 5 | 1.000 |
;; | C | 2 | 6 | 1.500 |
;; | A | 1 | 7 | 0.5000 |
;; | B | 2 | 8 | 1.000 |
;; | C | 1 | 9 | 1.500 |
(->> (ds/column-names DS)
(filter #(str/starts-with? (name %) "V"))
(ds/select-columns DS))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
(->> (ds/column-names DS)
(filter #(str/ends-with? (name %) "3"))
(ds/select-columns DS))
;; => _unnamed [9 1]:
;; | :V3 |
;; |--------|
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
(->> (ds/column-names DS)
(filter #(re-matches #".2" (name %)))
(ds/select-columns DS))
;; => _unnamed [9 1]:
;; | :V2 |
;; |-----|
;; | 1 |
;; | 2 |
;; | 3 |
;; | 4 |
;; | 5 |
;; | 6 |
;; | 7 |
;; | 8 |
;; | 9 |
(->> (ds/column-names DS)
(filter #{:V1 :X})
(ds/select-columns DS))
;; => _unnamed [9 1]:
;; | :V1 |
;; |-----|
;; | 1 |
;; | 2 |
;; | 1 |
;; | 2 |
;; | 1 |
;; | 2 |
;; | 1 |
;; | 2 |
;; | 1 |
(->> (ds/column-names DS)
(remove #(str/starts-with? (name %) "V2"))
(ds/select-columns DS))
;; => _unnamed [9 3]:
;; | :V1 | :V3 | :V4 |
;; |-----+--------+-----|
;; | 1 | 0.5000 | A |
;; | 2 | 1.000 | B |
;; | 1 | 1.500 | C |
;; | 2 | 0.5000 | A |
;; | 1 | 1.000 | B |
;; | 2 | 1.500 | C |
;; | 1 | 0.5000 | A |
;; | 2 | 1.000 | B |
;; | 1 | 1.500 | C |
;; ## Summarise data
;; ### Summarise one column
;; ---- data.table
;; DT[, sum(V1)] # returns a vector
;; DT[, .(sum(V1))] # returns a data.table
;; DT[, .(sumV1 = sum(V1))] # returns a data.table
(r '(bra ~DT nil (sum V1)))
;; => [1] 13
(r '(bra ~DT nil (. (sum V1))))
;; => V1
;; 1: 13
(r '(bra ~DT nil (. :sumV1 (sum V1))))
;; => sumV1
;; 1: 13
;; ---- dplyr
;; summarise(DF, sum(V1)) # returns a tibble
;; summarise(DF, sumV1 = sum(V1)) # returns a tibble
(dpl/summarise DF '(sum V1))
;; => # A tibble: 1 x 1
;; `sum(V1)`
;; <dbl>
;; 1 13
(dpl/summarise DF :sumV1 '(sum V1))
;; => # A tibble: 1 x 1
;; sumV1
;; <dbl>
;; 1 13
;; ---- tech.ml.dataset
;; NOTE: using optimized datatype function
(dfn/sum (DS :V1))
;; => 13.0
;; NOTE: using reduce
(reduce + (DS :V1))
;; => 13
;; NOTE: custom aggregation function to get back dataset (issue filled)
;; TODO: aggregate->dataset
(aggregate->dataset [#(dfn/sum (% :V1))] DS)
;; => _unnamed [1 1]:
;; | 0 |
;; |-------|
;; | 13.00 |
(aggregate->dataset {:sumV1 #(dfn/sum (% :V1))} DS)
;; => _unnamed [1 1]:
;; | :sumV1 |
;; |--------|
;; | 13.00 |
;; ### Summarise several columns
;; ---- data.table
;; DT[, .(sum(V1), sd(V3))]
(r '(bra ~DT nil (. (sum V1) (sd V3))))
;; => V1 V2
;; 1: 13 0.4330127
;; ---- dplyr
;; summarise(DF, sum(V1), sd(V3))
(dpl/summarise DF '(sum V1) '(sd V3))
;; => # A tibble: 1 x 2
;; `sum(V1)` `sd(V3)`
;; <dbl> <dbl>
;; 1 13 0.433
;; ---- tech.ml.dataset
(aggregate->dataset [#(dfn/sum (% :V1))
#(dfn/standard-deviation (% :V3))] DS)
;; => _unnamed [1 2]:
;; | 0 | 1 |
;; |-------+--------|
;; | 13.00 | 0.4330 |
;; ### Summarise several columns and assign column names
;; ---- data.table
;; DT[, .(sumv1 = sum(V1),
;; sdv3 = sd(V3))]
(r '(bra ~DT nil (. :sumv1 (sum V1) :sdv3 (sd V3))))
;; => sumv1 sdv3
;; 1: 13 0.4330127
;; ---- dplyr
;; DF %>%
;; summarise(sumv1 = sum(V1),
;; sdv3 = sd(V3))
(-> DF
(dpl/summarise :sumv1 '(sum V1)
:sdv3 '(sd V3)))
;; => # A tibble: 1 x 2
;; sumv1 sdv3
;; <dbl> <dbl>
;; 1 13 0.433
;; ---- tech.ml.dataset
(aggregate->dataset {:sumv1 #(dfn/sum (% :V1))
:sdv3 #(dfn/standard-deviation (% :V3))} DS)
;; => _unnamed [1 2]:
;; | :sumv1 | :sdv3 |
;; |--------+--------|
;; | 13.00 | 0.4330 |
;; ### Summarise a subset of rows
;; ---- data.table
;; DT[1:4, sum(V1)]
(r/bra DT (r/colon 1 4) '(sum V1))
;; => [1] 6
;; ---- dplyr
;; DF %>%
;; slice(1:4) %>%
;; summarise(sum(V1))
(-> DF
(dpl/slice (r/colon 1 4))
(dpl/summarise '(sum V1)))
;; => # A tibble: 1 x 1
;; `sum(V1)`
;; <dbl>
;; 1 6
;; ---- tech.ml.dataset
(-> DS
(ds/select-rows (range 4))
(->> (aggregate->dataset [#(dfn/sum (% :V1))])))
;; => _unnamed [1 1]:
;; | 0 |
;; |-------|
;; | 6.000 |
;; ### additional
;; ---- data.table
;; DT[, data.table::first(V3)]
;; DT[, data.table::last(V3)]
;; DT[5, V3]
;; DT[, uniqueN(V4)]
;; uniqueN(DT)
(r '(bra ~DT nil ((rsymbol data.table first) V3)))
;; => [1] 0.5
(r '(bra ~DT nil ((rsymbol data.table last) V3)))
;; => [1] 1.5
(r/bra DT 5 'V3)
;; => [1] 1
(r '(bra ~DT nil (uniqueN V4)))
;; => [1] 3
(dt/uniqueN DT)
;; => [1] 9
;; ---- dplyr
;; summarise(DF, dplyr::first(V3))
;; summarise(DF, dplyr::last(V3))
;; summarise(DF, nth(V3, 5))
;; summarise(DF, n_distinct(V4))
;; n_distinct(DF)
(dpl/summarise DF '((rsymbol dplyr first) V3))
;; => # A tibble: 1 x 1
;; `dplyr::first(V3)`
;; <dbl>
;; 1 0.5
(dpl/summarise DF '((rsymbol dplyr last) V3))
;; => # A tibble: 1 x 1
;; `dplyr::last(V3)`
;; <dbl>
;; 1 1.5
(dpl/summarise DF '(nth V3 5))
;; => # A tibble: 1 x 1
;; `nth(V3, 5)`
;; <dbl>
;; 1 1
(dpl/summarise DF '(n_distinct V4))
;; => # A tibble: 1 x 1
;; `n_distinct(V4)`
;; <int>
;; 1 3
(dpl/n_distinct DF)
;; => [1] 9
;; ---- tech.ml.dataset
(first (DS :V3))
;; => 0.5
(last (DS :V3))
;; => 1.5
(nth (DS :V3) 5)
;; => 1.5
(count (col/unique (DS :V3)))
;; => 3
(ds/row-count (ds/unique-by identity DS))
;; => 9
;; ## Add/update/delete columns
;; ### Modify a column
;; ---- data.table
;; DT[, V1 := V1^2]
;; DT
;; TODO (clojisr): another tricky binary operator
(r '(bra ~DT nil ((rsymbol ":=") V1 (** V1 2))))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 4 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 4 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 4 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 4 8 1.0 B
;; 9: 1 9 1.5 C
;; ---- dplyr
;; DF <- DF %>% mutate(V1 = V1^2)
;; DF
(def DF (-> DF (dpl/mutate :V1 '(** V1 2))))
DF
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 4 2 1 B
;; 3 1 3 1.5 C
;; 4 4 4 0.5 A
;; 5 1 5 1 B
;; 6 4 6 1.5 C
;; 7 1 7 0.5 A
;; 8 4 8 1 B
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
(ds/update-column DS :V1 #(map (fn [v] (m/pow v 2)) %))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-------+-----+--------+-----|
;; | 1.000 | 1 | 0.5000 | A |
;; | 4.000 | 2 | 1.000 | B |
;; | 1.000 | 3 | 1.500 | C |
;; | 4.000 | 4 | 0.5000 | A |
;; | 1.000 | 5 | 1.000 | B |
;; | 4.000 | 6 | 1.500 | C |
;; | 1.000 | 7 | 0.5000 | A |
;; | 4.000 | 8 | 1.000 | B |
;; | 1.000 | 9 | 1.500 | C |
;; NOTE: using reader (optimized)
(def DS (ds/update-column DS :V1 #(-> (dtype/->reader % :float64)
(dfn/pow 2))))
DS
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-------+-----+--------+-----|
;; | 1.000 | 1 | 0.5000 | A |
;; | 4.000 | 2 | 1.000 | B |
;; | 1.000 | 3 | 1.500 | C |
;; | 4.000 | 4 | 0.5000 | A |
;; | 1.000 | 5 | 1.000 | B |
;; | 4.000 | 6 | 1.500 | C |
;; | 1.000 | 7 | 0.5000 | A |
;; | 4.000 | 8 | 1.000 | B |
;; | 1.000 | 9 | 1.500 | C |
;; ### Add one column
;; ---- data.table
;; DT[, v5 := log(V1)][] # adding [] prints the result
(r '(bra (bra ~DT nil ((rsymbol ":=") v5 (log V1)))))
;; => V1 V2 V3 V4 v5
;; 1: 1 1 0.5 A 0.000000
;; 2: 4 2 1.0 B 1.386294
;; 3: 1 3 1.5 C 0.000000
;; 4: 4 4 0.5 A 1.386294
;; 5: 1 5 1.0 B 0.000000
;; 6: 4 6 1.5 C 1.386294
;; 7: 1 7 0.5 A 0.000000
;; 8: 4 8 1.0 B 1.386294
;; 9: 1 9 1.5 C 0.000000
;; ---- dplyr
(def DF (dpl/mutate DF :v5 '(log V1)))
DF
;; => # A tibble: 9 x 5
;; V1 V2 V3 V4 v5
;; <dbl> <int> <dbl> <chr> <dbl>
;; 1 1 1 0.5 A 0
;; 2 4 2 1 B 1.39
;; 3 1 3 1.5 C 0
;; 4 4 4 0.5 A 1.39
;; 5 1 5 1 B 0
;; 6 4 6 1.5 C 1.39
;; 7 1 7 0.5 A 0
;; 8 4 8 1 B 1.39
;; 9 1 9 1.5 C 0
;; ---- tech.ml.dataset
(def DS (ds/add-or-update-column DS :v5 (dfn/log (DS :V1))))
DS
;; => _unnamed [9 5]:
;; | :V1 | :V2 | :V3 | :V4 | :v5 |
;; |-------+-----+--------+-----+-------|
;; | 1.000 | 1 | 0.5000 | A | 0.000 |
;; | 4.000 | 2 | 1.000 | B | 1.386 |
;; | 1.000 | 3 | 1.500 | C | 0.000 |
;; | 4.000 | 4 | 0.5000 | A | 1.386 |
;; | 1.000 | 5 | 1.000 | B | 0.000 |
;; | 4.000 | 6 | 1.500 | C | 1.386 |
;; | 1.000 | 7 | 0.5000 | A | 0.000 |
;; | 4.000 | 8 | 1.000 | B | 1.386 |
;; | 1.000 | 9 | 1.500 | C | 0.000 |
;; ### Add several columns
;; ---- data.table
;; DT[, c("v6", "v7") := .(sqrt(V1), "X")]
;; DT[, ':='(v6 = sqrt(V1),
;; v7 = "X")] # same, functional form
(r '(bra ~DT nil ((rsymbol ":=") ["v6" "v7"] (. (sqrt V1) "X"))))
;; => V1 V2 V3 V4 v5 v6 v7
;; 1: 1 1 0.5 A 0.000000 1 X
;; 2: 4 2 1.0 B 1.386294 2 X
;; 3: 1 3 1.5 C 0.000000 1 X
;; 4: 4 4 0.5 A 1.386294 2 X
;; 5: 1 5 1.0 B 0.000000 1 X
;; 6: 4 6 1.5 C 1.386294 2 X
;; 7: 1 7 0.5 A 0.000000 1 X
;; 8: 4 8 1.0 B 1.386294 2 X
;; 9: 1 9 1.5 C 0.000000 1 X
(r '(bra ~DT nil ((rsymbol ":=") :v6 (sqrt V1) :v7 "X")))
;; => V1 V2 V3 V4 v5 v6 v7
;; 1: 1 1 0.5 A 0.000000 1 X
;; 2: 4 2 1.0 B 1.386294 2 X
;; 3: 1 3 1.5 C 0.000000 1 X
;; 4: 4 4 0.5 A 1.386294 2 X
;; 5: 1 5 1.0 B 0.000000 1 X
;; 6: 4 6 1.5 C 1.386294 2 X
;; 7: 1 7 0.5 A 0.000000 1 X
;; 8: 4 8 1.0 B 1.386294 2 X
;; 9: 1 9 1.5 C 0.000000 1 X
;; ---- dplyr
;; DF <- mutate(DF, v6 = sqrt(V1), v7 = "X")
(def DF (dpl/mutate DF :v6 '(sqrt V1) :v7 "X"))
DF
;; => # A tibble: 9 x 7
;; V1 V2 V3 V4 v5 v6 v7
;; <dbl> <int> <dbl> <chr> <dbl> <dbl> <chr>
;; 1 1 1 0.5 A 0 1 X
;; 2 4 2 1 B 1.39 2 X
;; 3 1 3 1.5 C 0 1 X
;; 4 4 4 0.5 A 1.39 2 X
;; 5 1 5 1 B 0 1 X
;; 6 4 6 1.5 C 1.39 2 X
;; 7 1 7 0.5 A 0 1 X
;; 8 4 8 1 B 1.39 2 X
;; 9 1 9 1.5 C 0 1 X
;; ---- tech.ml.dataset
(def DS (-> DS
(ds/add-or-update-column :v6 (dfn/sqrt (DS :V1)))
(ds/add-or-update-column :v7 (take (ds/row-count DS) (repeat "X")))))
DS
;; => _unnamed [9 7]:
;; | :V1 | :V2 | :V3 | :V4 | :v5 | :v6 | :v7 |
;; |-------+-----+--------+-----+-------+-------+-----|
;; | 1.000 | 1 | 0.5000 | A | 0.000 | 1.000 | X |
;; | 4.000 | 2 | 1.000 | B | 1.386 | 2.000 | X |
;; | 1.000 | 3 | 1.500 | C | 0.000 | 1.000 | X |
;; | 4.000 | 4 | 0.5000 | A | 1.386 | 2.000 | X |
;; | 1.000 | 5 | 1.000 | B | 0.000 | 1.000 | X |
;; | 4.000 | 6 | 1.500 | C | 1.386 | 2.000 | X |
;; | 1.000 | 7 | 0.5000 | A | 0.000 | 1.000 | X |
;; | 4.000 | 8 | 1.000 | B | 1.386 | 2.000 | X |
;; | 1.000 | 9 | 1.500 | C | 0.000 | 1.000 | X |
;; ### Create one column and remove the others
;; ---- data.table
;; DT[, .(v8 = V3 + 1)]
(r '(bra ~DT nil (. :v8 (+ V3 1))))
;; => v8
;; 1: 1.5
;; 2: 2.0
;; 3: 2.5
;; 4: 1.5
;; 5: 2.0
;; 6: 2.5
;; 7: 1.5
;; 8: 2.0
;; 9: 2.5
;; ---- dplyr
;; transmute(DF, v8 = V3 + 1)
(dpl/transmute DF :v8 '(+ V3 1))
;; => # A tibble: 9 x 1
;; v8
;; <dbl>
;; 1 1.5
;; 2 2
;; 3 2.5
;; 4 1.5
;; 5 2
;; 6 2.5
;; 7 1.5
;; 8 2
;; 9 2.5
;; ---- tech.ml.dataset
(ds/new-dataset [(col/new-column :v8 (dfn/+ (DS :V3) 1))])
;; => _unnamed [9 1]:
;; | :v8 |
;; |-------|
;; | 1.500 |
;; | 2.000 |
;; | 2.500 |
;; | 1.500 |
;; | 2.000 |
;; | 2.500 |
;; | 1.500 |
;; | 2.000 |
;; | 2.500 |
;; ### Remove one column
;; ---- data.table
;; DT[, v5 := NULL]
(r '(bra ~DT nil ((rsymbol ":=") v5 nil)))
;; => V1 V2 V3 V4 v6 v7
;; 1: 1 1 0.5 A 1 X
;; 2: 4 2 1.0 B 2 X
;; 3: 1 3 1.5 C 1 X
;; 4: 4 4 0.5 A 2 X
;; 5: 1 5 1.0 B 1 X
;; 6: 4 6 1.5 C 2 X
;; 7: 1 7 0.5 A 1 X
;; 8: 4 8 1.0 B 2 X
;; 9: 1 9 1.5 C 1 X
;; ---- dplyr
;; DF <- select(DF, -v5)
(def DF (dpl/select DF '(- v5)))
DF
;; => # A tibble: 9 x 6
;; V1 V2 V3 V4 v6 v7
;; <dbl> <int> <dbl> <chr> <dbl> <chr>
;; 1 1 1 0.5 A 1 X
;; 2 4 2 1 B 2 X
;; 3 1 3 1.5 C 1 X
;; 4 4 4 0.5 A 2 X
;; 5 1 5 1 B 1 X
;; 6 4 6 1.5 C 2 X
;; 7 1 7 0.5 A 1 X
;; 8 4 8 1 B 2 X
;; 9 1 9 1.5 C 1 X
;; ---- tech.ml.dataset
(def DS (ds/remove-column DS :v5))
DS
;; => _unnamed [9 6]:
;; | :V1 | :V2 | :V3 | :V4 | :v6 | :v7 |
;; |-------+-----+--------+-----+-------+-----|
;; | 1.000 | 1 | 0.5000 | A | 1.000 | X |
;; | 4.000 | 2 | 1.000 | B | 2.000 | X |
;; | 1.000 | 3 | 1.500 | C | 1.000 | X |
;; | 4.000 | 4 | 0.5000 | A | 2.000 | X |
;; | 1.000 | 5 | 1.000 | B | 1.000 | X |
;; | 4.000 | 6 | 1.500 | C | 2.000 | X |
;; | 1.000 | 7 | 0.5000 | A | 1.000 | X |
;; | 4.000 | 8 | 1.000 | B | 2.000 | X |
;; | 1.000 | 9 | 1.500 | C | 1.000 | X |
;; ### Remove several columns
;; ---- data.table
;; DT[, c("v6", "v7") := NULL]
(r '(bra ~DT nil ((rsymbol ":=") ["v6" "v7"] nil)))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 4 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 4 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 4 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 4 8 1.0 B
;; 9: 1 9 1.5 C
;; ---- dplyr
;; DF <- select(DF, -v6, -v7)
(def DF (dpl/select DF '(- v6) '(- v7)))
DF
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 4 2 1 B
;; 3 1 3 1.5 C
;; 4 4 4 0.5 A
;; 5 1 5 1 B
;; 6 4 6 1.5 C
;; 7 1 7 0.5 A
;; 8 4 8 1 B
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
(def DS (ds/drop-columns DS [:v6 :v7]))
DS
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-------+-----+--------+-----|
;; | 1.000 | 1 | 0.5000 | A |
;; | 4.000 | 2 | 1.000 | B |
;; | 1.000 | 3 | 1.500 | C |
;; | 4.000 | 4 | 0.5000 | A |
;; | 1.000 | 5 | 1.000 | B |
;; | 4.000 | 6 | 1.500 | C |
;; | 1.000 | 7 | 0.5000 | A |
;; | 4.000 | 8 | 1.000 | B |
;; | 1.000 | 9 | 1.500 | C |
;; ### Remove columns using a vector of colnames
;; ---- data.table
;; cols <- c("V3")
;; DT[, (cols) := NULL] # ! not DT[, cols := NULL]
(def cols (r.base/<- 'cols ["V3"]))
;; TODO (clojisr): enable wrapping into parantheses
;; hacking below
(r (str (:object-name DT) "[, (cols) := NULL]"))
;; => V1 V2 V4
;; 1: 1 1 A
;; 2: 4 2 B
;; 3: 1 3 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 6 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; cols <- c("V3")
;; DF <- select(DF, -one_of(cols))
(def cols ["V3"])
(def DF (dpl/select DF '(- (one_of ~cols))))
DF
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <int> <chr>
;; 1 1 1 A
;; 2 4 2 B
;; 3 1 3 C
;; 4 4 4 A
;; 5 1 5 B
;; 6 4 6 C
;; 7 1 7 A
;; 8 4 8 B
;; 9 1 9 C
;; ---- tech.ml.dataset
(def cols [:V3])
(def DS (ds/drop-columns DS cols))
DS
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-----+-----|
;; | 1.000 | 1 | A |
;; | 4.000 | 2 | B |
;; | 1.000 | 3 | C |
;; | 4.000 | 4 | A |
;; | 1.000 | 5 | B |
;; | 4.000 | 6 | C |
;; | 1.000 | 7 | A |
;; | 4.000 | 8 | B |
;; | 1.000 | 9 | C |
;; ### Replace values for rows matching a condition
;; ---- data.table
;; DT[V2 < 4, V2 := 0L]
(r/bra DT '(< V2 4) '((rsymbol ":=") V2 0))
;; => V1 V2 V4
;; 1: 1 0 A
;; 2: 4 0 B
;; 3: 1 0 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 6 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; DF <- mutate(DF, V2 = base::replace(V2, V2 < 4, 0L))
(def DF (dpl/mutate DF '(= V2 ((rsymbol base replace) V2 (< V2 4) 0))))
DF
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 1 0 A
;; 2 4 0 B
;; 3 1 0 C
;; 4 4 4 A
;; 5 1 5 B
;; 6 4 6 C
;; 7 1 7 A
;; 8 4 8 B
;; 9 1 9 C
;; tech.ml.dataset
(def DS (ds/update-column DS :V2 #(map (fn [^long v]
(if (< v 4) 0 v)) %)))
DS
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 1.000 | 0.000 | A |
;; | 4.000 | 0.000 | B |
;; | 1.000 | 0.000 | C |
;; | 4.000 | 4.000 | A |
;; | 1.000 | 5.000 | B |
;; | 4.000 | 6.000 | C |
;; | 1.000 | 7.000 | A |
;; | 4.000 | 8.000 | B |
;; | 1.000 | 9.000 | C |
;; ## by
;; ### By group
;; ---- data.table
;; # one-liner:
;; DT[, .(sumV2 = sum(V2)), by = "V4"]
;; # reordered and indented:
;; DT[, by = V4,
;; .(sumV2 = sum(V2))]
(r '(bra ~DT nil (. :sumV2 (sum V2)) :by "V4"))
;; => V4 sumV2
;; 1: A 11
;; 2: B 13
;; 3: C 15
(r '(bra ~DT nil :by "V4" (. :sumV2 (sum V2))))
;; => V4 sumV2
;; 1: A 11
;; 2: B 13
;; 3: C 15
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; summarise(sumV2 = sum(V2))
(-> DF
(dpl/group_by 'V4)
(dpl/summarise :sumV2 '(sum V2)))
;; => # A tibble: 3 x 2
;; V4 sumV2
;; <chr> <dbl>
;; 1 A 11
;; 2 B 13
;; 3 C 15
;; ---- tech.ml.dataset
;; TODO: group-by and aggragete -> dataset
(group-by-columns-or-fn-and-aggregate [:V4] {:sumV2 #(dfn/sum (% :V2))} DS)
;; => _unnamed [3 2]:
;; | :V4 | :sumV2 |
;; |-----+--------|
;; | B | 13.00 |
;; | C | 15.00 |
;; | A | 11.00 |
;; ### By several groups
;; ---- data.table
;; DT[, keyby = .(V4, V1),
;; .(sumV2 = sum(V2))]
(r '(bra ~DT nil :keyby (. V4 V1) (. :sumV2 (sum V2))))
;; => V4 V1 sumV2
;; 1: A 1 7
;; 2: A 4 4
;; 3: B 1 5
;; 4: B 4 8
;; 5: C 1 9
;; 6: C 4 6
;; ---- dplyr
;; DF %>%
;; group_by(V4, V1) %>%
;; summarise(sumV2 = sum(V2))
(-> DF
(dpl/group_by 'V4 'V1)
(dpl/summarise :sumV2 '(sum V2)))
;; => # A tibble: 6 x 3
;; # Groups: V4 [3]
;; V4 V1 sumV2
;; <chr> <dbl> <dbl>
;; 1 A 1 7
;; 2 A 4 4
;; 3 B 1 5
;; 4 B 4 8
;; 5 C 1 9
;; 6 C 4 6
;; ---- tech.ml.dataset
(->> (group-by-columns-or-fn-and-aggregate [:V4 :V1] {:sumV2 #(dfn/sum (% :V2))} DS)
(sort-by-columns-with-orders [:V4 :V1]))
;; => _unnamed [6 3]:
;; | :V4 | :V1 | :sumV2 |
;; |-----+-------+--------|
;; | A | 1.000 | 7.000 |
;; | A | 4.000 | 4.000 |
;; | B | 1.000 | 5.000 |
;; | B | 4.000 | 8.000 |
;; | C | 1.000 | 9.000 |
;; | C | 4.000 | 6.000 |
;; ### Calling function in by
;; ---- data.table
;; DT[, by = tolower(V4),
;; .(sumV1 = sum(V1))]
(r '(bra ~DT nil :by (tolower V4) (. :sumV1 (sum V1))))
;; => tolower sumV1
;; 1: a 6
;; 2: b 9
;; 3: c 6
;; ---- dplyr
;; DF %>%
;; group_by(tolower(V4)) %>%
;; summarise(sumV1 = sum(V1))
(-> DF
(dpl/group_by '(tolower V4))
(dpl/summarise :sumV1 '(sum V1)))
;; => # A tibble: 3 x 2
;; `tolower(V4)` sumV1
;; <chr> <dbl>
;; 1 a 6
;; 2 b 9
;; 3 c 6
;; ---- tech.ml.dataset
(->> (ds/update-column DS :V4 #(map str/lower-case %))
(group-by-columns-or-fn-and-aggregate [:V4] {:sumV1 #(dfn/sum (% :V1))})
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :sumV1 |
;; |-----+--------|
;; | a | 6.000 |
;; | b | 9.000 |
;; | c | 6.000 |
;; ### Assigning column name in by
;; ---- data.table
;; DT[, keyby = .(abc = tolower(V4)),
;; .(sumV1 = sum(V1))]
(r '(bra ~DT nil :keyby (. :abc (tolower V4)) (. :sumV1 (sum V1))))
;; => abc sumV1
;; 1: a 6
;; 2: b 9
;; 3: c 6
;; ---- dplyr
;; DF %>%
;; group_by(abc = tolower(V4)) %>%
;; summarise(sumV1 = sum(V1))
(-> DF
(dpl/group_by :abc '(tolower V4))
(dpl/summarise :sumV1 '(sum V1)))
;; => # A tibble: 3 x 2
;; abc sumV1
;; <chr> <dbl>
;; 1 a 6
;; 2 b 9
;; 3 c 6
;; ---- tech.ml.dataset
(-> (ds/update-column DS :V4 #(map str/lower-case %))
(ds/rename-columns {:V4 :abc})
(->> (group-by-columns-or-fn-and-aggregate [:abc] {:sumV1 #(dfn/sum (% :V1))})
(ds/sort-by-column :abc)))
;; => _unnamed [3 2]:
;; | :abc | :sumV1 |
;; |------+--------|
;; | a | 6.000 |
;; | b | 9.000 |
;; | c | 6.000 |
;; ### Using a condition in by
;; ---- data.table
;; DT[, keyby = V4 == "A", sum(V1)]
(r '(bra ~DT nil :keyby (== V4 "A") (sum V1)))
;; => V4 V1
;; 1: FALSE 15
;; 2: TRUE 6
;; ---- dplyr
;; DF %>%
;; group_by(V4 == "A") %>%
;; summarise(sum(V1))
(-> DF
(dpl/group_by '(== V4 "A"))
(dpl/summarise '(sum V1)))
;; => # A tibble: 2 x 2
;; `(V4 == "A")` `sum(V1)`
;; <lgl> <dbl>
;; 1 FALSE 15
;; 2 TRUE 6
;; ---- tech.ml.dataset
(group-by-columns-or-fn-and-aggregate #(= (% :V4) \A)
{:sumV1 #(dfn/sum (% :V1))}
DS)
;; => _unnamed [2 2]:
;; | :_fn | :sumV1 |
;; |-------+--------|
;; | false | 15.00 |
;; | true | 6.000 |
;; ### By on a subset of rows
;; ---- data.table
;; DT[1:5, # i
;; .(sumV1 = sum(V1)), # j
;; by = V4] # by
;; ## complete DT[i, j, by] expression!
(r/bra DT (r/colon 1 5) '(. :sumV1 (sum V1)) :by 'V4)
;; => V4 sumV1
;; 1: A 5
;; 2: B 5
;; 3: C 1
;; ---- dplyr
;; DF %>%
;; slice(1:5) %>%
;; group_by(V4) %>%
;; summarise(sumV1 = sum(V1))
(-> DF
(dpl/slice (r/colon 1 5))
(dpl/group_by 'V4)
(dpl/summarise :sumV1 '(sum V1)))
;; => # A tibble: 3 x 2
;; V4 sumV1
;; <chr> <dbl>
;; 1 A 5
;; 2 B 5
;; 3 C 1
;; ---- tech.ml.dataset
(->> (ds/select-rows DS (range 5))
(group-by-columns-or-fn-and-aggregate [:V4] {:sumV1 #(dfn/sum (% :V1))})
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :sumV1 |
;; |-----+--------|
;; | A | 5.000 |
;; | B | 5.000 |
;; | C | 1.000 |
;; ### Count number of observations for each group
;; ---- data.table
;; DT[, .N, by = V4]
(r '(bra ~DT nil .N :by V4))
;; => V4 N
;; 1: A 3
;; 2: B 3
;; 3: C 3
;; ---- dplyr
;; count(DF, V4)
;; DF %>%
;; group_by(V4) %>%
;; tally()
;; DF %>%
;; group_by(V4) %>%
;; summarise(n())
;; DF %>%
;; group_by(V4) %>%
;; group_size() # returns a vector
(dpl/count DF 'V4)
;; => # A tibble: 3 x 2
;; V4 n
;; <chr> <int>
;; 1 A 3
;; 2 B 3
;; 3 C 3
(-> DF (dpl/group_by 'V4) (dpl/tally))
;; => # A tibble: 3 x 2
;; V4 n
;; <chr> <int>
;; 1 A 3
;; 2 B 3
;; 3 C 3
(-> DF (dpl/group_by 'V4) (dpl/summarise '(n)))
;; => # A tibble: 3 x 2
;; V4 `n()`
;; <chr> <int>
;; 1 A 3
;; 2 B 3
;; 3 C 3
(-> DF (dpl/group_by 'V4) (dpl/group_size))
;; => [1] 3 3 3
;; ---- tech.ml.dataset
(group-by-columns-or-fn-and-aggregate [:V4] {:N ds/row-count} DS)
;; => _unnamed [3 2]:
;; | :V4 | :N |
;; |-----+----|
;; | B | 3 |
;; | C | 3 |
;; | A | 3 |
(map-v ds/row-count (ds/group-by-column :V4 DS))
;; => {\A 3, \B 3, \C 3}
(->> (vals (ds/group-by-column :V4 DS))
(map ds/row-count))
;; => (3 3 3)
;; ### Add a column with number of observations for each group
;; ---- data.table
;; DT[, n := .N, by = V1][]
;; DT[, n := NULL] # rm column for consistency
(r '(bra ~DT nil ((rsymbol ":=") n .N) :by V1))
;; => V1 V2 V4 n
;; 1: 1 0 A 5
;; 2: 4 0 B 4
;; 3: 1 0 C 5
;; 4: 4 4 A 4
;; 5: 1 5 B 5
;; 6: 4 6 C 4
;; 7: 1 7 A 5
;; 8: 4 8 B 4
;; 9: 1 9 C 5
;; cleaning
(r '(bra ~DT nil ((rsymbol ":=") n nil)))
;; => V1 V2 V4
;; 1: 1 0 A
;; 2: 4 0 B
;; 3: 1 0 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 6 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; add_count(DF, V1)
;; DF %>%
;; group_by(V1) %>%
;; add_tally()
(dpl/add_count DF 'V1)
;; => # A tibble: 9 x 4
;; V1 V2 V4 n
;; <dbl> <dbl> <chr> <int>
;; 1 1 0 A 5
;; 2 4 0 B 4
;; 3 1 0 C 5
;; 4 4 4 A 4
;; 5 1 5 B 5
;; 6 4 6 C 4
;; 7 1 7 A 5
;; 8 4 8 B 4
;; 9 1 9 C 5
(-> DF
(dpl/group_by 'V1)
(dpl/add_tally))
;; => # A tibble: 9 x 4
;; # Groups: V1 [2]
;; V1 V2 V4 n
;; <dbl> <dbl> <chr> <int>
;; 1 1 0 A 5
;; 2 4 0 B 4
;; 3 1 0 C 5
;; 4 4 4 A 4
;; 5 1 5 B 5
;; 6 4 6 C 4
;; 7 1 7 A 5
;; 8 4 8 B 4
;; 9 1 9 C 5
;; ---- tech.ml.dataset
;; TODO: how to do this optimally and keep order?
(->> (ds/group-by identity [:V1] DS)
(vals)
(map (fn [ds]
(let [rcnt (ds/row-count ds)]
(ds/new-column ds :n (repeat rcnt rcnt)))))
(apply ds/concat)
(sort-by-columns-with-orders [:V2 :V4]))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V4 | :n |
;; |-------+-------+-----+-------|
;; | 1.000 | 0.000 | A | 5.000 |
;; | 4.000 | 0.000 | B | 4.000 |
;; | 1.000 | 0.000 | C | 5.000 |
;; | 4.000 | 4.000 | A | 4.000 |
;; | 1.000 | 5.000 | B | 5.000 |
;; | 4.000 | 6.000 | C | 4.000 |
;; | 1.000 | 7.000 | A | 5.000 |
;; | 4.000 | 8.000 | B | 4.000 |
;; | 1.000 | 9.000 | C | 5.000 |
;; ### Retrieve the first/last/nth observation for each group
;; ---- data.table
;; DT[, data.table::first(V2), by = V4]
;; DT[, data.table::last(V2), by = V4]
;; DT[, V2[2], by = V4]
(r '(bra ~DT nil ((rsymbol data.table first) V2) :by V4))
;; => V4 V1
;; 1: A 0
;; 2: B 0
;; 3: C 0
(r '(bra ~DT nil ((rsymbol data.table last) V2) :by V4))
;; => V4 V1
;; 1: A 7
;; 2: B 8
;; 3: C 9
(r '(bra ~DT nil (bra V2 2) :by V4))
;; => V4 V1
;; 1: A 4
;; 2: B 5
;; 3: C 6
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; summarise(dplyr::first(V2))
;; DF %>%
;; group_by(V4) %>%
;; summarise(dplyr::last(V2))
;; DF %>%
;; group_by(V4) %>%
;; summarise(dplyr::nth(V2, 2))
(-> DF (dpl/group_by 'V4) (dpl/summarise '((rsymbol dplyr first) V2)))
;; => # A tibble: 3 x 2
;; V4 `dplyr::first(V2)`
;; <chr> <dbl>
;; 1 A 0
;; 2 B 0
;; 3 C 0
(-> DF (dpl/group_by 'V4) (dpl/summarise '((rsymbol dplyr last) V2)))
;; => # A tibble: 3 x 2
;; V4 `dplyr::last(V2)`
;; <chr> <dbl>
;; 1 A 7
;; 2 B 8
;; 3 C 9
(-> DF (dpl/group_by 'V4) (dpl/summarise '((rsymbol dplyr nth) V2 2)))
;; => # A tibble: 3 x 2
;; V4 `dplyr::nth(V2, 2)`
;; <chr> <dbl>
;; 1 A 4
;; 2 B 5
;; 3 C 6
;; ---- tech.ml.dataset
(->> (group-by-columns-or-fn-and-aggregate [:V4] {:v #(first (% :V2))} DS)
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :v |
;; |-----+-------|
;; | A | 0.000 |
;; | B | 0.000 |
;; | C | 0.000 |
(->> (group-by-columns-or-fn-and-aggregate [:V4] {:v #(last (% :V2))} DS)
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :v |
;; |-----+-------|
;; | A | 7.000 |
;; | B | 8.000 |
;; | C | 9.000 |
(->> (group-by-columns-or-fn-and-aggregate [:V4] {:v #(nth (% :V2) 1)} DS)
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :v |
;; |-----+-------|
;; | A | 4.000 |
;; | B | 5.000 |
;; | C | 6.000 |
;; -------------------------------
;; # Going further
;; ## Advanced columns manipulation
;; ### Summarise all the columns
;; ---- data.table
;; DT[, lapply(.SD, max)]
(r '(bra ~DT nil (lapply .SD max)))
;; => V1 V2 V4
;; 1: 4 9 C
;; ---- dplyr
;; summarise_all(DF, max)
(dpl/summarise_all DF r.base/max)
;; => # A tibble: 1 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 4 9 C
;; ---- tech.ml.dataset
;; TODO: dfn/max doesn't work
(apply-to-columns my-max :all DS)
;; => _unnamed [1 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 4.000 | 9.000 | C |
;; ### Summarise several columns
;; ---- data.table
;; DT[, lapply(.SD, mean),
;; .SDcols = c("V1", "V2")]
;; # .SDcols is like "_at"
(r '(bra ~DT nil (lapply .SD mean) :.SDcols ["V1" "V2"]))
;; => V1 V2
;; 1: 2.333333 4.333333
;; ---- dplyr
;; summarise_at(DF, c("V1", "V2"), mean)
(dpl/summarise_at DF ["V1" "V2"] r.base/mean)
;; => # A tibble: 1 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 2.33 4.33
;; ---- tech.ml.dataset
;; doesn't work on beta 39
#_(->> (ds/select-columns DS [:V1 :V2])
(apply-to-columns dfn/mean [:V1 :V2]))
;; => _unnamed [1 2]:
;; | :V1 | :V2 |
;; |-------+-------|
;; | 2.333 | 4.333 |
;; ### Summarise several columns by group
;; ---- data.table
;; DT[, by = V4,
;; lapply(.SD, mean),
;; .SDcols = c("V1", "V2")]
;; ## using patterns (regex)
;; DT[, by = V4,
;; lapply(.SD, mean),
;; .SDcols = patterns("V1|V2")]
(r '(bra ~DT nil :by V4 (lapply .SD mean) :.SDcols ["V1" "V2"]))
;; => V4 V1 V2
;; 1: A 2 3.666667
;; 2: B 3 4.333333
;; 3: C 2 5.000000
(r '(bra ~DT nil :by V4 (lapply .SD mean) :.SDcols (patterns "V1|V2")))
;; => V4 V1 V2
;; 1: A 2 3.666667
;; 2: B 3 4.333333
;; 3: C 2 5.000000
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; summarise_at(c("V1", "V2"), mean)
;; ## using select helpers
;; DF %>%
;; group_by(V4) %>%
;; summarise_at(vars(one_of("V1", "V2")), mean)
(-> DF (dpl/group_by 'V4) (dpl/summarise_at ["V1" "V2"] r.base/mean))
;; => # A tibble: 3 x 3
;; V4 V1 V2
;; <chr> <dbl> <dbl>
;; 1 A 2 3.67
;; 2 B 3 4.33
;; 3 C 2 5
(-> DF (dpl/group_by 'V4) (dpl/summarise_at '(vars (one_of "V1" "V2")) r.base/mean))
;; => # A tibble: 3 x 3
;; V4 V1 V2
;; <chr> <dbl> <dbl>
;; 1 A 2 3.67
;; 2 B 3 4.33
;; 3 C 2 5
;; ---- tech.ml.dataset
(->> DS
(group-by-columns-or-fn-and-aggregate [:V4] {:V1 #(dfn/mean (% :V1))
:V2 #(dfn/mean (% :V2))})
(ds/sort-by-column :V4))
;; => _unnamed [3 3]:
;; | :V4 | :V2 | :V1 |
;; |-----+-------+-------|
;; | A | 3.667 | 2.000 |
;; | B | 4.333 | 3.000 |
;; | C | 5.000 | 2.000 |
;; ### Summarise with more than one function by group
;; ---- data.table
;; DT[, by = V4,
;; c(lapply(.SD, sum),
;; lapply(.SD, mean))]
(r '(bra ~DT nil :by V4 [(lapply .SD sum)
(lapply .SD mean)]))
;; => V4 V1 V2 V1 V2
;; 1: A 6 11 2 3.666667
;; 2: B 9 13 3 4.333333
;; 3: C 6 15 2 5.000000
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; summarise_all(list(sum, mean))
(-> DF (dpl/group_by 'V4) (dpl/summarise_all [:!list 'sum 'mean]))
;; => # A tibble: 3 x 5
;; V4 V1_fn1 V2_fn1 V1_fn2 V2_fn2
;; <chr> <dbl> <dbl> <dbl> <dbl>
;; 1 A 6 11 2 3.67
;; 2 B 9 13 3 4.33
;; 3 C 6 15 2 5
;; tech.ml.dataset
(->> DS
(group-by-columns-or-fn-and-aggregate [:V4] {:V1-mean #(dfn/mean (% :V1))
:V2-mean #(dfn/mean (% :V2))
:V1-sum #(dfn/sum (% :V1))
:V2-sum #(dfn/sum (% :V2))})
(ds/sort-by-column :V4))
;; => _unnamed [3 5]:
;; | :V4 | :V2-sum | :V1-mean | :V1-sum | :V2-mean |
;; |-----+---------+----------+---------+----------|
;; | A | 11.00 | 2.000 | 6.000 | 3.667 |
;; | B | 13.00 | 3.000 | 9.000 | 4.333 |
;; | C | 15.00 | 2.000 | 6.000 | 5.000 |
;; ### Summarise using a condition
;; ---- data.table
;; cols <- names(DT)[sapply(DT, is.numeric)]
;; DT[, lapply(.SD, mean),
;; .SDcols = cols]
(def cols (r/bra (r.base/names DT) (r.base/sapply DT r.base/is-numeric)))
(r '(bra ~DT nil (lapply .SD mean) :.SDcols ~cols))
;; => V1 V2
;; 1: 2.333333 4.333333
;; ---- dplyr
;; summarise_if(DF, is.numeric, mean)
(dpl/summarise_if DF r.base/is-numeric r.base/mean)
;; => # A tibble: 1 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 2.33 4.33
;; ---- tech.ml.dataset
(def cols (->> DS
(ds/columns)
(map meta)
(filter (comp #{:float64} :datatype))
(map :name)))
(->> (ds/select-columns DS cols)
(apply-to-columns dfn/mean cols))
;; => _unnamed [1 2]:
;; | :V1 | :V2 |
;; |-------+-------|
;; | 2.333 | 4.333 |
;; ### Modify all the columns
;; ---- data.table
;; DT[, lapply(.SD, rev)]
(r '(bra ~DT nil (lapply .SD rev)))
;; => V1 V2 V4
;; 1: 1 9 C
;; 2: 4 8 B
;; 3: 1 7 A
;; 4: 4 6 C
;; 5: 1 5 B
;; 6: 4 4 A
;; 7: 1 0 C
;; 8: 4 0 B
;; 9: 1 0 A
;; ---- dplyr
;; mutate_all(DF, rev)
;; # transmute_all(DF, rev)
(dpl/mutate_all DF r.base/rev)
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 1 9 C
;; 2 4 8 B
;; 3 1 7 A
;; 4 4 6 C
;; 5 1 5 B
;; 6 4 4 A
;; 7 1 0 C
;; 8 4 0 B
;; 9 1 0 A
;; ---- tech.ml.dataset
(ds/update-columns DS (ds/column-names DS) reverse)
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 1.000 | 9.000 | C |
;; | 4.000 | 8.000 | B |
;; | 1.000 | 7.000 | A |
;; | 4.000 | 6.000 | C |
;; | 1.000 | 5.000 | B |
;; | 4.000 | 4.000 | A |
;; | 1.000 | 0.000 | C |
;; | 4.000 | 0.000 | B |
;; | 1.000 | 0.000 | A |
;; ### Modify several columns (dropping the others)
;; ---- data.table
;; DT[, lapply(.SD, sqrt),
;; .SDcols = V1:V2]
;; DT[, lapply(.SD, exp),
;; .SDcols = !"V4"]
(r '(bra ~DT nil (lapply .SD sqrt) :.SDcols (colon V1 V2)))
;; => V1 V2
;; 1: 1 0.000000
;; 2: 2 0.000000
;; 3: 1 0.000000
;; 4: 2 2.000000
;; 5: 1 2.236068
;; 6: 2 2.449490
;; 7: 1 2.645751
;; 8: 2 2.828427
;; 9: 1 3.000000
(r '(bra ~DT nil (lapply .SD exp) :.SDcols (! "V4")))
;; => V1 V2
;; 1: 2.718282 1.00000
;; 2: 54.598150 1.00000
;; 3: 2.718282 1.00000
;; 4: 54.598150 54.59815
;; 5: 2.718282 148.41316
;; 6: 54.598150 403.42879
;; 7: 2.718282 1096.63316
;; 8: 54.598150 2980.95799
;; 9: 2.718282 8103.08393
;; ---- dplyr
;; transmute_at(DF, c("V1", "V2"), sqrt)
;; transmute_at(DF, vars(-V4), exp)
(dpl/transmute_at DF ["V1" "V2"] 'sqrt)
;; => # A tibble: 9 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 1 0
;; 2 2 0
;; 3 1 0
;; 4 2 2
;; 5 1 2.24
;; 6 2 2.45
;; 7 1 2.65
;; 8 2 2.83
;; 9 1 3
(dpl/transmute_at DF '(vars (- V4)) 'exp)
;; => # A tibble: 9 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 2.72 1
;; 2 54.6 1
;; 3 2.72 1
;; 4 54.6 54.6
;; 5 2.72 148.
;; 6 54.6 403.
;; 7 2.72 1097.
;; 8 54.6 2981.
;; 9 2.72 8103.
;; ---- tech.ml. dataset
(->> (ds/select-columns DS [:V1 :V2])
(apply-to-columns dfn/sqrt :all))
;; => _unnamed [9 2]:
;; | :V1 | :V2 |
;; |-------+-------|
;; | 1.000 | 0.000 |
;; | 2.000 | 0.000 |
;; | 1.000 | 0.000 |
;; | 2.000 | 2.000 |
;; | 1.000 | 2.236 |
;; | 2.000 | 2.449 |
;; | 1.000 | 2.646 |
;; | 2.000 | 2.828 |
;; | 1.000 | 3.000 |
(->> (ds/drop-columns DS [:V4])
(apply-to-columns dfn/exp :all))
;; => _unnamed [9 2]:
;; | :V1 | :V2 |
;; |-------+-------|
;; | 2.718 | 1.000 |
;; | 54.60 | 1.000 |
;; | 2.718 | 1.000 |
;; | 54.60 | 54.60 |
;; | 2.718 | 148.4 |
;; | 54.60 | 403.4 |
;; | 2.718 | 1097 |
;; | 54.60 | 2981 |
;; | 2.718 | 8103 |
;; ### Modify several columns (keeping the others)
;; ---- data.table
;; DT[, c("V1", "V2") := lapply(.SD, sqrt),
;; .SDcols = c("V1", "V2")]
;; cols <- setdiff(names(DT), "V4")
;; DT[, (cols) := lapply(.SD, "^", 2L),
;; .SDcols = cols]
(r '(bra ~DT nil ((rsymbol ":=") ["V1" "V2"] (lapply .SD sqrt))
:.SDcols ["V1" "V2"]))
;; => V1 V2 V4
;; 1: 1 0.000000 A
;; 2: 2 0.000000 B
;; 3: 1 0.000000 C
;; 4: 2 2.000000 A
;; 5: 1 2.236068 B
;; 6: 2 2.449490 C
;; 7: 1 2.645751 A
;; 8: 2 2.828427 B
;; 9: 1 3.000000 C
(def cols (r.base/<- 'cols (r.base/setdiff (r.base/names DT) "V4")))
(r (str (:object-name DT) "[, (cols) := lapply(.SD, \"^\", 2L), .SDcols = cols]"))
;; => V1 V2 V4
;; 1: 1 0 A
;; 2: 4 0 B
;; 3: 1 0 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 6 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; DF <- mutate_at(DF, c("V1", "V2"), sqrt)
;; DF <- mutate_at(DF, vars(-V4), "^", 2L)
(def DF (dpl/mutate_at DF ["V1" "V2"] 'sqrt))
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 1 0 A
;; 2 2 0 B
;; 3 1 0 C
;; 4 2 2 A
;; 5 1 2.24 B
;; 6 2 2.45 C
;; 7 1 2.65 A
;; 8 2 2.83 B
;; 9 1 3 C
(def DF (dpl/mutate_at DF '(vars (- V4)) "^" 2))
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 1 0 A
;; 2 4 0 B
;; 3 1 0 C
;; 4 4 4 A
;; 5 1 5. B
;; 6 4 6.00 C
;; 7 1 7. A
;; 8 4 8. B
;; 9 1 9 C
;; ---- tech.ml.dataset
(def DS (apply-to-columns dfn/sqrt [:V1 :V2] DS))
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 1.000 | 0.000 | A |
;; | 2.000 | 0.000 | B |
;; | 1.000 | 0.000 | C |
;; | 2.000 | 2.000 | A |
;; | 1.000 | 2.236 | B |
;; | 2.000 | 2.449 | C |
;; | 1.000 | 2.646 | A |
;; | 2.000 | 2.828 | B |
;; | 1.000 | 3.000 | C |
(def DS (apply-to-columns #(dfn/pow % 2.0) [:V1 :V2] DS))
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 1.000 | 0.000 | A |
;; | 4.000 | 0.000 | B |
;; | 1.000 | 0.000 | C |
;; | 4.000 | 4.000 | A |
;; | 1.000 | 5.000 | B |
;; | 4.000 | 6.000 | C |
;; | 1.000 | 7.000 | A |
;; | 4.000 | 8.000 | B |
;; | 1.000 | 9.000 | C |
;; ### Modify columns using a condition (dropping the others)
;; ---- data.table
;; cols <- names(DT)[sapply(DT, is.numeric)]
;; DT[, .SD - 1,
;; .SDcols = cols]
(def cols (r/bra (r.base/names DT) (r.base/sapply DT r.base/is-numeric)))
(r '(bra ~DT nil (- .SD 1) :.SDcols ~cols))
;; => V1 V2
;; 1: 0 -1
;; 2: 3 -1
;; 3: 0 -1
;; 4: 3 3
;; 5: 0 4
;; 6: 3 5
;; 7: 0 6
;; 8: 3 7
;; 9: 0 8
;; ---- dplyr
;; transmute_if(DF, is.numeric, list(~ '-'(., 1L)))
(dpl/transmute_if DF r.base/is-numeric [:!list '(formula nil (- . 1))])
;; => # A tibble: 9 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 0 -1
;; 2 3 -1
;; 3 0 -1
;; 4 3 3
;; 5 0 4.
;; 6 3 5.00
;; 7 0 6.
;; 8 3 7.
;; 9 0 8
;; ---- tech.ml.dataset
(def cols (->> DS
(ds/columns)
(map meta)
(filter (comp #(= :float64 %) :datatype))
(map :name)))
(->> (ds/select-columns DS cols)
(apply-to-columns #(dfn/- % 1) cols))
;; => _unnamed [9 2]:
;; | :V1 | :V2 |
;; |-------+--------|
;; | 0.000 | -1.000 |
;; | 3.000 | -1.000 |
;; | 0.000 | -1.000 |
;; | 3.000 | 3.000 |
;; | 0.000 | 4.000 |
;; | 3.000 | 5.000 |
;; | 0.000 | 6.000 |
;; | 3.000 | 7.000 |
;; | 0.000 | 8.000 |
;; ### Modify columns using a condition (keeping the others)
;; ---- data.table
;; DT[, (cols) := lapply(.SD, as.integer),
;; .SDcols = cols]
(def cols (r.base/<- 'cols (r.base/setdiff (r.base/names DT) "V4")))
(r (str (:object-name DT) "[, (cols) := lapply(.SD, as.integer), .SDcols = cols]"))
;; => V1 V2 V4
;; 1: 1 0 A
;; 2: 4 0 B
;; 3: 1 0 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 5 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; DF <- mutate_if(DF, is.numeric, as.integer)
(def DF (dpl/mutate_if DF r.base/is-numeric r.base/as-integer))
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <int> <int> <chr>
;; 1 1 0 A
;; 2 4 0 B
;; 3 1 0 C
;; 4 4 4 A
;; 5 1 5 B
;; 6 4 5 C
;; 7 1 7 A
;; 8 4 8 B
;; 9 1 9 C
;; ----tech.ml.dataset
;; TODO: easier cast to given type
(def DS (apply-to-columns #(dtype/->reader % :int64) [:V1 :V2] DS))
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-----+-----+-----|
;; | 1 | 0 | A |
;; | 4 | 0 | B |
;; | 1 | 0 | C |
;; | 4 | 4 | A |
;; | 1 | 5 | B |
;; | 4 | 5 | C |
;; | 1 | 7 | A |
;; | 4 | 8 | B |
;; | 1 | 9 | C |
;; ### Use a complex expression
;; ---- data.table
;; DT[, by = V4, .(V1[1:2], "X")]
(r '(bra ~DT nil :by V4 (. (bra V1 (colon 1 2)) "X")))
;; => V4 V1 V2
;; 1: A 1 X
;; 2: A 4 X
;; 3: B 4 X
;; 4: B 1 X
;; 5: C 1 X
;; 6: C 4 X
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; slice(1:2) %>%
;; transmute(V1 = V1,
;; V2 = "X")
(-> DF
(dpl/group_by 'V4)
(dpl/slice (r/colon 1 2))
(dpl/transmute :V1 'V1 :V2 "X"))
;; => # A tibble: 6 x 3
;; # Groups: V4 [3]
;; V4 V1 V2
;; <chr> <int> <chr>
;; 1 A 1 X
;; 2 A 4 X
;; 3 B 4 X
;; 4 B 1 X
;; 5 C 1 X
;; 6 C 4 X
;; ---- tech.ml.dataset
(->> (ds/group-by-column :V4 DS)
(vals)
(map #(ds/head 2 %))
(map #(ds/add-or-update-column % :V2 (repeat (ds/row-count %) "X")))
(apply ds/concat))
;; => null [6 3]:
;; | :V1 | :V2 | :V4 |
;; |-----+-----+-----|
;; | 1 | X | A |
;; | 4 | X | A |
;; | 4 | X | B |
;; | 1 | X | B |
;; | 1 | X | C |
;; | 4 | X | C |
;; ### Use multiple expressions (with DT[,{j}])
;; ---- data.table
;; DT[, {print(V1) # comments here!
;; print(summary(V1))
;; x <- V1 + sum(V2)
;; .(A = 1:.N, B = x) # last list returned as a data.table
;; }]
(r (str (:object-name DT)
"[, {print(V1) # comments here!
print(summary(V1))
x <- V1 + sum(V2)
.(A = 1:.N, B = x)}]"))
;; => A B
;; 1: 1 39
;; 2: 2 42
;; 3: 3 39
;; 4: 4 42
;; 5: 5 39
;; 6: 6 42
;; 7: 7 39
;; 8: 8 42
;; 9: 9 39
;; printed:
;; [1] 1 4 1 4 1 4 1 4 1
;; Min. 1st Qu. Median Mean 3rd Qu. Max.
;; 1.000 1.000 1.000 2.333 4.000 4.000
;; ---- dplyr
;; no provided implementation
;; ---- tech.ml.dataset
(let [x (dfn/+ (DS :V1) (dfn/sum (DS :V2)))]
(println (DS :V1))
(println (dfn/descriptive-stats (DS :V2)))
(ds/name-values-seq->dataset {:A (map inc (range (ds/row-count DS)))
:B x}))
;; => _unnamed [9 2]:
;; | :A | :B |
;; |----+-------|
;; | 1 | 39.00 |
;; | 2 | 42.00 |
;; | 3 | 39.00 |
;; | 4 | 42.00 |
;; | 5 | 39.00 |
;; | 6 | 42.00 |
;; | 7 | 39.00 |
;; | 8 | 42.00 |
;; | 9 | 39.00 |
;; printed:
;; #tech.ml.dataset.column<int64>[9]
;; :V1
;; [1, 4, 1, 4, 1, 4, 1, 4, 1, ]
;; {:min 0.0, :mean 4.222222222222222, :skew -0.1481546009077147, :ecount 9, :standard-deviation 3.527668414752787, :median 5.0, :max 9.0}
| 115249 | (ns techtest.datatable-dplyr
(:require [tech.ml.dataset :as ds]
[tech.ml.dataset.column :as col]
[tech.v2.datatype.functional :as dfn]
[tech.v2.datatype :as dtype]
[fastmath.core :as m]
[clojure.string :as str]))
;; Comparizon of tech.ml.dataset with datatable and dplyr
;; Based on article "A data.table and dplyr tour" by <NAME> dated March 3, 2019
;; https://atrebas.github.io/post/2019-03-03-datatable-dplyr/
;; Dataset names used:
;;
;; DT - R data.table object
;; DF - R tibble (dplyr) object
;; DS - tech.ml.dataset object
;; # Preparation
;; load R package
(require '[clojisr.v1.r :as r :refer [r r->clj]]
'[clojisr.v1.require :refer [require-r]])
(require-r '[base]
'[utils]
'[stats]
'[tidyr]
'[dplyr :as dpl]
'[data.table :as dt])
(r.base/options :width 160)
(r.base/set-seed 1)
;; HELPER functions
(defn aggregate
([agg-fns-map ds]
(aggregate {} agg-fns-map ds))
([m agg-fns-map-or-vector ds]
(into m (map (fn [[k agg-fn]]
[k (agg-fn ds)]) (if (map? agg-fns-map-or-vector)
agg-fns-map-or-vector
(map-indexed vector agg-fns-map-or-vector))))))
(def aggregate->dataset (comp ds/->dataset vector aggregate))
(defn group-by-columns-or-fn-and-aggregate
[key-fn-or-gr-colls agg-fns-map ds]
(->> (if (fn? key-fn-or-gr-colls)
(ds/group-by key-fn-or-gr-colls ds)
(ds/group-by identity key-fn-or-gr-colls ds))
(map (fn [[group-idx group-ds]]
(let [group-idx-m (if (map? group-idx)
group-idx
{:_fn group-idx})]
(aggregate group-idx-m agg-fns-map group-ds))))
ds/->dataset))
(defn asc-desc-comparator
[orders]
(if (every? #(= % :asc) orders)
compare
(let [mults (map #(if (= % :asc) 1 -1) orders)]
(fn [v1 v2]
(reduce (fn [_ [a b ^long mult]]
(let [c (compare a b)]
(if-not (zero? c)
(reduced (* mult c))
c))) 0 (map vector v1 v2 mults))))))
(defn sort-by-columns-with-orders
([cols ds]
(sort-by-columns-with-orders cols (repeat (count cols) :asc) ds))
([cols orders ds]
(let [sel (apply juxt (map #(fn [ds] (get ds %)) cols))
comp-fn (asc-desc-comparator orders)]
(ds/sort-by sel comp-fn ds))))
(defn map-v [f coll]
(reduce-kv (fn [m k v] (assoc m k (f v))) (empty coll) coll))
(defn filter-by-external-values->indices
[pred values]
(->> values
(map-indexed vector)
(filter (comp pred second))
(map first)))
(defn my-max [xs] (reduce #(if (pos? (compare %1 %2)) %1 %2) xs))
(defn my-min [xs] (reduce #(if (pos? (compare %2 %1)) %1 %2) xs))
(defn- ensure-seq
[v]
(if (seqable? v) v [v]))
(defn apply-to-columns
[f columns ds]
(let [names (ds/column-names ds)
columns (set (if (= :all columns) names columns))
ff (fn [col]
(if (columns (col/column-name col))
(f col)
col))]
(->> names
(map (comp ensure-seq ff ds))
(zipmap names)
(ds/name-values-seq->dataset))))
;; # Create example data
;; ---- data.table
;; DT <- data.table(V1 = rep(c(1L, 2L), 5)[-10],
;; V2 = 1:9,
;; V3 = c(0.5, 1.0, 1.5),
;; V4 = rep(LETTERS[1:3], 3))
;; class(DT)
;; DT
(def DT (dt/data-table :V1 (r/bra (r.base/rep [1 2] 5) -10)
:V2 (r/colon 1 9)
:V3 [0.5 1.0 1.5]
:V4 (r.base/rep (r/bra 'LETTERS (r/colon 1 3)) 3)))
(r.base/class DT)
;; => [1] "data.table" "data.frame"
DT
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 2 8 1.0 B
;; 9: 1 9 1.5 C
;; ---- dplyr
;; DF <- tibble(V1 = rep(c(1L, 2L), 5)[-10],
;; V2 = 1:9,
;; V3 = rep(c(0.5, 1.0, 1.5), 3),
;; V4 = rep(LETTERS[1:3], 3))
;; class(DF)
;; DF
(def DF (dpl/tibble :V1 (r/bra (r.base/rep [1 2] 5) -10)
:V2 (r/colon 1 9)
:V3 (r.base/rep [0.5 1.0 1.5] 3)
:V4 (r.base/rep (r/bra 'LETTERS (r/colon 1 3)) 3)))
(r.base/class DF)
;; => [1] "tbl_df" "tbl" "data.frame"
DF
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; 4 2 4 0.5 A
;; 5 1 5 1 B
;; 6 2 6 1.5 C
;; 7 1 7 0.5 A
;; 8 2 8 1 B
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
(def DS (ds/name-values-seq->dataset {:V1 (take 9 (cycle [1 2]))
:V2 (range 1 10)
:V3 (take 9 (cycle [0.5 1.0 1.5]))
:V4 (take 9 (cycle [\A \B \C]))}))
(class DS)
;; => tech.ml.dataset.impl.dataset.Dataset
DS
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
;; TODO (tech.ml.dataset): char datatype? (now inferred as Object)
(col/metadata (DS :V4))
;; => {:name :V4, :size 9, :datatype :object}
;; # Basic operations
;; ## Filter rows
;; ### Filter rows using indices
;; ---- data.table
;; DT[3:4,]
;; DT[3:4] # same
;; we use symbolic call here since there is a bug about interpreting R empty symbol
(r '(bra ~DT (colon 3 4) nil))
;; => V1 V2 V3 V4
;; 1: 1 3 1.5 C
;; 2: 2 4 0.5 A
(r/bra DT (r/colon 3 4))
;; => V1 V2 V3 V4
;; 1: 1 3 1.5 C
;; 2: 2 4 0.5 A
;; ---- dplyr
;; DF[3:4,]
;; slice(DF, 3:4) # same
(r '(bra ~DF (colon 3 4) nil))
;; => # A tibble: 2 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 3 1.5 C
;; 2 2 4 0.5 A
(dpl/slice DF (r/colon 3 4))
;; => # A tibble: 2 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 3 1.5 C
;; 2 2 4 0.5 A
;; ------ tech.ml.datatable
;; NOTE: row ids start at `0`
(ds/select-rows DS [2 3])
;; => _unnamed [2 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; ### Discard rows using negative indices
;; ---- data.table
;; DT[!3:7,]
;; DT[-(3:7)] # same
(r '(bra ~DT (! (colon 3 7)) nil))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 2 8 1.0 B
;; 4: 1 9 1.5 C
(r/bra DT (r/r- (r/colon 3 7)))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 2 8 1.0 B
;; 4: 1 9 1.5 C
;; ---- dplyr
;; DF[-(3:7),]
;; slice(DF, -(3:7)) # same
;; TODO (clojisr): (symbolic) unary `-` on `colon` doesn't work (workaround below)
(r '(bra ~DF (- [(colon 3 7)]) nil))
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 2 8 1 B
;; 4 1 9 1.5 C
(dpl/slice DF (r/r- (r/colon 3 7)))
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 2 8 1 B
;; 4 1 9 1.5 C
;; ---- tech.ml.dataset
(ds/drop-rows DS (range 2 7))
;; => _unnamed [4 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
;; ### Filter rows using a logical expression
;; ---- data.table
;; DT[V2 > 5]
;; DT[V4 %chin% c("A", "C")] # fast %in% for character
(r/bra DT '(> V2 5))
;; => V1 V2 V3 V4
;; 1: 2 6 1.5 C
;; 2: 1 7 0.5 A
;; 3: 2 8 1.0 B
;; 4: 1 9 1.5 C
;; TODO (clojisr): add %chin% as binary operation
(r/bra DT '((rsymbol "%chin%") V4 ["A" "C"]))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 1 3 1.5 C
;; 3: 2 4 0.5 A
;; 4: 2 6 1.5 C
;; 5: 1 7 0.5 A
;; 6: 1 9 1.5 C
;; ---- dplyr
;; filter(DF, V2 > 5)
;; filter(DF, V4 %in% c("A", "C"))
(dpl/filter DF '(> V2 5))
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 2 6 1.5 C
;; 2 1 7 0.5 A
;; 3 2 8 1 B
;; 4 1 9 1.5 C
(dpl/filter DF '(%in% V4 ["A" "C"]))
;; => # A tibble: 6 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 1 3 1.5 C
;; 3 2 4 0.5 A
;; 4 2 6 1.5 C
;; 5 1 7 0.5 A
;; 6 1 9 1.5 C
;; ---- tech.ml.dataset
(ds/filter-column #(> ^long % 5) :V2 DS)
;; => _unnamed [4 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
(ds/filter-column #{\A \C} :V4 DS)
;; => _unnamed [6 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 1 | 9 | 1.500 | C |
;; ### Filter rows using multiple conditions
;; ---- data.table
;; DT[V1 == 1 & V4 == "A"]
(r/bra DT '(& (== V1 1)
(== V4 "A")))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 1 7 0.5 A
;; ---- dplyr
;; filter(DF, V1 == 1, V4 == "A")
(dpl/filter DF '(== V1 1) '(== V4 "A"))
;; => # A tibble: 2 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 1 7 0.5 A
;; ---- tech.ml.dataset
(ds/filter #(and (= (:V1 %) 1)
(= (:V4 %) \A)) DS)
;; => _unnamed [2 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 1 | 7 | 0.5000 | A |
;; ### Filter unique rows
;; ---- data.table
;; unique(DT)
;; unique(DT, by = c("V1", "V4")) # returns all cols
(r.base/unique DT)
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 2 8 1.0 B
;; 9: 1 9 1.5 C
(r.base/unique DT :by ["V1" "V4"])
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; ---- dplyr
;; distinct(DF) # distinct_all(DF)
;; distinct_at(DF, vars(V1, V4)) # returns selected cols
;; # see also ?distinct_if
(dpl/distinct DF)
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; 4 2 4 0.5 A
;; 5 1 5 1 B
;; 6 2 6 1.5 C
;; 7 1 7 0.5 A
;; 8 2 8 1 B
;; 9 1 9 1.5 C
(dpl/distinct_at DF (dpl/vars 'V1 'V4))
;; => # A tibble: 6 x 2
;; V1 V4
;; <dbl> <chr>
;; 1 1 A
;; 2 2 B
;; 3 1 C
;; 4 2 A
;; 5 1 B
;; 6 2 C
;; ---- tech.ml.dataset
(ds/unique-by identity {:column-name-seq (ds/column-names DS)} DS)
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
(ds/unique-by identity {:column-name-seq [:V1 :V4]} DS)
;; => _unnamed [6 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; ### Discard rows with missing values
;; ---- data.table
;; na.omit(DT, cols = 1:4) # fast S3 method with cols argument
(r.stats/na-omit DT :cols (r/colon 1 4))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 2 8 1.0 B
;; 9: 1 9 1.5 C
;; ---- dplyr
;; tidyr::drop_na(DF, names(DF))
(r.tidyr/drop_na DF (r.base/names DF))
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; 4 2 4 0.5 A
;; 5 1 5 1 B
;; 6 2 6 1.5 C
;; 7 1 7 0.5 A
;; 8 2 8 1 B
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
;; note: missing works on whole dataset, to select columns, first create dataset with selected columns
(ds/drop-rows DS (ds/missing DS))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
;; ### Other filters
;; ---- data.table
;; DT[sample(.N, 3)] # .N = nb of rows in DT
;; DT[sample(.N, .N / 2)]
;; DT[frankv(-V1, ties.method = "dense") < 2]
(r/bra DT '(sample .N 3))
;; => V1 V2 V3 V4
;; 1: 1 7 0.5 A
;; 2: 1 3 1.5 C
;; 3: 2 6 1.5 C
(r/bra DT '(sample .N (/ .N 2)))
;; => V1 V2 V3 V4
;; 1: 2 6 1.5 C
;; 2: 1 7 0.5 A
;; 3: 2 4 0.5 A
;; 4: 2 8 1.0 B
(r/bra DT '(< (frankv (- V1) :ties.method "dense") 2))
;; => V1 V2 V3 V4
;; 1: 2 2 1.0 B
;; 2: 2 4 0.5 A
;; 3: 2 6 1.5 C
;; 4: 2 8 1.0 B
;; ---- dplyr
;; sample_n(DF, 3) # n random rows
;; sample_frac(DF, 0.5) # fraction of random rows
;; top_n(DF, 1, V1) # top n entries (includes equals)
(dpl/sample_n DF 3)
;; => # A tibble: 3 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 5 1 B
(dpl/sample_frac DF 0.5)
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 7 0.5 A
;; 2 1 3 1.5 C
;; 3 2 6 1.5 C
;; 4 2 2 1 B
(dpl/top_n DF 1 'V1)
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 2 2 1 B
;; 2 2 4 0.5 A
;; 3 2 6 1.5 C
;; 4 2 8 1 B
;; ---- tech.ml.dataset
(ds/sample 3 DS)
;; => _unnamed [3 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
(ds/sample (/ (ds/row-count DS) 2) DS)
;; => _unnamed [4 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+-------+-----|
;; | 2 | 8 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; NOTE: Here we use `fastmath` to calculate rank.
;; We need also to translate rank to indices.
(->> (m/rank (map - (DS :V1)) :dense)
(filter-by-external-values->indices #(< ^long % 1))
(ds/select-rows DS))
;; => _unnamed [4 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 2 | 2 | 1.000 | B |
;; | 2 | 4 | 0.5000 | A |
;; | 2 | 6 | 1.500 | C |
;; | 2 | 8 | 1.000 | B |
;; #### Convenience functions
;; ---- data.table
;; DT[V4 %like% "^B"]
;; DT[V2 %between% c(3, 5)]
;; DT[data.table::between(V2, 3, 5, incbounds = FALSE)]
;; DT[V2 %inrange% list(-1:1, 1:3)] # see also ?inrange
(r/bra DT '((rsymbol "%like%") V4 "^B"))
;; => V1 V2 V3 V4
;; 1: 2 2 1 B
;; 2: 1 5 1 B
;; 3: 2 8 1 B
(r/bra DT '((rsymbol "%between%") V2 [3 5]))
;; => V1 V2 V3 V4
;; 1: 1 3 1.5 C
;; 2: 2 4 0.5 A
;; 3: 1 5 1.0 B
(r/bra DT '((rsymbol data.table between) V2 3 5 :incbounds false))
;; => V1 V2 V3 V4
;; 1: 2 4 0.5 A
(r/bra DT '((rsymbol "%inrange%") V2 [:!list (colon -1 1) (colon 1 3)]))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; ---- dplyr
;; filter(DF, grepl("^B", V4))
;; filter(DF, dplyr::between(V2, 3, 5))
;; filter(DF, V2 > 3 & V2 < 5)
;; filter(DF, V2 >= -1:1 & V2 <= 1:3)
(dpl/filter DF '(grepl "^B" V4))
;; => # A tibble: 3 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 2 2 1 B
;; 2 1 5 1 B
;; 3 2 8 1 B
(dpl/filter DF '((rsymbol dplyr between) V2 3 5))
;; => # A tibble: 3 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 3 1.5 C
;; 2 2 4 0.5 A
;; 3 1 5 1 B
(dpl/filter DF '(& (> V2 3) (< V2 5)))
;; => # A tibble: 1 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 2 4 0.5 A
(dpl/filter DF '(& (>= V2 (colon -1 1))
(<= V2 (colon 1 3))))
;; => # A tibble: 3 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; ---- tech.ml.dataset
(ds/filter #(re-matches #"^B" (str (:V4 %))) DS)
;; => _unnamed [3 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+-------+-----|
;; | 2 | 2 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
(ds/filter (comp (partial m/between? 3 5) :V2) DS)
;; => _unnamed [3 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
(ds/filter (comp #(< 3 % 5) :V2) DS)
;; => _unnamed [1 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 2 | 4 | 0.5000 | A |
;; note: there is no range on sequences, I have no idea why to use such
(let [mn (min -1 0 1)
mx (max 1 2 3)]
(ds/filter (comp (partial m/between? mn mx) :V2) DS))
;; => _unnamed [3 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; ## Sort rows
;; ### Sort rows by column
;; ---- data.table
;; DT[order(V3)] # see also setorder
(r/bra DT '(order V3))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 4 0.5 A
;; 3: 1 7 0.5 A
;; 4: 2 2 1.0 B
;; 5: 1 5 1.0 B
;; 6: 2 8 1.0 B
;; 7: 1 3 1.5 C
;; 8: 2 6 1.5 C
;; 9: 1 9 1.5 C
;; ---- dplyr
;; arrange(DF, V3)
(dpl/arrange DF 'V3)
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 4 0.5 A
;; 3 1 7 0.5 A
;; 4 2 2 1 B
;; 5 1 5 1 B
;; 6 2 8 1 B
;; 7 1 3 1.5 C
;; 8 2 6 1.5 C
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
(ds/sort-by-column :V3 DS)
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; alternative use of indices
(ds/select-rows DS (m/order (DS :V3)))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; ### Sort rows in decreasing order
;; ---- data.table
;; DT[order(-V3)]
(r/bra DT '(order (- V3)))
;; => V1 V2 V3 V4
;; 1: 1 3 1.5 C
;; 2: 2 6 1.5 C
;; 3: 1 9 1.5 C
;; 4: 2 2 1.0 B
;; 5: 1 5 1.0 B
;; 6: 2 8 1.0 B
;; 7: 1 1 0.5 A
;; 8: 2 4 0.5 A
;; 9: 1 7 0.5 A
;; ---- dplyr
;; arrange(DF, desc(V3))
(dpl/arrange DF '(desc V3))
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 3 1.5 C
;; 2 2 6 1.5 C
;; 3 1 9 1.5 C
;; 4 2 2 1 B
;; 5 1 5 1 B
;; 6 2 8 1 B
;; 7 1 1 0.5 A
;; 8 2 4 0.5 A
;; 9 1 7 0.5 A
;; ---- tech.ml.dataset
(ds/sort-by-column :V3 (comp - compare) DS)
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 3 | 1.500 | C |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 2 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 1 | 0.5000 | A |
;; using ordering indices
(ds/select-rows DS (m/order (DS :V3) true))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 3 | 1.500 | C |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 7 | 0.5000 | A |
;; ### Sort rows based on several columns
;; ---- data.table
;; DT[order(V1, -V2)]
(r/bra DT '(order V1 (- V2)))
;; => V1 V2 V3 V4
;; 1: 1 9 1.5 C
;; 2: 1 7 0.5 A
;; 3: 1 5 1.0 B
;; 4: 1 3 1.5 C
;; 5: 1 1 0.5 A
;; 6: 2 8 1.0 B
;; 7: 2 6 1.5 C
;; 8: 2 4 0.5 A
;; 9: 2 2 1.0 B
;; ---- dplyr
;; arrange(DF, V1, desc(V2))
(dpl/arrange DF 'V1 '(desc V2))
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 9 1.5 C
;; 2 1 7 0.5 A
;; 3 1 5 1 B
;; 4 1 3 1.5 C
;; 5 1 1 0.5 A
;; 6 2 8 1 B
;; 7 2 6 1.5 C
;; 8 2 4 0.5 A
;; 9 2 2 1 B
;; ---- tech.ml.dataset
;; TODO: improve sorting in general
(sort-by-columns-with-orders [:V1 :V2] [:asc :desc] DS)
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 9 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; ## Select columns
;; ### Select one column using an index (not recommended)
;; ---- data.table
;; DT[[3]] # returns a vector
;; DT[, 3] # returns a data.table
(r/brabra DT 3)
;; => [1] 0.5 1.0 1.5 0.5 1.0 1.5 0.5 1.0 1.5
(r '(bra ~DT nil 3))
;; => V3
;; 1: 0.5
;; 2: 1.0
;; 3: 1.5
;; 4: 0.5
;; 5: 1.0
;; 6: 1.5
;; 7: 0.5
;; 8: 1.0
;; 9: 1.5
;; ---- dplyr
;; DF[[3]] # returns a vector
;; DF[3] # returns a tibble
(r/brabra DF 3)
;; => [1] 0.5 1.0 1.5 0.5 1.0 1.5 0.5 1.0 1.5
(r/bra DF 3)
;; => # A tibble: 9 x 1
;; V3
;; <dbl>
;; 1 0.5
;; 2 1
;; 3 1.5
;; 4 0.5
;; 5 1
;; 6 1.5
;; 7 0.5
;; 8 1
;; 9 1.5
;; ---- tech.ml.dataset
;; NOTE: indices start at 0
(nth (seq DS) 2)
;; => #tech.ml.dataset.column<float64>[9]
;; :V3
;; [0.5000, 1.000, 1.500, 0.5000, 1.000, 1.500, 0.5000, 1.000, 1.500, ]
;; NOTE: column is seqable
(seq (nth (seq DS) 2))
;; => (0.5 1.0 1.5 0.5 1.0 1.5 0.5 1.0 1.5)
(ds/new-dataset [(nth (seq DS) 2)])
;; => _unnamed [9 1]:
;; | :V3 |
;; |--------|
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; ### Select one column using column name
;; DT[, list(V2)] # returns a data.table
;; DT[, .(V2)] # returns a data.table
;; # . is an alias for list
;; DT[, "V2"] # returns a data.table
;; DT[, V2] # returns a vector
;; DT[["V2"]] # returns a vector
;; ---- data.table
(r '(bra ~DT nil [:!list V2]))
;; => V2
;; 1: 1
;; 2: 2
;; 3: 3
;; 4: 4
;; 5: 5
;; 6: 6
;; 7: 7
;; 8: 8
;; 9: 9
(r '(bra ~DT nil (. V2)))
;; => V2
;; 1: 1
;; 2: 2
;; 3: 3
;; 4: 4
;; 5: 5
;; 6: 6
;; 7: 7
;; 8: 8
;; 9: 9
(r '(bra ~DT nil "V2"))
;; => V2
;; 1: 1
;; 2: 2
;; 3: 3
;; 4: 4
;; 5: 5
;; 6: 6
;; 7: 7
;; 8: 8
;; 9: 9
(r '(bra ~DT nil V2))
;; => [1] 1 2 3 4 5 6 7 8 9
(r/brabra DT "V2")
;; => [1] 1 2 3 4 5 6 7 8 9
;; ---- dplyr
;; select(DF, V2) # returns a tibble
;; pull(DF, V2) # returns a vector
;; DF[, "V2"] # returns a tibble
;; DF[["V2"]] # returns a vector
(dpl/select DF 'V2)
;; => # A tibble: 9 x 1
;; V2
;; <int>
;; 1 1
;; 2 2
;; 3 3
;; 4 4
;; 5 5
;; 6 6
;; 7 7
;; 8 8
;; 9 9
(dpl/pull DF 'V2)
;; => [1] 1 2 3 4 5 6 7 8 9
(r '(bra ~DF nil "V2"))
;; => # A tibble: 9 x 1
;; V2
;; <int>
;; 1 1
;; 2 2
;; 3 3
;; 4 4
;; 5 5
;; 6 6
;; 7 7
;; 8 8
;; 9 9
(r/brabra DF "V2")
;; => [1] 1 2 3 4 5 6 7 8 9
;; ---- tech.ml.dataset
;; NOTE: returns dataset
(ds/select-columns DS [:V2])
;; => _unnamed [9 1]:
;; | :V2 |
;; |-----|
;; | 1 |
;; | 2 |
;; | 3 |
;; | 4 |
;; | 5 |
;; | 6 |
;; | 7 |
;; | 8 |
;; | 9 |
;; NOTE: returns dataset
(ds/select DS [:V2] :all)
;; => _unnamed [9 1]:
;; | :V2 |
;; |-----|
;; | 1 |
;; | 2 |
;; | 3 |
;; | 4 |
;; | 5 |
;; | 6 |
;; | 7 |
;; | 8 |
;; | 9 |
;; NOTE: returns column (seqable)
(DS :V2)
;; => #tech.ml.dataset.column<int64>[9]
;; :V2
;; [1, 2, 3, 4, 5, 6, 7, 8, 9, ]
;; NOTE: column as sequence
(seq (DS :V2))
;; => (1 2 3 4 5 6 7 8 9)
;; NOTE: efficient access to data via reader
(dtype/->reader (DS :V2))
;; => [1 2 3 4 5 6 7 8 9]
;; NOTE: returns column
(ds/column DS :V2)
;; => #tech.ml.dataset.column<int64>[9]
;; :V2
;; [1, 2, 3, 4, 5, 6, 7, 8, 9, ]
;; ### Select several columns
;; ---- data.table
;; DT[, .(V2, V3, V4)]
;; DT[, list(V2, V3, V4)]
;; DT[, V2:V4] # select columns between V2 and V4
(r '(bra ~DT nil (. V2 V3 V4)))
;; => V2 V3 V4
;; 1: 1 0.5 A
;; 2: 2 1.0 B
;; 3: 3 1.5 C
;; 4: 4 0.5 A
;; 5: 5 1.0 B
;; 6: 6 1.5 C
;; 7: 7 0.5 A
;; 8: 8 1.0 B
;; 9: 9 1.5 C
(r '(bra ~DT nil (:!list V2 V3 V4)))
;; => V2 V3 V4
;; 1: 1 0.5 A
;; 2: 2 1.0 B
;; 3: 3 1.5 C
;; 4: 4 0.5 A
;; 5: 5 1.0 B
;; 6: 6 1.5 C
;; 7: 7 0.5 A
;; 8: 8 1.0 B
;; 9: 9 1.5 C
(r '(bra ~DT nil (colon V2 V4)))
;; => V2 V3 V4
;; 1: 1 0.5 A
;; 2: 2 1.0 B
;; 3: 3 1.5 C
;; 4: 4 0.5 A
;; 5: 5 1.0 B
;; 6: 6 1.5 C
;; 7: 7 0.5 A
;; 8: 8 1.0 B
;; 9: 9 1.5 C
;; ---- dplyr
;; select(DF, V2, V3, V4)
;; select(DF, V2:V4) # select columns between V2 and V4
(dpl/select DF 'V2 'V3 'V4)
;; => # A tibble: 9 x 3
;; V2 V3 V4
;; <int> <dbl> <chr>
;; 1 1 0.5 A
;; 2 2 1 B
;; 3 3 1.5 C
;; 4 4 0.5 A
;; 5 5 1 B
;; 6 6 1.5 C
;; 7 7 0.5 A
;; 8 8 1 B
;; 9 9 1.5 C
(dpl/select DF '(colon V2 V4))
;; => # A tibble: 9 x 3
;; V2 V3 V4
;; <int> <dbl> <chr>
;; 1 1 0.5 A
;; 2 2 1 B
;; 3 3 1.5 C
;; 4 4 0.5 A
;; 5 5 1 B
;; 6 6 1.5 C
;; 7 7 0.5 A
;; 8 8 1 B
;; 9 9 1.5 C
;; ---- tech.ml.dataset
(ds/select-columns DS [:V2 :V3 :V4])
;; => _unnamed [9 3]:
;; | :V2 | :V3 | :V4 |
;; |-----+--------+-----|
;; | 1 | 0.5000 | A |
;; | 2 | 1.000 | B |
;; | 3 | 1.500 | C |
;; | 4 | 0.5000 | A |
;; | 5 | 1.000 | B |
;; | 6 | 1.500 | C |
;; | 7 | 0.5000 | A |
;; | 8 | 1.000 | B |
;; | 9 | 1.500 | C |
(ds/select DS [:V2 :V3 :V4] :all)
;; => _unnamed [9 3]:
;; | :V2 | :V3 | :V4 |
;; |-----+--------+-----|
;; | 1 | 0.5000 | A |
;; | 2 | 1.000 | B |
;; | 3 | 1.500 | C |
;; | 4 | 0.5000 | A |
;; | 5 | 1.000 | B |
;; | 6 | 1.500 | C |
;; | 7 | 0.5000 | A |
;; | 8 | 1.000 | B |
;; | 9 | 1.500 | C |
;; NOTE: range is not available
;; ### Exclude columns
;; ---- data.table
;; DT[, !c("V2", "V3")]
(r '(bra ~DT nil (! ["V2" "V3"])))
;; => V1 V4
;; 1: 1 A
;; 2: 2 B
;; 3: 1 C
;; 4: 2 A
;; 5: 1 B
;; 6: 2 C
;; 7: 1 A
;; 8: 2 B
;; 9: 1 C
;; ---- dplyr
;; select(DF, -V2, -V3)
(dpl/select DF '(- V2) '(- V3))
;; => # A tibble: 9 x 2
;; V1 V4
;; <dbl> <chr>
;; 1 1 A
;; 2 2 B
;; 3 1 C
;; 4 2 A
;; 5 1 B
;; 6 2 C
;; 7 1 A
;; 8 2 B
;; 9 1 C
;; ---- tech.ml.dataset
(ds/drop-columns DS [:V2 :V3])
;; => _unnamed [9 2]:
;; | :V1 | :V4 |
;; |-----+-----|
;; | 1 | A |
;; | 2 | B |
;; | 1 | C |
;; | 2 | A |
;; | 1 | B |
;; | 2 | C |
;; | 1 | A |
;; | 2 | B |
;; | 1 | C |
;; ### Select/Exclude columns using a character vector
;; ---- data.table
;; cols <- c("V2", "V3")
;; DT[, ..cols] # .. prefix means 'one-level up'
;; DT[, !..cols] # or DT[, -..cols]
(def cols (r.base/<- 'cols ["V2" "V3"]))
(r '(bra ~DT nil ..cols))
;; => V2 V3
;; 1: 1 0.5
;; 2: 2 1.0
;; 3: 3 1.5
;; 4: 4 0.5
;; 5: 5 1.0
;; 6: 6 1.5
;; 7: 7 0.5
;; 8: 8 1.0
;; 9: 9 1.5
(r '(bra ~DT nil !..cols))
;; => V1 V4
;; 1: 1 A
;; 2: 2 B
;; 3: 1 C
;; 4: 2 A
;; 5: 1 B
;; 6: 2 C
;; 7: 1 A
;; 8: 2 B
;; 9: 1 C
(r '(bra ~DT nil -..cols))
;; => V1 V4
;; 1: 1 A
;; 2: 2 B
;; 3: 1 C
;; 4: 2 A
;; 5: 1 B
;; 6: 2 C
;; 7: 1 A
;; 8: 2 B
;; 9: 1 C
;; ---- dplyr
;; cols <- c("V2", "V3")
;; select(DF, !!cols) # unquoting
;; select(DF, -!!cols)
(def cols (r.base/<- 'cols ["V2" "V3"]))
(dpl/select DF '!!cols)
;; => # A tibble: 9 x 2
;; V2 V3
;; <int> <dbl>
;; 1 1 0.5
;; 2 2 1
;; 3 3 1.5
;; 4 4 0.5
;; 5 5 1
;; 6 6 1.5
;; 7 7 0.5
;; 8 8 1
;; 9 9 1.5
(dpl/select DF '-!!cols)
;; => # A tibble: 9 x 2
;; V1 V4
;; <dbl> <chr>
;; 1 1 A
;; 2 2 B
;; 3 1 C
;; 4 2 A
;; 5 1 B
;; 6 2 C
;; 7 1 A
;; 8 2 B
;; 9 1 C
;; ---- tech.ml.dataset
(def cols [:V2 :V3])
(ds/select-columns DS cols)
;; => _unnamed [9 2]:
;; | :V2 | :V3 |
;; |-----+--------|
;; | 1 | 0.5000 |
;; | 2 | 1.000 |
;; | 3 | 1.500 |
;; | 4 | 0.5000 |
;; | 5 | 1.000 |
;; | 6 | 1.500 |
;; | 7 | 0.5000 |
;; | 8 | 1.000 |
;; | 9 | 1.500 |
(ds/drop-columns DS cols)
;; => _unnamed [9 2]:
;; | :V1 | :V4 |
;; |-----+-----|
;; | 1 | A |
;; | 2 | B |
;; | 1 | C |
;; | 2 | A |
;; | 1 | B |
;; | 2 | C |
;; | 1 | A |
;; | 2 | B |
;; | 1 | C |
;; ### Other selections
;; ---- data.table
;; cols <- paste0("V", 1:2)
;; cols <- union("V4", names(DT))
;; cols <- grep("V", names(DT))
;; cols <- grep("3$", names(DT))
;; cols <- grep(".2", names(DT))
;; cols <- grep("^V1|X$", names(DT))
;; cols <- grep("^(?!V2)", names(DT), perl = TRUE)
;; DT[, ..cols]
(r.base/<- 'cols (r.base/paste0 "V" (r/colon 1 2)))
;; => [1] "V1" "V2"
(r '(bra ~DT nil ..cols))
;; => V1 V2
;; 1: 1 1
;; 2: 2 2
;; 3: 1 3
;; 4: 2 4
;; 5: 1 5
;; 6: 2 6
;; 7: 1 7
;; 8: 2 8
;; 9: 1 9
(r.base/<- 'cols (r.base/union "V4" (r.base/names DT)))
;; => [1] "V4" "V1" "V2" "V3"
(r '(bra ~DT nil ..cols))
;; => V4 V1 V2 V3
;; 1: A 1 1 0.5
;; 2: B 2 2 1.0
;; 3: C 1 3 1.5
;; 4: A 2 4 0.5
;; 5: B 1 5 1.0
;; 6: C 2 6 1.5
;; 7: A 1 7 0.5
;; 8: B 2 8 1.0
;; 9: C 1 9 1.5
(r.base/<- 'cols (r.base/grep "V" (r.base/names DT)))
;; => [1] 1 2 3 4
(r '(bra ~DT nil ..cols))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 2 8 1.0 B
;; 9: 1 9 1.5 C
(r.base/<- 'cols (r.base/grep "3$" (r.base/names DT)))
;; => [1] 3
(r '(bra ~DT nil ..cols))
;; => V3
;; 1: 0.5
;; 2: 1.0
;; 3: 1.5
;; 4: 0.5
;; 5: 1.0
;; 6: 1.5
;; 7: 0.5
;; 8: 1.0
;; 9: 1.5
(r.base/<- 'cols (r.base/grep ".2" (r.base/names DT)))
;; => [1] 2
(r '(bra ~DT nil ..cols))
;; => V2
;; 1: 1
;; 2: 2
;; 3: 3
;; 4: 4
;; 5: 5
;; 6: 6
;; 7: 7
;; 8: 8
;; 9: 9
(r.base/<- 'cols (r.base/grep "^V1|X$" (r.base/names DT)))
;; => [1] 1
(r '(bra ~DT nil ..cols))
;; => V1
;; 1: 1
;; 2: 2
;; 3: 1
;; 4: 2
;; 5: 1
;; 6: 2
;; 7: 1
;; 8: 2
;; 9: 1
(r.base/<- 'cols (r.base/grep "^(?!V2)" (r.base/names DT) :perl true))
;; => [1] 1 3 4
(r '(bra ~DT nil ..cols))
;; => V1 V3 V4
;; 1: 1 0.5 A
;; 2: 2 1.0 B
;; 3: 1 1.5 C
;; 4: 2 0.5 A
;; 5: 1 1.0 B
;; 6: 2 1.5 C
;; 7: 1 0.5 A
;; 8: 2 1.0 B
;; 9: 1 1.5 C
;; ---- dplyr
;; select(DF, num_range("V", 1:2))
;; select(DF, V4, everything()) # reorder columns
;; select(DF, contains("V"))
;; select(DF, ends_with("3"))
;; select(DF, matches(".2"))
;; select(DF, one_of(c("V1", "X")))
;; select(DF, -starts_with("V2"))
(dpl/select DF '(num_range "V" (colon 1 2)))
;; => # A tibble: 9 x 2
;; V1 V2
;; <dbl> <int>
;; 1 1 1
;; 2 2 2
;; 3 1 3
;; 4 2 4
;; 5 1 5
;; 6 2 6
;; 7 1 7
;; 8 2 8
;; 9 1 9
(dpl/select DF 'V4 '(everything))
;; => # A tibble: 9 x 4
;; V4 V1 V2 V3
;; <chr> <dbl> <int> <dbl>
;; 1 A 1 1 0.5
;; 2 B 2 2 1
;; 3 C 1 3 1.5
;; 4 A 2 4 0.5
;; 5 B 1 5 1
;; 6 C 2 6 1.5
;; 7 A 1 7 0.5
;; 8 B 2 8 1
;; 9 C 1 9 1.5
(dpl/select DF '(contains "V"))
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; 4 2 4 0.5 A
;; 5 1 5 1 B
;; 6 2 6 1.5 C
;; 7 1 7 0.5 A
;; 8 2 8 1 B
;; 9 1 9 1.5 C
(dpl/select DF '(ends_with "3"))
;; => # A tibble: 9 x 1
;; V3
;; <dbl>
;; 1 0.5
;; 2 1
;; 3 1.5
;; 4 0.5
;; 5 1
;; 6 1.5
;; 7 0.5
;; 8 1
;; 9 1.5
(dpl/select DF '(matches ".2"))
;; => # A tibble: 9 x 1
;; V2
;; <int>
;; 1 1
;; 2 2
;; 3 3
;; 4 4
;; 5 5
;; 6 6
;; 7 7
;; 8 8
;; 9 9
(dpl/select DF '(one_of ["V1" "X"]))
;; => # A tibble: 9 x 1
;; V1
;; <dbl>
;; 1 1
;; 2 2
;; 3 1
;; 4 2
;; 5 1
;; 6 2
;; 7 1
;; 8 2
;; 9 1
(dpl/select DF '(- (starts_with "V2")))
;; => # A tibble: 9 x 3
;; V1 V3 V4
;; <dbl> <dbl> <chr>
;; 1 1 0.5 A
;; 2 2 1 B
;; 3 1 1.5 C
;; 4 2 0.5 A
;; 5 1 1 B
;; 6 2 1.5 C
;; 7 1 0.5 A
;; 8 2 1 B
;; 9 1 1.5 C
;; ---- tech.ml.dataset
;; NOTE: we are using pure Clojure machinery to generate column names
(->> (map (comp keyword str) (repeat "V") (range 1 3))
(ds/select-columns DS))
;; => _unnamed [9 2]:
;; | :V1 | :V2 |
;; |-----+-----|
;; | 1 | 1 |
;; | 2 | 2 |
;; | 1 | 3 |
;; | 2 | 4 |
;; | 1 | 5 |
;; | 2 | 6 |
;; | 1 | 7 |
;; | 2 | 8 |
;; | 1 | 9 |
(->> (distinct (conj (ds/column-names DS) :V4))
(ds/select-columns DS))
;; => _unnamed [9 4]:
;; | :V4 | :V1 | :V2 | :V3 |
;; |-----+-----+-----+--------|
;; | A | 1 | 1 | 0.5000 |
;; | B | 2 | 2 | 1.000 |
;; | C | 1 | 3 | 1.500 |
;; | A | 2 | 4 | 0.5000 |
;; | B | 1 | 5 | 1.000 |
;; | C | 2 | 6 | 1.500 |
;; | A | 1 | 7 | 0.5000 |
;; | B | 2 | 8 | 1.000 |
;; | C | 1 | 9 | 1.500 |
(->> (ds/column-names DS)
(filter #(str/starts-with? (name %) "V"))
(ds/select-columns DS))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
(->> (ds/column-names DS)
(filter #(str/ends-with? (name %) "3"))
(ds/select-columns DS))
;; => _unnamed [9 1]:
;; | :V3 |
;; |--------|
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
(->> (ds/column-names DS)
(filter #(re-matches #".2" (name %)))
(ds/select-columns DS))
;; => _unnamed [9 1]:
;; | :V2 |
;; |-----|
;; | 1 |
;; | 2 |
;; | 3 |
;; | 4 |
;; | 5 |
;; | 6 |
;; | 7 |
;; | 8 |
;; | 9 |
(->> (ds/column-names DS)
(filter #{:V1 :X})
(ds/select-columns DS))
;; => _unnamed [9 1]:
;; | :V1 |
;; |-----|
;; | 1 |
;; | 2 |
;; | 1 |
;; | 2 |
;; | 1 |
;; | 2 |
;; | 1 |
;; | 2 |
;; | 1 |
(->> (ds/column-names DS)
(remove #(str/starts-with? (name %) "V2"))
(ds/select-columns DS))
;; => _unnamed [9 3]:
;; | :V1 | :V3 | :V4 |
;; |-----+--------+-----|
;; | 1 | 0.5000 | A |
;; | 2 | 1.000 | B |
;; | 1 | 1.500 | C |
;; | 2 | 0.5000 | A |
;; | 1 | 1.000 | B |
;; | 2 | 1.500 | C |
;; | 1 | 0.5000 | A |
;; | 2 | 1.000 | B |
;; | 1 | 1.500 | C |
;; ## Summarise data
;; ### Summarise one column
;; ---- data.table
;; DT[, sum(V1)] # returns a vector
;; DT[, .(sum(V1))] # returns a data.table
;; DT[, .(sumV1 = sum(V1))] # returns a data.table
(r '(bra ~DT nil (sum V1)))
;; => [1] 13
(r '(bra ~DT nil (. (sum V1))))
;; => V1
;; 1: 13
(r '(bra ~DT nil (. :sumV1 (sum V1))))
;; => sumV1
;; 1: 13
;; ---- dplyr
;; summarise(DF, sum(V1)) # returns a tibble
;; summarise(DF, sumV1 = sum(V1)) # returns a tibble
(dpl/summarise DF '(sum V1))
;; => # A tibble: 1 x 1
;; `sum(V1)`
;; <dbl>
;; 1 13
(dpl/summarise DF :sumV1 '(sum V1))
;; => # A tibble: 1 x 1
;; sumV1
;; <dbl>
;; 1 13
;; ---- tech.ml.dataset
;; NOTE: using optimized datatype function
(dfn/sum (DS :V1))
;; => 13.0
;; NOTE: using reduce
(reduce + (DS :V1))
;; => 13
;; NOTE: custom aggregation function to get back dataset (issue filled)
;; TODO: aggregate->dataset
(aggregate->dataset [#(dfn/sum (% :V1))] DS)
;; => _unnamed [1 1]:
;; | 0 |
;; |-------|
;; | 13.00 |
(aggregate->dataset {:sumV1 #(dfn/sum (% :V1))} DS)
;; => _unnamed [1 1]:
;; | :sumV1 |
;; |--------|
;; | 13.00 |
;; ### Summarise several columns
;; ---- data.table
;; DT[, .(sum(V1), sd(V3))]
(r '(bra ~DT nil (. (sum V1) (sd V3))))
;; => V1 V2
;; 1: 13 0.4330127
;; ---- dplyr
;; summarise(DF, sum(V1), sd(V3))
(dpl/summarise DF '(sum V1) '(sd V3))
;; => # A tibble: 1 x 2
;; `sum(V1)` `sd(V3)`
;; <dbl> <dbl>
;; 1 13 0.433
;; ---- tech.ml.dataset
(aggregate->dataset [#(dfn/sum (% :V1))
#(dfn/standard-deviation (% :V3))] DS)
;; => _unnamed [1 2]:
;; | 0 | 1 |
;; |-------+--------|
;; | 13.00 | 0.4330 |
;; ### Summarise several columns and assign column names
;; ---- data.table
;; DT[, .(sumv1 = sum(V1),
;; sdv3 = sd(V3))]
(r '(bra ~DT nil (. :sumv1 (sum V1) :sdv3 (sd V3))))
;; => sumv1 sdv3
;; 1: 13 0.4330127
;; ---- dplyr
;; DF %>%
;; summarise(sumv1 = sum(V1),
;; sdv3 = sd(V3))
(-> DF
(dpl/summarise :sumv1 '(sum V1)
:sdv3 '(sd V3)))
;; => # A tibble: 1 x 2
;; sumv1 sdv3
;; <dbl> <dbl>
;; 1 13 0.433
;; ---- tech.ml.dataset
(aggregate->dataset {:sumv1 #(dfn/sum (% :V1))
:sdv3 #(dfn/standard-deviation (% :V3))} DS)
;; => _unnamed [1 2]:
;; | :sumv1 | :sdv3 |
;; |--------+--------|
;; | 13.00 | 0.4330 |
;; ### Summarise a subset of rows
;; ---- data.table
;; DT[1:4, sum(V1)]
(r/bra DT (r/colon 1 4) '(sum V1))
;; => [1] 6
;; ---- dplyr
;; DF %>%
;; slice(1:4) %>%
;; summarise(sum(V1))
(-> DF
(dpl/slice (r/colon 1 4))
(dpl/summarise '(sum V1)))
;; => # A tibble: 1 x 1
;; `sum(V1)`
;; <dbl>
;; 1 6
;; ---- tech.ml.dataset
(-> DS
(ds/select-rows (range 4))
(->> (aggregate->dataset [#(dfn/sum (% :V1))])))
;; => _unnamed [1 1]:
;; | 0 |
;; |-------|
;; | 6.000 |
;; ### additional
;; ---- data.table
;; DT[, data.table::first(V3)]
;; DT[, data.table::last(V3)]
;; DT[5, V3]
;; DT[, uniqueN(V4)]
;; uniqueN(DT)
(r '(bra ~DT nil ((rsymbol data.table first) V3)))
;; => [1] 0.5
(r '(bra ~DT nil ((rsymbol data.table last) V3)))
;; => [1] 1.5
(r/bra DT 5 'V3)
;; => [1] 1
(r '(bra ~DT nil (uniqueN V4)))
;; => [1] 3
(dt/uniqueN DT)
;; => [1] 9
;; ---- dplyr
;; summarise(DF, dplyr::first(V3))
;; summarise(DF, dplyr::last(V3))
;; summarise(DF, nth(V3, 5))
;; summarise(DF, n_distinct(V4))
;; n_distinct(DF)
(dpl/summarise DF '((rsymbol dplyr first) V3))
;; => # A tibble: 1 x 1
;; `dplyr::first(V3)`
;; <dbl>
;; 1 0.5
(dpl/summarise DF '((rsymbol dplyr last) V3))
;; => # A tibble: 1 x 1
;; `dplyr::last(V3)`
;; <dbl>
;; 1 1.5
(dpl/summarise DF '(nth V3 5))
;; => # A tibble: 1 x 1
;; `nth(V3, 5)`
;; <dbl>
;; 1 1
(dpl/summarise DF '(n_distinct V4))
;; => # A tibble: 1 x 1
;; `n_distinct(V4)`
;; <int>
;; 1 3
(dpl/n_distinct DF)
;; => [1] 9
;; ---- tech.ml.dataset
(first (DS :V3))
;; => 0.5
(last (DS :V3))
;; => 1.5
(nth (DS :V3) 5)
;; => 1.5
(count (col/unique (DS :V3)))
;; => 3
(ds/row-count (ds/unique-by identity DS))
;; => 9
;; ## Add/update/delete columns
;; ### Modify a column
;; ---- data.table
;; DT[, V1 := V1^2]
;; DT
;; TODO (clojisr): another tricky binary operator
(r '(bra ~DT nil ((rsymbol ":=") V1 (** V1 2))))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 4 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 4 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 4 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 4 8 1.0 B
;; 9: 1 9 1.5 C
;; ---- dplyr
;; DF <- DF %>% mutate(V1 = V1^2)
;; DF
(def DF (-> DF (dpl/mutate :V1 '(** V1 2))))
DF
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 4 2 1 B
;; 3 1 3 1.5 C
;; 4 4 4 0.5 A
;; 5 1 5 1 B
;; 6 4 6 1.5 C
;; 7 1 7 0.5 A
;; 8 4 8 1 B
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
(ds/update-column DS :V1 #(map (fn [v] (m/pow v 2)) %))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-------+-----+--------+-----|
;; | 1.000 | 1 | 0.5000 | A |
;; | 4.000 | 2 | 1.000 | B |
;; | 1.000 | 3 | 1.500 | C |
;; | 4.000 | 4 | 0.5000 | A |
;; | 1.000 | 5 | 1.000 | B |
;; | 4.000 | 6 | 1.500 | C |
;; | 1.000 | 7 | 0.5000 | A |
;; | 4.000 | 8 | 1.000 | B |
;; | 1.000 | 9 | 1.500 | C |
;; NOTE: using reader (optimized)
(def DS (ds/update-column DS :V1 #(-> (dtype/->reader % :float64)
(dfn/pow 2))))
DS
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-------+-----+--------+-----|
;; | 1.000 | 1 | 0.5000 | A |
;; | 4.000 | 2 | 1.000 | B |
;; | 1.000 | 3 | 1.500 | C |
;; | 4.000 | 4 | 0.5000 | A |
;; | 1.000 | 5 | 1.000 | B |
;; | 4.000 | 6 | 1.500 | C |
;; | 1.000 | 7 | 0.5000 | A |
;; | 4.000 | 8 | 1.000 | B |
;; | 1.000 | 9 | 1.500 | C |
;; ### Add one column
;; ---- data.table
;; DT[, v5 := log(V1)][] # adding [] prints the result
(r '(bra (bra ~DT nil ((rsymbol ":=") v5 (log V1)))))
;; => V1 V2 V3 V4 v5
;; 1: 1 1 0.5 A 0.000000
;; 2: 4 2 1.0 B 1.386294
;; 3: 1 3 1.5 C 0.000000
;; 4: 4 4 0.5 A 1.386294
;; 5: 1 5 1.0 B 0.000000
;; 6: 4 6 1.5 C 1.386294
;; 7: 1 7 0.5 A 0.000000
;; 8: 4 8 1.0 B 1.386294
;; 9: 1 9 1.5 C 0.000000
;; ---- dplyr
(def DF (dpl/mutate DF :v5 '(log V1)))
DF
;; => # A tibble: 9 x 5
;; V1 V2 V3 V4 v5
;; <dbl> <int> <dbl> <chr> <dbl>
;; 1 1 1 0.5 A 0
;; 2 4 2 1 B 1.39
;; 3 1 3 1.5 C 0
;; 4 4 4 0.5 A 1.39
;; 5 1 5 1 B 0
;; 6 4 6 1.5 C 1.39
;; 7 1 7 0.5 A 0
;; 8 4 8 1 B 1.39
;; 9 1 9 1.5 C 0
;; ---- tech.ml.dataset
(def DS (ds/add-or-update-column DS :v5 (dfn/log (DS :V1))))
DS
;; => _unnamed [9 5]:
;; | :V1 | :V2 | :V3 | :V4 | :v5 |
;; |-------+-----+--------+-----+-------|
;; | 1.000 | 1 | 0.5000 | A | 0.000 |
;; | 4.000 | 2 | 1.000 | B | 1.386 |
;; | 1.000 | 3 | 1.500 | C | 0.000 |
;; | 4.000 | 4 | 0.5000 | A | 1.386 |
;; | 1.000 | 5 | 1.000 | B | 0.000 |
;; | 4.000 | 6 | 1.500 | C | 1.386 |
;; | 1.000 | 7 | 0.5000 | A | 0.000 |
;; | 4.000 | 8 | 1.000 | B | 1.386 |
;; | 1.000 | 9 | 1.500 | C | 0.000 |
;; ### Add several columns
;; ---- data.table
;; DT[, c("v6", "v7") := .(sqrt(V1), "X")]
;; DT[, ':='(v6 = sqrt(V1),
;; v7 = "X")] # same, functional form
(r '(bra ~DT nil ((rsymbol ":=") ["v6" "v7"] (. (sqrt V1) "X"))))
;; => V1 V2 V3 V4 v5 v6 v7
;; 1: 1 1 0.5 A 0.000000 1 X
;; 2: 4 2 1.0 B 1.386294 2 X
;; 3: 1 3 1.5 C 0.000000 1 X
;; 4: 4 4 0.5 A 1.386294 2 X
;; 5: 1 5 1.0 B 0.000000 1 X
;; 6: 4 6 1.5 C 1.386294 2 X
;; 7: 1 7 0.5 A 0.000000 1 X
;; 8: 4 8 1.0 B 1.386294 2 X
;; 9: 1 9 1.5 C 0.000000 1 X
(r '(bra ~DT nil ((rsymbol ":=") :v6 (sqrt V1) :v7 "X")))
;; => V1 V2 V3 V4 v5 v6 v7
;; 1: 1 1 0.5 A 0.000000 1 X
;; 2: 4 2 1.0 B 1.386294 2 X
;; 3: 1 3 1.5 C 0.000000 1 X
;; 4: 4 4 0.5 A 1.386294 2 X
;; 5: 1 5 1.0 B 0.000000 1 X
;; 6: 4 6 1.5 C 1.386294 2 X
;; 7: 1 7 0.5 A 0.000000 1 X
;; 8: 4 8 1.0 B 1.386294 2 X
;; 9: 1 9 1.5 C 0.000000 1 X
;; ---- dplyr
;; DF <- mutate(DF, v6 = sqrt(V1), v7 = "X")
(def DF (dpl/mutate DF :v6 '(sqrt V1) :v7 "X"))
DF
;; => # A tibble: 9 x 7
;; V1 V2 V3 V4 v5 v6 v7
;; <dbl> <int> <dbl> <chr> <dbl> <dbl> <chr>
;; 1 1 1 0.5 A 0 1 X
;; 2 4 2 1 B 1.39 2 X
;; 3 1 3 1.5 C 0 1 X
;; 4 4 4 0.5 A 1.39 2 X
;; 5 1 5 1 B 0 1 X
;; 6 4 6 1.5 C 1.39 2 X
;; 7 1 7 0.5 A 0 1 X
;; 8 4 8 1 B 1.39 2 X
;; 9 1 9 1.5 C 0 1 X
;; ---- tech.ml.dataset
(def DS (-> DS
(ds/add-or-update-column :v6 (dfn/sqrt (DS :V1)))
(ds/add-or-update-column :v7 (take (ds/row-count DS) (repeat "X")))))
DS
;; => _unnamed [9 7]:
;; | :V1 | :V2 | :V3 | :V4 | :v5 | :v6 | :v7 |
;; |-------+-----+--------+-----+-------+-------+-----|
;; | 1.000 | 1 | 0.5000 | A | 0.000 | 1.000 | X |
;; | 4.000 | 2 | 1.000 | B | 1.386 | 2.000 | X |
;; | 1.000 | 3 | 1.500 | C | 0.000 | 1.000 | X |
;; | 4.000 | 4 | 0.5000 | A | 1.386 | 2.000 | X |
;; | 1.000 | 5 | 1.000 | B | 0.000 | 1.000 | X |
;; | 4.000 | 6 | 1.500 | C | 1.386 | 2.000 | X |
;; | 1.000 | 7 | 0.5000 | A | 0.000 | 1.000 | X |
;; | 4.000 | 8 | 1.000 | B | 1.386 | 2.000 | X |
;; | 1.000 | 9 | 1.500 | C | 0.000 | 1.000 | X |
;; ### Create one column and remove the others
;; ---- data.table
;; DT[, .(v8 = V3 + 1)]
(r '(bra ~DT nil (. :v8 (+ V3 1))))
;; => v8
;; 1: 1.5
;; 2: 2.0
;; 3: 2.5
;; 4: 1.5
;; 5: 2.0
;; 6: 2.5
;; 7: 1.5
;; 8: 2.0
;; 9: 2.5
;; ---- dplyr
;; transmute(DF, v8 = V3 + 1)
(dpl/transmute DF :v8 '(+ V3 1))
;; => # A tibble: 9 x 1
;; v8
;; <dbl>
;; 1 1.5
;; 2 2
;; 3 2.5
;; 4 1.5
;; 5 2
;; 6 2.5
;; 7 1.5
;; 8 2
;; 9 2.5
;; ---- tech.ml.dataset
(ds/new-dataset [(col/new-column :v8 (dfn/+ (DS :V3) 1))])
;; => _unnamed [9 1]:
;; | :v8 |
;; |-------|
;; | 1.500 |
;; | 2.000 |
;; | 2.500 |
;; | 1.500 |
;; | 2.000 |
;; | 2.500 |
;; | 1.500 |
;; | 2.000 |
;; | 2.500 |
;; ### Remove one column
;; ---- data.table
;; DT[, v5 := NULL]
(r '(bra ~DT nil ((rsymbol ":=") v5 nil)))
;; => V1 V2 V3 V4 v6 v7
;; 1: 1 1 0.5 A 1 X
;; 2: 4 2 1.0 B 2 X
;; 3: 1 3 1.5 C 1 X
;; 4: 4 4 0.5 A 2 X
;; 5: 1 5 1.0 B 1 X
;; 6: 4 6 1.5 C 2 X
;; 7: 1 7 0.5 A 1 X
;; 8: 4 8 1.0 B 2 X
;; 9: 1 9 1.5 C 1 X
;; ---- dplyr
;; DF <- select(DF, -v5)
(def DF (dpl/select DF '(- v5)))
DF
;; => # A tibble: 9 x 6
;; V1 V2 V3 V4 v6 v7
;; <dbl> <int> <dbl> <chr> <dbl> <chr>
;; 1 1 1 0.5 A 1 X
;; 2 4 2 1 B 2 X
;; 3 1 3 1.5 C 1 X
;; 4 4 4 0.5 A 2 X
;; 5 1 5 1 B 1 X
;; 6 4 6 1.5 C 2 X
;; 7 1 7 0.5 A 1 X
;; 8 4 8 1 B 2 X
;; 9 1 9 1.5 C 1 X
;; ---- tech.ml.dataset
(def DS (ds/remove-column DS :v5))
DS
;; => _unnamed [9 6]:
;; | :V1 | :V2 | :V3 | :V4 | :v6 | :v7 |
;; |-------+-----+--------+-----+-------+-----|
;; | 1.000 | 1 | 0.5000 | A | 1.000 | X |
;; | 4.000 | 2 | 1.000 | B | 2.000 | X |
;; | 1.000 | 3 | 1.500 | C | 1.000 | X |
;; | 4.000 | 4 | 0.5000 | A | 2.000 | X |
;; | 1.000 | 5 | 1.000 | B | 1.000 | X |
;; | 4.000 | 6 | 1.500 | C | 2.000 | X |
;; | 1.000 | 7 | 0.5000 | A | 1.000 | X |
;; | 4.000 | 8 | 1.000 | B | 2.000 | X |
;; | 1.000 | 9 | 1.500 | C | 1.000 | X |
;; ### Remove several columns
;; ---- data.table
;; DT[, c("v6", "v7") := NULL]
(r '(bra ~DT nil ((rsymbol ":=") ["v6" "v7"] nil)))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 4 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 4 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 4 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 4 8 1.0 B
;; 9: 1 9 1.5 C
;; ---- dplyr
;; DF <- select(DF, -v6, -v7)
(def DF (dpl/select DF '(- v6) '(- v7)))
DF
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 4 2 1 B
;; 3 1 3 1.5 C
;; 4 4 4 0.5 A
;; 5 1 5 1 B
;; 6 4 6 1.5 C
;; 7 1 7 0.5 A
;; 8 4 8 1 B
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
(def DS (ds/drop-columns DS [:v6 :v7]))
DS
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-------+-----+--------+-----|
;; | 1.000 | 1 | 0.5000 | A |
;; | 4.000 | 2 | 1.000 | B |
;; | 1.000 | 3 | 1.500 | C |
;; | 4.000 | 4 | 0.5000 | A |
;; | 1.000 | 5 | 1.000 | B |
;; | 4.000 | 6 | 1.500 | C |
;; | 1.000 | 7 | 0.5000 | A |
;; | 4.000 | 8 | 1.000 | B |
;; | 1.000 | 9 | 1.500 | C |
;; ### Remove columns using a vector of colnames
;; ---- data.table
;; cols <- c("V3")
;; DT[, (cols) := NULL] # ! not DT[, cols := NULL]
(def cols (r.base/<- 'cols ["V3"]))
;; TODO (clojisr): enable wrapping into parantheses
;; hacking below
(r (str (:object-name DT) "[, (cols) := NULL]"))
;; => V1 V2 V4
;; 1: 1 1 A
;; 2: 4 2 B
;; 3: 1 3 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 6 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; cols <- c("V3")
;; DF <- select(DF, -one_of(cols))
(def cols ["V3"])
(def DF (dpl/select DF '(- (one_of ~cols))))
DF
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <int> <chr>
;; 1 1 1 A
;; 2 4 2 B
;; 3 1 3 C
;; 4 4 4 A
;; 5 1 5 B
;; 6 4 6 C
;; 7 1 7 A
;; 8 4 8 B
;; 9 1 9 C
;; ---- tech.ml.dataset
(def cols [:V3])
(def DS (ds/drop-columns DS cols))
DS
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-----+-----|
;; | 1.000 | 1 | A |
;; | 4.000 | 2 | B |
;; | 1.000 | 3 | C |
;; | 4.000 | 4 | A |
;; | 1.000 | 5 | B |
;; | 4.000 | 6 | C |
;; | 1.000 | 7 | A |
;; | 4.000 | 8 | B |
;; | 1.000 | 9 | C |
;; ### Replace values for rows matching a condition
;; ---- data.table
;; DT[V2 < 4, V2 := 0L]
(r/bra DT '(< V2 4) '((rsymbol ":=") V2 0))
;; => V1 V2 V4
;; 1: 1 0 A
;; 2: 4 0 B
;; 3: 1 0 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 6 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; DF <- mutate(DF, V2 = base::replace(V2, V2 < 4, 0L))
(def DF (dpl/mutate DF '(= V2 ((rsymbol base replace) V2 (< V2 4) 0))))
DF
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 1 0 A
;; 2 4 0 B
;; 3 1 0 C
;; 4 4 4 A
;; 5 1 5 B
;; 6 4 6 C
;; 7 1 7 A
;; 8 4 8 B
;; 9 1 9 C
;; tech.ml.dataset
(def DS (ds/update-column DS :V2 #(map (fn [^long v]
(if (< v 4) 0 v)) %)))
DS
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 1.000 | 0.000 | A |
;; | 4.000 | 0.000 | B |
;; | 1.000 | 0.000 | C |
;; | 4.000 | 4.000 | A |
;; | 1.000 | 5.000 | B |
;; | 4.000 | 6.000 | C |
;; | 1.000 | 7.000 | A |
;; | 4.000 | 8.000 | B |
;; | 1.000 | 9.000 | C |
;; ## by
;; ### By group
;; ---- data.table
;; # one-liner:
;; DT[, .(sumV2 = sum(V2)), by = "V4"]
;; # reordered and indented:
;; DT[, by = V4,
;; .(sumV2 = sum(V2))]
(r '(bra ~DT nil (. :sumV2 (sum V2)) :by "V4"))
;; => V4 sumV2
;; 1: A 11
;; 2: B 13
;; 3: C 15
(r '(bra ~DT nil :by "V4" (. :sumV2 (sum V2))))
;; => V4 sumV2
;; 1: A 11
;; 2: B 13
;; 3: C 15
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; summarise(sumV2 = sum(V2))
(-> DF
(dpl/group_by 'V4)
(dpl/summarise :sumV2 '(sum V2)))
;; => # A tibble: 3 x 2
;; V4 sumV2
;; <chr> <dbl>
;; 1 A 11
;; 2 B 13
;; 3 C 15
;; ---- tech.ml.dataset
;; TODO: group-by and aggragete -> dataset
(group-by-columns-or-fn-and-aggregate [:V4] {:sumV2 #(dfn/sum (% :V2))} DS)
;; => _unnamed [3 2]:
;; | :V4 | :sumV2 |
;; |-----+--------|
;; | B | 13.00 |
;; | C | 15.00 |
;; | A | 11.00 |
;; ### By several groups
;; ---- data.table
;; DT[, keyby = .(V4, V1),
;; .(sumV2 = sum(V2))]
(r '(bra ~DT nil :keyby (. V4 V1) (. :sumV2 (sum V2))))
;; => V4 V1 sumV2
;; 1: A 1 7
;; 2: A 4 4
;; 3: B 1 5
;; 4: B 4 8
;; 5: C 1 9
;; 6: C 4 6
;; ---- dplyr
;; DF %>%
;; group_by(V4, V1) %>%
;; summarise(sumV2 = sum(V2))
(-> DF
(dpl/group_by 'V4 'V1)
(dpl/summarise :sumV2 '(sum V2)))
;; => # A tibble: 6 x 3
;; # Groups: V4 [3]
;; V4 V1 sumV2
;; <chr> <dbl> <dbl>
;; 1 A 1 7
;; 2 A 4 4
;; 3 B 1 5
;; 4 B 4 8
;; 5 C 1 9
;; 6 C 4 6
;; ---- tech.ml.dataset
(->> (group-by-columns-or-fn-and-aggregate [:V4 :V1] {:sumV2 #(dfn/sum (% :V2))} DS)
(sort-by-columns-with-orders [:V4 :V1]))
;; => _unnamed [6 3]:
;; | :V4 | :V1 | :sumV2 |
;; |-----+-------+--------|
;; | A | 1.000 | 7.000 |
;; | A | 4.000 | 4.000 |
;; | B | 1.000 | 5.000 |
;; | B | 4.000 | 8.000 |
;; | C | 1.000 | 9.000 |
;; | C | 4.000 | 6.000 |
;; ### Calling function in by
;; ---- data.table
;; DT[, by = tolower(V4),
;; .(sumV1 = sum(V1))]
(r '(bra ~DT nil :by (tolower V4) (. :sumV1 (sum V1))))
;; => tolower sumV1
;; 1: a 6
;; 2: b 9
;; 3: c 6
;; ---- dplyr
;; DF %>%
;; group_by(tolower(V4)) %>%
;; summarise(sumV1 = sum(V1))
(-> DF
(dpl/group_by '(tolower V4))
(dpl/summarise :sumV1 '(sum V1)))
;; => # A tibble: 3 x 2
;; `tolower(V4)` sumV1
;; <chr> <dbl>
;; 1 a 6
;; 2 b 9
;; 3 c 6
;; ---- tech.ml.dataset
(->> (ds/update-column DS :V4 #(map str/lower-case %))
(group-by-columns-or-fn-and-aggregate [:V4] {:sumV1 #(dfn/sum (% :V1))})
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :sumV1 |
;; |-----+--------|
;; | a | 6.000 |
;; | b | 9.000 |
;; | c | 6.000 |
;; ### Assigning column name in by
;; ---- data.table
;; DT[, keyby = .(abc = tolower(V4)),
;; .(sumV1 = sum(V1))]
(r '(bra ~DT nil :keyby (. :abc (tolower V4)) (. :sumV1 (sum V1))))
;; => abc sumV1
;; 1: a 6
;; 2: b 9
;; 3: c 6
;; ---- dplyr
;; DF %>%
;; group_by(abc = tolower(V4)) %>%
;; summarise(sumV1 = sum(V1))
(-> DF
(dpl/group_by :abc '(tolower V4))
(dpl/summarise :sumV1 '(sum V1)))
;; => # A tibble: 3 x 2
;; abc sumV1
;; <chr> <dbl>
;; 1 a 6
;; 2 b 9
;; 3 c 6
;; ---- tech.ml.dataset
(-> (ds/update-column DS :V4 #(map str/lower-case %))
(ds/rename-columns {:V4 :abc})
(->> (group-by-columns-or-fn-and-aggregate [:abc] {:sumV1 #(dfn/sum (% :V1))})
(ds/sort-by-column :abc)))
;; => _unnamed [3 2]:
;; | :abc | :sumV1 |
;; |------+--------|
;; | a | 6.000 |
;; | b | 9.000 |
;; | c | 6.000 |
;; ### Using a condition in by
;; ---- data.table
;; DT[, keyby = V4 == "A", sum(V1)]
(r '(bra ~DT nil :keyby (== V4 "A") (sum V1)))
;; => V4 V1
;; 1: FALSE 15
;; 2: TRUE 6
;; ---- dplyr
;; DF %>%
;; group_by(V4 == "A") %>%
;; summarise(sum(V1))
(-> DF
(dpl/group_by '(== V4 "A"))
(dpl/summarise '(sum V1)))
;; => # A tibble: 2 x 2
;; `(V4 == "A")` `sum(V1)`
;; <lgl> <dbl>
;; 1 FALSE 15
;; 2 TRUE 6
;; ---- tech.ml.dataset
(group-by-columns-or-fn-and-aggregate #(= (% :V4) \A)
{:sumV1 #(dfn/sum (% :V1))}
DS)
;; => _unnamed [2 2]:
;; | :_fn | :sumV1 |
;; |-------+--------|
;; | false | 15.00 |
;; | true | 6.000 |
;; ### By on a subset of rows
;; ---- data.table
;; DT[1:5, # i
;; .(sumV1 = sum(V1)), # j
;; by = V4] # by
;; ## complete DT[i, j, by] expression!
(r/bra DT (r/colon 1 5) '(. :sumV1 (sum V1)) :by 'V4)
;; => V4 sumV1
;; 1: A 5
;; 2: B 5
;; 3: C 1
;; ---- dplyr
;; DF %>%
;; slice(1:5) %>%
;; group_by(V4) %>%
;; summarise(sumV1 = sum(V1))
(-> DF
(dpl/slice (r/colon 1 5))
(dpl/group_by 'V4)
(dpl/summarise :sumV1 '(sum V1)))
;; => # A tibble: 3 x 2
;; V4 sumV1
;; <chr> <dbl>
;; 1 A 5
;; 2 B 5
;; 3 C 1
;; ---- tech.ml.dataset
(->> (ds/select-rows DS (range 5))
(group-by-columns-or-fn-and-aggregate [:V4] {:sumV1 #(dfn/sum (% :V1))})
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :sumV1 |
;; |-----+--------|
;; | A | 5.000 |
;; | B | 5.000 |
;; | C | 1.000 |
;; ### Count number of observations for each group
;; ---- data.table
;; DT[, .N, by = V4]
(r '(bra ~DT nil .N :by V4))
;; => V4 N
;; 1: A 3
;; 2: B 3
;; 3: C 3
;; ---- dplyr
;; count(DF, V4)
;; DF %>%
;; group_by(V4) %>%
;; tally()
;; DF %>%
;; group_by(V4) %>%
;; summarise(n())
;; DF %>%
;; group_by(V4) %>%
;; group_size() # returns a vector
(dpl/count DF 'V4)
;; => # A tibble: 3 x 2
;; V4 n
;; <chr> <int>
;; 1 A 3
;; 2 B 3
;; 3 C 3
(-> DF (dpl/group_by 'V4) (dpl/tally))
;; => # A tibble: 3 x 2
;; V4 n
;; <chr> <int>
;; 1 A 3
;; 2 B 3
;; 3 C 3
(-> DF (dpl/group_by 'V4) (dpl/summarise '(n)))
;; => # A tibble: 3 x 2
;; V4 `n()`
;; <chr> <int>
;; 1 A 3
;; 2 B 3
;; 3 C 3
(-> DF (dpl/group_by 'V4) (dpl/group_size))
;; => [1] 3 3 3
;; ---- tech.ml.dataset
(group-by-columns-or-fn-and-aggregate [:V4] {:N ds/row-count} DS)
;; => _unnamed [3 2]:
;; | :V4 | :N |
;; |-----+----|
;; | B | 3 |
;; | C | 3 |
;; | A | 3 |
(map-v ds/row-count (ds/group-by-column :V4 DS))
;; => {\A 3, \B 3, \C 3}
(->> (vals (ds/group-by-column :V4 DS))
(map ds/row-count))
;; => (3 3 3)
;; ### Add a column with number of observations for each group
;; ---- data.table
;; DT[, n := .N, by = V1][]
;; DT[, n := NULL] # rm column for consistency
(r '(bra ~DT nil ((rsymbol ":=") n .N) :by V1))
;; => V1 V2 V4 n
;; 1: 1 0 A 5
;; 2: 4 0 B 4
;; 3: 1 0 C 5
;; 4: 4 4 A 4
;; 5: 1 5 B 5
;; 6: 4 6 C 4
;; 7: 1 7 A 5
;; 8: 4 8 B 4
;; 9: 1 9 C 5
;; cleaning
(r '(bra ~DT nil ((rsymbol ":=") n nil)))
;; => V1 V2 V4
;; 1: 1 0 A
;; 2: 4 0 B
;; 3: 1 0 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 6 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; add_count(DF, V1)
;; DF %>%
;; group_by(V1) %>%
;; add_tally()
(dpl/add_count DF 'V1)
;; => # A tibble: 9 x 4
;; V1 V2 V4 n
;; <dbl> <dbl> <chr> <int>
;; 1 1 0 A 5
;; 2 4 0 B 4
;; 3 1 0 C 5
;; 4 4 4 A 4
;; 5 1 5 B 5
;; 6 4 6 C 4
;; 7 1 7 A 5
;; 8 4 8 B 4
;; 9 1 9 C 5
(-> DF
(dpl/group_by 'V1)
(dpl/add_tally))
;; => # A tibble: 9 x 4
;; # Groups: V1 [2]
;; V1 V2 V4 n
;; <dbl> <dbl> <chr> <int>
;; 1 1 0 A 5
;; 2 4 0 B 4
;; 3 1 0 C 5
;; 4 4 4 A 4
;; 5 1 5 B 5
;; 6 4 6 C 4
;; 7 1 7 A 5
;; 8 4 8 B 4
;; 9 1 9 C 5
;; ---- tech.ml.dataset
;; TODO: how to do this optimally and keep order?
(->> (ds/group-by identity [:V1] DS)
(vals)
(map (fn [ds]
(let [rcnt (ds/row-count ds)]
(ds/new-column ds :n (repeat rcnt rcnt)))))
(apply ds/concat)
(sort-by-columns-with-orders [:V2 :V4]))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V4 | :n |
;; |-------+-------+-----+-------|
;; | 1.000 | 0.000 | A | 5.000 |
;; | 4.000 | 0.000 | B | 4.000 |
;; | 1.000 | 0.000 | C | 5.000 |
;; | 4.000 | 4.000 | A | 4.000 |
;; | 1.000 | 5.000 | B | 5.000 |
;; | 4.000 | 6.000 | C | 4.000 |
;; | 1.000 | 7.000 | A | 5.000 |
;; | 4.000 | 8.000 | B | 4.000 |
;; | 1.000 | 9.000 | C | 5.000 |
;; ### Retrieve the first/last/nth observation for each group
;; ---- data.table
;; DT[, data.table::first(V2), by = V4]
;; DT[, data.table::last(V2), by = V4]
;; DT[, V2[2], by = V4]
(r '(bra ~DT nil ((rsymbol data.table first) V2) :by V4))
;; => V4 V1
;; 1: A 0
;; 2: B 0
;; 3: C 0
(r '(bra ~DT nil ((rsymbol data.table last) V2) :by V4))
;; => V4 V1
;; 1: A 7
;; 2: B 8
;; 3: C 9
(r '(bra ~DT nil (bra V2 2) :by V4))
;; => V4 V1
;; 1: A 4
;; 2: B 5
;; 3: C 6
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; summarise(dplyr::first(V2))
;; DF %>%
;; group_by(V4) %>%
;; summarise(dplyr::last(V2))
;; DF %>%
;; group_by(V4) %>%
;; summarise(dplyr::nth(V2, 2))
(-> DF (dpl/group_by 'V4) (dpl/summarise '((rsymbol dplyr first) V2)))
;; => # A tibble: 3 x 2
;; V4 `dplyr::first(V2)`
;; <chr> <dbl>
;; 1 A 0
;; 2 B 0
;; 3 C 0
(-> DF (dpl/group_by 'V4) (dpl/summarise '((rsymbol dplyr last) V2)))
;; => # A tibble: 3 x 2
;; V4 `dplyr::last(V2)`
;; <chr> <dbl>
;; 1 A 7
;; 2 B 8
;; 3 C 9
(-> DF (dpl/group_by 'V4) (dpl/summarise '((rsymbol dplyr nth) V2 2)))
;; => # A tibble: 3 x 2
;; V4 `dplyr::nth(V2, 2)`
;; <chr> <dbl>
;; 1 A 4
;; 2 B 5
;; 3 C 6
;; ---- tech.ml.dataset
(->> (group-by-columns-or-fn-and-aggregate [:V4] {:v #(first (% :V2))} DS)
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :v |
;; |-----+-------|
;; | A | 0.000 |
;; | B | 0.000 |
;; | C | 0.000 |
(->> (group-by-columns-or-fn-and-aggregate [:V4] {:v #(last (% :V2))} DS)
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :v |
;; |-----+-------|
;; | A | 7.000 |
;; | B | 8.000 |
;; | C | 9.000 |
(->> (group-by-columns-or-fn-and-aggregate [:V4] {:v #(nth (% :V2) 1)} DS)
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :v |
;; |-----+-------|
;; | A | 4.000 |
;; | B | 5.000 |
;; | C | 6.000 |
;; -------------------------------
;; # Going further
;; ## Advanced columns manipulation
;; ### Summarise all the columns
;; ---- data.table
;; DT[, lapply(.SD, max)]
(r '(bra ~DT nil (lapply .SD max)))
;; => V1 V2 V4
;; 1: 4 9 C
;; ---- dplyr
;; summarise_all(DF, max)
(dpl/summarise_all DF r.base/max)
;; => # A tibble: 1 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 4 9 C
;; ---- tech.ml.dataset
;; TODO: dfn/max doesn't work
(apply-to-columns my-max :all DS)
;; => _unnamed [1 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 4.000 | 9.000 | C |
;; ### Summarise several columns
;; ---- data.table
;; DT[, lapply(.SD, mean),
;; .SDcols = c("V1", "V2")]
;; # .SDcols is like "_at"
(r '(bra ~DT nil (lapply .SD mean) :.SDcols ["V1" "V2"]))
;; => V1 V2
;; 1: 2.333333 4.333333
;; ---- dplyr
;; summarise_at(DF, c("V1", "V2"), mean)
(dpl/summarise_at DF ["V1" "V2"] r.base/mean)
;; => # A tibble: 1 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 2.33 4.33
;; ---- tech.ml.dataset
;; doesn't work on beta 39
#_(->> (ds/select-columns DS [:V1 :V2])
(apply-to-columns dfn/mean [:V1 :V2]))
;; => _unnamed [1 2]:
;; | :V1 | :V2 |
;; |-------+-------|
;; | 2.333 | 4.333 |
;; ### Summarise several columns by group
;; ---- data.table
;; DT[, by = V4,
;; lapply(.SD, mean),
;; .SDcols = c("V1", "V2")]
;; ## using patterns (regex)
;; DT[, by = V4,
;; lapply(.SD, mean),
;; .SDcols = patterns("V1|V2")]
(r '(bra ~DT nil :by V4 (lapply .SD mean) :.SDcols ["V1" "V2"]))
;; => V4 V1 V2
;; 1: A 2 3.666667
;; 2: B 3 4.333333
;; 3: C 2 5.000000
(r '(bra ~DT nil :by V4 (lapply .SD mean) :.SDcols (patterns "V1|V2")))
;; => V4 V1 V2
;; 1: A 2 3.666667
;; 2: B 3 4.333333
;; 3: C 2 5.000000
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; summarise_at(c("V1", "V2"), mean)
;; ## using select helpers
;; DF %>%
;; group_by(V4) %>%
;; summarise_at(vars(one_of("V1", "V2")), mean)
(-> DF (dpl/group_by 'V4) (dpl/summarise_at ["V1" "V2"] r.base/mean))
;; => # A tibble: 3 x 3
;; V4 V1 V2
;; <chr> <dbl> <dbl>
;; 1 A 2 3.67
;; 2 B 3 4.33
;; 3 C 2 5
(-> DF (dpl/group_by 'V4) (dpl/summarise_at '(vars (one_of "V1" "V2")) r.base/mean))
;; => # A tibble: 3 x 3
;; V4 V1 V2
;; <chr> <dbl> <dbl>
;; 1 A 2 3.67
;; 2 B 3 4.33
;; 3 C 2 5
;; ---- tech.ml.dataset
(->> DS
(group-by-columns-or-fn-and-aggregate [:V4] {:V1 #(dfn/mean (% :V1))
:V2 #(dfn/mean (% :V2))})
(ds/sort-by-column :V4))
;; => _unnamed [3 3]:
;; | :V4 | :V2 | :V1 |
;; |-----+-------+-------|
;; | A | 3.667 | 2.000 |
;; | B | 4.333 | 3.000 |
;; | C | 5.000 | 2.000 |
;; ### Summarise with more than one function by group
;; ---- data.table
;; DT[, by = V4,
;; c(lapply(.SD, sum),
;; lapply(.SD, mean))]
(r '(bra ~DT nil :by V4 [(lapply .SD sum)
(lapply .SD mean)]))
;; => V4 V1 V2 V1 V2
;; 1: A 6 11 2 3.666667
;; 2: B 9 13 3 4.333333
;; 3: C 6 15 2 5.000000
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; summarise_all(list(sum, mean))
(-> DF (dpl/group_by 'V4) (dpl/summarise_all [:!list 'sum 'mean]))
;; => # A tibble: 3 x 5
;; V4 V1_fn1 V2_fn1 V1_fn2 V2_fn2
;; <chr> <dbl> <dbl> <dbl> <dbl>
;; 1 A 6 11 2 3.67
;; 2 B 9 13 3 4.33
;; 3 C 6 15 2 5
;; tech.ml.dataset
(->> DS
(group-by-columns-or-fn-and-aggregate [:V4] {:V1-mean #(dfn/mean (% :V1))
:V2-mean #(dfn/mean (% :V2))
:V1-sum #(dfn/sum (% :V1))
:V2-sum #(dfn/sum (% :V2))})
(ds/sort-by-column :V4))
;; => _unnamed [3 5]:
;; | :V4 | :V2-sum | :V1-mean | :V1-sum | :V2-mean |
;; |-----+---------+----------+---------+----------|
;; | A | 11.00 | 2.000 | 6.000 | 3.667 |
;; | B | 13.00 | 3.000 | 9.000 | 4.333 |
;; | C | 15.00 | 2.000 | 6.000 | 5.000 |
;; ### Summarise using a condition
;; ---- data.table
;; cols <- names(DT)[sapply(DT, is.numeric)]
;; DT[, lapply(.SD, mean),
;; .SDcols = cols]
(def cols (r/bra (r.base/names DT) (r.base/sapply DT r.base/is-numeric)))
(r '(bra ~DT nil (lapply .SD mean) :.SDcols ~cols))
;; => V1 V2
;; 1: 2.333333 4.333333
;; ---- dplyr
;; summarise_if(DF, is.numeric, mean)
(dpl/summarise_if DF r.base/is-numeric r.base/mean)
;; => # A tibble: 1 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 2.33 4.33
;; ---- tech.ml.dataset
(def cols (->> DS
(ds/columns)
(map meta)
(filter (comp #{:float64} :datatype))
(map :name)))
(->> (ds/select-columns DS cols)
(apply-to-columns dfn/mean cols))
;; => _unnamed [1 2]:
;; | :V1 | :V2 |
;; |-------+-------|
;; | 2.333 | 4.333 |
;; ### Modify all the columns
;; ---- data.table
;; DT[, lapply(.SD, rev)]
(r '(bra ~DT nil (lapply .SD rev)))
;; => V1 V2 V4
;; 1: 1 9 C
;; 2: 4 8 B
;; 3: 1 7 A
;; 4: 4 6 C
;; 5: 1 5 B
;; 6: 4 4 A
;; 7: 1 0 C
;; 8: 4 0 B
;; 9: 1 0 A
;; ---- dplyr
;; mutate_all(DF, rev)
;; # transmute_all(DF, rev)
(dpl/mutate_all DF r.base/rev)
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 1 9 C
;; 2 4 8 B
;; 3 1 7 A
;; 4 4 6 C
;; 5 1 5 B
;; 6 4 4 A
;; 7 1 0 C
;; 8 4 0 B
;; 9 1 0 A
;; ---- tech.ml.dataset
(ds/update-columns DS (ds/column-names DS) reverse)
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 1.000 | 9.000 | C |
;; | 4.000 | 8.000 | B |
;; | 1.000 | 7.000 | A |
;; | 4.000 | 6.000 | C |
;; | 1.000 | 5.000 | B |
;; | 4.000 | 4.000 | A |
;; | 1.000 | 0.000 | C |
;; | 4.000 | 0.000 | B |
;; | 1.000 | 0.000 | A |
;; ### Modify several columns (dropping the others)
;; ---- data.table
;; DT[, lapply(.SD, sqrt),
;; .SDcols = V1:V2]
;; DT[, lapply(.SD, exp),
;; .SDcols = !"V4"]
(r '(bra ~DT nil (lapply .SD sqrt) :.SDcols (colon V1 V2)))
;; => V1 V2
;; 1: 1 0.000000
;; 2: 2 0.000000
;; 3: 1 0.000000
;; 4: 2 2.000000
;; 5: 1 2.236068
;; 6: 2 2.449490
;; 7: 1 2.645751
;; 8: 2 2.828427
;; 9: 1 3.000000
(r '(bra ~DT nil (lapply .SD exp) :.SDcols (! "V4")))
;; => V1 V2
;; 1: 2.718282 1.00000
;; 2: 54.598150 1.00000
;; 3: 2.718282 1.00000
;; 4: 54.598150 54.59815
;; 5: 2.718282 148.41316
;; 6: 54.598150 403.42879
;; 7: 2.718282 1096.63316
;; 8: 54.598150 2980.95799
;; 9: 2.718282 8103.08393
;; ---- dplyr
;; transmute_at(DF, c("V1", "V2"), sqrt)
;; transmute_at(DF, vars(-V4), exp)
(dpl/transmute_at DF ["V1" "V2"] 'sqrt)
;; => # A tibble: 9 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 1 0
;; 2 2 0
;; 3 1 0
;; 4 2 2
;; 5 1 2.24
;; 6 2 2.45
;; 7 1 2.65
;; 8 2 2.83
;; 9 1 3
(dpl/transmute_at DF '(vars (- V4)) 'exp)
;; => # A tibble: 9 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 2.72 1
;; 2 54.6 1
;; 3 2.72 1
;; 4 54.6 54.6
;; 5 2.72 148.
;; 6 54.6 403.
;; 7 2.72 1097.
;; 8 54.6 2981.
;; 9 2.72 8103.
;; ---- tech.ml. dataset
(->> (ds/select-columns DS [:V1 :V2])
(apply-to-columns dfn/sqrt :all))
;; => _unnamed [9 2]:
;; | :V1 | :V2 |
;; |-------+-------|
;; | 1.000 | 0.000 |
;; | 2.000 | 0.000 |
;; | 1.000 | 0.000 |
;; | 2.000 | 2.000 |
;; | 1.000 | 2.236 |
;; | 2.000 | 2.449 |
;; | 1.000 | 2.646 |
;; | 2.000 | 2.828 |
;; | 1.000 | 3.000 |
(->> (ds/drop-columns DS [:V4])
(apply-to-columns dfn/exp :all))
;; => _unnamed [9 2]:
;; | :V1 | :V2 |
;; |-------+-------|
;; | 2.718 | 1.000 |
;; | 54.60 | 1.000 |
;; | 2.718 | 1.000 |
;; | 54.60 | 54.60 |
;; | 2.718 | 148.4 |
;; | 54.60 | 403.4 |
;; | 2.718 | 1097 |
;; | 54.60 | 2981 |
;; | 2.718 | 8103 |
;; ### Modify several columns (keeping the others)
;; ---- data.table
;; DT[, c("V1", "V2") := lapply(.SD, sqrt),
;; .SDcols = c("V1", "V2")]
;; cols <- setdiff(names(DT), "V4")
;; DT[, (cols) := lapply(.SD, "^", 2L),
;; .SDcols = cols]
(r '(bra ~DT nil ((rsymbol ":=") ["V1" "V2"] (lapply .SD sqrt))
:.SDcols ["V1" "V2"]))
;; => V1 V2 V4
;; 1: 1 0.000000 A
;; 2: 2 0.000000 B
;; 3: 1 0.000000 C
;; 4: 2 2.000000 A
;; 5: 1 2.236068 B
;; 6: 2 2.449490 C
;; 7: 1 2.645751 A
;; 8: 2 2.828427 B
;; 9: 1 3.000000 C
(def cols (r.base/<- 'cols (r.base/setdiff (r.base/names DT) "V4")))
(r (str (:object-name DT) "[, (cols) := lapply(.SD, \"^\", 2L), .SDcols = cols]"))
;; => V1 V2 V4
;; 1: 1 0 A
;; 2: 4 0 B
;; 3: 1 0 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 6 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; DF <- mutate_at(DF, c("V1", "V2"), sqrt)
;; DF <- mutate_at(DF, vars(-V4), "^", 2L)
(def DF (dpl/mutate_at DF ["V1" "V2"] 'sqrt))
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 1 0 A
;; 2 2 0 B
;; 3 1 0 C
;; 4 2 2 A
;; 5 1 2.24 B
;; 6 2 2.45 C
;; 7 1 2.65 A
;; 8 2 2.83 B
;; 9 1 3 C
(def DF (dpl/mutate_at DF '(vars (- V4)) "^" 2))
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 1 0 A
;; 2 4 0 B
;; 3 1 0 C
;; 4 4 4 A
;; 5 1 5. B
;; 6 4 6.00 C
;; 7 1 7. A
;; 8 4 8. B
;; 9 1 9 C
;; ---- tech.ml.dataset
(def DS (apply-to-columns dfn/sqrt [:V1 :V2] DS))
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 1.000 | 0.000 | A |
;; | 2.000 | 0.000 | B |
;; | 1.000 | 0.000 | C |
;; | 2.000 | 2.000 | A |
;; | 1.000 | 2.236 | B |
;; | 2.000 | 2.449 | C |
;; | 1.000 | 2.646 | A |
;; | 2.000 | 2.828 | B |
;; | 1.000 | 3.000 | C |
(def DS (apply-to-columns #(dfn/pow % 2.0) [:V1 :V2] DS))
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 1.000 | 0.000 | A |
;; | 4.000 | 0.000 | B |
;; | 1.000 | 0.000 | C |
;; | 4.000 | 4.000 | A |
;; | 1.000 | 5.000 | B |
;; | 4.000 | 6.000 | C |
;; | 1.000 | 7.000 | A |
;; | 4.000 | 8.000 | B |
;; | 1.000 | 9.000 | C |
;; ### Modify columns using a condition (dropping the others)
;; ---- data.table
;; cols <- names(DT)[sapply(DT, is.numeric)]
;; DT[, .SD - 1,
;; .SDcols = cols]
(def cols (r/bra (r.base/names DT) (r.base/sapply DT r.base/is-numeric)))
(r '(bra ~DT nil (- .SD 1) :.SDcols ~cols))
;; => V1 V2
;; 1: 0 -1
;; 2: 3 -1
;; 3: 0 -1
;; 4: 3 3
;; 5: 0 4
;; 6: 3 5
;; 7: 0 6
;; 8: 3 7
;; 9: 0 8
;; ---- dplyr
;; transmute_if(DF, is.numeric, list(~ '-'(., 1L)))
(dpl/transmute_if DF r.base/is-numeric [:!list '(formula nil (- . 1))])
;; => # A tibble: 9 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 0 -1
;; 2 3 -1
;; 3 0 -1
;; 4 3 3
;; 5 0 4.
;; 6 3 5.00
;; 7 0 6.
;; 8 3 7.
;; 9 0 8
;; ---- tech.ml.dataset
(def cols (->> DS
(ds/columns)
(map meta)
(filter (comp #(= :float64 %) :datatype))
(map :name)))
(->> (ds/select-columns DS cols)
(apply-to-columns #(dfn/- % 1) cols))
;; => _unnamed [9 2]:
;; | :V1 | :V2 |
;; |-------+--------|
;; | 0.000 | -1.000 |
;; | 3.000 | -1.000 |
;; | 0.000 | -1.000 |
;; | 3.000 | 3.000 |
;; | 0.000 | 4.000 |
;; | 3.000 | 5.000 |
;; | 0.000 | 6.000 |
;; | 3.000 | 7.000 |
;; | 0.000 | 8.000 |
;; ### Modify columns using a condition (keeping the others)
;; ---- data.table
;; DT[, (cols) := lapply(.SD, as.integer),
;; .SDcols = cols]
(def cols (r.base/<- 'cols (r.base/setdiff (r.base/names DT) "V4")))
(r (str (:object-name DT) "[, (cols) := lapply(.SD, as.integer), .SDcols = cols]"))
;; => V1 V2 V4
;; 1: 1 0 A
;; 2: 4 0 B
;; 3: 1 0 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 5 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; DF <- mutate_if(DF, is.numeric, as.integer)
(def DF (dpl/mutate_if DF r.base/is-numeric r.base/as-integer))
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <int> <int> <chr>
;; 1 1 0 A
;; 2 4 0 B
;; 3 1 0 C
;; 4 4 4 A
;; 5 1 5 B
;; 6 4 5 C
;; 7 1 7 A
;; 8 4 8 B
;; 9 1 9 C
;; ----tech.ml.dataset
;; TODO: easier cast to given type
(def DS (apply-to-columns #(dtype/->reader % :int64) [:V1 :V2] DS))
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-----+-----+-----|
;; | 1 | 0 | A |
;; | 4 | 0 | B |
;; | 1 | 0 | C |
;; | 4 | 4 | A |
;; | 1 | 5 | B |
;; | 4 | 5 | C |
;; | 1 | 7 | A |
;; | 4 | 8 | B |
;; | 1 | 9 | C |
;; ### Use a complex expression
;; ---- data.table
;; DT[, by = V4, .(V1[1:2], "X")]
(r '(bra ~DT nil :by V4 (. (bra V1 (colon 1 2)) "X")))
;; => V4 V1 V2
;; 1: A 1 X
;; 2: A 4 X
;; 3: B 4 X
;; 4: B 1 X
;; 5: C 1 X
;; 6: C 4 X
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; slice(1:2) %>%
;; transmute(V1 = V1,
;; V2 = "X")
(-> DF
(dpl/group_by 'V4)
(dpl/slice (r/colon 1 2))
(dpl/transmute :V1 'V1 :V2 "X"))
;; => # A tibble: 6 x 3
;; # Groups: V4 [3]
;; V4 V1 V2
;; <chr> <int> <chr>
;; 1 A 1 X
;; 2 A 4 X
;; 3 B 4 X
;; 4 B 1 X
;; 5 C 1 X
;; 6 C 4 X
;; ---- tech.ml.dataset
(->> (ds/group-by-column :V4 DS)
(vals)
(map #(ds/head 2 %))
(map #(ds/add-or-update-column % :V2 (repeat (ds/row-count %) "X")))
(apply ds/concat))
;; => null [6 3]:
;; | :V1 | :V2 | :V4 |
;; |-----+-----+-----|
;; | 1 | X | A |
;; | 4 | X | A |
;; | 4 | X | B |
;; | 1 | X | B |
;; | 1 | X | C |
;; | 4 | X | C |
;; ### Use multiple expressions (with DT[,{j}])
;; ---- data.table
;; DT[, {print(V1) # comments here!
;; print(summary(V1))
;; x <- V1 + sum(V2)
;; .(A = 1:.N, B = x) # last list returned as a data.table
;; }]
(r (str (:object-name DT)
"[, {print(V1) # comments here!
print(summary(V1))
x <- V1 + sum(V2)
.(A = 1:.N, B = x)}]"))
;; => A B
;; 1: 1 39
;; 2: 2 42
;; 3: 3 39
;; 4: 4 42
;; 5: 5 39
;; 6: 6 42
;; 7: 7 39
;; 8: 8 42
;; 9: 9 39
;; printed:
;; [1] 1 4 1 4 1 4 1 4 1
;; Min. 1st Qu. Median Mean 3rd Qu. Max.
;; 1.000 1.000 1.000 2.333 4.000 4.000
;; ---- dplyr
;; no provided implementation
;; ---- tech.ml.dataset
(let [x (dfn/+ (DS :V1) (dfn/sum (DS :V2)))]
(println (DS :V1))
(println (dfn/descriptive-stats (DS :V2)))
(ds/name-values-seq->dataset {:A (map inc (range (ds/row-count DS)))
:B x}))
;; => _unnamed [9 2]:
;; | :A | :B |
;; |----+-------|
;; | 1 | 39.00 |
;; | 2 | 42.00 |
;; | 3 | 39.00 |
;; | 4 | 42.00 |
;; | 5 | 39.00 |
;; | 6 | 42.00 |
;; | 7 | 39.00 |
;; | 8 | 42.00 |
;; | 9 | 39.00 |
;; printed:
;; #tech.ml.dataset.column<int64>[9]
;; :V1
;; [1, 4, 1, 4, 1, 4, 1, 4, 1, ]
;; {:min 0.0, :mean 4.222222222222222, :skew -0.1481546009077147, :ecount 9, :standard-deviation 3.527668414752787, :median 5.0, :max 9.0}
| true | (ns techtest.datatable-dplyr
(:require [tech.ml.dataset :as ds]
[tech.ml.dataset.column :as col]
[tech.v2.datatype.functional :as dfn]
[tech.v2.datatype :as dtype]
[fastmath.core :as m]
[clojure.string :as str]))
;; Comparizon of tech.ml.dataset with datatable and dplyr
;; Based on article "A data.table and dplyr tour" by PI:NAME:<NAME>END_PI dated March 3, 2019
;; https://atrebas.github.io/post/2019-03-03-datatable-dplyr/
;; Dataset names used:
;;
;; DT - R data.table object
;; DF - R tibble (dplyr) object
;; DS - tech.ml.dataset object
;; # Preparation
;; load R package
(require '[clojisr.v1.r :as r :refer [r r->clj]]
'[clojisr.v1.require :refer [require-r]])
(require-r '[base]
'[utils]
'[stats]
'[tidyr]
'[dplyr :as dpl]
'[data.table :as dt])
(r.base/options :width 160)
(r.base/set-seed 1)
;; HELPER functions
(defn aggregate
([agg-fns-map ds]
(aggregate {} agg-fns-map ds))
([m agg-fns-map-or-vector ds]
(into m (map (fn [[k agg-fn]]
[k (agg-fn ds)]) (if (map? agg-fns-map-or-vector)
agg-fns-map-or-vector
(map-indexed vector agg-fns-map-or-vector))))))
(def aggregate->dataset (comp ds/->dataset vector aggregate))
(defn group-by-columns-or-fn-and-aggregate
[key-fn-or-gr-colls agg-fns-map ds]
(->> (if (fn? key-fn-or-gr-colls)
(ds/group-by key-fn-or-gr-colls ds)
(ds/group-by identity key-fn-or-gr-colls ds))
(map (fn [[group-idx group-ds]]
(let [group-idx-m (if (map? group-idx)
group-idx
{:_fn group-idx})]
(aggregate group-idx-m agg-fns-map group-ds))))
ds/->dataset))
(defn asc-desc-comparator
[orders]
(if (every? #(= % :asc) orders)
compare
(let [mults (map #(if (= % :asc) 1 -1) orders)]
(fn [v1 v2]
(reduce (fn [_ [a b ^long mult]]
(let [c (compare a b)]
(if-not (zero? c)
(reduced (* mult c))
c))) 0 (map vector v1 v2 mults))))))
(defn sort-by-columns-with-orders
([cols ds]
(sort-by-columns-with-orders cols (repeat (count cols) :asc) ds))
([cols orders ds]
(let [sel (apply juxt (map #(fn [ds] (get ds %)) cols))
comp-fn (asc-desc-comparator orders)]
(ds/sort-by sel comp-fn ds))))
(defn map-v [f coll]
(reduce-kv (fn [m k v] (assoc m k (f v))) (empty coll) coll))
(defn filter-by-external-values->indices
[pred values]
(->> values
(map-indexed vector)
(filter (comp pred second))
(map first)))
(defn my-max [xs] (reduce #(if (pos? (compare %1 %2)) %1 %2) xs))
(defn my-min [xs] (reduce #(if (pos? (compare %2 %1)) %1 %2) xs))
(defn- ensure-seq
[v]
(if (seqable? v) v [v]))
(defn apply-to-columns
[f columns ds]
(let [names (ds/column-names ds)
columns (set (if (= :all columns) names columns))
ff (fn [col]
(if (columns (col/column-name col))
(f col)
col))]
(->> names
(map (comp ensure-seq ff ds))
(zipmap names)
(ds/name-values-seq->dataset))))
;; # Create example data
;; ---- data.table
;; DT <- data.table(V1 = rep(c(1L, 2L), 5)[-10],
;; V2 = 1:9,
;; V3 = c(0.5, 1.0, 1.5),
;; V4 = rep(LETTERS[1:3], 3))
;; class(DT)
;; DT
(def DT (dt/data-table :V1 (r/bra (r.base/rep [1 2] 5) -10)
:V2 (r/colon 1 9)
:V3 [0.5 1.0 1.5]
:V4 (r.base/rep (r/bra 'LETTERS (r/colon 1 3)) 3)))
(r.base/class DT)
;; => [1] "data.table" "data.frame"
DT
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 2 8 1.0 B
;; 9: 1 9 1.5 C
;; ---- dplyr
;; DF <- tibble(V1 = rep(c(1L, 2L), 5)[-10],
;; V2 = 1:9,
;; V3 = rep(c(0.5, 1.0, 1.5), 3),
;; V4 = rep(LETTERS[1:3], 3))
;; class(DF)
;; DF
(def DF (dpl/tibble :V1 (r/bra (r.base/rep [1 2] 5) -10)
:V2 (r/colon 1 9)
:V3 (r.base/rep [0.5 1.0 1.5] 3)
:V4 (r.base/rep (r/bra 'LETTERS (r/colon 1 3)) 3)))
(r.base/class DF)
;; => [1] "tbl_df" "tbl" "data.frame"
DF
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; 4 2 4 0.5 A
;; 5 1 5 1 B
;; 6 2 6 1.5 C
;; 7 1 7 0.5 A
;; 8 2 8 1 B
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
(def DS (ds/name-values-seq->dataset {:V1 (take 9 (cycle [1 2]))
:V2 (range 1 10)
:V3 (take 9 (cycle [0.5 1.0 1.5]))
:V4 (take 9 (cycle [\A \B \C]))}))
(class DS)
;; => tech.ml.dataset.impl.dataset.Dataset
DS
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
;; TODO (tech.ml.dataset): char datatype? (now inferred as Object)
(col/metadata (DS :V4))
;; => {:name :V4, :size 9, :datatype :object}
;; # Basic operations
;; ## Filter rows
;; ### Filter rows using indices
;; ---- data.table
;; DT[3:4,]
;; DT[3:4] # same
;; we use symbolic call here since there is a bug about interpreting R empty symbol
(r '(bra ~DT (colon 3 4) nil))
;; => V1 V2 V3 V4
;; 1: 1 3 1.5 C
;; 2: 2 4 0.5 A
(r/bra DT (r/colon 3 4))
;; => V1 V2 V3 V4
;; 1: 1 3 1.5 C
;; 2: 2 4 0.5 A
;; ---- dplyr
;; DF[3:4,]
;; slice(DF, 3:4) # same
(r '(bra ~DF (colon 3 4) nil))
;; => # A tibble: 2 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 3 1.5 C
;; 2 2 4 0.5 A
(dpl/slice DF (r/colon 3 4))
;; => # A tibble: 2 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 3 1.5 C
;; 2 2 4 0.5 A
;; ------ tech.ml.datatable
;; NOTE: row ids start at `0`
(ds/select-rows DS [2 3])
;; => _unnamed [2 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; ### Discard rows using negative indices
;; ---- data.table
;; DT[!3:7,]
;; DT[-(3:7)] # same
(r '(bra ~DT (! (colon 3 7)) nil))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 2 8 1.0 B
;; 4: 1 9 1.5 C
(r/bra DT (r/r- (r/colon 3 7)))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 2 8 1.0 B
;; 4: 1 9 1.5 C
;; ---- dplyr
;; DF[-(3:7),]
;; slice(DF, -(3:7)) # same
;; TODO (clojisr): (symbolic) unary `-` on `colon` doesn't work (workaround below)
(r '(bra ~DF (- [(colon 3 7)]) nil))
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 2 8 1 B
;; 4 1 9 1.5 C
(dpl/slice DF (r/r- (r/colon 3 7)))
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 2 8 1 B
;; 4 1 9 1.5 C
;; ---- tech.ml.dataset
(ds/drop-rows DS (range 2 7))
;; => _unnamed [4 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
;; ### Filter rows using a logical expression
;; ---- data.table
;; DT[V2 > 5]
;; DT[V4 %chin% c("A", "C")] # fast %in% for character
(r/bra DT '(> V2 5))
;; => V1 V2 V3 V4
;; 1: 2 6 1.5 C
;; 2: 1 7 0.5 A
;; 3: 2 8 1.0 B
;; 4: 1 9 1.5 C
;; TODO (clojisr): add %chin% as binary operation
(r/bra DT '((rsymbol "%chin%") V4 ["A" "C"]))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 1 3 1.5 C
;; 3: 2 4 0.5 A
;; 4: 2 6 1.5 C
;; 5: 1 7 0.5 A
;; 6: 1 9 1.5 C
;; ---- dplyr
;; filter(DF, V2 > 5)
;; filter(DF, V4 %in% c("A", "C"))
(dpl/filter DF '(> V2 5))
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 2 6 1.5 C
;; 2 1 7 0.5 A
;; 3 2 8 1 B
;; 4 1 9 1.5 C
(dpl/filter DF '(%in% V4 ["A" "C"]))
;; => # A tibble: 6 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 1 3 1.5 C
;; 3 2 4 0.5 A
;; 4 2 6 1.5 C
;; 5 1 7 0.5 A
;; 6 1 9 1.5 C
;; ---- tech.ml.dataset
(ds/filter-column #(> ^long % 5) :V2 DS)
;; => _unnamed [4 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
(ds/filter-column #{\A \C} :V4 DS)
;; => _unnamed [6 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 1 | 9 | 1.500 | C |
;; ### Filter rows using multiple conditions
;; ---- data.table
;; DT[V1 == 1 & V4 == "A"]
(r/bra DT '(& (== V1 1)
(== V4 "A")))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 1 7 0.5 A
;; ---- dplyr
;; filter(DF, V1 == 1, V4 == "A")
(dpl/filter DF '(== V1 1) '(== V4 "A"))
;; => # A tibble: 2 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 1 7 0.5 A
;; ---- tech.ml.dataset
(ds/filter #(and (= (:V1 %) 1)
(= (:V4 %) \A)) DS)
;; => _unnamed [2 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 1 | 7 | 0.5000 | A |
;; ### Filter unique rows
;; ---- data.table
;; unique(DT)
;; unique(DT, by = c("V1", "V4")) # returns all cols
(r.base/unique DT)
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 2 8 1.0 B
;; 9: 1 9 1.5 C
(r.base/unique DT :by ["V1" "V4"])
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; ---- dplyr
;; distinct(DF) # distinct_all(DF)
;; distinct_at(DF, vars(V1, V4)) # returns selected cols
;; # see also ?distinct_if
(dpl/distinct DF)
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; 4 2 4 0.5 A
;; 5 1 5 1 B
;; 6 2 6 1.5 C
;; 7 1 7 0.5 A
;; 8 2 8 1 B
;; 9 1 9 1.5 C
(dpl/distinct_at DF (dpl/vars 'V1 'V4))
;; => # A tibble: 6 x 2
;; V1 V4
;; <dbl> <chr>
;; 1 1 A
;; 2 2 B
;; 3 1 C
;; 4 2 A
;; 5 1 B
;; 6 2 C
;; ---- tech.ml.dataset
(ds/unique-by identity {:column-name-seq (ds/column-names DS)} DS)
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
(ds/unique-by identity {:column-name-seq [:V1 :V4]} DS)
;; => _unnamed [6 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; ### Discard rows with missing values
;; ---- data.table
;; na.omit(DT, cols = 1:4) # fast S3 method with cols argument
(r.stats/na-omit DT :cols (r/colon 1 4))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 2 8 1.0 B
;; 9: 1 9 1.5 C
;; ---- dplyr
;; tidyr::drop_na(DF, names(DF))
(r.tidyr/drop_na DF (r.base/names DF))
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; 4 2 4 0.5 A
;; 5 1 5 1 B
;; 6 2 6 1.5 C
;; 7 1 7 0.5 A
;; 8 2 8 1 B
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
;; note: missing works on whole dataset, to select columns, first create dataset with selected columns
(ds/drop-rows DS (ds/missing DS))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
;; ### Other filters
;; ---- data.table
;; DT[sample(.N, 3)] # .N = nb of rows in DT
;; DT[sample(.N, .N / 2)]
;; DT[frankv(-V1, ties.method = "dense") < 2]
(r/bra DT '(sample .N 3))
;; => V1 V2 V3 V4
;; 1: 1 7 0.5 A
;; 2: 1 3 1.5 C
;; 3: 2 6 1.5 C
(r/bra DT '(sample .N (/ .N 2)))
;; => V1 V2 V3 V4
;; 1: 2 6 1.5 C
;; 2: 1 7 0.5 A
;; 3: 2 4 0.5 A
;; 4: 2 8 1.0 B
(r/bra DT '(< (frankv (- V1) :ties.method "dense") 2))
;; => V1 V2 V3 V4
;; 1: 2 2 1.0 B
;; 2: 2 4 0.5 A
;; 3: 2 6 1.5 C
;; 4: 2 8 1.0 B
;; ---- dplyr
;; sample_n(DF, 3) # n random rows
;; sample_frac(DF, 0.5) # fraction of random rows
;; top_n(DF, 1, V1) # top n entries (includes equals)
(dpl/sample_n DF 3)
;; => # A tibble: 3 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 5 1 B
(dpl/sample_frac DF 0.5)
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 7 0.5 A
;; 2 1 3 1.5 C
;; 3 2 6 1.5 C
;; 4 2 2 1 B
(dpl/top_n DF 1 'V1)
;; => # A tibble: 4 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 2 2 1 B
;; 2 2 4 0.5 A
;; 3 2 6 1.5 C
;; 4 2 8 1 B
;; ---- tech.ml.dataset
(ds/sample 3 DS)
;; => _unnamed [3 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
(ds/sample (/ (ds/row-count DS) 2) DS)
;; => _unnamed [4 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+-------+-----|
;; | 2 | 8 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; NOTE: Here we use `fastmath` to calculate rank.
;; We need also to translate rank to indices.
(->> (m/rank (map - (DS :V1)) :dense)
(filter-by-external-values->indices #(< ^long % 1))
(ds/select-rows DS))
;; => _unnamed [4 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 2 | 2 | 1.000 | B |
;; | 2 | 4 | 0.5000 | A |
;; | 2 | 6 | 1.500 | C |
;; | 2 | 8 | 1.000 | B |
;; #### Convenience functions
;; ---- data.table
;; DT[V4 %like% "^B"]
;; DT[V2 %between% c(3, 5)]
;; DT[data.table::between(V2, 3, 5, incbounds = FALSE)]
;; DT[V2 %inrange% list(-1:1, 1:3)] # see also ?inrange
(r/bra DT '((rsymbol "%like%") V4 "^B"))
;; => V1 V2 V3 V4
;; 1: 2 2 1 B
;; 2: 1 5 1 B
;; 3: 2 8 1 B
(r/bra DT '((rsymbol "%between%") V2 [3 5]))
;; => V1 V2 V3 V4
;; 1: 1 3 1.5 C
;; 2: 2 4 0.5 A
;; 3: 1 5 1.0 B
(r/bra DT '((rsymbol data.table between) V2 3 5 :incbounds false))
;; => V1 V2 V3 V4
;; 1: 2 4 0.5 A
(r/bra DT '((rsymbol "%inrange%") V2 [:!list (colon -1 1) (colon 1 3)]))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; ---- dplyr
;; filter(DF, grepl("^B", V4))
;; filter(DF, dplyr::between(V2, 3, 5))
;; filter(DF, V2 > 3 & V2 < 5)
;; filter(DF, V2 >= -1:1 & V2 <= 1:3)
(dpl/filter DF '(grepl "^B" V4))
;; => # A tibble: 3 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 2 2 1 B
;; 2 1 5 1 B
;; 3 2 8 1 B
(dpl/filter DF '((rsymbol dplyr between) V2 3 5))
;; => # A tibble: 3 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 3 1.5 C
;; 2 2 4 0.5 A
;; 3 1 5 1 B
(dpl/filter DF '(& (> V2 3) (< V2 5)))
;; => # A tibble: 1 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 2 4 0.5 A
(dpl/filter DF '(& (>= V2 (colon -1 1))
(<= V2 (colon 1 3))))
;; => # A tibble: 3 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; ---- tech.ml.dataset
(ds/filter #(re-matches #"^B" (str (:V4 %))) DS)
;; => _unnamed [3 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+-------+-----|
;; | 2 | 2 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
(ds/filter (comp (partial m/between? 3 5) :V2) DS)
;; => _unnamed [3 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
(ds/filter (comp #(< 3 % 5) :V2) DS)
;; => _unnamed [1 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 2 | 4 | 0.5000 | A |
;; note: there is no range on sequences, I have no idea why to use such
(let [mn (min -1 0 1)
mx (max 1 2 3)]
(ds/filter (comp (partial m/between? mn mx) :V2) DS))
;; => _unnamed [3 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; ## Sort rows
;; ### Sort rows by column
;; ---- data.table
;; DT[order(V3)] # see also setorder
(r/bra DT '(order V3))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 4 0.5 A
;; 3: 1 7 0.5 A
;; 4: 2 2 1.0 B
;; 5: 1 5 1.0 B
;; 6: 2 8 1.0 B
;; 7: 1 3 1.5 C
;; 8: 2 6 1.5 C
;; 9: 1 9 1.5 C
;; ---- dplyr
;; arrange(DF, V3)
(dpl/arrange DF 'V3)
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 4 0.5 A
;; 3 1 7 0.5 A
;; 4 2 2 1 B
;; 5 1 5 1 B
;; 6 2 8 1 B
;; 7 1 3 1.5 C
;; 8 2 6 1.5 C
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
(ds/sort-by-column :V3 DS)
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; alternative use of indices
(ds/select-rows DS (m/order (DS :V3)))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; ### Sort rows in decreasing order
;; ---- data.table
;; DT[order(-V3)]
(r/bra DT '(order (- V3)))
;; => V1 V2 V3 V4
;; 1: 1 3 1.5 C
;; 2: 2 6 1.5 C
;; 3: 1 9 1.5 C
;; 4: 2 2 1.0 B
;; 5: 1 5 1.0 B
;; 6: 2 8 1.0 B
;; 7: 1 1 0.5 A
;; 8: 2 4 0.5 A
;; 9: 1 7 0.5 A
;; ---- dplyr
;; arrange(DF, desc(V3))
(dpl/arrange DF '(desc V3))
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 3 1.5 C
;; 2 2 6 1.5 C
;; 3 1 9 1.5 C
;; 4 2 2 1 B
;; 5 1 5 1 B
;; 6 2 8 1 B
;; 7 1 1 0.5 A
;; 8 2 4 0.5 A
;; 9 1 7 0.5 A
;; ---- tech.ml.dataset
(ds/sort-by-column :V3 (comp - compare) DS)
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 3 | 1.500 | C |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 2 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 1 | 0.5000 | A |
;; using ordering indices
(ds/select-rows DS (m/order (DS :V3) true))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 3 | 1.500 | C |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 9 | 1.500 | C |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 7 | 0.5000 | A |
;; ### Sort rows based on several columns
;; ---- data.table
;; DT[order(V1, -V2)]
(r/bra DT '(order V1 (- V2)))
;; => V1 V2 V3 V4
;; 1: 1 9 1.5 C
;; 2: 1 7 0.5 A
;; 3: 1 5 1.0 B
;; 4: 1 3 1.5 C
;; 5: 1 1 0.5 A
;; 6: 2 8 1.0 B
;; 7: 2 6 1.5 C
;; 8: 2 4 0.5 A
;; 9: 2 2 1.0 B
;; ---- dplyr
;; arrange(DF, V1, desc(V2))
(dpl/arrange DF 'V1 '(desc V2))
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 9 1.5 C
;; 2 1 7 0.5 A
;; 3 1 5 1 B
;; 4 1 3 1.5 C
;; 5 1 1 0.5 A
;; 6 2 8 1 B
;; 7 2 6 1.5 C
;; 8 2 4 0.5 A
;; 9 2 2 1 B
;; ---- tech.ml.dataset
;; TODO: improve sorting in general
(sort-by-columns-with-orders [:V1 :V2] [:asc :desc] DS)
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 9 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; ## Select columns
;; ### Select one column using an index (not recommended)
;; ---- data.table
;; DT[[3]] # returns a vector
;; DT[, 3] # returns a data.table
(r/brabra DT 3)
;; => [1] 0.5 1.0 1.5 0.5 1.0 1.5 0.5 1.0 1.5
(r '(bra ~DT nil 3))
;; => V3
;; 1: 0.5
;; 2: 1.0
;; 3: 1.5
;; 4: 0.5
;; 5: 1.0
;; 6: 1.5
;; 7: 0.5
;; 8: 1.0
;; 9: 1.5
;; ---- dplyr
;; DF[[3]] # returns a vector
;; DF[3] # returns a tibble
(r/brabra DF 3)
;; => [1] 0.5 1.0 1.5 0.5 1.0 1.5 0.5 1.0 1.5
(r/bra DF 3)
;; => # A tibble: 9 x 1
;; V3
;; <dbl>
;; 1 0.5
;; 2 1
;; 3 1.5
;; 4 0.5
;; 5 1
;; 6 1.5
;; 7 0.5
;; 8 1
;; 9 1.5
;; ---- tech.ml.dataset
;; NOTE: indices start at 0
(nth (seq DS) 2)
;; => #tech.ml.dataset.column<float64>[9]
;; :V3
;; [0.5000, 1.000, 1.500, 0.5000, 1.000, 1.500, 0.5000, 1.000, 1.500, ]
;; NOTE: column is seqable
(seq (nth (seq DS) 2))
;; => (0.5 1.0 1.5 0.5 1.0 1.5 0.5 1.0 1.5)
(ds/new-dataset [(nth (seq DS) 2)])
;; => _unnamed [9 1]:
;; | :V3 |
;; |--------|
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; ### Select one column using column name
;; DT[, list(V2)] # returns a data.table
;; DT[, .(V2)] # returns a data.table
;; # . is an alias for list
;; DT[, "V2"] # returns a data.table
;; DT[, V2] # returns a vector
;; DT[["V2"]] # returns a vector
;; ---- data.table
(r '(bra ~DT nil [:!list V2]))
;; => V2
;; 1: 1
;; 2: 2
;; 3: 3
;; 4: 4
;; 5: 5
;; 6: 6
;; 7: 7
;; 8: 8
;; 9: 9
(r '(bra ~DT nil (. V2)))
;; => V2
;; 1: 1
;; 2: 2
;; 3: 3
;; 4: 4
;; 5: 5
;; 6: 6
;; 7: 7
;; 8: 8
;; 9: 9
(r '(bra ~DT nil "V2"))
;; => V2
;; 1: 1
;; 2: 2
;; 3: 3
;; 4: 4
;; 5: 5
;; 6: 6
;; 7: 7
;; 8: 8
;; 9: 9
(r '(bra ~DT nil V2))
;; => [1] 1 2 3 4 5 6 7 8 9
(r/brabra DT "V2")
;; => [1] 1 2 3 4 5 6 7 8 9
;; ---- dplyr
;; select(DF, V2) # returns a tibble
;; pull(DF, V2) # returns a vector
;; DF[, "V2"] # returns a tibble
;; DF[["V2"]] # returns a vector
(dpl/select DF 'V2)
;; => # A tibble: 9 x 1
;; V2
;; <int>
;; 1 1
;; 2 2
;; 3 3
;; 4 4
;; 5 5
;; 6 6
;; 7 7
;; 8 8
;; 9 9
(dpl/pull DF 'V2)
;; => [1] 1 2 3 4 5 6 7 8 9
(r '(bra ~DF nil "V2"))
;; => # A tibble: 9 x 1
;; V2
;; <int>
;; 1 1
;; 2 2
;; 3 3
;; 4 4
;; 5 5
;; 6 6
;; 7 7
;; 8 8
;; 9 9
(r/brabra DF "V2")
;; => [1] 1 2 3 4 5 6 7 8 9
;; ---- tech.ml.dataset
;; NOTE: returns dataset
(ds/select-columns DS [:V2])
;; => _unnamed [9 1]:
;; | :V2 |
;; |-----|
;; | 1 |
;; | 2 |
;; | 3 |
;; | 4 |
;; | 5 |
;; | 6 |
;; | 7 |
;; | 8 |
;; | 9 |
;; NOTE: returns dataset
(ds/select DS [:V2] :all)
;; => _unnamed [9 1]:
;; | :V2 |
;; |-----|
;; | 1 |
;; | 2 |
;; | 3 |
;; | 4 |
;; | 5 |
;; | 6 |
;; | 7 |
;; | 8 |
;; | 9 |
;; NOTE: returns column (seqable)
(DS :V2)
;; => #tech.ml.dataset.column<int64>[9]
;; :V2
;; [1, 2, 3, 4, 5, 6, 7, 8, 9, ]
;; NOTE: column as sequence
(seq (DS :V2))
;; => (1 2 3 4 5 6 7 8 9)
;; NOTE: efficient access to data via reader
(dtype/->reader (DS :V2))
;; => [1 2 3 4 5 6 7 8 9]
;; NOTE: returns column
(ds/column DS :V2)
;; => #tech.ml.dataset.column<int64>[9]
;; :V2
;; [1, 2, 3, 4, 5, 6, 7, 8, 9, ]
;; ### Select several columns
;; ---- data.table
;; DT[, .(V2, V3, V4)]
;; DT[, list(V2, V3, V4)]
;; DT[, V2:V4] # select columns between V2 and V4
(r '(bra ~DT nil (. V2 V3 V4)))
;; => V2 V3 V4
;; 1: 1 0.5 A
;; 2: 2 1.0 B
;; 3: 3 1.5 C
;; 4: 4 0.5 A
;; 5: 5 1.0 B
;; 6: 6 1.5 C
;; 7: 7 0.5 A
;; 8: 8 1.0 B
;; 9: 9 1.5 C
(r '(bra ~DT nil (:!list V2 V3 V4)))
;; => V2 V3 V4
;; 1: 1 0.5 A
;; 2: 2 1.0 B
;; 3: 3 1.5 C
;; 4: 4 0.5 A
;; 5: 5 1.0 B
;; 6: 6 1.5 C
;; 7: 7 0.5 A
;; 8: 8 1.0 B
;; 9: 9 1.5 C
(r '(bra ~DT nil (colon V2 V4)))
;; => V2 V3 V4
;; 1: 1 0.5 A
;; 2: 2 1.0 B
;; 3: 3 1.5 C
;; 4: 4 0.5 A
;; 5: 5 1.0 B
;; 6: 6 1.5 C
;; 7: 7 0.5 A
;; 8: 8 1.0 B
;; 9: 9 1.5 C
;; ---- dplyr
;; select(DF, V2, V3, V4)
;; select(DF, V2:V4) # select columns between V2 and V4
(dpl/select DF 'V2 'V3 'V4)
;; => # A tibble: 9 x 3
;; V2 V3 V4
;; <int> <dbl> <chr>
;; 1 1 0.5 A
;; 2 2 1 B
;; 3 3 1.5 C
;; 4 4 0.5 A
;; 5 5 1 B
;; 6 6 1.5 C
;; 7 7 0.5 A
;; 8 8 1 B
;; 9 9 1.5 C
(dpl/select DF '(colon V2 V4))
;; => # A tibble: 9 x 3
;; V2 V3 V4
;; <int> <dbl> <chr>
;; 1 1 0.5 A
;; 2 2 1 B
;; 3 3 1.5 C
;; 4 4 0.5 A
;; 5 5 1 B
;; 6 6 1.5 C
;; 7 7 0.5 A
;; 8 8 1 B
;; 9 9 1.5 C
;; ---- tech.ml.dataset
(ds/select-columns DS [:V2 :V3 :V4])
;; => _unnamed [9 3]:
;; | :V2 | :V3 | :V4 |
;; |-----+--------+-----|
;; | 1 | 0.5000 | A |
;; | 2 | 1.000 | B |
;; | 3 | 1.500 | C |
;; | 4 | 0.5000 | A |
;; | 5 | 1.000 | B |
;; | 6 | 1.500 | C |
;; | 7 | 0.5000 | A |
;; | 8 | 1.000 | B |
;; | 9 | 1.500 | C |
(ds/select DS [:V2 :V3 :V4] :all)
;; => _unnamed [9 3]:
;; | :V2 | :V3 | :V4 |
;; |-----+--------+-----|
;; | 1 | 0.5000 | A |
;; | 2 | 1.000 | B |
;; | 3 | 1.500 | C |
;; | 4 | 0.5000 | A |
;; | 5 | 1.000 | B |
;; | 6 | 1.500 | C |
;; | 7 | 0.5000 | A |
;; | 8 | 1.000 | B |
;; | 9 | 1.500 | C |
;; NOTE: range is not available
;; ### Exclude columns
;; ---- data.table
;; DT[, !c("V2", "V3")]
(r '(bra ~DT nil (! ["V2" "V3"])))
;; => V1 V4
;; 1: 1 A
;; 2: 2 B
;; 3: 1 C
;; 4: 2 A
;; 5: 1 B
;; 6: 2 C
;; 7: 1 A
;; 8: 2 B
;; 9: 1 C
;; ---- dplyr
;; select(DF, -V2, -V3)
(dpl/select DF '(- V2) '(- V3))
;; => # A tibble: 9 x 2
;; V1 V4
;; <dbl> <chr>
;; 1 1 A
;; 2 2 B
;; 3 1 C
;; 4 2 A
;; 5 1 B
;; 6 2 C
;; 7 1 A
;; 8 2 B
;; 9 1 C
;; ---- tech.ml.dataset
(ds/drop-columns DS [:V2 :V3])
;; => _unnamed [9 2]:
;; | :V1 | :V4 |
;; |-----+-----|
;; | 1 | A |
;; | 2 | B |
;; | 1 | C |
;; | 2 | A |
;; | 1 | B |
;; | 2 | C |
;; | 1 | A |
;; | 2 | B |
;; | 1 | C |
;; ### Select/Exclude columns using a character vector
;; ---- data.table
;; cols <- c("V2", "V3")
;; DT[, ..cols] # .. prefix means 'one-level up'
;; DT[, !..cols] # or DT[, -..cols]
(def cols (r.base/<- 'cols ["V2" "V3"]))
(r '(bra ~DT nil ..cols))
;; => V2 V3
;; 1: 1 0.5
;; 2: 2 1.0
;; 3: 3 1.5
;; 4: 4 0.5
;; 5: 5 1.0
;; 6: 6 1.5
;; 7: 7 0.5
;; 8: 8 1.0
;; 9: 9 1.5
(r '(bra ~DT nil !..cols))
;; => V1 V4
;; 1: 1 A
;; 2: 2 B
;; 3: 1 C
;; 4: 2 A
;; 5: 1 B
;; 6: 2 C
;; 7: 1 A
;; 8: 2 B
;; 9: 1 C
(r '(bra ~DT nil -..cols))
;; => V1 V4
;; 1: 1 A
;; 2: 2 B
;; 3: 1 C
;; 4: 2 A
;; 5: 1 B
;; 6: 2 C
;; 7: 1 A
;; 8: 2 B
;; 9: 1 C
;; ---- dplyr
;; cols <- c("V2", "V3")
;; select(DF, !!cols) # unquoting
;; select(DF, -!!cols)
(def cols (r.base/<- 'cols ["V2" "V3"]))
(dpl/select DF '!!cols)
;; => # A tibble: 9 x 2
;; V2 V3
;; <int> <dbl>
;; 1 1 0.5
;; 2 2 1
;; 3 3 1.5
;; 4 4 0.5
;; 5 5 1
;; 6 6 1.5
;; 7 7 0.5
;; 8 8 1
;; 9 9 1.5
(dpl/select DF '-!!cols)
;; => # A tibble: 9 x 2
;; V1 V4
;; <dbl> <chr>
;; 1 1 A
;; 2 2 B
;; 3 1 C
;; 4 2 A
;; 5 1 B
;; 6 2 C
;; 7 1 A
;; 8 2 B
;; 9 1 C
;; ---- tech.ml.dataset
(def cols [:V2 :V3])
(ds/select-columns DS cols)
;; => _unnamed [9 2]:
;; | :V2 | :V3 |
;; |-----+--------|
;; | 1 | 0.5000 |
;; | 2 | 1.000 |
;; | 3 | 1.500 |
;; | 4 | 0.5000 |
;; | 5 | 1.000 |
;; | 6 | 1.500 |
;; | 7 | 0.5000 |
;; | 8 | 1.000 |
;; | 9 | 1.500 |
(ds/drop-columns DS cols)
;; => _unnamed [9 2]:
;; | :V1 | :V4 |
;; |-----+-----|
;; | 1 | A |
;; | 2 | B |
;; | 1 | C |
;; | 2 | A |
;; | 1 | B |
;; | 2 | C |
;; | 1 | A |
;; | 2 | B |
;; | 1 | C |
;; ### Other selections
;; ---- data.table
;; cols <- paste0("V", 1:2)
;; cols <- union("V4", names(DT))
;; cols <- grep("V", names(DT))
;; cols <- grep("3$", names(DT))
;; cols <- grep(".2", names(DT))
;; cols <- grep("^V1|X$", names(DT))
;; cols <- grep("^(?!V2)", names(DT), perl = TRUE)
;; DT[, ..cols]
(r.base/<- 'cols (r.base/paste0 "V" (r/colon 1 2)))
;; => [1] "V1" "V2"
(r '(bra ~DT nil ..cols))
;; => V1 V2
;; 1: 1 1
;; 2: 2 2
;; 3: 1 3
;; 4: 2 4
;; 5: 1 5
;; 6: 2 6
;; 7: 1 7
;; 8: 2 8
;; 9: 1 9
(r.base/<- 'cols (r.base/union "V4" (r.base/names DT)))
;; => [1] "V4" "V1" "V2" "V3"
(r '(bra ~DT nil ..cols))
;; => V4 V1 V2 V3
;; 1: A 1 1 0.5
;; 2: B 2 2 1.0
;; 3: C 1 3 1.5
;; 4: A 2 4 0.5
;; 5: B 1 5 1.0
;; 6: C 2 6 1.5
;; 7: A 1 7 0.5
;; 8: B 2 8 1.0
;; 9: C 1 9 1.5
(r.base/<- 'cols (r.base/grep "V" (r.base/names DT)))
;; => [1] 1 2 3 4
(r '(bra ~DT nil ..cols))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 2 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 2 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 2 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 2 8 1.0 B
;; 9: 1 9 1.5 C
(r.base/<- 'cols (r.base/grep "3$" (r.base/names DT)))
;; => [1] 3
(r '(bra ~DT nil ..cols))
;; => V3
;; 1: 0.5
;; 2: 1.0
;; 3: 1.5
;; 4: 0.5
;; 5: 1.0
;; 6: 1.5
;; 7: 0.5
;; 8: 1.0
;; 9: 1.5
(r.base/<- 'cols (r.base/grep ".2" (r.base/names DT)))
;; => [1] 2
(r '(bra ~DT nil ..cols))
;; => V2
;; 1: 1
;; 2: 2
;; 3: 3
;; 4: 4
;; 5: 5
;; 6: 6
;; 7: 7
;; 8: 8
;; 9: 9
(r.base/<- 'cols (r.base/grep "^V1|X$" (r.base/names DT)))
;; => [1] 1
(r '(bra ~DT nil ..cols))
;; => V1
;; 1: 1
;; 2: 2
;; 3: 1
;; 4: 2
;; 5: 1
;; 6: 2
;; 7: 1
;; 8: 2
;; 9: 1
(r.base/<- 'cols (r.base/grep "^(?!V2)" (r.base/names DT) :perl true))
;; => [1] 1 3 4
(r '(bra ~DT nil ..cols))
;; => V1 V3 V4
;; 1: 1 0.5 A
;; 2: 2 1.0 B
;; 3: 1 1.5 C
;; 4: 2 0.5 A
;; 5: 1 1.0 B
;; 6: 2 1.5 C
;; 7: 1 0.5 A
;; 8: 2 1.0 B
;; 9: 1 1.5 C
;; ---- dplyr
;; select(DF, num_range("V", 1:2))
;; select(DF, V4, everything()) # reorder columns
;; select(DF, contains("V"))
;; select(DF, ends_with("3"))
;; select(DF, matches(".2"))
;; select(DF, one_of(c("V1", "X")))
;; select(DF, -starts_with("V2"))
(dpl/select DF '(num_range "V" (colon 1 2)))
;; => # A tibble: 9 x 2
;; V1 V2
;; <dbl> <int>
;; 1 1 1
;; 2 2 2
;; 3 1 3
;; 4 2 4
;; 5 1 5
;; 6 2 6
;; 7 1 7
;; 8 2 8
;; 9 1 9
(dpl/select DF 'V4 '(everything))
;; => # A tibble: 9 x 4
;; V4 V1 V2 V3
;; <chr> <dbl> <int> <dbl>
;; 1 A 1 1 0.5
;; 2 B 2 2 1
;; 3 C 1 3 1.5
;; 4 A 2 4 0.5
;; 5 B 1 5 1
;; 6 C 2 6 1.5
;; 7 A 1 7 0.5
;; 8 B 2 8 1
;; 9 C 1 9 1.5
(dpl/select DF '(contains "V"))
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 2 2 1 B
;; 3 1 3 1.5 C
;; 4 2 4 0.5 A
;; 5 1 5 1 B
;; 6 2 6 1.5 C
;; 7 1 7 0.5 A
;; 8 2 8 1 B
;; 9 1 9 1.5 C
(dpl/select DF '(ends_with "3"))
;; => # A tibble: 9 x 1
;; V3
;; <dbl>
;; 1 0.5
;; 2 1
;; 3 1.5
;; 4 0.5
;; 5 1
;; 6 1.5
;; 7 0.5
;; 8 1
;; 9 1.5
(dpl/select DF '(matches ".2"))
;; => # A tibble: 9 x 1
;; V2
;; <int>
;; 1 1
;; 2 2
;; 3 3
;; 4 4
;; 5 5
;; 6 6
;; 7 7
;; 8 8
;; 9 9
(dpl/select DF '(one_of ["V1" "X"]))
;; => # A tibble: 9 x 1
;; V1
;; <dbl>
;; 1 1
;; 2 2
;; 3 1
;; 4 2
;; 5 1
;; 6 2
;; 7 1
;; 8 2
;; 9 1
(dpl/select DF '(- (starts_with "V2")))
;; => # A tibble: 9 x 3
;; V1 V3 V4
;; <dbl> <dbl> <chr>
;; 1 1 0.5 A
;; 2 2 1 B
;; 3 1 1.5 C
;; 4 2 0.5 A
;; 5 1 1 B
;; 6 2 1.5 C
;; 7 1 0.5 A
;; 8 2 1 B
;; 9 1 1.5 C
;; ---- tech.ml.dataset
;; NOTE: we are using pure Clojure machinery to generate column names
(->> (map (comp keyword str) (repeat "V") (range 1 3))
(ds/select-columns DS))
;; => _unnamed [9 2]:
;; | :V1 | :V2 |
;; |-----+-----|
;; | 1 | 1 |
;; | 2 | 2 |
;; | 1 | 3 |
;; | 2 | 4 |
;; | 1 | 5 |
;; | 2 | 6 |
;; | 1 | 7 |
;; | 2 | 8 |
;; | 1 | 9 |
(->> (distinct (conj (ds/column-names DS) :V4))
(ds/select-columns DS))
;; => _unnamed [9 4]:
;; | :V4 | :V1 | :V2 | :V3 |
;; |-----+-----+-----+--------|
;; | A | 1 | 1 | 0.5000 |
;; | B | 2 | 2 | 1.000 |
;; | C | 1 | 3 | 1.500 |
;; | A | 2 | 4 | 0.5000 |
;; | B | 1 | 5 | 1.000 |
;; | C | 2 | 6 | 1.500 |
;; | A | 1 | 7 | 0.5000 |
;; | B | 2 | 8 | 1.000 |
;; | C | 1 | 9 | 1.500 |
(->> (ds/column-names DS)
(filter #(str/starts-with? (name %) "V"))
(ds/select-columns DS))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-----+-----+--------+-----|
;; | 1 | 1 | 0.5000 | A |
;; | 2 | 2 | 1.000 | B |
;; | 1 | 3 | 1.500 | C |
;; | 2 | 4 | 0.5000 | A |
;; | 1 | 5 | 1.000 | B |
;; | 2 | 6 | 1.500 | C |
;; | 1 | 7 | 0.5000 | A |
;; | 2 | 8 | 1.000 | B |
;; | 1 | 9 | 1.500 | C |
(->> (ds/column-names DS)
(filter #(str/ends-with? (name %) "3"))
(ds/select-columns DS))
;; => _unnamed [9 1]:
;; | :V3 |
;; |--------|
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
;; | 0.5000 |
;; | 1.000 |
;; | 1.500 |
(->> (ds/column-names DS)
(filter #(re-matches #".2" (name %)))
(ds/select-columns DS))
;; => _unnamed [9 1]:
;; | :V2 |
;; |-----|
;; | 1 |
;; | 2 |
;; | 3 |
;; | 4 |
;; | 5 |
;; | 6 |
;; | 7 |
;; | 8 |
;; | 9 |
(->> (ds/column-names DS)
(filter #{:V1 :X})
(ds/select-columns DS))
;; => _unnamed [9 1]:
;; | :V1 |
;; |-----|
;; | 1 |
;; | 2 |
;; | 1 |
;; | 2 |
;; | 1 |
;; | 2 |
;; | 1 |
;; | 2 |
;; | 1 |
(->> (ds/column-names DS)
(remove #(str/starts-with? (name %) "V2"))
(ds/select-columns DS))
;; => _unnamed [9 3]:
;; | :V1 | :V3 | :V4 |
;; |-----+--------+-----|
;; | 1 | 0.5000 | A |
;; | 2 | 1.000 | B |
;; | 1 | 1.500 | C |
;; | 2 | 0.5000 | A |
;; | 1 | 1.000 | B |
;; | 2 | 1.500 | C |
;; | 1 | 0.5000 | A |
;; | 2 | 1.000 | B |
;; | 1 | 1.500 | C |
;; ## Summarise data
;; ### Summarise one column
;; ---- data.table
;; DT[, sum(V1)] # returns a vector
;; DT[, .(sum(V1))] # returns a data.table
;; DT[, .(sumV1 = sum(V1))] # returns a data.table
(r '(bra ~DT nil (sum V1)))
;; => [1] 13
(r '(bra ~DT nil (. (sum V1))))
;; => V1
;; 1: 13
(r '(bra ~DT nil (. :sumV1 (sum V1))))
;; => sumV1
;; 1: 13
;; ---- dplyr
;; summarise(DF, sum(V1)) # returns a tibble
;; summarise(DF, sumV1 = sum(V1)) # returns a tibble
(dpl/summarise DF '(sum V1))
;; => # A tibble: 1 x 1
;; `sum(V1)`
;; <dbl>
;; 1 13
(dpl/summarise DF :sumV1 '(sum V1))
;; => # A tibble: 1 x 1
;; sumV1
;; <dbl>
;; 1 13
;; ---- tech.ml.dataset
;; NOTE: using optimized datatype function
(dfn/sum (DS :V1))
;; => 13.0
;; NOTE: using reduce
(reduce + (DS :V1))
;; => 13
;; NOTE: custom aggregation function to get back dataset (issue filled)
;; TODO: aggregate->dataset
(aggregate->dataset [#(dfn/sum (% :V1))] DS)
;; => _unnamed [1 1]:
;; | 0 |
;; |-------|
;; | 13.00 |
(aggregate->dataset {:sumV1 #(dfn/sum (% :V1))} DS)
;; => _unnamed [1 1]:
;; | :sumV1 |
;; |--------|
;; | 13.00 |
;; ### Summarise several columns
;; ---- data.table
;; DT[, .(sum(V1), sd(V3))]
(r '(bra ~DT nil (. (sum V1) (sd V3))))
;; => V1 V2
;; 1: 13 0.4330127
;; ---- dplyr
;; summarise(DF, sum(V1), sd(V3))
(dpl/summarise DF '(sum V1) '(sd V3))
;; => # A tibble: 1 x 2
;; `sum(V1)` `sd(V3)`
;; <dbl> <dbl>
;; 1 13 0.433
;; ---- tech.ml.dataset
(aggregate->dataset [#(dfn/sum (% :V1))
#(dfn/standard-deviation (% :V3))] DS)
;; => _unnamed [1 2]:
;; | 0 | 1 |
;; |-------+--------|
;; | 13.00 | 0.4330 |
;; ### Summarise several columns and assign column names
;; ---- data.table
;; DT[, .(sumv1 = sum(V1),
;; sdv3 = sd(V3))]
(r '(bra ~DT nil (. :sumv1 (sum V1) :sdv3 (sd V3))))
;; => sumv1 sdv3
;; 1: 13 0.4330127
;; ---- dplyr
;; DF %>%
;; summarise(sumv1 = sum(V1),
;; sdv3 = sd(V3))
(-> DF
(dpl/summarise :sumv1 '(sum V1)
:sdv3 '(sd V3)))
;; => # A tibble: 1 x 2
;; sumv1 sdv3
;; <dbl> <dbl>
;; 1 13 0.433
;; ---- tech.ml.dataset
(aggregate->dataset {:sumv1 #(dfn/sum (% :V1))
:sdv3 #(dfn/standard-deviation (% :V3))} DS)
;; => _unnamed [1 2]:
;; | :sumv1 | :sdv3 |
;; |--------+--------|
;; | 13.00 | 0.4330 |
;; ### Summarise a subset of rows
;; ---- data.table
;; DT[1:4, sum(V1)]
(r/bra DT (r/colon 1 4) '(sum V1))
;; => [1] 6
;; ---- dplyr
;; DF %>%
;; slice(1:4) %>%
;; summarise(sum(V1))
(-> DF
(dpl/slice (r/colon 1 4))
(dpl/summarise '(sum V1)))
;; => # A tibble: 1 x 1
;; `sum(V1)`
;; <dbl>
;; 1 6
;; ---- tech.ml.dataset
(-> DS
(ds/select-rows (range 4))
(->> (aggregate->dataset [#(dfn/sum (% :V1))])))
;; => _unnamed [1 1]:
;; | 0 |
;; |-------|
;; | 6.000 |
;; ### additional
;; ---- data.table
;; DT[, data.table::first(V3)]
;; DT[, data.table::last(V3)]
;; DT[5, V3]
;; DT[, uniqueN(V4)]
;; uniqueN(DT)
(r '(bra ~DT nil ((rsymbol data.table first) V3)))
;; => [1] 0.5
(r '(bra ~DT nil ((rsymbol data.table last) V3)))
;; => [1] 1.5
(r/bra DT 5 'V3)
;; => [1] 1
(r '(bra ~DT nil (uniqueN V4)))
;; => [1] 3
(dt/uniqueN DT)
;; => [1] 9
;; ---- dplyr
;; summarise(DF, dplyr::first(V3))
;; summarise(DF, dplyr::last(V3))
;; summarise(DF, nth(V3, 5))
;; summarise(DF, n_distinct(V4))
;; n_distinct(DF)
(dpl/summarise DF '((rsymbol dplyr first) V3))
;; => # A tibble: 1 x 1
;; `dplyr::first(V3)`
;; <dbl>
;; 1 0.5
(dpl/summarise DF '((rsymbol dplyr last) V3))
;; => # A tibble: 1 x 1
;; `dplyr::last(V3)`
;; <dbl>
;; 1 1.5
(dpl/summarise DF '(nth V3 5))
;; => # A tibble: 1 x 1
;; `nth(V3, 5)`
;; <dbl>
;; 1 1
(dpl/summarise DF '(n_distinct V4))
;; => # A tibble: 1 x 1
;; `n_distinct(V4)`
;; <int>
;; 1 3
(dpl/n_distinct DF)
;; => [1] 9
;; ---- tech.ml.dataset
(first (DS :V3))
;; => 0.5
(last (DS :V3))
;; => 1.5
(nth (DS :V3) 5)
;; => 1.5
(count (col/unique (DS :V3)))
;; => 3
(ds/row-count (ds/unique-by identity DS))
;; => 9
;; ## Add/update/delete columns
;; ### Modify a column
;; ---- data.table
;; DT[, V1 := V1^2]
;; DT
;; TODO (clojisr): another tricky binary operator
(r '(bra ~DT nil ((rsymbol ":=") V1 (** V1 2))))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 4 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 4 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 4 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 4 8 1.0 B
;; 9: 1 9 1.5 C
;; ---- dplyr
;; DF <- DF %>% mutate(V1 = V1^2)
;; DF
(def DF (-> DF (dpl/mutate :V1 '(** V1 2))))
DF
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 4 2 1 B
;; 3 1 3 1.5 C
;; 4 4 4 0.5 A
;; 5 1 5 1 B
;; 6 4 6 1.5 C
;; 7 1 7 0.5 A
;; 8 4 8 1 B
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
(ds/update-column DS :V1 #(map (fn [v] (m/pow v 2)) %))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-------+-----+--------+-----|
;; | 1.000 | 1 | 0.5000 | A |
;; | 4.000 | 2 | 1.000 | B |
;; | 1.000 | 3 | 1.500 | C |
;; | 4.000 | 4 | 0.5000 | A |
;; | 1.000 | 5 | 1.000 | B |
;; | 4.000 | 6 | 1.500 | C |
;; | 1.000 | 7 | 0.5000 | A |
;; | 4.000 | 8 | 1.000 | B |
;; | 1.000 | 9 | 1.500 | C |
;; NOTE: using reader (optimized)
(def DS (ds/update-column DS :V1 #(-> (dtype/->reader % :float64)
(dfn/pow 2))))
DS
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-------+-----+--------+-----|
;; | 1.000 | 1 | 0.5000 | A |
;; | 4.000 | 2 | 1.000 | B |
;; | 1.000 | 3 | 1.500 | C |
;; | 4.000 | 4 | 0.5000 | A |
;; | 1.000 | 5 | 1.000 | B |
;; | 4.000 | 6 | 1.500 | C |
;; | 1.000 | 7 | 0.5000 | A |
;; | 4.000 | 8 | 1.000 | B |
;; | 1.000 | 9 | 1.500 | C |
;; ### Add one column
;; ---- data.table
;; DT[, v5 := log(V1)][] # adding [] prints the result
(r '(bra (bra ~DT nil ((rsymbol ":=") v5 (log V1)))))
;; => V1 V2 V3 V4 v5
;; 1: 1 1 0.5 A 0.000000
;; 2: 4 2 1.0 B 1.386294
;; 3: 1 3 1.5 C 0.000000
;; 4: 4 4 0.5 A 1.386294
;; 5: 1 5 1.0 B 0.000000
;; 6: 4 6 1.5 C 1.386294
;; 7: 1 7 0.5 A 0.000000
;; 8: 4 8 1.0 B 1.386294
;; 9: 1 9 1.5 C 0.000000
;; ---- dplyr
(def DF (dpl/mutate DF :v5 '(log V1)))
DF
;; => # A tibble: 9 x 5
;; V1 V2 V3 V4 v5
;; <dbl> <int> <dbl> <chr> <dbl>
;; 1 1 1 0.5 A 0
;; 2 4 2 1 B 1.39
;; 3 1 3 1.5 C 0
;; 4 4 4 0.5 A 1.39
;; 5 1 5 1 B 0
;; 6 4 6 1.5 C 1.39
;; 7 1 7 0.5 A 0
;; 8 4 8 1 B 1.39
;; 9 1 9 1.5 C 0
;; ---- tech.ml.dataset
(def DS (ds/add-or-update-column DS :v5 (dfn/log (DS :V1))))
DS
;; => _unnamed [9 5]:
;; | :V1 | :V2 | :V3 | :V4 | :v5 |
;; |-------+-----+--------+-----+-------|
;; | 1.000 | 1 | 0.5000 | A | 0.000 |
;; | 4.000 | 2 | 1.000 | B | 1.386 |
;; | 1.000 | 3 | 1.500 | C | 0.000 |
;; | 4.000 | 4 | 0.5000 | A | 1.386 |
;; | 1.000 | 5 | 1.000 | B | 0.000 |
;; | 4.000 | 6 | 1.500 | C | 1.386 |
;; | 1.000 | 7 | 0.5000 | A | 0.000 |
;; | 4.000 | 8 | 1.000 | B | 1.386 |
;; | 1.000 | 9 | 1.500 | C | 0.000 |
;; ### Add several columns
;; ---- data.table
;; DT[, c("v6", "v7") := .(sqrt(V1), "X")]
;; DT[, ':='(v6 = sqrt(V1),
;; v7 = "X")] # same, functional form
(r '(bra ~DT nil ((rsymbol ":=") ["v6" "v7"] (. (sqrt V1) "X"))))
;; => V1 V2 V3 V4 v5 v6 v7
;; 1: 1 1 0.5 A 0.000000 1 X
;; 2: 4 2 1.0 B 1.386294 2 X
;; 3: 1 3 1.5 C 0.000000 1 X
;; 4: 4 4 0.5 A 1.386294 2 X
;; 5: 1 5 1.0 B 0.000000 1 X
;; 6: 4 6 1.5 C 1.386294 2 X
;; 7: 1 7 0.5 A 0.000000 1 X
;; 8: 4 8 1.0 B 1.386294 2 X
;; 9: 1 9 1.5 C 0.000000 1 X
(r '(bra ~DT nil ((rsymbol ":=") :v6 (sqrt V1) :v7 "X")))
;; => V1 V2 V3 V4 v5 v6 v7
;; 1: 1 1 0.5 A 0.000000 1 X
;; 2: 4 2 1.0 B 1.386294 2 X
;; 3: 1 3 1.5 C 0.000000 1 X
;; 4: 4 4 0.5 A 1.386294 2 X
;; 5: 1 5 1.0 B 0.000000 1 X
;; 6: 4 6 1.5 C 1.386294 2 X
;; 7: 1 7 0.5 A 0.000000 1 X
;; 8: 4 8 1.0 B 1.386294 2 X
;; 9: 1 9 1.5 C 0.000000 1 X
;; ---- dplyr
;; DF <- mutate(DF, v6 = sqrt(V1), v7 = "X")
(def DF (dpl/mutate DF :v6 '(sqrt V1) :v7 "X"))
DF
;; => # A tibble: 9 x 7
;; V1 V2 V3 V4 v5 v6 v7
;; <dbl> <int> <dbl> <chr> <dbl> <dbl> <chr>
;; 1 1 1 0.5 A 0 1 X
;; 2 4 2 1 B 1.39 2 X
;; 3 1 3 1.5 C 0 1 X
;; 4 4 4 0.5 A 1.39 2 X
;; 5 1 5 1 B 0 1 X
;; 6 4 6 1.5 C 1.39 2 X
;; 7 1 7 0.5 A 0 1 X
;; 8 4 8 1 B 1.39 2 X
;; 9 1 9 1.5 C 0 1 X
;; ---- tech.ml.dataset
(def DS (-> DS
(ds/add-or-update-column :v6 (dfn/sqrt (DS :V1)))
(ds/add-or-update-column :v7 (take (ds/row-count DS) (repeat "X")))))
DS
;; => _unnamed [9 7]:
;; | :V1 | :V2 | :V3 | :V4 | :v5 | :v6 | :v7 |
;; |-------+-----+--------+-----+-------+-------+-----|
;; | 1.000 | 1 | 0.5000 | A | 0.000 | 1.000 | X |
;; | 4.000 | 2 | 1.000 | B | 1.386 | 2.000 | X |
;; | 1.000 | 3 | 1.500 | C | 0.000 | 1.000 | X |
;; | 4.000 | 4 | 0.5000 | A | 1.386 | 2.000 | X |
;; | 1.000 | 5 | 1.000 | B | 0.000 | 1.000 | X |
;; | 4.000 | 6 | 1.500 | C | 1.386 | 2.000 | X |
;; | 1.000 | 7 | 0.5000 | A | 0.000 | 1.000 | X |
;; | 4.000 | 8 | 1.000 | B | 1.386 | 2.000 | X |
;; | 1.000 | 9 | 1.500 | C | 0.000 | 1.000 | X |
;; ### Create one column and remove the others
;; ---- data.table
;; DT[, .(v8 = V3 + 1)]
(r '(bra ~DT nil (. :v8 (+ V3 1))))
;; => v8
;; 1: 1.5
;; 2: 2.0
;; 3: 2.5
;; 4: 1.5
;; 5: 2.0
;; 6: 2.5
;; 7: 1.5
;; 8: 2.0
;; 9: 2.5
;; ---- dplyr
;; transmute(DF, v8 = V3 + 1)
(dpl/transmute DF :v8 '(+ V3 1))
;; => # A tibble: 9 x 1
;; v8
;; <dbl>
;; 1 1.5
;; 2 2
;; 3 2.5
;; 4 1.5
;; 5 2
;; 6 2.5
;; 7 1.5
;; 8 2
;; 9 2.5
;; ---- tech.ml.dataset
(ds/new-dataset [(col/new-column :v8 (dfn/+ (DS :V3) 1))])
;; => _unnamed [9 1]:
;; | :v8 |
;; |-------|
;; | 1.500 |
;; | 2.000 |
;; | 2.500 |
;; | 1.500 |
;; | 2.000 |
;; | 2.500 |
;; | 1.500 |
;; | 2.000 |
;; | 2.500 |
;; ### Remove one column
;; ---- data.table
;; DT[, v5 := NULL]
(r '(bra ~DT nil ((rsymbol ":=") v5 nil)))
;; => V1 V2 V3 V4 v6 v7
;; 1: 1 1 0.5 A 1 X
;; 2: 4 2 1.0 B 2 X
;; 3: 1 3 1.5 C 1 X
;; 4: 4 4 0.5 A 2 X
;; 5: 1 5 1.0 B 1 X
;; 6: 4 6 1.5 C 2 X
;; 7: 1 7 0.5 A 1 X
;; 8: 4 8 1.0 B 2 X
;; 9: 1 9 1.5 C 1 X
;; ---- dplyr
;; DF <- select(DF, -v5)
(def DF (dpl/select DF '(- v5)))
DF
;; => # A tibble: 9 x 6
;; V1 V2 V3 V4 v6 v7
;; <dbl> <int> <dbl> <chr> <dbl> <chr>
;; 1 1 1 0.5 A 1 X
;; 2 4 2 1 B 2 X
;; 3 1 3 1.5 C 1 X
;; 4 4 4 0.5 A 2 X
;; 5 1 5 1 B 1 X
;; 6 4 6 1.5 C 2 X
;; 7 1 7 0.5 A 1 X
;; 8 4 8 1 B 2 X
;; 9 1 9 1.5 C 1 X
;; ---- tech.ml.dataset
(def DS (ds/remove-column DS :v5))
DS
;; => _unnamed [9 6]:
;; | :V1 | :V2 | :V3 | :V4 | :v6 | :v7 |
;; |-------+-----+--------+-----+-------+-----|
;; | 1.000 | 1 | 0.5000 | A | 1.000 | X |
;; | 4.000 | 2 | 1.000 | B | 2.000 | X |
;; | 1.000 | 3 | 1.500 | C | 1.000 | X |
;; | 4.000 | 4 | 0.5000 | A | 2.000 | X |
;; | 1.000 | 5 | 1.000 | B | 1.000 | X |
;; | 4.000 | 6 | 1.500 | C | 2.000 | X |
;; | 1.000 | 7 | 0.5000 | A | 1.000 | X |
;; | 4.000 | 8 | 1.000 | B | 2.000 | X |
;; | 1.000 | 9 | 1.500 | C | 1.000 | X |
;; ### Remove several columns
;; ---- data.table
;; DT[, c("v6", "v7") := NULL]
(r '(bra ~DT nil ((rsymbol ":=") ["v6" "v7"] nil)))
;; => V1 V2 V3 V4
;; 1: 1 1 0.5 A
;; 2: 4 2 1.0 B
;; 3: 1 3 1.5 C
;; 4: 4 4 0.5 A
;; 5: 1 5 1.0 B
;; 6: 4 6 1.5 C
;; 7: 1 7 0.5 A
;; 8: 4 8 1.0 B
;; 9: 1 9 1.5 C
;; ---- dplyr
;; DF <- select(DF, -v6, -v7)
(def DF (dpl/select DF '(- v6) '(- v7)))
DF
;; => # A tibble: 9 x 4
;; V1 V2 V3 V4
;; <dbl> <int> <dbl> <chr>
;; 1 1 1 0.5 A
;; 2 4 2 1 B
;; 3 1 3 1.5 C
;; 4 4 4 0.5 A
;; 5 1 5 1 B
;; 6 4 6 1.5 C
;; 7 1 7 0.5 A
;; 8 4 8 1 B
;; 9 1 9 1.5 C
;; ---- tech.ml.dataset
(def DS (ds/drop-columns DS [:v6 :v7]))
DS
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V3 | :V4 |
;; |-------+-----+--------+-----|
;; | 1.000 | 1 | 0.5000 | A |
;; | 4.000 | 2 | 1.000 | B |
;; | 1.000 | 3 | 1.500 | C |
;; | 4.000 | 4 | 0.5000 | A |
;; | 1.000 | 5 | 1.000 | B |
;; | 4.000 | 6 | 1.500 | C |
;; | 1.000 | 7 | 0.5000 | A |
;; | 4.000 | 8 | 1.000 | B |
;; | 1.000 | 9 | 1.500 | C |
;; ### Remove columns using a vector of colnames
;; ---- data.table
;; cols <- c("V3")
;; DT[, (cols) := NULL] # ! not DT[, cols := NULL]
(def cols (r.base/<- 'cols ["V3"]))
;; TODO (clojisr): enable wrapping into parantheses
;; hacking below
(r (str (:object-name DT) "[, (cols) := NULL]"))
;; => V1 V2 V4
;; 1: 1 1 A
;; 2: 4 2 B
;; 3: 1 3 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 6 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; cols <- c("V3")
;; DF <- select(DF, -one_of(cols))
(def cols ["V3"])
(def DF (dpl/select DF '(- (one_of ~cols))))
DF
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <int> <chr>
;; 1 1 1 A
;; 2 4 2 B
;; 3 1 3 C
;; 4 4 4 A
;; 5 1 5 B
;; 6 4 6 C
;; 7 1 7 A
;; 8 4 8 B
;; 9 1 9 C
;; ---- tech.ml.dataset
(def cols [:V3])
(def DS (ds/drop-columns DS cols))
DS
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-----+-----|
;; | 1.000 | 1 | A |
;; | 4.000 | 2 | B |
;; | 1.000 | 3 | C |
;; | 4.000 | 4 | A |
;; | 1.000 | 5 | B |
;; | 4.000 | 6 | C |
;; | 1.000 | 7 | A |
;; | 4.000 | 8 | B |
;; | 1.000 | 9 | C |
;; ### Replace values for rows matching a condition
;; ---- data.table
;; DT[V2 < 4, V2 := 0L]
(r/bra DT '(< V2 4) '((rsymbol ":=") V2 0))
;; => V1 V2 V4
;; 1: 1 0 A
;; 2: 4 0 B
;; 3: 1 0 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 6 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; DF <- mutate(DF, V2 = base::replace(V2, V2 < 4, 0L))
(def DF (dpl/mutate DF '(= V2 ((rsymbol base replace) V2 (< V2 4) 0))))
DF
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 1 0 A
;; 2 4 0 B
;; 3 1 0 C
;; 4 4 4 A
;; 5 1 5 B
;; 6 4 6 C
;; 7 1 7 A
;; 8 4 8 B
;; 9 1 9 C
;; tech.ml.dataset
(def DS (ds/update-column DS :V2 #(map (fn [^long v]
(if (< v 4) 0 v)) %)))
DS
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 1.000 | 0.000 | A |
;; | 4.000 | 0.000 | B |
;; | 1.000 | 0.000 | C |
;; | 4.000 | 4.000 | A |
;; | 1.000 | 5.000 | B |
;; | 4.000 | 6.000 | C |
;; | 1.000 | 7.000 | A |
;; | 4.000 | 8.000 | B |
;; | 1.000 | 9.000 | C |
;; ## by
;; ### By group
;; ---- data.table
;; # one-liner:
;; DT[, .(sumV2 = sum(V2)), by = "V4"]
;; # reordered and indented:
;; DT[, by = V4,
;; .(sumV2 = sum(V2))]
(r '(bra ~DT nil (. :sumV2 (sum V2)) :by "V4"))
;; => V4 sumV2
;; 1: A 11
;; 2: B 13
;; 3: C 15
(r '(bra ~DT nil :by "V4" (. :sumV2 (sum V2))))
;; => V4 sumV2
;; 1: A 11
;; 2: B 13
;; 3: C 15
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; summarise(sumV2 = sum(V2))
(-> DF
(dpl/group_by 'V4)
(dpl/summarise :sumV2 '(sum V2)))
;; => # A tibble: 3 x 2
;; V4 sumV2
;; <chr> <dbl>
;; 1 A 11
;; 2 B 13
;; 3 C 15
;; ---- tech.ml.dataset
;; TODO: group-by and aggragete -> dataset
(group-by-columns-or-fn-and-aggregate [:V4] {:sumV2 #(dfn/sum (% :V2))} DS)
;; => _unnamed [3 2]:
;; | :V4 | :sumV2 |
;; |-----+--------|
;; | B | 13.00 |
;; | C | 15.00 |
;; | A | 11.00 |
;; ### By several groups
;; ---- data.table
;; DT[, keyby = .(V4, V1),
;; .(sumV2 = sum(V2))]
(r '(bra ~DT nil :keyby (. V4 V1) (. :sumV2 (sum V2))))
;; => V4 V1 sumV2
;; 1: A 1 7
;; 2: A 4 4
;; 3: B 1 5
;; 4: B 4 8
;; 5: C 1 9
;; 6: C 4 6
;; ---- dplyr
;; DF %>%
;; group_by(V4, V1) %>%
;; summarise(sumV2 = sum(V2))
(-> DF
(dpl/group_by 'V4 'V1)
(dpl/summarise :sumV2 '(sum V2)))
;; => # A tibble: 6 x 3
;; # Groups: V4 [3]
;; V4 V1 sumV2
;; <chr> <dbl> <dbl>
;; 1 A 1 7
;; 2 A 4 4
;; 3 B 1 5
;; 4 B 4 8
;; 5 C 1 9
;; 6 C 4 6
;; ---- tech.ml.dataset
(->> (group-by-columns-or-fn-and-aggregate [:V4 :V1] {:sumV2 #(dfn/sum (% :V2))} DS)
(sort-by-columns-with-orders [:V4 :V1]))
;; => _unnamed [6 3]:
;; | :V4 | :V1 | :sumV2 |
;; |-----+-------+--------|
;; | A | 1.000 | 7.000 |
;; | A | 4.000 | 4.000 |
;; | B | 1.000 | 5.000 |
;; | B | 4.000 | 8.000 |
;; | C | 1.000 | 9.000 |
;; | C | 4.000 | 6.000 |
;; ### Calling function in by
;; ---- data.table
;; DT[, by = tolower(V4),
;; .(sumV1 = sum(V1))]
(r '(bra ~DT nil :by (tolower V4) (. :sumV1 (sum V1))))
;; => tolower sumV1
;; 1: a 6
;; 2: b 9
;; 3: c 6
;; ---- dplyr
;; DF %>%
;; group_by(tolower(V4)) %>%
;; summarise(sumV1 = sum(V1))
(-> DF
(dpl/group_by '(tolower V4))
(dpl/summarise :sumV1 '(sum V1)))
;; => # A tibble: 3 x 2
;; `tolower(V4)` sumV1
;; <chr> <dbl>
;; 1 a 6
;; 2 b 9
;; 3 c 6
;; ---- tech.ml.dataset
(->> (ds/update-column DS :V4 #(map str/lower-case %))
(group-by-columns-or-fn-and-aggregate [:V4] {:sumV1 #(dfn/sum (% :V1))})
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :sumV1 |
;; |-----+--------|
;; | a | 6.000 |
;; | b | 9.000 |
;; | c | 6.000 |
;; ### Assigning column name in by
;; ---- data.table
;; DT[, keyby = .(abc = tolower(V4)),
;; .(sumV1 = sum(V1))]
(r '(bra ~DT nil :keyby (. :abc (tolower V4)) (. :sumV1 (sum V1))))
;; => abc sumV1
;; 1: a 6
;; 2: b 9
;; 3: c 6
;; ---- dplyr
;; DF %>%
;; group_by(abc = tolower(V4)) %>%
;; summarise(sumV1 = sum(V1))
(-> DF
(dpl/group_by :abc '(tolower V4))
(dpl/summarise :sumV1 '(sum V1)))
;; => # A tibble: 3 x 2
;; abc sumV1
;; <chr> <dbl>
;; 1 a 6
;; 2 b 9
;; 3 c 6
;; ---- tech.ml.dataset
(-> (ds/update-column DS :V4 #(map str/lower-case %))
(ds/rename-columns {:V4 :abc})
(->> (group-by-columns-or-fn-and-aggregate [:abc] {:sumV1 #(dfn/sum (% :V1))})
(ds/sort-by-column :abc)))
;; => _unnamed [3 2]:
;; | :abc | :sumV1 |
;; |------+--------|
;; | a | 6.000 |
;; | b | 9.000 |
;; | c | 6.000 |
;; ### Using a condition in by
;; ---- data.table
;; DT[, keyby = V4 == "A", sum(V1)]
(r '(bra ~DT nil :keyby (== V4 "A") (sum V1)))
;; => V4 V1
;; 1: FALSE 15
;; 2: TRUE 6
;; ---- dplyr
;; DF %>%
;; group_by(V4 == "A") %>%
;; summarise(sum(V1))
(-> DF
(dpl/group_by '(== V4 "A"))
(dpl/summarise '(sum V1)))
;; => # A tibble: 2 x 2
;; `(V4 == "A")` `sum(V1)`
;; <lgl> <dbl>
;; 1 FALSE 15
;; 2 TRUE 6
;; ---- tech.ml.dataset
(group-by-columns-or-fn-and-aggregate #(= (% :V4) \A)
{:sumV1 #(dfn/sum (% :V1))}
DS)
;; => _unnamed [2 2]:
;; | :_fn | :sumV1 |
;; |-------+--------|
;; | false | 15.00 |
;; | true | 6.000 |
;; ### By on a subset of rows
;; ---- data.table
;; DT[1:5, # i
;; .(sumV1 = sum(V1)), # j
;; by = V4] # by
;; ## complete DT[i, j, by] expression!
(r/bra DT (r/colon 1 5) '(. :sumV1 (sum V1)) :by 'V4)
;; => V4 sumV1
;; 1: A 5
;; 2: B 5
;; 3: C 1
;; ---- dplyr
;; DF %>%
;; slice(1:5) %>%
;; group_by(V4) %>%
;; summarise(sumV1 = sum(V1))
(-> DF
(dpl/slice (r/colon 1 5))
(dpl/group_by 'V4)
(dpl/summarise :sumV1 '(sum V1)))
;; => # A tibble: 3 x 2
;; V4 sumV1
;; <chr> <dbl>
;; 1 A 5
;; 2 B 5
;; 3 C 1
;; ---- tech.ml.dataset
(->> (ds/select-rows DS (range 5))
(group-by-columns-or-fn-and-aggregate [:V4] {:sumV1 #(dfn/sum (% :V1))})
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :sumV1 |
;; |-----+--------|
;; | A | 5.000 |
;; | B | 5.000 |
;; | C | 1.000 |
;; ### Count number of observations for each group
;; ---- data.table
;; DT[, .N, by = V4]
(r '(bra ~DT nil .N :by V4))
;; => V4 N
;; 1: A 3
;; 2: B 3
;; 3: C 3
;; ---- dplyr
;; count(DF, V4)
;; DF %>%
;; group_by(V4) %>%
;; tally()
;; DF %>%
;; group_by(V4) %>%
;; summarise(n())
;; DF %>%
;; group_by(V4) %>%
;; group_size() # returns a vector
(dpl/count DF 'V4)
;; => # A tibble: 3 x 2
;; V4 n
;; <chr> <int>
;; 1 A 3
;; 2 B 3
;; 3 C 3
(-> DF (dpl/group_by 'V4) (dpl/tally))
;; => # A tibble: 3 x 2
;; V4 n
;; <chr> <int>
;; 1 A 3
;; 2 B 3
;; 3 C 3
(-> DF (dpl/group_by 'V4) (dpl/summarise '(n)))
;; => # A tibble: 3 x 2
;; V4 `n()`
;; <chr> <int>
;; 1 A 3
;; 2 B 3
;; 3 C 3
(-> DF (dpl/group_by 'V4) (dpl/group_size))
;; => [1] 3 3 3
;; ---- tech.ml.dataset
(group-by-columns-or-fn-and-aggregate [:V4] {:N ds/row-count} DS)
;; => _unnamed [3 2]:
;; | :V4 | :N |
;; |-----+----|
;; | B | 3 |
;; | C | 3 |
;; | A | 3 |
(map-v ds/row-count (ds/group-by-column :V4 DS))
;; => {\A 3, \B 3, \C 3}
(->> (vals (ds/group-by-column :V4 DS))
(map ds/row-count))
;; => (3 3 3)
;; ### Add a column with number of observations for each group
;; ---- data.table
;; DT[, n := .N, by = V1][]
;; DT[, n := NULL] # rm column for consistency
(r '(bra ~DT nil ((rsymbol ":=") n .N) :by V1))
;; => V1 V2 V4 n
;; 1: 1 0 A 5
;; 2: 4 0 B 4
;; 3: 1 0 C 5
;; 4: 4 4 A 4
;; 5: 1 5 B 5
;; 6: 4 6 C 4
;; 7: 1 7 A 5
;; 8: 4 8 B 4
;; 9: 1 9 C 5
;; cleaning
(r '(bra ~DT nil ((rsymbol ":=") n nil)))
;; => V1 V2 V4
;; 1: 1 0 A
;; 2: 4 0 B
;; 3: 1 0 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 6 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; add_count(DF, V1)
;; DF %>%
;; group_by(V1) %>%
;; add_tally()
(dpl/add_count DF 'V1)
;; => # A tibble: 9 x 4
;; V1 V2 V4 n
;; <dbl> <dbl> <chr> <int>
;; 1 1 0 A 5
;; 2 4 0 B 4
;; 3 1 0 C 5
;; 4 4 4 A 4
;; 5 1 5 B 5
;; 6 4 6 C 4
;; 7 1 7 A 5
;; 8 4 8 B 4
;; 9 1 9 C 5
(-> DF
(dpl/group_by 'V1)
(dpl/add_tally))
;; => # A tibble: 9 x 4
;; # Groups: V1 [2]
;; V1 V2 V4 n
;; <dbl> <dbl> <chr> <int>
;; 1 1 0 A 5
;; 2 4 0 B 4
;; 3 1 0 C 5
;; 4 4 4 A 4
;; 5 1 5 B 5
;; 6 4 6 C 4
;; 7 1 7 A 5
;; 8 4 8 B 4
;; 9 1 9 C 5
;; ---- tech.ml.dataset
;; TODO: how to do this optimally and keep order?
(->> (ds/group-by identity [:V1] DS)
(vals)
(map (fn [ds]
(let [rcnt (ds/row-count ds)]
(ds/new-column ds :n (repeat rcnt rcnt)))))
(apply ds/concat)
(sort-by-columns-with-orders [:V2 :V4]))
;; => _unnamed [9 4]:
;; | :V1 | :V2 | :V4 | :n |
;; |-------+-------+-----+-------|
;; | 1.000 | 0.000 | A | 5.000 |
;; | 4.000 | 0.000 | B | 4.000 |
;; | 1.000 | 0.000 | C | 5.000 |
;; | 4.000 | 4.000 | A | 4.000 |
;; | 1.000 | 5.000 | B | 5.000 |
;; | 4.000 | 6.000 | C | 4.000 |
;; | 1.000 | 7.000 | A | 5.000 |
;; | 4.000 | 8.000 | B | 4.000 |
;; | 1.000 | 9.000 | C | 5.000 |
;; ### Retrieve the first/last/nth observation for each group
;; ---- data.table
;; DT[, data.table::first(V2), by = V4]
;; DT[, data.table::last(V2), by = V4]
;; DT[, V2[2], by = V4]
(r '(bra ~DT nil ((rsymbol data.table first) V2) :by V4))
;; => V4 V1
;; 1: A 0
;; 2: B 0
;; 3: C 0
(r '(bra ~DT nil ((rsymbol data.table last) V2) :by V4))
;; => V4 V1
;; 1: A 7
;; 2: B 8
;; 3: C 9
(r '(bra ~DT nil (bra V2 2) :by V4))
;; => V4 V1
;; 1: A 4
;; 2: B 5
;; 3: C 6
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; summarise(dplyr::first(V2))
;; DF %>%
;; group_by(V4) %>%
;; summarise(dplyr::last(V2))
;; DF %>%
;; group_by(V4) %>%
;; summarise(dplyr::nth(V2, 2))
(-> DF (dpl/group_by 'V4) (dpl/summarise '((rsymbol dplyr first) V2)))
;; => # A tibble: 3 x 2
;; V4 `dplyr::first(V2)`
;; <chr> <dbl>
;; 1 A 0
;; 2 B 0
;; 3 C 0
(-> DF (dpl/group_by 'V4) (dpl/summarise '((rsymbol dplyr last) V2)))
;; => # A tibble: 3 x 2
;; V4 `dplyr::last(V2)`
;; <chr> <dbl>
;; 1 A 7
;; 2 B 8
;; 3 C 9
(-> DF (dpl/group_by 'V4) (dpl/summarise '((rsymbol dplyr nth) V2 2)))
;; => # A tibble: 3 x 2
;; V4 `dplyr::nth(V2, 2)`
;; <chr> <dbl>
;; 1 A 4
;; 2 B 5
;; 3 C 6
;; ---- tech.ml.dataset
(->> (group-by-columns-or-fn-and-aggregate [:V4] {:v #(first (% :V2))} DS)
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :v |
;; |-----+-------|
;; | A | 0.000 |
;; | B | 0.000 |
;; | C | 0.000 |
(->> (group-by-columns-or-fn-and-aggregate [:V4] {:v #(last (% :V2))} DS)
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :v |
;; |-----+-------|
;; | A | 7.000 |
;; | B | 8.000 |
;; | C | 9.000 |
(->> (group-by-columns-or-fn-and-aggregate [:V4] {:v #(nth (% :V2) 1)} DS)
(ds/sort-by-column :V4))
;; => _unnamed [3 2]:
;; | :V4 | :v |
;; |-----+-------|
;; | A | 4.000 |
;; | B | 5.000 |
;; | C | 6.000 |
;; -------------------------------
;; # Going further
;; ## Advanced columns manipulation
;; ### Summarise all the columns
;; ---- data.table
;; DT[, lapply(.SD, max)]
(r '(bra ~DT nil (lapply .SD max)))
;; => V1 V2 V4
;; 1: 4 9 C
;; ---- dplyr
;; summarise_all(DF, max)
(dpl/summarise_all DF r.base/max)
;; => # A tibble: 1 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 4 9 C
;; ---- tech.ml.dataset
;; TODO: dfn/max doesn't work
(apply-to-columns my-max :all DS)
;; => _unnamed [1 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 4.000 | 9.000 | C |
;; ### Summarise several columns
;; ---- data.table
;; DT[, lapply(.SD, mean),
;; .SDcols = c("V1", "V2")]
;; # .SDcols is like "_at"
(r '(bra ~DT nil (lapply .SD mean) :.SDcols ["V1" "V2"]))
;; => V1 V2
;; 1: 2.333333 4.333333
;; ---- dplyr
;; summarise_at(DF, c("V1", "V2"), mean)
(dpl/summarise_at DF ["V1" "V2"] r.base/mean)
;; => # A tibble: 1 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 2.33 4.33
;; ---- tech.ml.dataset
;; doesn't work on beta 39
#_(->> (ds/select-columns DS [:V1 :V2])
(apply-to-columns dfn/mean [:V1 :V2]))
;; => _unnamed [1 2]:
;; | :V1 | :V2 |
;; |-------+-------|
;; | 2.333 | 4.333 |
;; ### Summarise several columns by group
;; ---- data.table
;; DT[, by = V4,
;; lapply(.SD, mean),
;; .SDcols = c("V1", "V2")]
;; ## using patterns (regex)
;; DT[, by = V4,
;; lapply(.SD, mean),
;; .SDcols = patterns("V1|V2")]
(r '(bra ~DT nil :by V4 (lapply .SD mean) :.SDcols ["V1" "V2"]))
;; => V4 V1 V2
;; 1: A 2 3.666667
;; 2: B 3 4.333333
;; 3: C 2 5.000000
(r '(bra ~DT nil :by V4 (lapply .SD mean) :.SDcols (patterns "V1|V2")))
;; => V4 V1 V2
;; 1: A 2 3.666667
;; 2: B 3 4.333333
;; 3: C 2 5.000000
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; summarise_at(c("V1", "V2"), mean)
;; ## using select helpers
;; DF %>%
;; group_by(V4) %>%
;; summarise_at(vars(one_of("V1", "V2")), mean)
(-> DF (dpl/group_by 'V4) (dpl/summarise_at ["V1" "V2"] r.base/mean))
;; => # A tibble: 3 x 3
;; V4 V1 V2
;; <chr> <dbl> <dbl>
;; 1 A 2 3.67
;; 2 B 3 4.33
;; 3 C 2 5
(-> DF (dpl/group_by 'V4) (dpl/summarise_at '(vars (one_of "V1" "V2")) r.base/mean))
;; => # A tibble: 3 x 3
;; V4 V1 V2
;; <chr> <dbl> <dbl>
;; 1 A 2 3.67
;; 2 B 3 4.33
;; 3 C 2 5
;; ---- tech.ml.dataset
(->> DS
(group-by-columns-or-fn-and-aggregate [:V4] {:V1 #(dfn/mean (% :V1))
:V2 #(dfn/mean (% :V2))})
(ds/sort-by-column :V4))
;; => _unnamed [3 3]:
;; | :V4 | :V2 | :V1 |
;; |-----+-------+-------|
;; | A | 3.667 | 2.000 |
;; | B | 4.333 | 3.000 |
;; | C | 5.000 | 2.000 |
;; ### Summarise with more than one function by group
;; ---- data.table
;; DT[, by = V4,
;; c(lapply(.SD, sum),
;; lapply(.SD, mean))]
(r '(bra ~DT nil :by V4 [(lapply .SD sum)
(lapply .SD mean)]))
;; => V4 V1 V2 V1 V2
;; 1: A 6 11 2 3.666667
;; 2: B 9 13 3 4.333333
;; 3: C 6 15 2 5.000000
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; summarise_all(list(sum, mean))
(-> DF (dpl/group_by 'V4) (dpl/summarise_all [:!list 'sum 'mean]))
;; => # A tibble: 3 x 5
;; V4 V1_fn1 V2_fn1 V1_fn2 V2_fn2
;; <chr> <dbl> <dbl> <dbl> <dbl>
;; 1 A 6 11 2 3.67
;; 2 B 9 13 3 4.33
;; 3 C 6 15 2 5
;; tech.ml.dataset
(->> DS
(group-by-columns-or-fn-and-aggregate [:V4] {:V1-mean #(dfn/mean (% :V1))
:V2-mean #(dfn/mean (% :V2))
:V1-sum #(dfn/sum (% :V1))
:V2-sum #(dfn/sum (% :V2))})
(ds/sort-by-column :V4))
;; => _unnamed [3 5]:
;; | :V4 | :V2-sum | :V1-mean | :V1-sum | :V2-mean |
;; |-----+---------+----------+---------+----------|
;; | A | 11.00 | 2.000 | 6.000 | 3.667 |
;; | B | 13.00 | 3.000 | 9.000 | 4.333 |
;; | C | 15.00 | 2.000 | 6.000 | 5.000 |
;; ### Summarise using a condition
;; ---- data.table
;; cols <- names(DT)[sapply(DT, is.numeric)]
;; DT[, lapply(.SD, mean),
;; .SDcols = cols]
(def cols (r/bra (r.base/names DT) (r.base/sapply DT r.base/is-numeric)))
(r '(bra ~DT nil (lapply .SD mean) :.SDcols ~cols))
;; => V1 V2
;; 1: 2.333333 4.333333
;; ---- dplyr
;; summarise_if(DF, is.numeric, mean)
(dpl/summarise_if DF r.base/is-numeric r.base/mean)
;; => # A tibble: 1 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 2.33 4.33
;; ---- tech.ml.dataset
(def cols (->> DS
(ds/columns)
(map meta)
(filter (comp #{:float64} :datatype))
(map :name)))
(->> (ds/select-columns DS cols)
(apply-to-columns dfn/mean cols))
;; => _unnamed [1 2]:
;; | :V1 | :V2 |
;; |-------+-------|
;; | 2.333 | 4.333 |
;; ### Modify all the columns
;; ---- data.table
;; DT[, lapply(.SD, rev)]
(r '(bra ~DT nil (lapply .SD rev)))
;; => V1 V2 V4
;; 1: 1 9 C
;; 2: 4 8 B
;; 3: 1 7 A
;; 4: 4 6 C
;; 5: 1 5 B
;; 6: 4 4 A
;; 7: 1 0 C
;; 8: 4 0 B
;; 9: 1 0 A
;; ---- dplyr
;; mutate_all(DF, rev)
;; # transmute_all(DF, rev)
(dpl/mutate_all DF r.base/rev)
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 1 9 C
;; 2 4 8 B
;; 3 1 7 A
;; 4 4 6 C
;; 5 1 5 B
;; 6 4 4 A
;; 7 1 0 C
;; 8 4 0 B
;; 9 1 0 A
;; ---- tech.ml.dataset
(ds/update-columns DS (ds/column-names DS) reverse)
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 1.000 | 9.000 | C |
;; | 4.000 | 8.000 | B |
;; | 1.000 | 7.000 | A |
;; | 4.000 | 6.000 | C |
;; | 1.000 | 5.000 | B |
;; | 4.000 | 4.000 | A |
;; | 1.000 | 0.000 | C |
;; | 4.000 | 0.000 | B |
;; | 1.000 | 0.000 | A |
;; ### Modify several columns (dropping the others)
;; ---- data.table
;; DT[, lapply(.SD, sqrt),
;; .SDcols = V1:V2]
;; DT[, lapply(.SD, exp),
;; .SDcols = !"V4"]
(r '(bra ~DT nil (lapply .SD sqrt) :.SDcols (colon V1 V2)))
;; => V1 V2
;; 1: 1 0.000000
;; 2: 2 0.000000
;; 3: 1 0.000000
;; 4: 2 2.000000
;; 5: 1 2.236068
;; 6: 2 2.449490
;; 7: 1 2.645751
;; 8: 2 2.828427
;; 9: 1 3.000000
(r '(bra ~DT nil (lapply .SD exp) :.SDcols (! "V4")))
;; => V1 V2
;; 1: 2.718282 1.00000
;; 2: 54.598150 1.00000
;; 3: 2.718282 1.00000
;; 4: 54.598150 54.59815
;; 5: 2.718282 148.41316
;; 6: 54.598150 403.42879
;; 7: 2.718282 1096.63316
;; 8: 54.598150 2980.95799
;; 9: 2.718282 8103.08393
;; ---- dplyr
;; transmute_at(DF, c("V1", "V2"), sqrt)
;; transmute_at(DF, vars(-V4), exp)
(dpl/transmute_at DF ["V1" "V2"] 'sqrt)
;; => # A tibble: 9 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 1 0
;; 2 2 0
;; 3 1 0
;; 4 2 2
;; 5 1 2.24
;; 6 2 2.45
;; 7 1 2.65
;; 8 2 2.83
;; 9 1 3
(dpl/transmute_at DF '(vars (- V4)) 'exp)
;; => # A tibble: 9 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 2.72 1
;; 2 54.6 1
;; 3 2.72 1
;; 4 54.6 54.6
;; 5 2.72 148.
;; 6 54.6 403.
;; 7 2.72 1097.
;; 8 54.6 2981.
;; 9 2.72 8103.
;; ---- tech.ml. dataset
(->> (ds/select-columns DS [:V1 :V2])
(apply-to-columns dfn/sqrt :all))
;; => _unnamed [9 2]:
;; | :V1 | :V2 |
;; |-------+-------|
;; | 1.000 | 0.000 |
;; | 2.000 | 0.000 |
;; | 1.000 | 0.000 |
;; | 2.000 | 2.000 |
;; | 1.000 | 2.236 |
;; | 2.000 | 2.449 |
;; | 1.000 | 2.646 |
;; | 2.000 | 2.828 |
;; | 1.000 | 3.000 |
(->> (ds/drop-columns DS [:V4])
(apply-to-columns dfn/exp :all))
;; => _unnamed [9 2]:
;; | :V1 | :V2 |
;; |-------+-------|
;; | 2.718 | 1.000 |
;; | 54.60 | 1.000 |
;; | 2.718 | 1.000 |
;; | 54.60 | 54.60 |
;; | 2.718 | 148.4 |
;; | 54.60 | 403.4 |
;; | 2.718 | 1097 |
;; | 54.60 | 2981 |
;; | 2.718 | 8103 |
;; ### Modify several columns (keeping the others)
;; ---- data.table
;; DT[, c("V1", "V2") := lapply(.SD, sqrt),
;; .SDcols = c("V1", "V2")]
;; cols <- setdiff(names(DT), "V4")
;; DT[, (cols) := lapply(.SD, "^", 2L),
;; .SDcols = cols]
(r '(bra ~DT nil ((rsymbol ":=") ["V1" "V2"] (lapply .SD sqrt))
:.SDcols ["V1" "V2"]))
;; => V1 V2 V4
;; 1: 1 0.000000 A
;; 2: 2 0.000000 B
;; 3: 1 0.000000 C
;; 4: 2 2.000000 A
;; 5: 1 2.236068 B
;; 6: 2 2.449490 C
;; 7: 1 2.645751 A
;; 8: 2 2.828427 B
;; 9: 1 3.000000 C
(def cols (r.base/<- 'cols (r.base/setdiff (r.base/names DT) "V4")))
(r (str (:object-name DT) "[, (cols) := lapply(.SD, \"^\", 2L), .SDcols = cols]"))
;; => V1 V2 V4
;; 1: 1 0 A
;; 2: 4 0 B
;; 3: 1 0 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 6 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; DF <- mutate_at(DF, c("V1", "V2"), sqrt)
;; DF <- mutate_at(DF, vars(-V4), "^", 2L)
(def DF (dpl/mutate_at DF ["V1" "V2"] 'sqrt))
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 1 0 A
;; 2 2 0 B
;; 3 1 0 C
;; 4 2 2 A
;; 5 1 2.24 B
;; 6 2 2.45 C
;; 7 1 2.65 A
;; 8 2 2.83 B
;; 9 1 3 C
(def DF (dpl/mutate_at DF '(vars (- V4)) "^" 2))
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <dbl> <dbl> <chr>
;; 1 1 0 A
;; 2 4 0 B
;; 3 1 0 C
;; 4 4 4 A
;; 5 1 5. B
;; 6 4 6.00 C
;; 7 1 7. A
;; 8 4 8. B
;; 9 1 9 C
;; ---- tech.ml.dataset
(def DS (apply-to-columns dfn/sqrt [:V1 :V2] DS))
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 1.000 | 0.000 | A |
;; | 2.000 | 0.000 | B |
;; | 1.000 | 0.000 | C |
;; | 2.000 | 2.000 | A |
;; | 1.000 | 2.236 | B |
;; | 2.000 | 2.449 | C |
;; | 1.000 | 2.646 | A |
;; | 2.000 | 2.828 | B |
;; | 1.000 | 3.000 | C |
(def DS (apply-to-columns #(dfn/pow % 2.0) [:V1 :V2] DS))
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-------+-------+-----|
;; | 1.000 | 0.000 | A |
;; | 4.000 | 0.000 | B |
;; | 1.000 | 0.000 | C |
;; | 4.000 | 4.000 | A |
;; | 1.000 | 5.000 | B |
;; | 4.000 | 6.000 | C |
;; | 1.000 | 7.000 | A |
;; | 4.000 | 8.000 | B |
;; | 1.000 | 9.000 | C |
;; ### Modify columns using a condition (dropping the others)
;; ---- data.table
;; cols <- names(DT)[sapply(DT, is.numeric)]
;; DT[, .SD - 1,
;; .SDcols = cols]
(def cols (r/bra (r.base/names DT) (r.base/sapply DT r.base/is-numeric)))
(r '(bra ~DT nil (- .SD 1) :.SDcols ~cols))
;; => V1 V2
;; 1: 0 -1
;; 2: 3 -1
;; 3: 0 -1
;; 4: 3 3
;; 5: 0 4
;; 6: 3 5
;; 7: 0 6
;; 8: 3 7
;; 9: 0 8
;; ---- dplyr
;; transmute_if(DF, is.numeric, list(~ '-'(., 1L)))
(dpl/transmute_if DF r.base/is-numeric [:!list '(formula nil (- . 1))])
;; => # A tibble: 9 x 2
;; V1 V2
;; <dbl> <dbl>
;; 1 0 -1
;; 2 3 -1
;; 3 0 -1
;; 4 3 3
;; 5 0 4.
;; 6 3 5.00
;; 7 0 6.
;; 8 3 7.
;; 9 0 8
;; ---- tech.ml.dataset
(def cols (->> DS
(ds/columns)
(map meta)
(filter (comp #(= :float64 %) :datatype))
(map :name)))
(->> (ds/select-columns DS cols)
(apply-to-columns #(dfn/- % 1) cols))
;; => _unnamed [9 2]:
;; | :V1 | :V2 |
;; |-------+--------|
;; | 0.000 | -1.000 |
;; | 3.000 | -1.000 |
;; | 0.000 | -1.000 |
;; | 3.000 | 3.000 |
;; | 0.000 | 4.000 |
;; | 3.000 | 5.000 |
;; | 0.000 | 6.000 |
;; | 3.000 | 7.000 |
;; | 0.000 | 8.000 |
;; ### Modify columns using a condition (keeping the others)
;; ---- data.table
;; DT[, (cols) := lapply(.SD, as.integer),
;; .SDcols = cols]
(def cols (r.base/<- 'cols (r.base/setdiff (r.base/names DT) "V4")))
(r (str (:object-name DT) "[, (cols) := lapply(.SD, as.integer), .SDcols = cols]"))
;; => V1 V2 V4
;; 1: 1 0 A
;; 2: 4 0 B
;; 3: 1 0 C
;; 4: 4 4 A
;; 5: 1 5 B
;; 6: 4 5 C
;; 7: 1 7 A
;; 8: 4 8 B
;; 9: 1 9 C
;; ---- dplyr
;; DF <- mutate_if(DF, is.numeric, as.integer)
(def DF (dpl/mutate_if DF r.base/is-numeric r.base/as-integer))
;; => # A tibble: 9 x 3
;; V1 V2 V4
;; <int> <int> <chr>
;; 1 1 0 A
;; 2 4 0 B
;; 3 1 0 C
;; 4 4 4 A
;; 5 1 5 B
;; 6 4 5 C
;; 7 1 7 A
;; 8 4 8 B
;; 9 1 9 C
;; ----tech.ml.dataset
;; TODO: easier cast to given type
(def DS (apply-to-columns #(dtype/->reader % :int64) [:V1 :V2] DS))
;; => _unnamed [9 3]:
;; | :V1 | :V2 | :V4 |
;; |-----+-----+-----|
;; | 1 | 0 | A |
;; | 4 | 0 | B |
;; | 1 | 0 | C |
;; | 4 | 4 | A |
;; | 1 | 5 | B |
;; | 4 | 5 | C |
;; | 1 | 7 | A |
;; | 4 | 8 | B |
;; | 1 | 9 | C |
;; ### Use a complex expression
;; ---- data.table
;; DT[, by = V4, .(V1[1:2], "X")]
(r '(bra ~DT nil :by V4 (. (bra V1 (colon 1 2)) "X")))
;; => V4 V1 V2
;; 1: A 1 X
;; 2: A 4 X
;; 3: B 4 X
;; 4: B 1 X
;; 5: C 1 X
;; 6: C 4 X
;; ---- dplyr
;; DF %>%
;; group_by(V4) %>%
;; slice(1:2) %>%
;; transmute(V1 = V1,
;; V2 = "X")
(-> DF
(dpl/group_by 'V4)
(dpl/slice (r/colon 1 2))
(dpl/transmute :V1 'V1 :V2 "X"))
;; => # A tibble: 6 x 3
;; # Groups: V4 [3]
;; V4 V1 V2
;; <chr> <int> <chr>
;; 1 A 1 X
;; 2 A 4 X
;; 3 B 4 X
;; 4 B 1 X
;; 5 C 1 X
;; 6 C 4 X
;; ---- tech.ml.dataset
(->> (ds/group-by-column :V4 DS)
(vals)
(map #(ds/head 2 %))
(map #(ds/add-or-update-column % :V2 (repeat (ds/row-count %) "X")))
(apply ds/concat))
;; => null [6 3]:
;; | :V1 | :V2 | :V4 |
;; |-----+-----+-----|
;; | 1 | X | A |
;; | 4 | X | A |
;; | 4 | X | B |
;; | 1 | X | B |
;; | 1 | X | C |
;; | 4 | X | C |
;; ### Use multiple expressions (with DT[,{j}])
;; ---- data.table
;; DT[, {print(V1) # comments here!
;; print(summary(V1))
;; x <- V1 + sum(V2)
;; .(A = 1:.N, B = x) # last list returned as a data.table
;; }]
(r (str (:object-name DT)
"[, {print(V1) # comments here!
print(summary(V1))
x <- V1 + sum(V2)
.(A = 1:.N, B = x)}]"))
;; => A B
;; 1: 1 39
;; 2: 2 42
;; 3: 3 39
;; 4: 4 42
;; 5: 5 39
;; 6: 6 42
;; 7: 7 39
;; 8: 8 42
;; 9: 9 39
;; printed:
;; [1] 1 4 1 4 1 4 1 4 1
;; Min. 1st Qu. Median Mean 3rd Qu. Max.
;; 1.000 1.000 1.000 2.333 4.000 4.000
;; ---- dplyr
;; no provided implementation
;; ---- tech.ml.dataset
(let [x (dfn/+ (DS :V1) (dfn/sum (DS :V2)))]
(println (DS :V1))
(println (dfn/descriptive-stats (DS :V2)))
(ds/name-values-seq->dataset {:A (map inc (range (ds/row-count DS)))
:B x}))
;; => _unnamed [9 2]:
;; | :A | :B |
;; |----+-------|
;; | 1 | 39.00 |
;; | 2 | 42.00 |
;; | 3 | 39.00 |
;; | 4 | 42.00 |
;; | 5 | 39.00 |
;; | 6 | 42.00 |
;; | 7 | 39.00 |
;; | 8 | 42.00 |
;; | 9 | 39.00 |
;; printed:
;; #tech.ml.dataset.column<int64>[9]
;; :V1
;; [1, 4, 1, 4, 1, 4, 1, 4, 1, ]
;; {:min 0.0, :mean 4.222222222222222, :skew -0.1481546009077147, :ecount 9, :standard-deviation 3.527668414752787, :median 5.0, :max 9.0}
|
[
{
"context": "n-name]\n (let [user1-token (e/login (s/context) \"user1\")\n {:keys [status body]} (search/retrieve-",
"end": 2607,
"score": 0.6633791923522949,
"start": 2602,
"tag": "USERNAME",
"value": "user1"
},
{
"context": "tryTitle \"entry-title1\"})\n {:token \"mock-echo-system-token\"})]\n (doseq [accept-format [mt/umm-json]];; ni",
"end": 6130,
"score": 0.6544350981712341,
"start": 6108,
"tag": "PASSWORD",
"value": "mock-echo-system-token"
}
] | system-int-test/test/cmr/system_int_test/search/subscription/concept_retrieval_test.clj | chris-durbin/Common-Metadata-Repository | 294 | (ns cmr.system-int-test.search.subscription.concept-retrieval-test
"Integration test for subscription retrieval via the following endpoints:
* /concepts/:concept-id
* /concepts/:concept-id/:revision-id"
(:require
[cheshire.core :as json]
[clojure.test :refer :all]
[cmr.access-control.test.util :as ac-util]
[cmr.common.mime-types :as mt]
[cmr.mock-echo.client.echo-util :as e]
[cmr.system-int-test.data2.core :as data-core]
[cmr.system-int-test.data2.umm-spec-collection :as data-umm-c]
[cmr.system-int-test.system :as s]
[cmr.system-int-test.utils.index-util :as index]
[cmr.system-int-test.utils.ingest-util :as ingest]
[cmr.system-int-test.utils.metadata-db-util :as mdb]
[cmr.system-int-test.utils.search-util :as search]
[cmr.system-int-test.utils.subscription-util :as subscription]))
(use-fixtures
:each
(join-fixtures
[(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2"})
(subscription/grant-all-subscription-fixture {"provguid1" "PROV1"} [:read :update] [:read :update])
(subscription/grant-all-subscription-fixture {"provguid2" "PROV2"} [:update] [:read :update])]))
(defn- assert-retrieved-concept-as-subscriber
"Verify the retrieved concept by checking against the expected subscription name,
which we have deliberately set to be different for each concept revision."
[concept-id revision-id accept-format expected-subscription-name token]
(let [{:keys [status body]} (search/retrieve-concept
concept-id revision-id {:accept accept-format
:query-params {:token token}})]
(is (= 200 status))
(is (= expected-subscription-name
(:Name (json/parse-string body true))))))
(defn- assert-retrieved-concept
"Verify the retrieved concept by checking against the expected subscription name,
which we have deliberately set to be different for each concept revision."
[concept-id revision-id accept-format expected-subscription-name]
(let [{:keys [status body]} (search/retrieve-concept
concept-id revision-id {:accept accept-format})]
(is (= 200 status))
(is (= expected-subscription-name
(:Name (json/parse-string body true))))))
(defn- assert-retrieved-concept-with-registered-user
"Verify the retrieved concept by checking against the expected subscription name,
which we have deliberately set to be different for each concept revision."
[concept-id revision-id accept-format expected-subscription-name]
(let [user1-token (e/login (s/context) "user1")
{:keys [status body]} (search/retrieve-concept
concept-id revision-id {:accept accept-format
:query-params {:token user1-token}})]
(is (= 200 status))
(is (= expected-subscription-name
(:Name (json/parse-string body true))))))
(defmulti handle-retrieve-concept-error
"Execute the retrieve concept call with the given parameters and returns the status and errors
based on the result format."
(fn [concept-id revision-id accept-format]
accept-format))
(defmethod handle-retrieve-concept-error mt/umm-json
[concept-id revision-id accept-format]
(let [{:keys [status body]} (search/retrieve-concept concept-id revision-id
{:accept accept-format})
errors (:errors (json/parse-string body true))]
{:status status :errors errors}))
(defmethod handle-retrieve-concept-error :default
[concept-id revision-id accept-format]
(search/get-search-failure-xml-data
(search/retrieve-concept concept-id revision-id {:accept accept-format
:throw-exceptions true})))
(defn- assert-retrieved-concept-error
"Verify the expected error code and error message are returned when retrieving the given concept."
[concept-id revision-id accept-format err-code err-message]
(let [{:keys [status errors]} (handle-retrieve-concept-error
concept-id revision-id accept-format)]
(is (= err-code status))
(is (= [err-message] errors))))
(defmulti handle-retrieve-concept-as-subscriber-error
"Execute the retrieve concept call with the given parameters and returns the status and errors
based on the result format."
(fn [concept-id revision-id accept-format token]
accept-format))
(defmethod handle-retrieve-concept-as-subscriber-error mt/umm-json
[concept-id revision-id accept-format token]
(let [{:keys [status body]} (search/retrieve-concept concept-id revision-id
{:accept accept-format
:query-params {:token token}})
errors (:errors (json/parse-string body true))]
{:status status :errors errors}))
(defmethod handle-retrieve-concept-as-subscriber-error :default
[concept-id revision-id accept-format token]
(search/get-search-failure-xml-data
(search/retrieve-concept concept-id revision-id {:accept accept-format
:query-params {:token token}
:throw-exceptions true})))
(defn- assert-retrieved-concept-as-subscriber-recieved-error
"Verify the expected error code and error message are returned when retrieving the given concept."
[concept-id revision-id accept-format err-code token err-message]
(let [{:keys [status errors]} (handle-retrieve-concept-as-subscriber-error
concept-id revision-id accept-format token)]
(is (= err-code status))
(is (= [err-message] errors))))
(deftest retrieve-subscription-by-concept-id-various-read-permission
;; We support UMM JSON format; No format and any format are also accepted.
(let [coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(doseq [accept-format [mt/umm-json]];; nil mt/any]]
(let [suffix (if accept-format
(mt/mime-type->format accept-format)
"nil")
;; append result format to subscription name to make it unique
;; for different formats so that the test can be run for multiple formats
sub1-r1-name (str "s1-r1" suffix)
sub1-r2-name (str "s1-r2" suffix)
native-id (str "subscription1" suffix)
sub1-r1 (subscription/ingest-subscription-with-attrs {:provider-id "PROV2"
:Name sub1-r1-name
:CollectionConceptId (:concept-id coll1)
:native-id native-id})
sub1-r2 (subscription/ingest-subscription-with-attrs {:provider-id "PROV2"
:Name sub1-r2-name
:CollectionConceptId (:concept-id coll1)
:native-id native-id})
concept-id (:concept-id sub1-r1)]
(index/wait-until-indexed)
(testing "Sanity check that the test subscription got updated and its revision id was incremented"
(is (= concept-id (:concept-id sub1-r2)))
(is (= 1 (:revision-id sub1-r1)))
(is (= 2 (:revision-id sub1-r2))))
;; no read permission granted for guest on provider "PROV2" so, no subscription could be found.
(testing "retrieval by subscription concept-id and revision id returns error"
(assert-retrieved-concept-error concept-id 1 accept-format 404
(format "Concept with concept-id [%s] and revision-id [1] could not be found." concept-id))
(assert-retrieved-concept-error concept-id 2 accept-format 404
(format "Concept with concept-id [%s] and revision-id [2] could not be found." concept-id)))
(testing "retrieval by only subscription concept-id returns error"
(assert-retrieved-concept-error concept-id nil accept-format 404
(format "Concept with concept-id [%s] could not be found." concept-id)))
;; read permission is granted for registered user, subscriptions will be found
(testing "retrieval by subscription concept-id and revision id returns the specified revision"
(assert-retrieved-concept-with-registered-user concept-id 1 accept-format sub1-r1-name)
(assert-retrieved-concept-with-registered-user concept-id 2 accept-format sub1-r2-name))
(testing "retrieval by only subscription concept-id returns the latest revision"
(assert-retrieved-concept-with-registered-user concept-id nil accept-format sub1-r2-name))))))
(deftest retrieve-subscription-by-concept-id
;; We support UMM JSON format; No format and any format are also accepted.
(let [coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(doseq [accept-format [mt/umm-json]];; nil mt/any]]
(let [suffix (if accept-format
(mt/mime-type->format accept-format)
"nil")
;; append result format to subscription name to make it unique
;; for different formats so that the test can be run for multiple formats
sub1-r1-name (str "s1-r1" suffix)
sub1-r2-name (str "s1-r2" suffix)
native-id (str "subscription1" suffix)
sub1-r1 (subscription/ingest-subscription-with-attrs {:Name sub1-r1-name
:CollectionConceptId (:concept-id coll1)
:native-id native-id})
sub1-r2 (subscription/ingest-subscription-with-attrs {:Name sub1-r2-name
:CollectionConceptId (:concept-id coll1)
:native-id native-id})
concept-id (:concept-id sub1-r1)
sub1-concept (mdb/get-concept concept-id)]
(index/wait-until-indexed)
(testing "Sanity check that the test subscription got updated and its revision id was incremented"
(is (= concept-id (:concept-id sub1-r2)))
(is (= 1 (:revision-id sub1-r1)))
(is (= 2 (:revision-id sub1-r2))))
(testing "retrieval by subscription concept-id and revision id returns the specified revision"
(assert-retrieved-concept concept-id 1 accept-format sub1-r1-name)
(assert-retrieved-concept concept-id 2 accept-format sub1-r2-name))
(testing "retrieval by only subscription concept-id returns the latest revision"
(assert-retrieved-concept concept-id nil accept-format sub1-r2-name))
(testing "retrieval by non-existent revision returns error"
(assert-retrieved-concept-error concept-id 3 accept-format 404
(format "Concept with concept-id [%s] and revision-id [3] does not exist." concept-id)))
(testing "retrieval by non-existent concept-id returns error"
(assert-retrieved-concept-error "SUB404404404-PROV1" nil accept-format 404
"Concept with concept-id [SUB404404404-PROV1] could not be found."))
(testing "retrieval by non-existent concept-id and revision-id returns error"
(assert-retrieved-concept-error "SUB404404404-PROV1" 1 accept-format 404
"Concept with concept-id [SUB404404404-PROV1] and revision-id [1] does not exist."))
(testing "retrieval of deleted concept"
;; delete the subscription concept
(ingest/delete-concept sub1-concept (subscription/token-opts (e/login (s/context) "user1")))
(index/wait-until-indexed)
(testing "retrieval of deleted concept without revision id results in error"
(assert-retrieved-concept-error concept-id nil accept-format 404
(format "Concept with concept-id [%s] could not be found." concept-id)))
(testing "retrieval of deleted concept with revision id returns a 400 error"
(assert-retrieved-concept-error concept-id 3 accept-format 400
(format (str "The revision [3] of concept [%s] represents "
"a deleted concept and does not contain metadata.")
concept-id))))))))
(deftest retrieve-subscription-with-invalid-format
(testing "unsupported accept header results in error"
(let [unsupported-mt "unsupported/mime-type"]
(assert-retrieved-concept-error "SUB1111-PROV1" nil unsupported-mt 400
(format "The mime types specified in the accept header [%s] are not supported."
unsupported-mt)))))
(deftest retrieve-subscription-by-concept-id-with-subscriber
(e/ungrant-by-search (s/context)
{:provider "PROV1"
:target ["SUBSCRIPTION_MANAGEMENT" "INGEST_MANAGEMENT_ACL"]})
(ac-util/wait-until-indexed)
(let [coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(doseq [accept-format [mt/umm-json]]
(let [suffix (if accept-format
(mt/mime-type->format accept-format)
"nil")
subscriber-token (e/login (s/context) "subscriber")
sub1-r1-name (str "s1-r1" suffix)
native-id (str "subscription1" suffix)
sub1-r1 (subscription/ingest-subscription (subscription/make-subscription-concept
{:Name sub1-r1-name
:CollectionConceptId (:concept-id coll1)
:SubscriberId "subscriber"
:native-id native-id})
{:token "mock-echo-system-token"})
concept-id (:concept-id sub1-r1)
sub1-concept (mdb/get-concept concept-id)]
(index/wait-until-indexed)
(testing "retrieval by subscription concept-id and revision id returns the specified revision"
(assert-retrieved-concept-as-subscriber concept-id 1 accept-format sub1-r1-name subscriber-token))
(testing "retrieval by only subscription concept-id returns the latest revision"
(assert-retrieved-concept-as-subscriber concept-id nil accept-format sub1-r1-name subscriber-token))
(testing "retrieval by non-existent revision returns error"
(assert-retrieved-concept-as-subscriber-recieved-error concept-id 3 accept-format 404 subscriber-token
(format "Concept with concept-id [%s] and revision-id [3] does not exist." concept-id)))
(testing "retrieval by non-existent concept-id returns error"
(assert-retrieved-concept-as-subscriber-recieved-error "SUB404404404-PROV1" nil accept-format 404 subscriber-token
"Concept with concept-id [SUB404404404-PROV1] could not be found."))
(testing "retrieval by non-existent concept-id and revision-id returns error"
(assert-retrieved-concept-as-subscriber-recieved-error "SUB404404404-PROV1" 1 accept-format 404 subscriber-token
"Concept with concept-id [SUB404404404-PROV1] and revision-id [1] does not exist."))
(testing "retrieval of deleted concept"
;; delete the subscription concept
(ingest/delete-concept sub1-concept (subscription/token-opts "mock-echo-system-token"))
(index/wait-until-indexed)
(testing "retrieval of deleted concept without revision id results in error"
(assert-retrieved-concept-as-subscriber-recieved-error concept-id nil accept-format 404 subscriber-token
(format "Concept with concept-id [%s] could not be found." concept-id)))
(testing "retrieval of deleted concept with revision id returns a 400 error"
(assert-retrieved-concept-as-subscriber-recieved-error concept-id 2 accept-format 400 subscriber-token
(format (str "The revision [2] of concept [%s] represents "
"a deleted concept and does not contain metadata.")
concept-id))))))))
| 111694 | (ns cmr.system-int-test.search.subscription.concept-retrieval-test
"Integration test for subscription retrieval via the following endpoints:
* /concepts/:concept-id
* /concepts/:concept-id/:revision-id"
(:require
[cheshire.core :as json]
[clojure.test :refer :all]
[cmr.access-control.test.util :as ac-util]
[cmr.common.mime-types :as mt]
[cmr.mock-echo.client.echo-util :as e]
[cmr.system-int-test.data2.core :as data-core]
[cmr.system-int-test.data2.umm-spec-collection :as data-umm-c]
[cmr.system-int-test.system :as s]
[cmr.system-int-test.utils.index-util :as index]
[cmr.system-int-test.utils.ingest-util :as ingest]
[cmr.system-int-test.utils.metadata-db-util :as mdb]
[cmr.system-int-test.utils.search-util :as search]
[cmr.system-int-test.utils.subscription-util :as subscription]))
(use-fixtures
:each
(join-fixtures
[(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2"})
(subscription/grant-all-subscription-fixture {"provguid1" "PROV1"} [:read :update] [:read :update])
(subscription/grant-all-subscription-fixture {"provguid2" "PROV2"} [:update] [:read :update])]))
(defn- assert-retrieved-concept-as-subscriber
"Verify the retrieved concept by checking against the expected subscription name,
which we have deliberately set to be different for each concept revision."
[concept-id revision-id accept-format expected-subscription-name token]
(let [{:keys [status body]} (search/retrieve-concept
concept-id revision-id {:accept accept-format
:query-params {:token token}})]
(is (= 200 status))
(is (= expected-subscription-name
(:Name (json/parse-string body true))))))
(defn- assert-retrieved-concept
"Verify the retrieved concept by checking against the expected subscription name,
which we have deliberately set to be different for each concept revision."
[concept-id revision-id accept-format expected-subscription-name]
(let [{:keys [status body]} (search/retrieve-concept
concept-id revision-id {:accept accept-format})]
(is (= 200 status))
(is (= expected-subscription-name
(:Name (json/parse-string body true))))))
(defn- assert-retrieved-concept-with-registered-user
"Verify the retrieved concept by checking against the expected subscription name,
which we have deliberately set to be different for each concept revision."
[concept-id revision-id accept-format expected-subscription-name]
(let [user1-token (e/login (s/context) "user1")
{:keys [status body]} (search/retrieve-concept
concept-id revision-id {:accept accept-format
:query-params {:token user1-token}})]
(is (= 200 status))
(is (= expected-subscription-name
(:Name (json/parse-string body true))))))
(defmulti handle-retrieve-concept-error
"Execute the retrieve concept call with the given parameters and returns the status and errors
based on the result format."
(fn [concept-id revision-id accept-format]
accept-format))
(defmethod handle-retrieve-concept-error mt/umm-json
[concept-id revision-id accept-format]
(let [{:keys [status body]} (search/retrieve-concept concept-id revision-id
{:accept accept-format})
errors (:errors (json/parse-string body true))]
{:status status :errors errors}))
(defmethod handle-retrieve-concept-error :default
[concept-id revision-id accept-format]
(search/get-search-failure-xml-data
(search/retrieve-concept concept-id revision-id {:accept accept-format
:throw-exceptions true})))
(defn- assert-retrieved-concept-error
"Verify the expected error code and error message are returned when retrieving the given concept."
[concept-id revision-id accept-format err-code err-message]
(let [{:keys [status errors]} (handle-retrieve-concept-error
concept-id revision-id accept-format)]
(is (= err-code status))
(is (= [err-message] errors))))
(defmulti handle-retrieve-concept-as-subscriber-error
"Execute the retrieve concept call with the given parameters and returns the status and errors
based on the result format."
(fn [concept-id revision-id accept-format token]
accept-format))
(defmethod handle-retrieve-concept-as-subscriber-error mt/umm-json
[concept-id revision-id accept-format token]
(let [{:keys [status body]} (search/retrieve-concept concept-id revision-id
{:accept accept-format
:query-params {:token token}})
errors (:errors (json/parse-string body true))]
{:status status :errors errors}))
(defmethod handle-retrieve-concept-as-subscriber-error :default
[concept-id revision-id accept-format token]
(search/get-search-failure-xml-data
(search/retrieve-concept concept-id revision-id {:accept accept-format
:query-params {:token token}
:throw-exceptions true})))
(defn- assert-retrieved-concept-as-subscriber-recieved-error
"Verify the expected error code and error message are returned when retrieving the given concept."
[concept-id revision-id accept-format err-code token err-message]
(let [{:keys [status errors]} (handle-retrieve-concept-as-subscriber-error
concept-id revision-id accept-format token)]
(is (= err-code status))
(is (= [err-message] errors))))
(deftest retrieve-subscription-by-concept-id-various-read-permission
;; We support UMM JSON format; No format and any format are also accepted.
(let [coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "<PASSWORD>"})]
(doseq [accept-format [mt/umm-json]];; nil mt/any]]
(let [suffix (if accept-format
(mt/mime-type->format accept-format)
"nil")
;; append result format to subscription name to make it unique
;; for different formats so that the test can be run for multiple formats
sub1-r1-name (str "s1-r1" suffix)
sub1-r2-name (str "s1-r2" suffix)
native-id (str "subscription1" suffix)
sub1-r1 (subscription/ingest-subscription-with-attrs {:provider-id "PROV2"
:Name sub1-r1-name
:CollectionConceptId (:concept-id coll1)
:native-id native-id})
sub1-r2 (subscription/ingest-subscription-with-attrs {:provider-id "PROV2"
:Name sub1-r2-name
:CollectionConceptId (:concept-id coll1)
:native-id native-id})
concept-id (:concept-id sub1-r1)]
(index/wait-until-indexed)
(testing "Sanity check that the test subscription got updated and its revision id was incremented"
(is (= concept-id (:concept-id sub1-r2)))
(is (= 1 (:revision-id sub1-r1)))
(is (= 2 (:revision-id sub1-r2))))
;; no read permission granted for guest on provider "PROV2" so, no subscription could be found.
(testing "retrieval by subscription concept-id and revision id returns error"
(assert-retrieved-concept-error concept-id 1 accept-format 404
(format "Concept with concept-id [%s] and revision-id [1] could not be found." concept-id))
(assert-retrieved-concept-error concept-id 2 accept-format 404
(format "Concept with concept-id [%s] and revision-id [2] could not be found." concept-id)))
(testing "retrieval by only subscription concept-id returns error"
(assert-retrieved-concept-error concept-id nil accept-format 404
(format "Concept with concept-id [%s] could not be found." concept-id)))
;; read permission is granted for registered user, subscriptions will be found
(testing "retrieval by subscription concept-id and revision id returns the specified revision"
(assert-retrieved-concept-with-registered-user concept-id 1 accept-format sub1-r1-name)
(assert-retrieved-concept-with-registered-user concept-id 2 accept-format sub1-r2-name))
(testing "retrieval by only subscription concept-id returns the latest revision"
(assert-retrieved-concept-with-registered-user concept-id nil accept-format sub1-r2-name))))))
(deftest retrieve-subscription-by-concept-id
;; We support UMM JSON format; No format and any format are also accepted.
(let [coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(doseq [accept-format [mt/umm-json]];; nil mt/any]]
(let [suffix (if accept-format
(mt/mime-type->format accept-format)
"nil")
;; append result format to subscription name to make it unique
;; for different formats so that the test can be run for multiple formats
sub1-r1-name (str "s1-r1" suffix)
sub1-r2-name (str "s1-r2" suffix)
native-id (str "subscription1" suffix)
sub1-r1 (subscription/ingest-subscription-with-attrs {:Name sub1-r1-name
:CollectionConceptId (:concept-id coll1)
:native-id native-id})
sub1-r2 (subscription/ingest-subscription-with-attrs {:Name sub1-r2-name
:CollectionConceptId (:concept-id coll1)
:native-id native-id})
concept-id (:concept-id sub1-r1)
sub1-concept (mdb/get-concept concept-id)]
(index/wait-until-indexed)
(testing "Sanity check that the test subscription got updated and its revision id was incremented"
(is (= concept-id (:concept-id sub1-r2)))
(is (= 1 (:revision-id sub1-r1)))
(is (= 2 (:revision-id sub1-r2))))
(testing "retrieval by subscription concept-id and revision id returns the specified revision"
(assert-retrieved-concept concept-id 1 accept-format sub1-r1-name)
(assert-retrieved-concept concept-id 2 accept-format sub1-r2-name))
(testing "retrieval by only subscription concept-id returns the latest revision"
(assert-retrieved-concept concept-id nil accept-format sub1-r2-name))
(testing "retrieval by non-existent revision returns error"
(assert-retrieved-concept-error concept-id 3 accept-format 404
(format "Concept with concept-id [%s] and revision-id [3] does not exist." concept-id)))
(testing "retrieval by non-existent concept-id returns error"
(assert-retrieved-concept-error "SUB404404404-PROV1" nil accept-format 404
"Concept with concept-id [SUB404404404-PROV1] could not be found."))
(testing "retrieval by non-existent concept-id and revision-id returns error"
(assert-retrieved-concept-error "SUB404404404-PROV1" 1 accept-format 404
"Concept with concept-id [SUB404404404-PROV1] and revision-id [1] does not exist."))
(testing "retrieval of deleted concept"
;; delete the subscription concept
(ingest/delete-concept sub1-concept (subscription/token-opts (e/login (s/context) "user1")))
(index/wait-until-indexed)
(testing "retrieval of deleted concept without revision id results in error"
(assert-retrieved-concept-error concept-id nil accept-format 404
(format "Concept with concept-id [%s] could not be found." concept-id)))
(testing "retrieval of deleted concept with revision id returns a 400 error"
(assert-retrieved-concept-error concept-id 3 accept-format 400
(format (str "The revision [3] of concept [%s] represents "
"a deleted concept and does not contain metadata.")
concept-id))))))))
(deftest retrieve-subscription-with-invalid-format
(testing "unsupported accept header results in error"
(let [unsupported-mt "unsupported/mime-type"]
(assert-retrieved-concept-error "SUB1111-PROV1" nil unsupported-mt 400
(format "The mime types specified in the accept header [%s] are not supported."
unsupported-mt)))))
(deftest retrieve-subscription-by-concept-id-with-subscriber
(e/ungrant-by-search (s/context)
{:provider "PROV1"
:target ["SUBSCRIPTION_MANAGEMENT" "INGEST_MANAGEMENT_ACL"]})
(ac-util/wait-until-indexed)
(let [coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(doseq [accept-format [mt/umm-json]]
(let [suffix (if accept-format
(mt/mime-type->format accept-format)
"nil")
subscriber-token (e/login (s/context) "subscriber")
sub1-r1-name (str "s1-r1" suffix)
native-id (str "subscription1" suffix)
sub1-r1 (subscription/ingest-subscription (subscription/make-subscription-concept
{:Name sub1-r1-name
:CollectionConceptId (:concept-id coll1)
:SubscriberId "subscriber"
:native-id native-id})
{:token "mock-echo-system-token"})
concept-id (:concept-id sub1-r1)
sub1-concept (mdb/get-concept concept-id)]
(index/wait-until-indexed)
(testing "retrieval by subscription concept-id and revision id returns the specified revision"
(assert-retrieved-concept-as-subscriber concept-id 1 accept-format sub1-r1-name subscriber-token))
(testing "retrieval by only subscription concept-id returns the latest revision"
(assert-retrieved-concept-as-subscriber concept-id nil accept-format sub1-r1-name subscriber-token))
(testing "retrieval by non-existent revision returns error"
(assert-retrieved-concept-as-subscriber-recieved-error concept-id 3 accept-format 404 subscriber-token
(format "Concept with concept-id [%s] and revision-id [3] does not exist." concept-id)))
(testing "retrieval by non-existent concept-id returns error"
(assert-retrieved-concept-as-subscriber-recieved-error "SUB404404404-PROV1" nil accept-format 404 subscriber-token
"Concept with concept-id [SUB404404404-PROV1] could not be found."))
(testing "retrieval by non-existent concept-id and revision-id returns error"
(assert-retrieved-concept-as-subscriber-recieved-error "SUB404404404-PROV1" 1 accept-format 404 subscriber-token
"Concept with concept-id [SUB404404404-PROV1] and revision-id [1] does not exist."))
(testing "retrieval of deleted concept"
;; delete the subscription concept
(ingest/delete-concept sub1-concept (subscription/token-opts "mock-echo-system-token"))
(index/wait-until-indexed)
(testing "retrieval of deleted concept without revision id results in error"
(assert-retrieved-concept-as-subscriber-recieved-error concept-id nil accept-format 404 subscriber-token
(format "Concept with concept-id [%s] could not be found." concept-id)))
(testing "retrieval of deleted concept with revision id returns a 400 error"
(assert-retrieved-concept-as-subscriber-recieved-error concept-id 2 accept-format 400 subscriber-token
(format (str "The revision [2] of concept [%s] represents "
"a deleted concept and does not contain metadata.")
concept-id))))))))
| true | (ns cmr.system-int-test.search.subscription.concept-retrieval-test
"Integration test for subscription retrieval via the following endpoints:
* /concepts/:concept-id
* /concepts/:concept-id/:revision-id"
(:require
[cheshire.core :as json]
[clojure.test :refer :all]
[cmr.access-control.test.util :as ac-util]
[cmr.common.mime-types :as mt]
[cmr.mock-echo.client.echo-util :as e]
[cmr.system-int-test.data2.core :as data-core]
[cmr.system-int-test.data2.umm-spec-collection :as data-umm-c]
[cmr.system-int-test.system :as s]
[cmr.system-int-test.utils.index-util :as index]
[cmr.system-int-test.utils.ingest-util :as ingest]
[cmr.system-int-test.utils.metadata-db-util :as mdb]
[cmr.system-int-test.utils.search-util :as search]
[cmr.system-int-test.utils.subscription-util :as subscription]))
(use-fixtures
:each
(join-fixtures
[(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2"})
(subscription/grant-all-subscription-fixture {"provguid1" "PROV1"} [:read :update] [:read :update])
(subscription/grant-all-subscription-fixture {"provguid2" "PROV2"} [:update] [:read :update])]))
(defn- assert-retrieved-concept-as-subscriber
"Verify the retrieved concept by checking against the expected subscription name,
which we have deliberately set to be different for each concept revision."
[concept-id revision-id accept-format expected-subscription-name token]
(let [{:keys [status body]} (search/retrieve-concept
concept-id revision-id {:accept accept-format
:query-params {:token token}})]
(is (= 200 status))
(is (= expected-subscription-name
(:Name (json/parse-string body true))))))
(defn- assert-retrieved-concept
"Verify the retrieved concept by checking against the expected subscription name,
which we have deliberately set to be different for each concept revision."
[concept-id revision-id accept-format expected-subscription-name]
(let [{:keys [status body]} (search/retrieve-concept
concept-id revision-id {:accept accept-format})]
(is (= 200 status))
(is (= expected-subscription-name
(:Name (json/parse-string body true))))))
(defn- assert-retrieved-concept-with-registered-user
"Verify the retrieved concept by checking against the expected subscription name,
which we have deliberately set to be different for each concept revision."
[concept-id revision-id accept-format expected-subscription-name]
(let [user1-token (e/login (s/context) "user1")
{:keys [status body]} (search/retrieve-concept
concept-id revision-id {:accept accept-format
:query-params {:token user1-token}})]
(is (= 200 status))
(is (= expected-subscription-name
(:Name (json/parse-string body true))))))
(defmulti handle-retrieve-concept-error
"Execute the retrieve concept call with the given parameters and returns the status and errors
based on the result format."
(fn [concept-id revision-id accept-format]
accept-format))
(defmethod handle-retrieve-concept-error mt/umm-json
[concept-id revision-id accept-format]
(let [{:keys [status body]} (search/retrieve-concept concept-id revision-id
{:accept accept-format})
errors (:errors (json/parse-string body true))]
{:status status :errors errors}))
(defmethod handle-retrieve-concept-error :default
[concept-id revision-id accept-format]
(search/get-search-failure-xml-data
(search/retrieve-concept concept-id revision-id {:accept accept-format
:throw-exceptions true})))
(defn- assert-retrieved-concept-error
"Verify the expected error code and error message are returned when retrieving the given concept."
[concept-id revision-id accept-format err-code err-message]
(let [{:keys [status errors]} (handle-retrieve-concept-error
concept-id revision-id accept-format)]
(is (= err-code status))
(is (= [err-message] errors))))
(defmulti handle-retrieve-concept-as-subscriber-error
"Execute the retrieve concept call with the given parameters and returns the status and errors
based on the result format."
(fn [concept-id revision-id accept-format token]
accept-format))
(defmethod handle-retrieve-concept-as-subscriber-error mt/umm-json
[concept-id revision-id accept-format token]
(let [{:keys [status body]} (search/retrieve-concept concept-id revision-id
{:accept accept-format
:query-params {:token token}})
errors (:errors (json/parse-string body true))]
{:status status :errors errors}))
(defmethod handle-retrieve-concept-as-subscriber-error :default
[concept-id revision-id accept-format token]
(search/get-search-failure-xml-data
(search/retrieve-concept concept-id revision-id {:accept accept-format
:query-params {:token token}
:throw-exceptions true})))
(defn- assert-retrieved-concept-as-subscriber-recieved-error
"Verify the expected error code and error message are returned when retrieving the given concept."
[concept-id revision-id accept-format err-code token err-message]
(let [{:keys [status errors]} (handle-retrieve-concept-as-subscriber-error
concept-id revision-id accept-format token)]
(is (= err-code status))
(is (= [err-message] errors))))
(deftest retrieve-subscription-by-concept-id-various-read-permission
;; We support UMM JSON format; No format and any format are also accepted.
(let [coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "PI:PASSWORD:<PASSWORD>END_PI"})]
(doseq [accept-format [mt/umm-json]];; nil mt/any]]
(let [suffix (if accept-format
(mt/mime-type->format accept-format)
"nil")
;; append result format to subscription name to make it unique
;; for different formats so that the test can be run for multiple formats
sub1-r1-name (str "s1-r1" suffix)
sub1-r2-name (str "s1-r2" suffix)
native-id (str "subscription1" suffix)
sub1-r1 (subscription/ingest-subscription-with-attrs {:provider-id "PROV2"
:Name sub1-r1-name
:CollectionConceptId (:concept-id coll1)
:native-id native-id})
sub1-r2 (subscription/ingest-subscription-with-attrs {:provider-id "PROV2"
:Name sub1-r2-name
:CollectionConceptId (:concept-id coll1)
:native-id native-id})
concept-id (:concept-id sub1-r1)]
(index/wait-until-indexed)
(testing "Sanity check that the test subscription got updated and its revision id was incremented"
(is (= concept-id (:concept-id sub1-r2)))
(is (= 1 (:revision-id sub1-r1)))
(is (= 2 (:revision-id sub1-r2))))
;; no read permission granted for guest on provider "PROV2" so, no subscription could be found.
(testing "retrieval by subscription concept-id and revision id returns error"
(assert-retrieved-concept-error concept-id 1 accept-format 404
(format "Concept with concept-id [%s] and revision-id [1] could not be found." concept-id))
(assert-retrieved-concept-error concept-id 2 accept-format 404
(format "Concept with concept-id [%s] and revision-id [2] could not be found." concept-id)))
(testing "retrieval by only subscription concept-id returns error"
(assert-retrieved-concept-error concept-id nil accept-format 404
(format "Concept with concept-id [%s] could not be found." concept-id)))
;; read permission is granted for registered user, subscriptions will be found
(testing "retrieval by subscription concept-id and revision id returns the specified revision"
(assert-retrieved-concept-with-registered-user concept-id 1 accept-format sub1-r1-name)
(assert-retrieved-concept-with-registered-user concept-id 2 accept-format sub1-r2-name))
(testing "retrieval by only subscription concept-id returns the latest revision"
(assert-retrieved-concept-with-registered-user concept-id nil accept-format sub1-r2-name))))))
(deftest retrieve-subscription-by-concept-id
;; We support UMM JSON format; No format and any format are also accepted.
(let [coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(doseq [accept-format [mt/umm-json]];; nil mt/any]]
(let [suffix (if accept-format
(mt/mime-type->format accept-format)
"nil")
;; append result format to subscription name to make it unique
;; for different formats so that the test can be run for multiple formats
sub1-r1-name (str "s1-r1" suffix)
sub1-r2-name (str "s1-r2" suffix)
native-id (str "subscription1" suffix)
sub1-r1 (subscription/ingest-subscription-with-attrs {:Name sub1-r1-name
:CollectionConceptId (:concept-id coll1)
:native-id native-id})
sub1-r2 (subscription/ingest-subscription-with-attrs {:Name sub1-r2-name
:CollectionConceptId (:concept-id coll1)
:native-id native-id})
concept-id (:concept-id sub1-r1)
sub1-concept (mdb/get-concept concept-id)]
(index/wait-until-indexed)
(testing "Sanity check that the test subscription got updated and its revision id was incremented"
(is (= concept-id (:concept-id sub1-r2)))
(is (= 1 (:revision-id sub1-r1)))
(is (= 2 (:revision-id sub1-r2))))
(testing "retrieval by subscription concept-id and revision id returns the specified revision"
(assert-retrieved-concept concept-id 1 accept-format sub1-r1-name)
(assert-retrieved-concept concept-id 2 accept-format sub1-r2-name))
(testing "retrieval by only subscription concept-id returns the latest revision"
(assert-retrieved-concept concept-id nil accept-format sub1-r2-name))
(testing "retrieval by non-existent revision returns error"
(assert-retrieved-concept-error concept-id 3 accept-format 404
(format "Concept with concept-id [%s] and revision-id [3] does not exist." concept-id)))
(testing "retrieval by non-existent concept-id returns error"
(assert-retrieved-concept-error "SUB404404404-PROV1" nil accept-format 404
"Concept with concept-id [SUB404404404-PROV1] could not be found."))
(testing "retrieval by non-existent concept-id and revision-id returns error"
(assert-retrieved-concept-error "SUB404404404-PROV1" 1 accept-format 404
"Concept with concept-id [SUB404404404-PROV1] and revision-id [1] does not exist."))
(testing "retrieval of deleted concept"
;; delete the subscription concept
(ingest/delete-concept sub1-concept (subscription/token-opts (e/login (s/context) "user1")))
(index/wait-until-indexed)
(testing "retrieval of deleted concept without revision id results in error"
(assert-retrieved-concept-error concept-id nil accept-format 404
(format "Concept with concept-id [%s] could not be found." concept-id)))
(testing "retrieval of deleted concept with revision id returns a 400 error"
(assert-retrieved-concept-error concept-id 3 accept-format 400
(format (str "The revision [3] of concept [%s] represents "
"a deleted concept and does not contain metadata.")
concept-id))))))))
(deftest retrieve-subscription-with-invalid-format
(testing "unsupported accept header results in error"
(let [unsupported-mt "unsupported/mime-type"]
(assert-retrieved-concept-error "SUB1111-PROV1" nil unsupported-mt 400
(format "The mime types specified in the accept header [%s] are not supported."
unsupported-mt)))))
(deftest retrieve-subscription-by-concept-id-with-subscriber
(e/ungrant-by-search (s/context)
{:provider "PROV1"
:target ["SUBSCRIPTION_MANAGEMENT" "INGEST_MANAGEMENT_ACL"]})
(ac-util/wait-until-indexed)
(let [coll1 (data-core/ingest-umm-spec-collection "PROV1"
(data-umm-c/collection
{:ShortName "coll1"
:EntryTitle "entry-title1"})
{:token "mock-echo-system-token"})]
(doseq [accept-format [mt/umm-json]]
(let [suffix (if accept-format
(mt/mime-type->format accept-format)
"nil")
subscriber-token (e/login (s/context) "subscriber")
sub1-r1-name (str "s1-r1" suffix)
native-id (str "subscription1" suffix)
sub1-r1 (subscription/ingest-subscription (subscription/make-subscription-concept
{:Name sub1-r1-name
:CollectionConceptId (:concept-id coll1)
:SubscriberId "subscriber"
:native-id native-id})
{:token "mock-echo-system-token"})
concept-id (:concept-id sub1-r1)
sub1-concept (mdb/get-concept concept-id)]
(index/wait-until-indexed)
(testing "retrieval by subscription concept-id and revision id returns the specified revision"
(assert-retrieved-concept-as-subscriber concept-id 1 accept-format sub1-r1-name subscriber-token))
(testing "retrieval by only subscription concept-id returns the latest revision"
(assert-retrieved-concept-as-subscriber concept-id nil accept-format sub1-r1-name subscriber-token))
(testing "retrieval by non-existent revision returns error"
(assert-retrieved-concept-as-subscriber-recieved-error concept-id 3 accept-format 404 subscriber-token
(format "Concept with concept-id [%s] and revision-id [3] does not exist." concept-id)))
(testing "retrieval by non-existent concept-id returns error"
(assert-retrieved-concept-as-subscriber-recieved-error "SUB404404404-PROV1" nil accept-format 404 subscriber-token
"Concept with concept-id [SUB404404404-PROV1] could not be found."))
(testing "retrieval by non-existent concept-id and revision-id returns error"
(assert-retrieved-concept-as-subscriber-recieved-error "SUB404404404-PROV1" 1 accept-format 404 subscriber-token
"Concept with concept-id [SUB404404404-PROV1] and revision-id [1] does not exist."))
(testing "retrieval of deleted concept"
;; delete the subscription concept
(ingest/delete-concept sub1-concept (subscription/token-opts "mock-echo-system-token"))
(index/wait-until-indexed)
(testing "retrieval of deleted concept without revision id results in error"
(assert-retrieved-concept-as-subscriber-recieved-error concept-id nil accept-format 404 subscriber-token
(format "Concept with concept-id [%s] could not be found." concept-id)))
(testing "retrieval of deleted concept with revision id returns a 400 error"
(assert-retrieved-concept-as-subscriber-recieved-error concept-id 2 accept-format 400 subscriber-token
(format (str "The revision [2] of concept [%s] represents "
"a deleted concept and does not contain metadata.")
concept-id))))))))
|
[
{
"context": "I\n; Date: February 25, 2016.\n; Authors:\n; A01020319 Fernando Gómez Herrera\n;-----------------",
"end": 145,
"score": 0.505190372467041,
"start": 144,
"tag": "USERNAME",
"value": "A"
},
{
"context": "February 25, 2016.\n; Authors:\n; A01020319 Fernando Gómez Herrera\n;------------------------------------------------",
"end": 176,
"score": 0.9998648166656494,
"start": 154,
"tag": "NAME",
"value": "Fernando Gómez Herrera"
}
] | sequences.clj | gomezhyuuga/CEM_tc2006 | 1 | ;----------------------------------------------------------
; Activity: Using the Sequence API
; Date: February 25, 2016.
; Authors:
; A01020319 Fernando Gómez Herrera
;----------------------------------------------------------
(use 'clojure.test)
(defn positives
"Takes a list of numbers lst as its argument, and returns a new list that
only contains the positive numbers of lst."
[lst]
(filter pos? lst))
(defn dot-product
"Takes two arguments: the lists a and b. It returns the result of performing
the dot product of a times b."
[a b]
(cond
(empty? a) 0
(empty? b) 0
:else (reduce + (map (fn [one two] (* one two)) a b))))
(defn pow
"Takes two arguments as input: a number a and a positive integer b. It returns
the result of computing a raised to the power b."
[a b]
(reduce * (repeat b a)))
(defn replic
"takes two arguments: a list lst and an integer number n, where n ≥ 0. It
returns a new list that replicates n times each element contained in lst."
[n lst]
(mapcat (fn [el] (repeat n el)) lst))
(defn expand
"Takes a list lst as its argument. It returns a list where the first element
of lst appears one time, the second elements appears two times, the third
element appears three times, and so on."
[lst]
(mapcat identity (map-indexed (fn [index item] (repeat (inc index) item)) lst)))
(defn largest
"Takes as argument a nonempty list of numbers lst. It returns the largest
value contained in lst. Use the reduce function to solve this problem."
[lst]
(reduce (fn [a b] (if (> a b) a b)) lst))
(defn drop-every
"Takes two arguments: an integer number n, where n ≥ 1, and a list lst. It
returns a new list that drops every n-th element from lst."
[n lst]
(remove list? (map-indexed (fn [index item] (if (not (zero? (rem (inc index) n))) item ())) lst)))
(defn rotate-left
"Takes two arguments: an integer number n and a list lst. It returns the list
that results from rotating lst a total of n elements to the left. If n is
negative, it rotates to the right."
[n lst]
(if (empty? lst)
()
(let [rotations (mod n (count lst))]
(concat (drop rotations lst) (take rotations lst)))))
(defn gcd
"Takes two positive integer arguments a and b as arguments, where a > 0 and b
> 0. It returns the greatest common divisor (GCD) of a and b."
[a b]
(let [n (min a b)]
(->>
(iterate (fn [[f, s, n]] [f, s, (dec n)]) [a, b, n])
(map (fn [[f, s, n]] [(+ (rem f n) (rem s n)), n]))
(drop-while (fn [[g, n]] (not (zero? g))))
first
second)))
(defn insert-everywhere
"Takes two arguments as input: an object x and a list lst. It returns a new
list with all the possible ways in which x can be inserted into every position
of lst"
[x lst]
(->>
(range 0 (inc (count lst)))
(map #(let [[t h] (split-at % lst)]
(concat t (list x) h)))))
(deftest test-positives
(is (= () (positives '())))
(is (= () (positives '(-4 -1 -10 -13 -5))))
(is (= '(3 6) (positives '(-4 3 -1 -10 -13 6 -5))))
(is (= '(4 3 1 10 13 6 5) (positives '(4 3 1 10 13 6 5)))))
(deftest test-dot-product
(is (= 0 (dot-product () ())))
(is (= 32 (dot-product '(1 2 3) '(4 5 6))))
(is (= 21.45 (dot-product '(1.3 3.4 5.7 9.5 10.4) '(-4.5 3.0 1.5 0.9 0.0)))))
(deftest test-pow
(is (= 1 (pow 0 0)))
(is (= 0 (pow 0 1)))
(is (= 1 (pow 5 0)))
(is (= 5 (pow 5 1)))
(is (= 125 (pow 5 3)))
(is (= 25 (pow -5 2)))
(is (= -125 (pow -5 3)))
(is (= 1024 (pow 2 10)))
(is (= 525.21875 (pow 3.5 5)))
(is (= 129746337890625 (pow 15 12)))
(is (= 3909821048582988049 (pow 7 22))))
(deftest test-replic
(is (= () (replic 7 ())))
(is (= () (replic 0 '(a b c))))
(is (= '(a a a) (replic 3 '(a))))
(is (= '(1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4) (replic 4 '(1 2 3 4)))))
(deftest test-expand
(is (= () (expand ())))
(is (= '(a) (expand '(a))))
(is (= '(1 2 2 3 3 3 4 4 4 4) (expand '(1 2 3 4))))
(is (= '(a b b c c c d d d d e e e e e) (expand '(a b c d e)))))
(deftest test-largest
(is (= 31 (largest '(31))))
(is (= 5 (largest '(1 2 3 4 5))))
(is (= -1 (largest '(-1 -2 -3 -4 -5))))
(is (= 52 (largest '(32 -1 45 12 -42 52 17 0 21 2)))))
(deftest test-drop-every
(is (= () (drop-every 5 ())))
(is (= '(1 2 3) (drop-every 4 '(1 2 3 4))))
(is (= '(1 3 5 7) (drop-every 2 '(1 2 3 4 5 6 7 8))))
(is (= '(1 3 5 7 9) (drop-every 2 '(1 2 3 4 5 6 7 8 9))))
(is (= '(a b d e g h j) (drop-every 3 '(a b c d e f g h i j))))
(is (= '(a b c d e f g h i j)
(drop-every 20 '(a b c d e f g h i j))))
(is (= () (drop-every 1 '(a b c d e f g h i j)))))
(deftest test-rotate-left
(is (= () (rotate-left 5 ())))
(is (= '(a b c d e f g) (rotate-left 0 '(a b c d e f g))))
(is (= '(b c d e f g a) (rotate-left 1 '(a b c d e f g))))
(is (= '(g a b c d e f) (rotate-left -1 '(a b c d e f g))))
(is (= '(d e f g a b c) (rotate-left 3 '(a b c d e f g))))
(is (= '(e f g a b c d) (rotate-left -3 '(a b c d e f g))))
(is (= '(a b c d e f g) (rotate-left 7 '(a b c d e f g))))
(is (= '(a b c d e f g) (rotate-left -7 '(a b c d e f g))))
(is (= '(b c d e f g a) (rotate-left 8 '(a b c d e f g))))
(is (= '(g a b c d e f) (rotate-left -8 '(a b c d e f g))))
(is (= '(d e f g a b c) (rotate-left 45 '(a b c d e f g))))
(is (= '(e f g a b c d) (rotate-left -45 '(a b c d e f g)))))
(deftest test-gcd
(is (= 1 (gcd 13 7919)))
(is (= 4 (gcd 20 16)))
(is (= 6 (gcd 54 24)))
(is (= 7 (gcd 6307 1995)))
(is (= 12 (gcd 48 180)))
(is (= 14 (gcd 42 56))))
(deftest test-insert-everywhere
(is (= '((1)) (insert-everywhere 1 ())))
(is (= '((1 a) (a 1)) (insert-everywhere 1 '(a))))
(is (= '((1 a b c) (a 1 b c) (a b 1 c) (a b c 1))
(insert-everywhere 1 '(a b c))))
(is (= '((1 a b c d e)
(a 1 b c d e)
(a b 1 c d e)
(a b c 1 d e)
(a b c d 1 e)
(a b c d e 1))
(insert-everywhere 1 '(a b c d e))))
(is (= '((x 1 2 3 4 5 6 7 8 9 10)
(1 x 2 3 4 5 6 7 8 9 10)
(1 2 x 3 4 5 6 7 8 9 10)
(1 2 3 x 4 5 6 7 8 9 10)
(1 2 3 4 x 5 6 7 8 9 10)
(1 2 3 4 5 x 6 7 8 9 10)
(1 2 3 4 5 6 x 7 8 9 10)
(1 2 3 4 5 6 7 x 8 9 10)
(1 2 3 4 5 6 7 8 x 9 10)
(1 2 3 4 5 6 7 8 9 x 10)
(1 2 3 4 5 6 7 8 9 10 x))
(insert-everywhere 'x '(1 2 3 4 5 6 7 8 9 10)))))
(run-tests)
| 75167 | ;----------------------------------------------------------
; Activity: Using the Sequence API
; Date: February 25, 2016.
; Authors:
; A01020319 <NAME>
;----------------------------------------------------------
(use 'clojure.test)
(defn positives
"Takes a list of numbers lst as its argument, and returns a new list that
only contains the positive numbers of lst."
[lst]
(filter pos? lst))
(defn dot-product
"Takes two arguments: the lists a and b. It returns the result of performing
the dot product of a times b."
[a b]
(cond
(empty? a) 0
(empty? b) 0
:else (reduce + (map (fn [one two] (* one two)) a b))))
(defn pow
"Takes two arguments as input: a number a and a positive integer b. It returns
the result of computing a raised to the power b."
[a b]
(reduce * (repeat b a)))
(defn replic
"takes two arguments: a list lst and an integer number n, where n ≥ 0. It
returns a new list that replicates n times each element contained in lst."
[n lst]
(mapcat (fn [el] (repeat n el)) lst))
(defn expand
"Takes a list lst as its argument. It returns a list where the first element
of lst appears one time, the second elements appears two times, the third
element appears three times, and so on."
[lst]
(mapcat identity (map-indexed (fn [index item] (repeat (inc index) item)) lst)))
(defn largest
"Takes as argument a nonempty list of numbers lst. It returns the largest
value contained in lst. Use the reduce function to solve this problem."
[lst]
(reduce (fn [a b] (if (> a b) a b)) lst))
(defn drop-every
"Takes two arguments: an integer number n, where n ≥ 1, and a list lst. It
returns a new list that drops every n-th element from lst."
[n lst]
(remove list? (map-indexed (fn [index item] (if (not (zero? (rem (inc index) n))) item ())) lst)))
(defn rotate-left
"Takes two arguments: an integer number n and a list lst. It returns the list
that results from rotating lst a total of n elements to the left. If n is
negative, it rotates to the right."
[n lst]
(if (empty? lst)
()
(let [rotations (mod n (count lst))]
(concat (drop rotations lst) (take rotations lst)))))
(defn gcd
"Takes two positive integer arguments a and b as arguments, where a > 0 and b
> 0. It returns the greatest common divisor (GCD) of a and b."
[a b]
(let [n (min a b)]
(->>
(iterate (fn [[f, s, n]] [f, s, (dec n)]) [a, b, n])
(map (fn [[f, s, n]] [(+ (rem f n) (rem s n)), n]))
(drop-while (fn [[g, n]] (not (zero? g))))
first
second)))
(defn insert-everywhere
"Takes two arguments as input: an object x and a list lst. It returns a new
list with all the possible ways in which x can be inserted into every position
of lst"
[x lst]
(->>
(range 0 (inc (count lst)))
(map #(let [[t h] (split-at % lst)]
(concat t (list x) h)))))
(deftest test-positives
(is (= () (positives '())))
(is (= () (positives '(-4 -1 -10 -13 -5))))
(is (= '(3 6) (positives '(-4 3 -1 -10 -13 6 -5))))
(is (= '(4 3 1 10 13 6 5) (positives '(4 3 1 10 13 6 5)))))
(deftest test-dot-product
(is (= 0 (dot-product () ())))
(is (= 32 (dot-product '(1 2 3) '(4 5 6))))
(is (= 21.45 (dot-product '(1.3 3.4 5.7 9.5 10.4) '(-4.5 3.0 1.5 0.9 0.0)))))
(deftest test-pow
(is (= 1 (pow 0 0)))
(is (= 0 (pow 0 1)))
(is (= 1 (pow 5 0)))
(is (= 5 (pow 5 1)))
(is (= 125 (pow 5 3)))
(is (= 25 (pow -5 2)))
(is (= -125 (pow -5 3)))
(is (= 1024 (pow 2 10)))
(is (= 525.21875 (pow 3.5 5)))
(is (= 129746337890625 (pow 15 12)))
(is (= 3909821048582988049 (pow 7 22))))
(deftest test-replic
(is (= () (replic 7 ())))
(is (= () (replic 0 '(a b c))))
(is (= '(a a a) (replic 3 '(a))))
(is (= '(1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4) (replic 4 '(1 2 3 4)))))
(deftest test-expand
(is (= () (expand ())))
(is (= '(a) (expand '(a))))
(is (= '(1 2 2 3 3 3 4 4 4 4) (expand '(1 2 3 4))))
(is (= '(a b b c c c d d d d e e e e e) (expand '(a b c d e)))))
(deftest test-largest
(is (= 31 (largest '(31))))
(is (= 5 (largest '(1 2 3 4 5))))
(is (= -1 (largest '(-1 -2 -3 -4 -5))))
(is (= 52 (largest '(32 -1 45 12 -42 52 17 0 21 2)))))
(deftest test-drop-every
(is (= () (drop-every 5 ())))
(is (= '(1 2 3) (drop-every 4 '(1 2 3 4))))
(is (= '(1 3 5 7) (drop-every 2 '(1 2 3 4 5 6 7 8))))
(is (= '(1 3 5 7 9) (drop-every 2 '(1 2 3 4 5 6 7 8 9))))
(is (= '(a b d e g h j) (drop-every 3 '(a b c d e f g h i j))))
(is (= '(a b c d e f g h i j)
(drop-every 20 '(a b c d e f g h i j))))
(is (= () (drop-every 1 '(a b c d e f g h i j)))))
(deftest test-rotate-left
(is (= () (rotate-left 5 ())))
(is (= '(a b c d e f g) (rotate-left 0 '(a b c d e f g))))
(is (= '(b c d e f g a) (rotate-left 1 '(a b c d e f g))))
(is (= '(g a b c d e f) (rotate-left -1 '(a b c d e f g))))
(is (= '(d e f g a b c) (rotate-left 3 '(a b c d e f g))))
(is (= '(e f g a b c d) (rotate-left -3 '(a b c d e f g))))
(is (= '(a b c d e f g) (rotate-left 7 '(a b c d e f g))))
(is (= '(a b c d e f g) (rotate-left -7 '(a b c d e f g))))
(is (= '(b c d e f g a) (rotate-left 8 '(a b c d e f g))))
(is (= '(g a b c d e f) (rotate-left -8 '(a b c d e f g))))
(is (= '(d e f g a b c) (rotate-left 45 '(a b c d e f g))))
(is (= '(e f g a b c d) (rotate-left -45 '(a b c d e f g)))))
(deftest test-gcd
(is (= 1 (gcd 13 7919)))
(is (= 4 (gcd 20 16)))
(is (= 6 (gcd 54 24)))
(is (= 7 (gcd 6307 1995)))
(is (= 12 (gcd 48 180)))
(is (= 14 (gcd 42 56))))
(deftest test-insert-everywhere
(is (= '((1)) (insert-everywhere 1 ())))
(is (= '((1 a) (a 1)) (insert-everywhere 1 '(a))))
(is (= '((1 a b c) (a 1 b c) (a b 1 c) (a b c 1))
(insert-everywhere 1 '(a b c))))
(is (= '((1 a b c d e)
(a 1 b c d e)
(a b 1 c d e)
(a b c 1 d e)
(a b c d 1 e)
(a b c d e 1))
(insert-everywhere 1 '(a b c d e))))
(is (= '((x 1 2 3 4 5 6 7 8 9 10)
(1 x 2 3 4 5 6 7 8 9 10)
(1 2 x 3 4 5 6 7 8 9 10)
(1 2 3 x 4 5 6 7 8 9 10)
(1 2 3 4 x 5 6 7 8 9 10)
(1 2 3 4 5 x 6 7 8 9 10)
(1 2 3 4 5 6 x 7 8 9 10)
(1 2 3 4 5 6 7 x 8 9 10)
(1 2 3 4 5 6 7 8 x 9 10)
(1 2 3 4 5 6 7 8 9 x 10)
(1 2 3 4 5 6 7 8 9 10 x))
(insert-everywhere 'x '(1 2 3 4 5 6 7 8 9 10)))))
(run-tests)
| true | ;----------------------------------------------------------
; Activity: Using the Sequence API
; Date: February 25, 2016.
; Authors:
; A01020319 PI:NAME:<NAME>END_PI
;----------------------------------------------------------
(use 'clojure.test)
(defn positives
"Takes a list of numbers lst as its argument, and returns a new list that
only contains the positive numbers of lst."
[lst]
(filter pos? lst))
(defn dot-product
"Takes two arguments: the lists a and b. It returns the result of performing
the dot product of a times b."
[a b]
(cond
(empty? a) 0
(empty? b) 0
:else (reduce + (map (fn [one two] (* one two)) a b))))
(defn pow
"Takes two arguments as input: a number a and a positive integer b. It returns
the result of computing a raised to the power b."
[a b]
(reduce * (repeat b a)))
(defn replic
"takes two arguments: a list lst and an integer number n, where n ≥ 0. It
returns a new list that replicates n times each element contained in lst."
[n lst]
(mapcat (fn [el] (repeat n el)) lst))
(defn expand
"Takes a list lst as its argument. It returns a list where the first element
of lst appears one time, the second elements appears two times, the third
element appears three times, and so on."
[lst]
(mapcat identity (map-indexed (fn [index item] (repeat (inc index) item)) lst)))
(defn largest
"Takes as argument a nonempty list of numbers lst. It returns the largest
value contained in lst. Use the reduce function to solve this problem."
[lst]
(reduce (fn [a b] (if (> a b) a b)) lst))
(defn drop-every
"Takes two arguments: an integer number n, where n ≥ 1, and a list lst. It
returns a new list that drops every n-th element from lst."
[n lst]
(remove list? (map-indexed (fn [index item] (if (not (zero? (rem (inc index) n))) item ())) lst)))
(defn rotate-left
"Takes two arguments: an integer number n and a list lst. It returns the list
that results from rotating lst a total of n elements to the left. If n is
negative, it rotates to the right."
[n lst]
(if (empty? lst)
()
(let [rotations (mod n (count lst))]
(concat (drop rotations lst) (take rotations lst)))))
(defn gcd
"Takes two positive integer arguments a and b as arguments, where a > 0 and b
> 0. It returns the greatest common divisor (GCD) of a and b."
[a b]
(let [n (min a b)]
(->>
(iterate (fn [[f, s, n]] [f, s, (dec n)]) [a, b, n])
(map (fn [[f, s, n]] [(+ (rem f n) (rem s n)), n]))
(drop-while (fn [[g, n]] (not (zero? g))))
first
second)))
(defn insert-everywhere
"Takes two arguments as input: an object x and a list lst. It returns a new
list with all the possible ways in which x can be inserted into every position
of lst"
[x lst]
(->>
(range 0 (inc (count lst)))
(map #(let [[t h] (split-at % lst)]
(concat t (list x) h)))))
(deftest test-positives
(is (= () (positives '())))
(is (= () (positives '(-4 -1 -10 -13 -5))))
(is (= '(3 6) (positives '(-4 3 -1 -10 -13 6 -5))))
(is (= '(4 3 1 10 13 6 5) (positives '(4 3 1 10 13 6 5)))))
(deftest test-dot-product
(is (= 0 (dot-product () ())))
(is (= 32 (dot-product '(1 2 3) '(4 5 6))))
(is (= 21.45 (dot-product '(1.3 3.4 5.7 9.5 10.4) '(-4.5 3.0 1.5 0.9 0.0)))))
(deftest test-pow
(is (= 1 (pow 0 0)))
(is (= 0 (pow 0 1)))
(is (= 1 (pow 5 0)))
(is (= 5 (pow 5 1)))
(is (= 125 (pow 5 3)))
(is (= 25 (pow -5 2)))
(is (= -125 (pow -5 3)))
(is (= 1024 (pow 2 10)))
(is (= 525.21875 (pow 3.5 5)))
(is (= 129746337890625 (pow 15 12)))
(is (= 3909821048582988049 (pow 7 22))))
(deftest test-replic
(is (= () (replic 7 ())))
(is (= () (replic 0 '(a b c))))
(is (= '(a a a) (replic 3 '(a))))
(is (= '(1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4) (replic 4 '(1 2 3 4)))))
(deftest test-expand
(is (= () (expand ())))
(is (= '(a) (expand '(a))))
(is (= '(1 2 2 3 3 3 4 4 4 4) (expand '(1 2 3 4))))
(is (= '(a b b c c c d d d d e e e e e) (expand '(a b c d e)))))
(deftest test-largest
(is (= 31 (largest '(31))))
(is (= 5 (largest '(1 2 3 4 5))))
(is (= -1 (largest '(-1 -2 -3 -4 -5))))
(is (= 52 (largest '(32 -1 45 12 -42 52 17 0 21 2)))))
(deftest test-drop-every
(is (= () (drop-every 5 ())))
(is (= '(1 2 3) (drop-every 4 '(1 2 3 4))))
(is (= '(1 3 5 7) (drop-every 2 '(1 2 3 4 5 6 7 8))))
(is (= '(1 3 5 7 9) (drop-every 2 '(1 2 3 4 5 6 7 8 9))))
(is (= '(a b d e g h j) (drop-every 3 '(a b c d e f g h i j))))
(is (= '(a b c d e f g h i j)
(drop-every 20 '(a b c d e f g h i j))))
(is (= () (drop-every 1 '(a b c d e f g h i j)))))
(deftest test-rotate-left
(is (= () (rotate-left 5 ())))
(is (= '(a b c d e f g) (rotate-left 0 '(a b c d e f g))))
(is (= '(b c d e f g a) (rotate-left 1 '(a b c d e f g))))
(is (= '(g a b c d e f) (rotate-left -1 '(a b c d e f g))))
(is (= '(d e f g a b c) (rotate-left 3 '(a b c d e f g))))
(is (= '(e f g a b c d) (rotate-left -3 '(a b c d e f g))))
(is (= '(a b c d e f g) (rotate-left 7 '(a b c d e f g))))
(is (= '(a b c d e f g) (rotate-left -7 '(a b c d e f g))))
(is (= '(b c d e f g a) (rotate-left 8 '(a b c d e f g))))
(is (= '(g a b c d e f) (rotate-left -8 '(a b c d e f g))))
(is (= '(d e f g a b c) (rotate-left 45 '(a b c d e f g))))
(is (= '(e f g a b c d) (rotate-left -45 '(a b c d e f g)))))
(deftest test-gcd
(is (= 1 (gcd 13 7919)))
(is (= 4 (gcd 20 16)))
(is (= 6 (gcd 54 24)))
(is (= 7 (gcd 6307 1995)))
(is (= 12 (gcd 48 180)))
(is (= 14 (gcd 42 56))))
(deftest test-insert-everywhere
(is (= '((1)) (insert-everywhere 1 ())))
(is (= '((1 a) (a 1)) (insert-everywhere 1 '(a))))
(is (= '((1 a b c) (a 1 b c) (a b 1 c) (a b c 1))
(insert-everywhere 1 '(a b c))))
(is (= '((1 a b c d e)
(a 1 b c d e)
(a b 1 c d e)
(a b c 1 d e)
(a b c d 1 e)
(a b c d e 1))
(insert-everywhere 1 '(a b c d e))))
(is (= '((x 1 2 3 4 5 6 7 8 9 10)
(1 x 2 3 4 5 6 7 8 9 10)
(1 2 x 3 4 5 6 7 8 9 10)
(1 2 3 x 4 5 6 7 8 9 10)
(1 2 3 4 x 5 6 7 8 9 10)
(1 2 3 4 5 x 6 7 8 9 10)
(1 2 3 4 5 6 x 7 8 9 10)
(1 2 3 4 5 6 7 x 8 9 10)
(1 2 3 4 5 6 7 8 x 9 10)
(1 2 3 4 5 6 7 8 9 x 10)
(1 2 3 4 5 6 7 8 9 10 x))
(insert-everywhere 'x '(1 2 3 4 5 6 7 8 9 10)))))
(run-tests)
|
[
{
"context": "----------------\n;; File project.clj\n;; Written by Chris Frisz\n;; \n;; Created 4 Feb 2012\n;; Last modified 3 Se",
"end": 118,
"score": 0.9998686909675598,
"start": 107,
"tag": "NAME",
"value": "Chris Frisz"
},
{
"context": "ant-space tail calls.\"\n :url \"https://github.com/cjfrisz/clojure-tco\"\n :license {:name \"The MIT License\"\n",
"end": 444,
"score": 0.979720413684845,
"start": 437,
"tag": "USERNAME",
"value": "cjfrisz"
}
] | project.clj | cjfrisz/clojure-tco | 64 | ;;----------------------------------------------------------------------
;; File project.clj
;; Written by Chris Frisz
;;
;; Created 4 Feb 2012
;; Last modified 3 Sep 2013
;;
;; Project declaration for clojure-tco.
;;----------------------------------------------------------------------
(defproject chrisfrisz.com/ctco "0.5.0"
:description "Improving Clojure's support for constant-space tail calls."
:url "https://github.com/cjfrisz/clojure-tco"
:license {:name "The MIT License"
:url "http://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure
"1.5.0-alpha3"]
[org.clojure/core.match "0.2.0-rc5"]]
:repl-options {:init-ns ctco.core
:init (println "It's TCO time, boys and girls")})
| 26667 | ;;----------------------------------------------------------------------
;; File project.clj
;; Written by <NAME>
;;
;; Created 4 Feb 2012
;; Last modified 3 Sep 2013
;;
;; Project declaration for clojure-tco.
;;----------------------------------------------------------------------
(defproject chrisfrisz.com/ctco "0.5.0"
:description "Improving Clojure's support for constant-space tail calls."
:url "https://github.com/cjfrisz/clojure-tco"
:license {:name "The MIT License"
:url "http://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure
"1.5.0-alpha3"]
[org.clojure/core.match "0.2.0-rc5"]]
:repl-options {:init-ns ctco.core
:init (println "It's TCO time, boys and girls")})
| true | ;;----------------------------------------------------------------------
;; File project.clj
;; Written by PI:NAME:<NAME>END_PI
;;
;; Created 4 Feb 2012
;; Last modified 3 Sep 2013
;;
;; Project declaration for clojure-tco.
;;----------------------------------------------------------------------
(defproject chrisfrisz.com/ctco "0.5.0"
:description "Improving Clojure's support for constant-space tail calls."
:url "https://github.com/cjfrisz/clojure-tco"
:license {:name "The MIT License"
:url "http://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure
"1.5.0-alpha3"]
[org.clojure/core.match "0.2.0-rc5"]]
:repl-options {:init-ns ctco.core
:init (println "It's TCO time, boys and girls")})
|
[
{
"context": "guration (sanitize (config/config config) [\"pwd\" \"passwd\"])}]\n (assoc\n (s/aggregate-",
"end": 2013,
"score": 0.9195526242256165,
"start": 2007,
"tag": "PASSWORD",
"value": "passwd"
}
] | core/src/gorillalabs/tesla/component/appstate.clj | gorillalabs/tesla | 7 | (ns gorillalabs.tesla.component.appstate
(:require [mount.core :as mnt]
[de.otto.status :as s]
[clojure.data.json :as json]
[clojure.tools.logging :as log]
[clojure.string :as str]
[clj-time.local :as local-time]
[gorillalabs.tesla.component.configuration :as config]
[clojure.string :refer [join split]]))
(declare appstate)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; internal helper functions
(defn- deconj [seq item]
(filterv (partial not= item) seq))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; functions to compile an aggregated appstate
(defmulti aggregation-strategy
"Selects the status aggregation strategy based upon config."
(fn [config]
(keyword (config/config config [:appstate :aggregation]))))
(defmethod aggregation-strategy :forgiving [_]
s/forgiving-strategy)
(defmethod aggregation-strategy :default [_]
s/strict-strategy)
(defn- keyword-to-state [kw]
(str/upper-case (name kw)))
(defn- sanitize-str [s]
(join (repeat (count s) "*")))
(defn- sanitize-mapentry [checklist [k v]]
{k (if (some true? (map #(.contains (name k) %) checklist))
(sanitize-str v)
v)})
(defn- sanitize [config checklist]
(into {}
(map (partial sanitize-mapentry checklist) config)))
(defn- system-infos [config]
{:systemTime (local-time/format-local-time (local-time/local-now) :date-time-no-ms)
:hostname (config/external-hostname config)
:port (config/external-port config)})
(defn current-state [appstate config]
(let [extra-info {:name (config/config config [:name])
:version (config/config config [:version])
:git (config/config config [:commit])
:configuration (sanitize (config/config config) ["pwd" "passwd"])}]
(assoc
(s/aggregate-status :application
(aggregation-strategy config)
@appstate
extra-info)
:system (system-infos config))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; http related stuff
(defn- to-json [compiled-state]
(into {} (map
(fn [[k v]]
{k (update-in v [:status] keyword-to-state)})
compiled-state)))
(defn- response-body [appstate config]
(-> (current-state appstate config)
(update-in [:application :statusDetails] to-json)
(update-in [:application :status] keyword-to-state)))
(defn- response [appstate config _]
{:status 200
:headers {"Content-Type" "application/json"}
:body (json/write-str (response-body appstate config))})
(defn route [config]
(config/config config [:appstate :path] "/state"))
(defn handler [appstate config]
(partial response appstate config))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; lifecycle functions
(defn- create-appstate []
(atom []))
(defn- start []
(log/info "-> start appstate")
(create-appstate))
(defn- stop [self]
(log/info "<- Stopping appstate")
(reset! self [])
self)
(mnt/defstate ^{:on-reload :noop}
appstate
:start (start)
:stop (stop appstate))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; API to this component
(defn register-state-fn [appstate state-fn]
(swap! appstate conj state-fn)
appstate)
(defn deregister-state-fn [appstate state-fn]
(swap! appstate deconj state-fn)
appstate)
| 112072 | (ns gorillalabs.tesla.component.appstate
(:require [mount.core :as mnt]
[de.otto.status :as s]
[clojure.data.json :as json]
[clojure.tools.logging :as log]
[clojure.string :as str]
[clj-time.local :as local-time]
[gorillalabs.tesla.component.configuration :as config]
[clojure.string :refer [join split]]))
(declare appstate)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; internal helper functions
(defn- deconj [seq item]
(filterv (partial not= item) seq))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; functions to compile an aggregated appstate
(defmulti aggregation-strategy
"Selects the status aggregation strategy based upon config."
(fn [config]
(keyword (config/config config [:appstate :aggregation]))))
(defmethod aggregation-strategy :forgiving [_]
s/forgiving-strategy)
(defmethod aggregation-strategy :default [_]
s/strict-strategy)
(defn- keyword-to-state [kw]
(str/upper-case (name kw)))
(defn- sanitize-str [s]
(join (repeat (count s) "*")))
(defn- sanitize-mapentry [checklist [k v]]
{k (if (some true? (map #(.contains (name k) %) checklist))
(sanitize-str v)
v)})
(defn- sanitize [config checklist]
(into {}
(map (partial sanitize-mapentry checklist) config)))
(defn- system-infos [config]
{:systemTime (local-time/format-local-time (local-time/local-now) :date-time-no-ms)
:hostname (config/external-hostname config)
:port (config/external-port config)})
(defn current-state [appstate config]
(let [extra-info {:name (config/config config [:name])
:version (config/config config [:version])
:git (config/config config [:commit])
:configuration (sanitize (config/config config) ["pwd" "<PASSWORD>"])}]
(assoc
(s/aggregate-status :application
(aggregation-strategy config)
@appstate
extra-info)
:system (system-infos config))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; http related stuff
(defn- to-json [compiled-state]
(into {} (map
(fn [[k v]]
{k (update-in v [:status] keyword-to-state)})
compiled-state)))
(defn- response-body [appstate config]
(-> (current-state appstate config)
(update-in [:application :statusDetails] to-json)
(update-in [:application :status] keyword-to-state)))
(defn- response [appstate config _]
{:status 200
:headers {"Content-Type" "application/json"}
:body (json/write-str (response-body appstate config))})
(defn route [config]
(config/config config [:appstate :path] "/state"))
(defn handler [appstate config]
(partial response appstate config))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; lifecycle functions
(defn- create-appstate []
(atom []))
(defn- start []
(log/info "-> start appstate")
(create-appstate))
(defn- stop [self]
(log/info "<- Stopping appstate")
(reset! self [])
self)
(mnt/defstate ^{:on-reload :noop}
appstate
:start (start)
:stop (stop appstate))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; API to this component
(defn register-state-fn [appstate state-fn]
(swap! appstate conj state-fn)
appstate)
(defn deregister-state-fn [appstate state-fn]
(swap! appstate deconj state-fn)
appstate)
| true | (ns gorillalabs.tesla.component.appstate
(:require [mount.core :as mnt]
[de.otto.status :as s]
[clojure.data.json :as json]
[clojure.tools.logging :as log]
[clojure.string :as str]
[clj-time.local :as local-time]
[gorillalabs.tesla.component.configuration :as config]
[clojure.string :refer [join split]]))
(declare appstate)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; internal helper functions
(defn- deconj [seq item]
(filterv (partial not= item) seq))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; functions to compile an aggregated appstate
(defmulti aggregation-strategy
"Selects the status aggregation strategy based upon config."
(fn [config]
(keyword (config/config config [:appstate :aggregation]))))
(defmethod aggregation-strategy :forgiving [_]
s/forgiving-strategy)
(defmethod aggregation-strategy :default [_]
s/strict-strategy)
(defn- keyword-to-state [kw]
(str/upper-case (name kw)))
(defn- sanitize-str [s]
(join (repeat (count s) "*")))
(defn- sanitize-mapentry [checklist [k v]]
{k (if (some true? (map #(.contains (name k) %) checklist))
(sanitize-str v)
v)})
(defn- sanitize [config checklist]
(into {}
(map (partial sanitize-mapentry checklist) config)))
(defn- system-infos [config]
{:systemTime (local-time/format-local-time (local-time/local-now) :date-time-no-ms)
:hostname (config/external-hostname config)
:port (config/external-port config)})
(defn current-state [appstate config]
(let [extra-info {:name (config/config config [:name])
:version (config/config config [:version])
:git (config/config config [:commit])
:configuration (sanitize (config/config config) ["pwd" "PI:PASSWORD:<PASSWORD>END_PI"])}]
(assoc
(s/aggregate-status :application
(aggregation-strategy config)
@appstate
extra-info)
:system (system-infos config))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; http related stuff
(defn- to-json [compiled-state]
(into {} (map
(fn [[k v]]
{k (update-in v [:status] keyword-to-state)})
compiled-state)))
(defn- response-body [appstate config]
(-> (current-state appstate config)
(update-in [:application :statusDetails] to-json)
(update-in [:application :status] keyword-to-state)))
(defn- response [appstate config _]
{:status 200
:headers {"Content-Type" "application/json"}
:body (json/write-str (response-body appstate config))})
(defn route [config]
(config/config config [:appstate :path] "/state"))
(defn handler [appstate config]
(partial response appstate config))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; lifecycle functions
(defn- create-appstate []
(atom []))
(defn- start []
(log/info "-> start appstate")
(create-appstate))
(defn- stop [self]
(log/info "<- Stopping appstate")
(reset! self [])
self)
(mnt/defstate ^{:on-reload :noop}
appstate
:start (start)
:stop (stop appstate))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; API to this component
(defn register-state-fn [appstate state-fn]
(swap! appstate conj state-fn)
appstate)
(defn deregister-state-fn [appstate state-fn]
(swap! appstate deconj state-fn)
appstate)
|
[
{
"context": "; Copyright (c) 2011-2013, Tom Van Cutsem, Vrije Universiteit Brussel\n; All rights reserved",
"end": 41,
"score": 0.9998576641082764,
"start": 27,
"tag": "NAME",
"value": "Tom Van Cutsem"
},
{
"context": "Clojure\n;; Multicore Programming\n;; (c) 2011-2013, Tom Van Cutsem\n\n;; version 1 - simple revision-based STM\n;; base",
"end": 1680,
"score": 0.9998174905776978,
"start": 1666,
"tag": "NAME",
"value": "Tom Van Cutsem"
}
] | stm/v1_simple.clj | tvcutsem/stm-in-clojure | 33 | ; Copyright (c) 2011-2013, Tom Van Cutsem, Vrije Universiteit Brussel
; 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 Vrije Universiteit Brussel 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 VRIJE UNIVERSITEIT BRUSSEL 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.
;; MC-STM: meta-circular STM in Clojure
;; Multicore Programming
;; (c) 2011-2013, Tom Van Cutsem
;; version 1 - simple revision-based STM
;; based on Daniel Spiwak's article:
;; http://www.codecommit.com/blog/scala/software-transactional-memory-in-scala
;; Limitations:
;; - internal consistency is not guaranteed
;; (a transaction may read a value for a ref before another transaction T
;; committed, and read a value for another ref after T committed,
;; leading to potentially mutually inconsistent ref values)
;; - a single global commit-lock for all transactions
;; (= bottleneck, but makes it easy to validate and commit)
;; (note: lock only acquired on commit, not while running the transaction!)
;; - naive support for commute
;; - naive support for ensure (to prevent write skew)
(ns stm.v1-simple)
;; === MC-STM internals ===
; a thread-local var that holds the current transaction executed by this thread
; if the thread does not execute a transaction, this is set to nil
(def ^:dynamic *current-transaction* nil)
(def NEXT_TRANSACTION_ID (atom 0))
(defn make-transaction
"create and return a new transaction data structure"
[]
{ :id (swap! NEXT_TRANSACTION_ID inc),
:in-tx-values (atom {}), ; map: ref -> any value
:written-refs (atom #{}), ; set of refs
:last-seen-rev (atom {}) }) ; map: ref -> revision id
(defn tx-read
"read the value of ref inside transaction tx"
[tx ref]
(let [in-tx-values (:in-tx-values tx)]
(if (contains? @in-tx-values ref)
(@in-tx-values ref) ; return the in-tx-value
; important: read both ref's value and revision atomically
(let [{in-tx-value :value
read-revision :revision} @ref]
; cache the value
(swap! in-tx-values assoc ref in-tx-value)
; remember first revision read
(swap! (:last-seen-rev tx) assoc ref read-revision)
in-tx-value)))) ; save and return the ref's value
(defn tx-write
"write val to ref inside transaction tx"
[tx ref val]
(swap! (:in-tx-values tx) assoc ref val)
(swap! (:written-refs tx) conj ref)
(if (not (contains? @(:last-seen-rev tx) ref))
; remember first revision written
(swap! (:last-seen-rev tx) assoc ref (:revision @ref)))
val)
; a single global lock for all transactions to acquire on commit
; we use the monitor of a fresh empty Java object
; all threads share the same root-binding, so will acquire the same lock
(def COMMIT_LOCK (new java.lang.Object))
(defn tx-commit
"returns a boolean indicating whether tx committed successfully"
[tx]
(let [validate
(fn [refs]
(every? (fn [ref]
(= (:revision @ref)
(@(:last-seen-rev tx) ref))) refs))]
(locking COMMIT_LOCK
(let [in-tx-values @(:in-tx-values tx)
success (validate (keys in-tx-values))]
(if success
; if validation OK, make in-tx-value of all written refs public
(doseq [ref @(:written-refs tx)]
(swap! ref assoc
:value (in-tx-values ref)
:revision (:id tx) )))
success))))
(defn tx-run
"runs zero-argument fun as the body of transaction tx"
[tx fun]
(let [result (binding [*current-transaction* tx] (fun))]
(if (tx-commit tx)
result ; commit succeeded, return result
(recur (make-transaction) fun)))) ; commit failed, retry with fresh tx
;; === MC-STM public API ===
(defn mc-ref [val]
(atom {:value val
:revision 0}))
; Note: an alternative but perhaps less accessible way to code up these
; functions would be to redefine mc-deref and mc-ref-set in the scope of
; a running transaction using 'binding', avoiding the if-test
(defn mc-deref [ref]
(if (nil? *current-transaction*)
; reading a ref outside of a transaction
(:value @ref)
; reading a ref inside a transaction
(tx-read *current-transaction* ref)))
(defn mc-ref-set [ref newval]
(if (nil? *current-transaction*)
; writing a ref outside of a transaction
(throw (IllegalStateException. "can't set mc-ref outside transaction"))
; writing a ref inside a transaction
(tx-write *current-transaction* ref newval)))
(defn mc-alter [ref fun & args]
(mc-ref-set ref (apply fun (mc-deref ref) args)))
; naive but correct implementation of commute
; naive because two transactions that commute the same ref will be
; in conflict, while they should not be (that's the whole point of commute)
(defn mc-commute [ref fun & args]
(apply mc-alter ref fun args))
; naive implementation of ensure
; naive because two transactions that ensure the same ref will
; be in conflict, while they should not be
(defn mc-ensure [ref]
(mc-alter ref identity))
(defmacro mc-dosync [& exps]
`(mc-sync (fn [] ~@exps)))
(defn mc-sync [fun]
(if (nil? *current-transaction*)
(tx-run (make-transaction) fun)
(fun))) ; nested dosync blocks implicitly run in the parent transaction | 112105 | ; Copyright (c) 2011-2013, <NAME>, Vrije Universiteit Brussel
; 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 Vrije Universiteit Brussel 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 VRIJE UNIVERSITEIT BRUSSEL 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.
;; MC-STM: meta-circular STM in Clojure
;; Multicore Programming
;; (c) 2011-2013, <NAME>
;; version 1 - simple revision-based STM
;; based on Daniel Spiwak's article:
;; http://www.codecommit.com/blog/scala/software-transactional-memory-in-scala
;; Limitations:
;; - internal consistency is not guaranteed
;; (a transaction may read a value for a ref before another transaction T
;; committed, and read a value for another ref after T committed,
;; leading to potentially mutually inconsistent ref values)
;; - a single global commit-lock for all transactions
;; (= bottleneck, but makes it easy to validate and commit)
;; (note: lock only acquired on commit, not while running the transaction!)
;; - naive support for commute
;; - naive support for ensure (to prevent write skew)
(ns stm.v1-simple)
;; === MC-STM internals ===
; a thread-local var that holds the current transaction executed by this thread
; if the thread does not execute a transaction, this is set to nil
(def ^:dynamic *current-transaction* nil)
(def NEXT_TRANSACTION_ID (atom 0))
(defn make-transaction
"create and return a new transaction data structure"
[]
{ :id (swap! NEXT_TRANSACTION_ID inc),
:in-tx-values (atom {}), ; map: ref -> any value
:written-refs (atom #{}), ; set of refs
:last-seen-rev (atom {}) }) ; map: ref -> revision id
(defn tx-read
"read the value of ref inside transaction tx"
[tx ref]
(let [in-tx-values (:in-tx-values tx)]
(if (contains? @in-tx-values ref)
(@in-tx-values ref) ; return the in-tx-value
; important: read both ref's value and revision atomically
(let [{in-tx-value :value
read-revision :revision} @ref]
; cache the value
(swap! in-tx-values assoc ref in-tx-value)
; remember first revision read
(swap! (:last-seen-rev tx) assoc ref read-revision)
in-tx-value)))) ; save and return the ref's value
(defn tx-write
"write val to ref inside transaction tx"
[tx ref val]
(swap! (:in-tx-values tx) assoc ref val)
(swap! (:written-refs tx) conj ref)
(if (not (contains? @(:last-seen-rev tx) ref))
; remember first revision written
(swap! (:last-seen-rev tx) assoc ref (:revision @ref)))
val)
; a single global lock for all transactions to acquire on commit
; we use the monitor of a fresh empty Java object
; all threads share the same root-binding, so will acquire the same lock
(def COMMIT_LOCK (new java.lang.Object))
(defn tx-commit
"returns a boolean indicating whether tx committed successfully"
[tx]
(let [validate
(fn [refs]
(every? (fn [ref]
(= (:revision @ref)
(@(:last-seen-rev tx) ref))) refs))]
(locking COMMIT_LOCK
(let [in-tx-values @(:in-tx-values tx)
success (validate (keys in-tx-values))]
(if success
; if validation OK, make in-tx-value of all written refs public
(doseq [ref @(:written-refs tx)]
(swap! ref assoc
:value (in-tx-values ref)
:revision (:id tx) )))
success))))
(defn tx-run
"runs zero-argument fun as the body of transaction tx"
[tx fun]
(let [result (binding [*current-transaction* tx] (fun))]
(if (tx-commit tx)
result ; commit succeeded, return result
(recur (make-transaction) fun)))) ; commit failed, retry with fresh tx
;; === MC-STM public API ===
(defn mc-ref [val]
(atom {:value val
:revision 0}))
; Note: an alternative but perhaps less accessible way to code up these
; functions would be to redefine mc-deref and mc-ref-set in the scope of
; a running transaction using 'binding', avoiding the if-test
(defn mc-deref [ref]
(if (nil? *current-transaction*)
; reading a ref outside of a transaction
(:value @ref)
; reading a ref inside a transaction
(tx-read *current-transaction* ref)))
(defn mc-ref-set [ref newval]
(if (nil? *current-transaction*)
; writing a ref outside of a transaction
(throw (IllegalStateException. "can't set mc-ref outside transaction"))
; writing a ref inside a transaction
(tx-write *current-transaction* ref newval)))
(defn mc-alter [ref fun & args]
(mc-ref-set ref (apply fun (mc-deref ref) args)))
; naive but correct implementation of commute
; naive because two transactions that commute the same ref will be
; in conflict, while they should not be (that's the whole point of commute)
(defn mc-commute [ref fun & args]
(apply mc-alter ref fun args))
; naive implementation of ensure
; naive because two transactions that ensure the same ref will
; be in conflict, while they should not be
(defn mc-ensure [ref]
(mc-alter ref identity))
(defmacro mc-dosync [& exps]
`(mc-sync (fn [] ~@exps)))
(defn mc-sync [fun]
(if (nil? *current-transaction*)
(tx-run (make-transaction) fun)
(fun))) ; nested dosync blocks implicitly run in the parent transaction | true | ; Copyright (c) 2011-2013, PI:NAME:<NAME>END_PI, Vrije Universiteit Brussel
; 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 Vrije Universiteit Brussel 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 VRIJE UNIVERSITEIT BRUSSEL 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.
;; MC-STM: meta-circular STM in Clojure
;; Multicore Programming
;; (c) 2011-2013, PI:NAME:<NAME>END_PI
;; version 1 - simple revision-based STM
;; based on Daniel Spiwak's article:
;; http://www.codecommit.com/blog/scala/software-transactional-memory-in-scala
;; Limitations:
;; - internal consistency is not guaranteed
;; (a transaction may read a value for a ref before another transaction T
;; committed, and read a value for another ref after T committed,
;; leading to potentially mutually inconsistent ref values)
;; - a single global commit-lock for all transactions
;; (= bottleneck, but makes it easy to validate and commit)
;; (note: lock only acquired on commit, not while running the transaction!)
;; - naive support for commute
;; - naive support for ensure (to prevent write skew)
(ns stm.v1-simple)
;; === MC-STM internals ===
; a thread-local var that holds the current transaction executed by this thread
; if the thread does not execute a transaction, this is set to nil
(def ^:dynamic *current-transaction* nil)
(def NEXT_TRANSACTION_ID (atom 0))
(defn make-transaction
"create and return a new transaction data structure"
[]
{ :id (swap! NEXT_TRANSACTION_ID inc),
:in-tx-values (atom {}), ; map: ref -> any value
:written-refs (atom #{}), ; set of refs
:last-seen-rev (atom {}) }) ; map: ref -> revision id
(defn tx-read
"read the value of ref inside transaction tx"
[tx ref]
(let [in-tx-values (:in-tx-values tx)]
(if (contains? @in-tx-values ref)
(@in-tx-values ref) ; return the in-tx-value
; important: read both ref's value and revision atomically
(let [{in-tx-value :value
read-revision :revision} @ref]
; cache the value
(swap! in-tx-values assoc ref in-tx-value)
; remember first revision read
(swap! (:last-seen-rev tx) assoc ref read-revision)
in-tx-value)))) ; save and return the ref's value
(defn tx-write
"write val to ref inside transaction tx"
[tx ref val]
(swap! (:in-tx-values tx) assoc ref val)
(swap! (:written-refs tx) conj ref)
(if (not (contains? @(:last-seen-rev tx) ref))
; remember first revision written
(swap! (:last-seen-rev tx) assoc ref (:revision @ref)))
val)
; a single global lock for all transactions to acquire on commit
; we use the monitor of a fresh empty Java object
; all threads share the same root-binding, so will acquire the same lock
(def COMMIT_LOCK (new java.lang.Object))
(defn tx-commit
"returns a boolean indicating whether tx committed successfully"
[tx]
(let [validate
(fn [refs]
(every? (fn [ref]
(= (:revision @ref)
(@(:last-seen-rev tx) ref))) refs))]
(locking COMMIT_LOCK
(let [in-tx-values @(:in-tx-values tx)
success (validate (keys in-tx-values))]
(if success
; if validation OK, make in-tx-value of all written refs public
(doseq [ref @(:written-refs tx)]
(swap! ref assoc
:value (in-tx-values ref)
:revision (:id tx) )))
success))))
(defn tx-run
"runs zero-argument fun as the body of transaction tx"
[tx fun]
(let [result (binding [*current-transaction* tx] (fun))]
(if (tx-commit tx)
result ; commit succeeded, return result
(recur (make-transaction) fun)))) ; commit failed, retry with fresh tx
;; === MC-STM public API ===
(defn mc-ref [val]
(atom {:value val
:revision 0}))
; Note: an alternative but perhaps less accessible way to code up these
; functions would be to redefine mc-deref and mc-ref-set in the scope of
; a running transaction using 'binding', avoiding the if-test
(defn mc-deref [ref]
(if (nil? *current-transaction*)
; reading a ref outside of a transaction
(:value @ref)
; reading a ref inside a transaction
(tx-read *current-transaction* ref)))
(defn mc-ref-set [ref newval]
(if (nil? *current-transaction*)
; writing a ref outside of a transaction
(throw (IllegalStateException. "can't set mc-ref outside transaction"))
; writing a ref inside a transaction
(tx-write *current-transaction* ref newval)))
(defn mc-alter [ref fun & args]
(mc-ref-set ref (apply fun (mc-deref ref) args)))
; naive but correct implementation of commute
; naive because two transactions that commute the same ref will be
; in conflict, while they should not be (that's the whole point of commute)
(defn mc-commute [ref fun & args]
(apply mc-alter ref fun args))
; naive implementation of ensure
; naive because two transactions that ensure the same ref will
; be in conflict, while they should not be
(defn mc-ensure [ref]
(mc-alter ref identity))
(defmacro mc-dosync [& exps]
`(mc-sync (fn [] ~@exps)))
(defn mc-sync [fun]
(if (nil? *current-transaction*)
(tx-run (make-transaction) fun)
(fun))) ; nested dosync blocks implicitly run in the parent transaction |
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9998689889907837,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": ":doc \"The core Clojure language.\"\n :author \"Rich Hickey\"}\n clojure.core)\n\n(def unquote)\n(def unquote-spl",
"end": 532,
"score": 0.9998775720596313,
"start": 521,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "))))\n\n;;;;;;;;;;; require/use/load, contributed by Stephen C. Gilardi ;;;;;;;;;;;;;;;;;;\n\n(defonce\n #^{:private true\n ",
"end": 134363,
"score": 0.9998865723609924,
"start": 134345,
"tag": "NAME",
"value": "Stephen C. Gilardi"
}
] | ThirdParty/clojure-1.1.0/src/clj/clojure/core.clj | allertonm/Couverjure | 3 | ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns #^{:doc "The core Clojure language."
:author "Rich Hickey"}
clojure.core)
(def unquote)
(def unquote-splicing)
(def
#^{:arglists '([& items])
:doc "Creates a new list containing the items."}
list (. clojure.lang.PersistentList creator))
(def
#^{:arglists '([x seq])
:doc "Returns a new seq where x is the first element and seq is
the rest."}
cons (fn* cons [x seq] (. clojure.lang.RT (cons x seq))))
;during bootstrap we don't have destructuring let, loop or fn, will redefine later
(def
#^{:macro true}
let (fn* let [& decl] (cons 'let* decl)))
(def
#^{:macro true}
loop (fn* loop [& decl] (cons 'loop* decl)))
(def
#^{:macro true}
fn (fn* fn [& decl] (cons 'fn* decl)))
(def
#^{:arglists '([coll])
:doc "Returns the first item in the collection. Calls seq on its
argument. If coll is nil, returns nil."}
first (fn first [coll] (. clojure.lang.RT (first coll))))
(def
#^{:arglists '([coll])
:tag clojure.lang.ISeq
:doc "Returns a seq of the items after the first. Calls seq on its
argument. If there are no more items, returns nil."}
next (fn next [x] (. clojure.lang.RT (next x))))
(def
#^{:arglists '([coll])
:tag clojure.lang.ISeq
:doc "Returns a possibly empty seq of the items after the first. Calls seq on its
argument."}
rest (fn rest [x] (. clojure.lang.RT (more x))))
(def
#^{:arglists '([coll x] [coll x & xs])
:doc "conj[oin]. Returns a new collection with the xs
'added'. (conj nil item) returns (item). The 'addition' may
happen at different 'places' depending on the concrete type."}
conj (fn conj
([coll x] (. clojure.lang.RT (conj coll x)))
([coll x & xs]
(if xs
(recur (conj coll x) (first xs) (next xs))
(conj coll x)))))
(def
#^{:doc "Same as (first (next x))"
:arglists '([x])}
second (fn second [x] (first (next x))))
(def
#^{:doc "Same as (first (first x))"
:arglists '([x])}
ffirst (fn ffirst [x] (first (first x))))
(def
#^{:doc "Same as (next (first x))"
:arglists '([x])}
nfirst (fn nfirst [x] (next (first x))))
(def
#^{:doc "Same as (first (next x))"
:arglists '([x])}
fnext (fn fnext [x] (first (next x))))
(def
#^{:doc "Same as (next (next x))"
:arglists '([x])}
nnext (fn nnext [x] (next (next x))))
(def
#^{:arglists '([coll])
:doc "Returns a seq on the collection. If the collection is
empty, returns nil. (seq nil) returns nil. seq also works on
Strings, native Java arrays (of reference types) and any objects
that implement Iterable."
:tag clojure.lang.ISeq}
seq (fn seq [coll] (. clojure.lang.RT (seq coll))))
(def
#^{:arglists '([#^Class c x])
:doc "Evaluates x and tests if it is an instance of the class
c. Returns true or false"}
instance? (fn instance? [#^Class c x] (. c (isInstance x))))
(def
#^{:arglists '([x])
:doc "Return true if x implements ISeq"}
seq? (fn seq? [x] (instance? clojure.lang.ISeq x)))
(def
#^{:arglists '([x])
:doc "Return true if x is a Character"}
char? (fn char? [x] (instance? Character x)))
(def
#^{:arglists '([x])
:doc "Return true if x is a String"}
string? (fn string? [x] (instance? String x)))
(def
#^{:arglists '([x])
:doc "Return true if x implements IPersistentMap"}
map? (fn map? [x] (instance? clojure.lang.IPersistentMap x)))
(def
#^{:arglists '([x])
:doc "Return true if x implements IPersistentVector "}
vector? (fn vector? [x] (instance? clojure.lang.IPersistentVector x)))
(def
#^{:arglists '([map key val] [map key val & kvs])
:doc "assoc[iate]. When applied to a map, returns a new map of the
same (hashed/sorted) type, that contains the mapping of key(s) to
val(s). When applied to a vector, returns a new vector that
contains val at index. Note - index must be <= (count vector)."}
assoc
(fn assoc
([map key val] (. clojure.lang.RT (assoc map key val)))
([map key val & kvs]
(let [ret (assoc map key val)]
(if kvs
(recur ret (first kvs) (second kvs) (nnext kvs))
ret)))))
;;;;;;;;;;;;;;;;; metadata ;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def
#^{:arglists '([obj])
:doc "Returns the metadata of obj, returns nil if there is no metadata."}
meta (fn meta [x]
(if (instance? clojure.lang.IMeta x)
(. #^clojure.lang.IMeta x (meta)))))
(def
#^{:arglists '([#^clojure.lang.IObj obj m])
:doc "Returns an object of the same type and value as obj, with
map m as its metadata."}
with-meta (fn with-meta [#^clojure.lang.IObj x m]
(. x (withMeta m))))
(def
#^{:private true}
sigs
(fn [fdecl]
(let [asig
(fn [fdecl]
(let [arglist (first fdecl)
body (next fdecl)]
(if (map? (first body))
(if (next body)
(with-meta arglist (conj (if (meta arglist) (meta arglist) {}) (first body)))
arglist)
arglist)))]
(if (seq? (first fdecl))
(loop [ret [] fdecls fdecl]
(if fdecls
(recur (conj ret (asig (first fdecls))) (next fdecls))
(seq ret)))
(list (asig fdecl))))))
(def
#^{:arglists '([coll])
:doc "Return the last item in coll, in linear time"}
last (fn last [s]
(if (next s)
(recur (next s))
(first s))))
(def
#^{:arglists '([coll])
:doc "Return a seq of all but the last item in coll, in linear time"}
butlast (fn butlast [s]
(loop [ret [] s s]
(if (next s)
(recur (conj ret (first s)) (next s))
(seq ret)))))
(def
#^{:doc "Same as (def name (fn [params* ] exprs*)) or (def
name (fn ([params* ] exprs*)+)) with any doc-string or attrs added
to the var metadata"
:arglists '([name doc-string? attr-map? [params*] body]
[name doc-string? attr-map? ([params*] body)+ attr-map?])}
defn (fn defn [name & fdecl]
(let [m (if (string? (first fdecl))
{:doc (first fdecl)}
{})
fdecl (if (string? (first fdecl))
(next fdecl)
fdecl)
m (if (map? (first fdecl))
(conj m (first fdecl))
m)
fdecl (if (map? (first fdecl))
(next fdecl)
fdecl)
fdecl (if (vector? (first fdecl))
(list fdecl)
fdecl)
m (if (map? (last fdecl))
(conj m (last fdecl))
m)
fdecl (if (map? (last fdecl))
(butlast fdecl)
fdecl)
m (conj {:arglists (list 'quote (sigs fdecl))} m)
m (let [inline (:inline m)
ifn (first inline)
iname (second inline)]
;; same as: (if (and (= 'fn ifn) (not (symbol? iname))) ...)
(if (if (clojure.lang.Util/equiv 'fn ifn)
(if (instance? clojure.lang.Symbol iname) false true))
;; inserts the same fn name to the inline fn if it does not have one
(assoc m :inline (cons ifn (cons name (next inline))))
m))]
(list 'def (with-meta name (conj (if (meta name) (meta name) {}) m))
(cons `fn fdecl)))))
(. (var defn) (setMacro))
(defn cast
"Throws a ClassCastException if x is not a c, else returns x."
[#^Class c x]
(. c (cast x)))
(defn to-array
"Returns an array of Objects containing the contents of coll, which
can be any Collection. Maps to java.util.Collection.toArray()."
{:tag "[Ljava.lang.Object;"}
[coll] (. clojure.lang.RT (toArray coll)))
(defn vector
"Creates a new vector containing the args."
([] [])
([& args]
(. clojure.lang.LazilyPersistentVector (create args))))
(defn vec
"Creates a new vector containing the contents of coll."
([coll]
(if (instance? java.util.Collection coll)
(clojure.lang.LazilyPersistentVector/create coll)
(. clojure.lang.LazilyPersistentVector (createOwning (to-array coll))))))
(defn hash-map
"keyval => key val
Returns a new hash map with supplied mappings."
([] {})
([& keyvals]
(. clojure.lang.PersistentHashMap (create keyvals))))
(defn hash-set
"Returns a new hash set with supplied keys."
([] #{})
([& keys]
(clojure.lang.PersistentHashSet/create keys)))
(defn sorted-map
"keyval => key val
Returns a new sorted map with supplied mappings."
([& keyvals]
(clojure.lang.PersistentTreeMap/create keyvals)))
(defn sorted-map-by
"keyval => key val
Returns a new sorted map with supplied mappings, using the supplied comparator."
([comparator & keyvals]
(clojure.lang.PersistentTreeMap/create comparator keyvals)))
(defn sorted-set
"Returns a new sorted set with supplied keys."
([& keys]
(clojure.lang.PersistentTreeSet/create keys)))
(defn sorted-set-by
"Returns a new sorted set with supplied keys, using the supplied comparator."
([comparator & keys]
(clojure.lang.PersistentTreeSet/create comparator keys)))
;;;;;;;;;;;;;;;;;;;;
(def
#^{:doc "Like defn, but the resulting function name is declared as a
macro and will be used as a macro by the compiler when it is
called."
:arglists '([name doc-string? attr-map? [params*] body]
[name doc-string? attr-map? ([params*] body)+ attr-map?])}
defmacro (fn [name & args]
(list 'do
(cons `defn (cons name args))
(list '. (list 'var name) '(setMacro))
(list 'var name))))
(. (var defmacro) (setMacro))
(defmacro when
"Evaluates test. If logical true, evaluates body in an implicit do."
[test & body]
(list 'if test (cons 'do body)))
(defmacro when-not
"Evaluates test. If logical false, evaluates body in an implicit do."
[test & body]
(list 'if test nil (cons 'do body)))
(defn nil?
"Returns true if x is nil, false otherwise."
{:tag Boolean}
[x] (identical? x nil))
(defn false?
"Returns true if x is the value false, false otherwise."
{:tag Boolean}
[x] (identical? x false))
(defn true?
"Returns true if x is the value true, false otherwise."
{:tag Boolean}
[x] (identical? x true))
(defn not
"Returns true if x is logical false, false otherwise."
{:tag Boolean}
[x] (if x false true))
(defn str
"With no args, returns the empty string. With one arg x, returns
x.toString(). (str nil) returns the empty string. With more than
one arg, returns the concatenation of the str values of the args."
{:tag String}
([] "")
([#^Object x]
(if (nil? x) "" (. x (toString))))
([x & ys]
((fn [#^StringBuilder sb more]
(if more
(recur (. sb (append (str (first more)))) (next more))
(str sb)))
(new StringBuilder #^String (str x)) ys)))
(defn symbol?
"Return true if x is a Symbol"
[x] (instance? clojure.lang.Symbol x))
(defn keyword?
"Return true if x is a Keyword"
[x] (instance? clojure.lang.Keyword x))
(defn symbol
"Returns a Symbol with the given namespace and name."
{:tag clojure.lang.Symbol}
([name] (if (symbol? name) name (clojure.lang.Symbol/intern name)))
([ns name] (clojure.lang.Symbol/intern ns name)))
(defn keyword
"Returns a Keyword with the given namespace and name. Do not use :
in the keyword strings, it will be added automatically."
{:tag clojure.lang.Keyword}
([name] (if (keyword? name) name (clojure.lang.Keyword/intern name)))
([ns name] (clojure.lang.Keyword/intern ns name)))
(defn gensym
"Returns a new symbol with a unique name. If a prefix string is
supplied, the name is prefix# where # is some unique number. If
prefix is not supplied, the prefix is 'G__'."
([] (gensym "G__"))
([prefix-string] (. clojure.lang.Symbol (intern (str prefix-string (str (. clojure.lang.RT (nextID))))))))
(defmacro cond
"Takes a set of test/expr pairs. It evaluates each test one at a
time. If a test returns logical true, cond evaluates and returns
the value of the corresponding expr and doesn't evaluate any of the
other tests or exprs. (cond) returns nil."
[& clauses]
(when clauses
(list 'if (first clauses)
(if (next clauses)
(second clauses)
(throw (IllegalArgumentException.
"cond requires an even number of forms")))
(cons 'clojure.core/cond (next (next clauses))))))
(defn spread
{:private true}
[arglist]
(cond
(nil? arglist) nil
(nil? (next arglist)) (seq (first arglist))
:else (cons (first arglist) (spread (next arglist)))))
(defn list*
"Creates a new list containing the items prepended to the rest, the
last of which will be treated as a sequence."
([args] (seq args))
([a args] (cons a args))
([a b args] (cons a (cons b args)))
([a b c args] (cons a (cons b (cons c args))))
([a b c d & more]
(cons a (cons b (cons c (cons d (spread more)))))))
(defn apply
"Applies fn f to the argument list formed by prepending args to argseq."
{:arglists '([f args* argseq])}
([#^clojure.lang.IFn f args]
(. f (applyTo (seq args))))
([#^clojure.lang.IFn f x args]
(. f (applyTo (list* x args))))
([#^clojure.lang.IFn f x y args]
(. f (applyTo (list* x y args))))
([#^clojure.lang.IFn f x y z args]
(. f (applyTo (list* x y z args))))
([#^clojure.lang.IFn f a b c d & args]
(. f (applyTo (cons a (cons b (cons c (cons d (spread args)))))))))
(defn vary-meta
"Returns an object of the same type and value as obj, with
(apply f (meta obj) args) as its metadata."
[obj f & args]
(with-meta obj (apply f (meta obj) args)))
(defmacro lazy-seq
"Takes a body of expressions that returns an ISeq or nil, and yields
a Seqable object that will invoke the body only the first time seq
is called, and will cache the result and return it on all subsequent
seq calls."
[& body]
(list 'new 'clojure.lang.LazySeq (list* '#^{:once true} fn* [] body)))
(defn #^clojure.lang.ChunkBuffer chunk-buffer [capacity]
(clojure.lang.ChunkBuffer. capacity))
(defn chunk-append [#^clojure.lang.ChunkBuffer b x]
(.add b x))
(defn chunk [#^clojure.lang.ChunkBuffer b]
(.chunk b))
(defn #^clojure.lang.IChunk chunk-first [#^clojure.lang.IChunkedSeq s]
(.chunkedFirst s))
(defn #^clojure.lang.ISeq chunk-rest [#^clojure.lang.IChunkedSeq s]
(.chunkedMore s))
(defn #^clojure.lang.ISeq chunk-next [#^clojure.lang.IChunkedSeq s]
(.chunkedNext s))
(defn chunk-cons [chunk rest]
(if (clojure.lang.Numbers/isZero (clojure.lang.RT/count chunk))
rest
(clojure.lang.ChunkedCons. chunk rest)))
(defn chunked-seq? [s]
(instance? clojure.lang.IChunkedSeq s))
(defn concat
"Returns a lazy seq representing the concatenation of the elements in the supplied colls."
([] (lazy-seq nil))
([x] (lazy-seq x))
([x y]
(lazy-seq
(let [s (seq x)]
(if s
(if (chunked-seq? s)
(chunk-cons (chunk-first s) (concat (chunk-rest s) y))
(cons (first s) (concat (rest s) y)))
y))))
([x y & zs]
(let [cat (fn cat [xys zs]
(lazy-seq
(let [xys (seq xys)]
(if xys
(if (chunked-seq? xys)
(chunk-cons (chunk-first xys)
(cat (chunk-rest xys) zs))
(cons (first xys) (cat (rest xys) zs)))
(when zs
(cat (first zs) (next zs)))))))]
(cat (concat x y) zs))))
;;;;;;;;;;;;;;;;at this point all the support for syntax-quote exists;;;;;;;;;;;;;;;;;;;;;;
(defmacro delay
"Takes a body of expressions and yields a Delay object that will
invoke the body only the first time it is forced (with force), and
will cache the result and return it on all subsequent force
calls."
[& body]
(list 'new 'clojure.lang.Delay (list* `#^{:once true} fn* [] body)))
(defn delay?
"returns true if x is a Delay created with delay"
[x] (instance? clojure.lang.Delay x))
(defn force
"If x is a Delay, returns the (possibly cached) value of its expression, else returns x"
[x] (. clojure.lang.Delay (force x)))
(defmacro if-not
"Evaluates test. If logical false, evaluates and returns then expr,
otherwise else expr, if supplied, else nil."
([test then] `(if-not ~test ~then nil))
([test then else]
`(if (not ~test) ~then ~else)))
(defn =
"Equality. Returns true if x equals y, false if not. Same as
Java x.equals(y) except it also works for nil, and compares
numbers and collections in a type-independent manner. Clojure's immutable data
structures define equals() (and thus =) as a value, not an identity,
comparison."
{:tag Boolean
:inline (fn [x y] `(. clojure.lang.Util equiv ~x ~y))
:inline-arities #{2}}
([x] true)
([x y] (clojure.lang.Util/equiv x y))
([x y & more]
(if (= x y)
(if (next more)
(recur y (first more) (next more))
(= y (first more)))
false)))
(defn not=
"Same as (not (= obj1 obj2))"
{:tag Boolean}
([x] false)
([x y] (not (= x y)))
([x y & more]
(not (apply = x y more))))
(defn compare
"Comparator. Returns a negative number, zero, or a positive number
when x is logically 'less than', 'equal to', or 'greater than'
y. Same as Java x.compareTo(y) except it also works for nil, and
compares numbers and collections in a type-independent manner. x
must implement Comparable"
{:tag Integer
:inline (fn [x y] `(. clojure.lang.Util compare ~x ~y))}
[x y] (. clojure.lang.Util (compare x y)))
(defmacro and
"Evaluates exprs one at a time, from left to right. If a form
returns logical false (nil or false), and returns that value and
doesn't evaluate any of the other expressions, otherwise it returns
the value of the last expr. (and) returns true."
([] true)
([x] x)
([x & next]
`(let [and# ~x]
(if and# (and ~@next) and#))))
(defmacro or
"Evaluates exprs one at a time, from left to right. If a form
returns a logical true value, or returns that value and doesn't
evaluate any of the other expressions, otherwise it returns the
value of the last expression. (or) returns nil."
([] nil)
([x] x)
([x & next]
`(let [or# ~x]
(if or# or# (or ~@next)))))
;;;;;;;;;;;;;;;;;;; sequence fns ;;;;;;;;;;;;;;;;;;;;;;;
(defn zero?
"Returns true if num is zero, else false"
{:tag Boolean
:inline (fn [x] `(. clojure.lang.Numbers (isZero ~x)))}
[x] (. clojure.lang.Numbers (isZero x)))
(defn count
"Returns the number of items in the collection. (count nil) returns
0. Also works on strings, arrays, and Java Collections and Maps"
[coll] (clojure.lang.RT/count coll))
(defn int
"Coerce to int"
{:tag Integer
:inline (fn [x] `(. clojure.lang.RT (intCast ~x)))}
[x] (. clojure.lang.RT (intCast x)))
(defn nth
"Returns the value at the index. get returns nil if index out of
bounds, nth throws an exception unless not-found is supplied. nth
also works for strings, Java arrays, regex Matchers and Lists, and,
in O(n) time, for sequences."
{:inline (fn [c i & nf] `(. clojure.lang.RT (nth ~c ~i ~@nf)))
:inline-arities #{2 3}}
([coll index] (. clojure.lang.RT (nth coll index)))
([coll index not-found] (. clojure.lang.RT (nth coll index not-found))))
(defn <
"Returns non-nil if nums are in monotonically increasing order,
otherwise false."
{:inline (fn [x y] `(. clojure.lang.Numbers (lt ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (lt x y)))
([x y & more]
(if (< x y)
(if (next more)
(recur y (first more) (next more))
(< y (first more)))
false)))
(defn inc
"Returns a number one greater than num."
{:inline (fn [x] `(. clojure.lang.Numbers (inc ~x)))}
[x] (. clojure.lang.Numbers (inc x)))
(defn reduce
"f should be a function of 2 arguments. If val is not supplied,
returns the result of applying f to the first 2 items in coll, then
applying f to that result and the 3rd item, etc. If coll contains no
items, f must accept no arguments as well, and reduce returns the
result of calling f with no arguments. If coll has only 1 item, it
is returned and f is not called. If val is supplied, returns the
result of applying f to val and the first item in coll, then
applying f to that result and the 2nd item, etc. If coll contains no
items, returns val and f is not called."
([f coll]
(let [s (seq coll)]
(if s
(reduce f (first s) (next s))
(f))))
([f val coll]
(let [s (seq coll)]
(if s
(if (chunked-seq? s)
(recur f
(.reduce (chunk-first s) f val)
(chunk-next s))
(recur f (f val (first s)) (next s)))
val))))
(defn reverse
"Returns a seq of the items in coll in reverse order. Not lazy."
[coll]
(reduce conj () coll))
;;math stuff
(defn +
"Returns the sum of nums. (+) returns 0."
{:inline (fn [x y] `(. clojure.lang.Numbers (add ~x ~y)))
:inline-arities #{2}}
([] 0)
([x] (cast Number x))
([x y] (. clojure.lang.Numbers (add x y)))
([x y & more]
(reduce + (+ x y) more)))
(defn *
"Returns the product of nums. (*) returns 1."
{:inline (fn [x y] `(. clojure.lang.Numbers (multiply ~x ~y)))
:inline-arities #{2}}
([] 1)
([x] (cast Number x))
([x y] (. clojure.lang.Numbers (multiply x y)))
([x y & more]
(reduce * (* x y) more)))
(defn /
"If no denominators are supplied, returns 1/numerator,
else returns numerator divided by all of the denominators."
{:inline (fn [x y] `(. clojure.lang.Numbers (divide ~x ~y)))
:inline-arities #{2}}
([x] (/ 1 x))
([x y] (. clojure.lang.Numbers (divide x y)))
([x y & more]
(reduce / (/ x y) more)))
(defn -
"If no ys are supplied, returns the negation of x, else subtracts
the ys from x and returns the result."
{:inline (fn [& args] `(. clojure.lang.Numbers (minus ~@args)))
:inline-arities #{1 2}}
([x] (. clojure.lang.Numbers (minus x)))
([x y] (. clojure.lang.Numbers (minus x y)))
([x y & more]
(reduce - (- x y) more)))
(defn <=
"Returns non-nil if nums are in monotonically non-decreasing order,
otherwise false."
{:inline (fn [x y] `(. clojure.lang.Numbers (lte ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (lte x y)))
([x y & more]
(if (<= x y)
(if (next more)
(recur y (first more) (next more))
(<= y (first more)))
false)))
(defn >
"Returns non-nil if nums are in monotonically decreasing order,
otherwise false."
{:inline (fn [x y] `(. clojure.lang.Numbers (gt ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (gt x y)))
([x y & more]
(if (> x y)
(if (next more)
(recur y (first more) (next more))
(> y (first more)))
false)))
(defn >=
"Returns non-nil if nums are in monotonically non-increasing order,
otherwise false."
{:inline (fn [x y] `(. clojure.lang.Numbers (gte ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (gte x y)))
([x y & more]
(if (>= x y)
(if (next more)
(recur y (first more) (next more))
(>= y (first more)))
false)))
(defn ==
"Returns non-nil if nums all have the same value, otherwise false"
{:inline (fn [x y] `(. clojure.lang.Numbers (equiv ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (equiv x y)))
([x y & more]
(if (== x y)
(if (next more)
(recur y (first more) (next more))
(== y (first more)))
false)))
(defn max
"Returns the greatest of the nums."
([x] x)
([x y] (if (> x y) x y))
([x y & more]
(reduce max (max x y) more)))
(defn min
"Returns the least of the nums."
([x] x)
([x y] (if (< x y) x y))
([x y & more]
(reduce min (min x y) more)))
(defn dec
"Returns a number one less than num."
{:inline (fn [x] `(. clojure.lang.Numbers (dec ~x)))}
[x] (. clojure.lang.Numbers (dec x)))
(defn unchecked-inc
"Returns a number one greater than x, an int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x] `(. clojure.lang.Numbers (unchecked_inc ~x)))}
[x] (. clojure.lang.Numbers (unchecked_inc x)))
(defn unchecked-dec
"Returns a number one less than x, an int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x] `(. clojure.lang.Numbers (unchecked_dec ~x)))}
[x] (. clojure.lang.Numbers (unchecked_dec x)))
(defn unchecked-negate
"Returns the negation of x, an int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x] `(. clojure.lang.Numbers (unchecked_negate ~x)))}
[x] (. clojure.lang.Numbers (unchecked_negate x)))
(defn unchecked-add
"Returns the sum of x and y, both int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_add ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_add x y)))
(defn unchecked-subtract
"Returns the difference of x and y, both int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_subtract ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_subtract x y)))
(defn unchecked-multiply
"Returns the product of x and y, both int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_multiply ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_multiply x y)))
(defn unchecked-divide
"Returns the division of x by y, both int or long.
Note - uses a primitive operator subject to truncation."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_divide ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_divide x y)))
(defn unchecked-remainder
"Returns the remainder of division of x by y, both int or long.
Note - uses a primitive operator subject to truncation."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_remainder ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_remainder x y)))
(defn pos?
"Returns true if num is greater than zero, else false"
{:tag Boolean
:inline (fn [x] `(. clojure.lang.Numbers (isPos ~x)))}
[x] (. clojure.lang.Numbers (isPos x)))
(defn neg?
"Returns true if num is less than zero, else false"
{:tag Boolean
:inline (fn [x] `(. clojure.lang.Numbers (isNeg ~x)))}
[x] (. clojure.lang.Numbers (isNeg x)))
(defn quot
"quot[ient] of dividing numerator by denominator."
[num div]
(. clojure.lang.Numbers (quotient num div)))
(defn rem
"remainder of dividing numerator by denominator."
[num div]
(. clojure.lang.Numbers (remainder num div)))
(defn rationalize
"returns the rational value of num"
[num]
(. clojure.lang.Numbers (rationalize num)))
;;Bit ops
(defn bit-not
"Bitwise complement"
{:inline (fn [x] `(. clojure.lang.Numbers (not ~x)))}
[x] (. clojure.lang.Numbers not x))
(defn bit-and
"Bitwise and"
{:inline (fn [x y] `(. clojure.lang.Numbers (and ~x ~y)))}
[x y] (. clojure.lang.Numbers and x y))
(defn bit-or
"Bitwise or"
{:inline (fn [x y] `(. clojure.lang.Numbers (or ~x ~y)))}
[x y] (. clojure.lang.Numbers or x y))
(defn bit-xor
"Bitwise exclusive or"
{:inline (fn [x y] `(. clojure.lang.Numbers (xor ~x ~y)))}
[x y] (. clojure.lang.Numbers xor x y))
(defn bit-and-not
"Bitwise and with complement"
[x y] (. clojure.lang.Numbers andNot x y))
(defn bit-clear
"Clear bit at index n"
[x n] (. clojure.lang.Numbers clearBit x n))
(defn bit-set
"Set bit at index n"
[x n] (. clojure.lang.Numbers setBit x n))
(defn bit-flip
"Flip bit at index n"
[x n] (. clojure.lang.Numbers flipBit x n))
(defn bit-test
"Test bit at index n"
[x n] (. clojure.lang.Numbers testBit x n))
(defn bit-shift-left
"Bitwise shift left"
[x n] (. clojure.lang.Numbers shiftLeft x n))
(defn bit-shift-right
"Bitwise shift right"
[x n] (. clojure.lang.Numbers shiftRight x n))
(defn even?
"Returns true if n is even, throws an exception if n is not an integer"
[n] (zero? (bit-and n 1)))
(defn odd?
"Returns true if n is odd, throws an exception if n is not an integer"
[n] (not (even? n)))
;;
(defn complement
"Takes a fn f and returns a fn that takes the same arguments as f,
has the same effects, if any, and returns the opposite truth value."
[f]
(fn
([] (not (f)))
([x] (not (f x)))
([x y] (not (f x y)))
([x y & zs] (not (apply f x y zs)))))
(defn constantly
"Returns a function that takes any number of arguments and returns x."
[x] (fn [& args] x))
(defn identity
"Returns its argument."
[x] x)
;;Collection stuff
;;list stuff
(defn peek
"For a list or queue, same as first, for a vector, same as, but much
more efficient than, last. If the collection is empty, returns nil."
[coll] (. clojure.lang.RT (peek coll)))
(defn pop
"For a list or queue, returns a new list/queue without the first
item, for a vector, returns a new vector without the last item. If
the collection is empty, throws an exception. Note - not the same
as next/butlast."
[coll] (. clojure.lang.RT (pop coll)))
;;map stuff
(defn contains?
"Returns true if key is present in the given collection, otherwise
returns false. Note that for numerically indexed collections like
vectors and Java arrays, this tests if the numeric key is within the
range of indexes. 'contains?' operates constant or logarithmic time;
it will not perform a linear search for a value. See also 'some'."
[coll key] (. clojure.lang.RT (contains coll key)))
(defn get
"Returns the value mapped to key, not-found or nil if key not present."
([map key]
(. clojure.lang.RT (get map key)))
([map key not-found]
(. clojure.lang.RT (get map key not-found))))
(defn dissoc
"dissoc[iate]. Returns a new map of the same (hashed/sorted) type,
that does not contain a mapping for key(s)."
([map] map)
([map key]
(. clojure.lang.RT (dissoc map key)))
([map key & ks]
(let [ret (dissoc map key)]
(if ks
(recur ret (first ks) (next ks))
ret))))
(defn disj
"disj[oin]. Returns a new set of the same (hashed/sorted) type, that
does not contain key(s)."
([set] set)
([#^clojure.lang.IPersistentSet set key]
(. set (disjoin key)))
([set key & ks]
(let [ret (disj set key)]
(if ks
(recur ret (first ks) (next ks))
ret))))
(defn find
"Returns the map entry for key, or nil if key not present."
[map key] (. clojure.lang.RT (find map key)))
(defn select-keys
"Returns a map containing only those entries in map whose key is in keys"
[map keyseq]
(loop [ret {} keys (seq keyseq)]
(if keys
(let [entry (. clojure.lang.RT (find map (first keys)))]
(recur
(if entry
(conj ret entry)
ret)
(next keys)))
ret)))
(defn keys
"Returns a sequence of the map's keys."
[map] (. clojure.lang.RT (keys map)))
(defn vals
"Returns a sequence of the map's values."
[map] (. clojure.lang.RT (vals map)))
(defn key
"Returns the key of the map entry."
[#^java.util.Map$Entry e]
(. e (getKey)))
(defn val
"Returns the value in the map entry."
[#^java.util.Map$Entry e]
(. e (getValue)))
(defn rseq
"Returns, in constant time, a seq of the items in rev (which
can be a vector or sorted-map), in reverse order. If rev is empty returns nil"
[#^clojure.lang.Reversible rev]
(. rev (rseq)))
(defn name
"Returns the name String of a symbol or keyword."
{:tag String}
[#^clojure.lang.Named x]
(. x (getName)))
(defn namespace
"Returns the namespace String of a symbol or keyword, or nil if not present."
{:tag String}
[#^clojure.lang.Named x]
(. x (getNamespace)))
(defmacro locking
"Executes exprs in an implicit do, while holding the monitor of x.
Will release the monitor of x in all circumstances."
[x & body]
`(let [lockee# ~x]
(try
(monitor-enter lockee#)
~@body
(finally
(monitor-exit lockee#)))))
(defmacro ..
"form => fieldName-symbol or (instanceMethodName-symbol args*)
Expands into a member access (.) of the first member on the first
argument, followed by the next member on the result, etc. For
instance:
(.. System (getProperties) (get \"os.name\"))
expands to:
(. (. System (getProperties)) (get \"os.name\"))
but is easier to write, read, and understand."
([x form] `(. ~x ~form))
([x form & more] `(.. (. ~x ~form) ~@more)))
(defmacro ->
"Threads the expr through the forms. Inserts x as the
second item in the first form, making a list of it if it is not a
list already. If there are more forms, inserts the first form as the
second item in second form, etc."
([x] x)
([x form] (if (seq? form)
(with-meta `(~(first form) ~x ~@(next form)) (meta form))
(list form x)))
([x form & more] `(-> (-> ~x ~form) ~@more)))
(defmacro ->>
"Threads the expr through the forms. Inserts x as the
last item in the first form, making a list of it if it is not a
list already. If there are more forms, inserts the first form as the
last item in second form, etc."
([x form] (if (seq? form)
(with-meta `(~(first form) ~@(next form) ~x) (meta form))
(list form x)))
([x form & more] `(->> (->> ~x ~form) ~@more)))
;;multimethods
(def global-hierarchy)
(defmacro defmulti
"Creates a new multimethod with the associated dispatch function.
The docstring and attribute-map are optional.
Options are key-value pairs and may be one of:
:default the default dispatch value, defaults to :default
:hierarchy the isa? hierarchy to use for dispatching
defaults to the global hierarchy"
{:arglists '([name docstring? attr-map? dispatch-fn & options])}
[mm-name & options]
(let [docstring (if (string? (first options))
(first options)
nil)
options (if (string? (first options))
(next options)
options)
m (if (map? (first options))
(first options)
{})
options (if (map? (first options))
(next options)
options)
dispatch-fn (first options)
options (next options)
m (assoc m :tag 'clojure.lang.MultiFn)
m (if docstring
(assoc m :doc docstring)
m)
m (if (meta mm-name)
(conj (meta mm-name) m)
m)]
(when (= (count options) 1)
(throw (Exception. "The syntax for defmulti has changed. Example: (defmulti name dispatch-fn :default dispatch-value)")))
(let [options (apply hash-map options)
default (get options :default :default)
hierarchy (get options :hierarchy #'global-hierarchy)]
`(def ~(with-meta mm-name m)
(new clojure.lang.MultiFn ~(name mm-name) ~dispatch-fn ~default ~hierarchy)))))
(defmacro defmethod
"Creates and installs a new method of multimethod associated with dispatch-value. "
[multifn dispatch-val & fn-tail]
`(. ~(with-meta multifn {:tag 'clojure.lang.MultiFn}) addMethod ~dispatch-val (fn ~@fn-tail)))
(defn remove-method
"Removes the method of multimethod associated with dispatch-value."
[#^clojure.lang.MultiFn multifn dispatch-val]
(. multifn removeMethod dispatch-val))
(defn prefer-method
"Causes the multimethod to prefer matches of dispatch-val-x over dispatch-val-y
when there is a conflict"
[#^clojure.lang.MultiFn multifn dispatch-val-x dispatch-val-y]
(. multifn preferMethod dispatch-val-x dispatch-val-y))
(defn methods
"Given a multimethod, returns a map of dispatch values -> dispatch fns"
[#^clojure.lang.MultiFn multifn] (.getMethodTable multifn))
(defn get-method
"Given a multimethod and a dispatch value, returns the dispatch fn
that would apply to that value, or nil if none apply and no default"
[#^clojure.lang.MultiFn multifn dispatch-val] (.getMethod multifn dispatch-val))
(defn prefers
"Given a multimethod, returns a map of preferred value -> set of other values"
[#^clojure.lang.MultiFn multifn] (.getPreferTable multifn))
;;;;;;;;; var stuff
(defmacro #^{:private true} assert-args [fnname & pairs]
`(do (when-not ~(first pairs)
(throw (IllegalArgumentException.
~(str fnname " requires " (second pairs)))))
~(let [more (nnext pairs)]
(when more
(list* `assert-args fnname more)))))
(defmacro if-let
"bindings => binding-form test
If test is true, evaluates then with binding-form bound to the value of
test, if not, yields else"
([bindings then]
`(if-let ~bindings ~then nil))
([bindings then else & oldform]
(assert-args if-let
(and (vector? bindings) (nil? oldform)) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [form (bindings 0) tst (bindings 1)]
`(let [temp# ~tst]
(if temp#
(let [~form temp#]
~then)
~else)))))
(defmacro when-let
"bindings => binding-form test
When test is true, evaluates body with binding-form bound to the value of test"
[bindings & body]
(assert-args when-let
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [form (bindings 0) tst (bindings 1)]
`(let [temp# ~tst]
(when temp#
(let [~form temp#]
~@body)))))
(defn push-thread-bindings
"WARNING: This is a low-level function. Prefer high-level macros like
binding where ever possible.
Takes a map of Var/value pairs. Binds each Var to the associated value for
the current thread. Each call *MUST* be accompanied by a matching call to
pop-thread-bindings wrapped in a try-finally!
(push-thread-bindings bindings)
(try
...
(finally
(pop-thread-bindings)))"
[bindings]
(clojure.lang.Var/pushThreadBindings bindings))
(defn pop-thread-bindings
"Pop one set of bindings pushed with push-binding before. It is an error to
pop bindings without pushing before."
[]
(clojure.lang.Var/popThreadBindings))
(defn get-thread-bindings
"Get a map with the Var/value pairs which is currently in effect for the
current thread."
[]
(clojure.lang.Var/getThreadBindings))
(defmacro binding
"binding => var-symbol init-expr
Creates new bindings for the (already-existing) vars, with the
supplied initial values, executes the exprs in an implicit do, then
re-establishes the bindings that existed before. The new bindings
are made in parallel (unlike let); all init-exprs are evaluated
before the vars are bound to their new values."
[bindings & body]
(assert-args binding
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(let [var-ize (fn [var-vals]
(loop [ret [] vvs (seq var-vals)]
(if vvs
(recur (conj (conj ret `(var ~(first vvs))) (second vvs))
(next (next vvs)))
(seq ret))))]
`(let []
(push-thread-bindings (hash-map ~@(var-ize bindings)))
(try
~@body
(finally
(pop-thread-bindings))))))
(defn with-bindings*
"Takes a map of Var/value pairs. Installs for the given Vars the associated
values as thread-local bindings. Then calls f with the supplied arguments.
Pops the installed bindings after f returned. Returns whatever f returns."
[binding-map f & args]
(push-thread-bindings binding-map)
(try
(apply f args)
(finally
(pop-thread-bindings))))
(defmacro with-bindings
"Takes a map of Var/value pairs. Installs for the given Vars the associated
values as thread-local bindings. The executes body. Pops the installed
bindings after body was evaluated. Returns the value of body."
[binding-map & body]
`(with-bindings* ~binding-map (fn [] ~@body)))
(defn bound-fn*
"Returns a function, which will install the same bindings in effect as in
the thread at the time bound-fn* was called and then call f with any given
arguments. This may be used to define a helper function which runs on a
different thread, but needs the same bindings in place."
[f]
(let [bindings (get-thread-bindings)]
(fn [& args]
(apply with-bindings* bindings f args))))
(defmacro bound-fn
"Returns a function defined by the given fntail, which will install the
same bindings in effect as in the thread at the time bound-fn was called.
This may be used to define a helper function which runs on a different
thread, but needs the same bindings in place."
[& fntail]
`(bound-fn* (fn ~@fntail)))
(defn find-var
"Returns the global var named by the namespace-qualified symbol, or
nil if no var with that name."
[sym] (. clojure.lang.Var (find sym)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Refs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn #^{:private true}
setup-reference [#^clojure.lang.ARef r options]
(let [opts (apply hash-map options)]
(when (:meta opts)
(.resetMeta r (:meta opts)))
(when (:validator opts)
(.setValidator r (:validator opts)))
r))
(defn agent
"Creates and returns an agent with an initial value of state and
zero or more options (in any order):
:meta metadata-map
:validator validate-fn
If metadata-map is supplied, it will be come the metadata on the
agent. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception."
([state] (new clojure.lang.Agent state))
([state & options]
(setup-reference (agent state) options)))
(defn send
"Dispatch an action to an agent. Returns the agent immediately.
Subsequently, in a thread from a thread pool, the state of the agent
will be set to the value of:
(apply action-fn state-of-agent args)"
[#^clojure.lang.Agent a f & args]
(. a (dispatch f args false)))
(defn send-off
"Dispatch a potentially blocking action to an agent. Returns the
agent immediately. Subsequently, in a separate thread, the state of
the agent will be set to the value of:
(apply action-fn state-of-agent args)"
[#^clojure.lang.Agent a f & args]
(. a (dispatch f args true)))
(defn release-pending-sends
"Normally, actions sent directly or indirectly during another action
are held until the action completes (changes the agent's
state). This function can be used to dispatch any pending sent
actions immediately. This has no impact on actions sent during a
transaction, which are still held until commit. If no action is
occurring, does nothing. Returns the number of actions dispatched."
[] (clojure.lang.Agent/releasePendingSends))
(defn add-watch
"Alpha - subject to change.
Adds a watch function to an agent/atom/var/ref reference. The watch
fn must be a fn of 4 args: a key, the reference, its old-state, its
new-state. Whenever the reference's state might have been changed,
any registered watches will have their functions called. The watch fn
will be called synchronously, on the agent's thread if an agent,
before any pending sends if agent or ref. Note that an atom's or
ref's state may have changed again prior to the fn call, so use
old/new-state rather than derefing the reference. Note also that watch
fns may be called from multiple threads simultaneously. Var watchers
are triggered only by root binding changes, not thread-local
set!s. Keys must be unique per reference, and can be used to remove
the watch with remove-watch, but are otherwise considered opaque by
the watch mechanism."
[#^clojure.lang.IRef reference key fn] (.addWatch reference key fn))
(defn remove-watch
"Alpha - subject to change.
Removes a watch (set by add-watch) from a reference"
[#^clojure.lang.IRef reference key]
(.removeWatch reference key))
(defn agent-errors
"Returns a sequence of the exceptions thrown during asynchronous
actions of the agent."
[#^clojure.lang.Agent a] (. a (getErrors)))
(defn clear-agent-errors
"Clears any exceptions thrown during asynchronous actions of the
agent, allowing subsequent actions to occur."
[#^clojure.lang.Agent a] (. a (clearErrors)))
(defn shutdown-agents
"Initiates a shutdown of the thread pools that back the agent
system. Running actions will complete, but no new actions will be
accepted"
[] (. clojure.lang.Agent shutdown))
(defn ref
"Creates and returns a Ref with an initial value of x and zero or
more options (in any order):
:meta metadata-map
:validator validate-fn
:min-history (default 0)
:max-history (default 10)
If metadata-map is supplied, it will be come the metadata on the
ref. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception. validate-fn will be called on
transaction commit, when all refs have their final values.
Normally refs accumulate history dynamically as needed to deal with
read demands. If you know in advance you will need history you can
set :min-history to ensure it will be available when first needed (instead
of after a read fault). History is limited, and the limit can be set
with :max-history."
([x] (new clojure.lang.Ref x))
([x & options]
(let [r #^clojure.lang.Ref (setup-reference (ref x) options)
opts (apply hash-map options)]
(when (:max-history opts)
(.setMaxHistory r (:max-history opts)))
(when (:min-history opts)
(.setMinHistory r (:min-history opts)))
r)))
(defn deref
"Also reader macro: @ref/@agent/@var/@atom/@delay/@future. Within a transaction,
returns the in-transaction-value of ref, else returns the
most-recently-committed value of ref. When applied to a var, agent
or atom, returns its current state. When applied to a delay, forces
it if not already forced. When applied to a future, will block if
computation not complete"
[#^clojure.lang.IDeref ref] (.deref ref))
(defn atom
"Creates and returns an Atom with an initial value of x and zero or
more options (in any order):
:meta metadata-map
:validator validate-fn
If metadata-map is supplied, it will be come the metadata on the
atom. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception."
([x] (new clojure.lang.Atom x))
([x & options] (setup-reference (atom x) options)))
(defn swap!
"Atomically swaps the value of atom to be:
(apply f current-value-of-atom args). Note that f may be called
multiple times, and thus should be free of side effects. Returns
the value that was swapped in."
([#^clojure.lang.Atom atom f] (.swap atom f))
([#^clojure.lang.Atom atom f x] (.swap atom f x))
([#^clojure.lang.Atom atom f x y] (.swap atom f x y))
([#^clojure.lang.Atom atom f x y & args] (.swap atom f x y args)))
(defn compare-and-set!
"Atomically sets the value of atom to newval if and only if the
current value of the atom is identical to oldval. Returns true if
set happened, else false"
[#^clojure.lang.Atom atom oldval newval] (.compareAndSet atom oldval newval))
(defn reset!
"Sets the value of atom to newval without regard for the
current value. Returns newval."
[#^clojure.lang.Atom atom newval] (.reset atom newval))
(defn set-validator!
"Sets the validator-fn for a var/ref/agent/atom. validator-fn must be nil or a
side-effect-free fn of one argument, which will be passed the intended
new state on any state change. If the new state is unacceptable, the
validator-fn should return false or throw an exception. If the current state (root
value if var) is not acceptable to the new validator, an exception
will be thrown and the validator will not be changed."
[#^clojure.lang.IRef iref validator-fn] (. iref (setValidator validator-fn)))
(defn get-validator
"Gets the validator-fn for a var/ref/agent/atom."
[#^clojure.lang.IRef iref] (. iref (getValidator)))
(defn alter-meta!
"Atomically sets the metadata for a namespace/var/ref/agent/atom to be:
(apply f its-current-meta args)
f must be free of side-effects"
[#^clojure.lang.IReference iref f & args] (.alterMeta iref f args))
(defn reset-meta!
"Atomically resets the metadata for a namespace/var/ref/agent/atom"
[#^clojure.lang.IReference iref metadata-map] (.resetMeta iref metadata-map))
(defn commute
"Must be called in a transaction. Sets the in-transaction-value of
ref to:
(apply fun in-transaction-value-of-ref args)
and returns the in-transaction-value of ref.
At the commit point of the transaction, sets the value of ref to be:
(apply fun most-recently-committed-value-of-ref args)
Thus fun should be commutative, or, failing that, you must accept
last-one-in-wins behavior. commute allows for more concurrency than
ref-set."
[#^clojure.lang.Ref ref fun & args]
(. ref (commute fun args)))
(defn alter
"Must be called in a transaction. Sets the in-transaction-value of
ref to:
(apply fun in-transaction-value-of-ref args)
and returns the in-transaction-value of ref."
[#^clojure.lang.Ref ref fun & args]
(. ref (alter fun args)))
(defn ref-set
"Must be called in a transaction. Sets the value of ref.
Returns val."
[#^clojure.lang.Ref ref val]
(. ref (set val)))
(defn ref-history-count
"Returns the history count of a ref"
[#^clojure.lang.Ref ref]
(.getHistoryCount ref))
(defn ref-min-history
"Gets the min-history of a ref, or sets it and returns the ref"
([#^clojure.lang.Ref ref]
(.getMinHistory ref))
([#^clojure.lang.Ref ref n]
(.setMinHistory ref n)))
(defn ref-max-history
"Gets the max-history of a ref, or sets it and returns the ref"
([#^clojure.lang.Ref ref]
(.getMaxHistory ref))
([#^clojure.lang.Ref ref n]
(.setMaxHistory ref n)))
(defn ensure
"Must be called in a transaction. Protects the ref from modification
by other transactions. Returns the in-transaction-value of
ref. Allows for more concurrency than (ref-set ref @ref)"
[#^clojure.lang.Ref ref]
(. ref (touch))
(. ref (deref)))
(defmacro sync
"transaction-flags => TBD, pass nil for now
Runs the exprs (in an implicit do) in a transaction that encompasses
exprs and any nested calls. Starts a transaction if none is already
running on this thread. Any uncaught exception will abort the
transaction and flow out of sync. The exprs may be run more than
once, but any effects on Refs will be atomic."
[flags-ignored-for-now & body]
`(. clojure.lang.LockingTransaction
(runInTransaction (fn [] ~@body))))
(defmacro io!
"If an io! block occurs in a transaction, throws an
IllegalStateException, else runs body in an implicit do. If the
first expression in body is a literal string, will use that as the
exception message."
[& body]
(let [message (when (string? (first body)) (first body))
body (if message (next body) body)]
`(if (clojure.lang.LockingTransaction/isRunning)
(throw (new IllegalStateException ~(or message "I/O in transaction")))
(do ~@body))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; fn stuff ;;;;;;;;;;;;;;;;
(defn comp
"Takes a set of functions and returns a fn that is the composition
of those fns. The returned fn takes a variable number of args,
applies the rightmost of fns to the args, the next
fn (right-to-left) to the result, etc."
([f] f)
([f g]
(fn
([] (f (g)))
([x] (f (g x)))
([x y] (f (g x y)))
([x y z] (f (g x y z)))
([x y z & args] (f (apply g x y z args)))))
([f g h]
(fn
([] (f (g (h))))
([x] (f (g (h x))))
([x y] (f (g (h x y))))
([x y z] (f (g (h x y z))))
([x y z & args] (f (g (apply h x y z args))))))
([f1 f2 f3 & fs]
(let [fs (reverse (list* f1 f2 f3 fs))]
(fn [& args]
(loop [ret (apply (first fs) args) fs (next fs)]
(if fs
(recur ((first fs) ret) (next fs))
ret))))))
(defn juxt
"Alpha - name subject to change.
Takes a set of functions and returns a fn that is the juxtaposition
of those fns. The returned fn takes a variable number of args, and
returns a vector containing the result of applying each fn to the
args (left-to-right).
((juxt a b c) x) => [(a x) (b x) (c x)]"
([f]
(fn
([] [(f)])
([x] [(f x)])
([x y] [(f x y)])
([x y z] [(f x y z)])
([x y z & args] [(apply f x y z args)])))
([f g]
(fn
([] [(f) (g)])
([x] [(f x) (g x)])
([x y] [(f x y) (g x y)])
([x y z] [(f x y z) (g x y z)])
([x y z & args] [(apply f x y z args) (apply g x y z args)])))
([f g h]
(fn
([] [(f) (g) (h)])
([x] [(f x) (g x) (h x)])
([x y] [(f x y) (g x y) (h x y)])
([x y z] [(f x y z) (g x y z) (h x y z)])
([x y z & args] [(apply f x y z args) (apply g x y z args) (apply h x y z args)])))
([f g h & fs]
(let [fs (list* f g h fs)]
(fn
([] (reduce #(conj %1 (%2)) [] fs))
([x] (reduce #(conj %1 (%2 x)) [] fs))
([x y] (reduce #(conj %1 (%2 x y)) [] fs))
([x y z] (reduce #(conj %1 (%2 x y z)) [] fs))
([x y z & args] (reduce #(conj %1 (apply %2 x y z args)) [] fs))))))
(defn partial
"Takes a function f and fewer than the normal arguments to f, and
returns a fn that takes a variable number of additional args. When
called, the returned function calls f with args + additional args."
([f arg1]
(fn [& args] (apply f arg1 args)))
([f arg1 arg2]
(fn [& args] (apply f arg1 arg2 args)))
([f arg1 arg2 arg3]
(fn [& args] (apply f arg1 arg2 arg3 args)))
([f arg1 arg2 arg3 & more]
(fn [& args] (apply f arg1 arg2 arg3 (concat more args)))))
;;;;;;;;;;;;;;;;;;; sequence fns ;;;;;;;;;;;;;;;;;;;;;;;
(defn stream?
"Returns true if x is an instance of Stream"
[x] (instance? clojure.lang.Stream x))
(defn sequence
"Coerces coll to a (possibly empty) sequence, if it is not already
one. Will not force a lazy seq. (sequence nil) yields ()"
[coll]
(cond
(seq? coll) coll
(stream? coll) (.sequence #^clojure.lang.Stream coll)
:else (or (seq coll) ())))
(defn every?
"Returns true if (pred x) is logical true for every x in coll, else
false."
{:tag Boolean}
[pred coll]
(cond
(nil? (seq coll)) true
(pred (first coll)) (recur pred (next coll))
:else false))
(def
#^{:tag Boolean
:doc "Returns false if (pred x) is logical true for every x in
coll, else true."
:arglists '([pred coll])}
not-every? (comp not every?))
(defn some
"Returns the first logical true value of (pred x) for any x in coll,
else nil. One common idiom is to use a set as pred, for example
this will return :fred if :fred is in the sequence, otherwise nil:
(some #{:fred} coll)"
[pred coll]
(when (seq coll)
(or (pred (first coll)) (recur pred (next coll)))))
(def
#^{:tag Boolean
:doc "Returns false if (pred x) is logical true for any x in coll,
else true."
:arglists '([pred coll])}
not-any? (comp not some))
;will be redefed later with arg checks
(defmacro dotimes
"bindings => name n
Repeatedly executes body (presumably for side-effects) with name
bound to integers from 0 through n-1."
[bindings & body]
(let [i (first bindings)
n (second bindings)]
`(let [n# (int ~n)]
(loop [~i (int 0)]
(when (< ~i n#)
~@body
(recur (inc ~i)))))))
(defn map
"Returns a lazy sequence consisting of the result of applying f to the
set of first items of each coll, followed by applying f to the set
of second items in each coll, until any one of the colls is
exhausted. Any remaining items in other colls are ignored. Function
f should accept number-of-colls arguments."
([f coll]
(lazy-seq
(when-let [s (seq coll)]
(if (chunked-seq? s)
(let [c (chunk-first s)
size (int (count c))
b (chunk-buffer size)]
(dotimes [i size]
(chunk-append b (f (.nth c i))))
(chunk-cons (chunk b) (map f (chunk-rest s))))
(cons (f (first s)) (map f (rest s)))))))
([f c1 c2]
(lazy-seq
(let [s1 (seq c1) s2 (seq c2)]
(when (and s1 s2)
(cons (f (first s1) (first s2))
(map f (rest s1) (rest s2)))))))
([f c1 c2 c3]
(lazy-seq
(let [s1 (seq c1) s2 (seq c2) s3 (seq c3)]
(when (and s1 s2 s3)
(cons (f (first s1) (first s2) (first s3))
(map f (rest s1) (rest s2) (rest s3)))))))
([f c1 c2 c3 & colls]
(let [step (fn step [cs]
(lazy-seq
(let [ss (map seq cs)]
(when (every? identity ss)
(cons (map first ss) (step (map rest ss)))))))]
(map #(apply f %) (step (conj colls c3 c2 c1))))))
(defn mapcat
"Returns the result of applying concat to the result of applying map
to f and colls. Thus function f should return a collection."
[f & colls]
(apply concat (apply map f colls)))
(defn filter
"Returns a lazy sequence of the items in coll for which
(pred item) returns true. pred must be free of side-effects."
([pred coll]
(lazy-seq
(when-let [s (seq coll)]
(if (chunked-seq? s)
(let [c (chunk-first s)
size (count c)
b (chunk-buffer size)]
(dotimes [i size]
(when (pred (.nth c i))
(chunk-append b (.nth c i))))
(chunk-cons (chunk b) (filter pred (chunk-rest s))))
(let [f (first s) r (rest s)]
(if (pred f)
(cons f (filter pred r))
(filter pred r))))))))
(defn remove
"Returns a lazy sequence of the items in coll for which
(pred item) returns false. pred must be free of side-effects."
[pred coll]
(filter (complement pred) coll))
(defn take
"Returns a lazy sequence of the first n items in coll, or all items if
there are fewer than n."
[n coll]
(lazy-seq
(when (pos? n)
(when-let [s (seq coll)]
(cons (first s) (take (dec n) (rest s)))))))
(defn take-while
"Returns a lazy sequence of successive items from coll while
(pred item) returns true. pred must be free of side-effects."
[pred coll]
(lazy-seq
(when-let [s (seq coll)]
(when (pred (first s))
(cons (first s) (take-while pred (rest s)))))))
(defn drop
"Returns a lazy sequence of all but the first n items in coll."
[n coll]
(let [step (fn [n coll]
(let [s (seq coll)]
(if (and (pos? n) s)
(recur (dec n) (rest s))
s)))]
(lazy-seq (step n coll))))
(defn drop-last
"Return a lazy sequence of all but the last n (default 1) items in coll"
([s] (drop-last 1 s))
([n s] (map (fn [x _] x) s (drop n s))))
(defn take-last
"Returns a seq of the last n items in coll. Depending on the type
of coll may be no better than linear time. For vectors, see also subvec."
[n coll]
(loop [s (seq coll), lead (seq (drop n coll))]
(if lead
(recur (next s) (next lead))
s)))
(defn drop-while
"Returns a lazy sequence of the items in coll starting from the first
item for which (pred item) returns nil."
[pred coll]
(let [step (fn [pred coll]
(let [s (seq coll)]
(if (and s (pred (first s)))
(recur pred (rest s))
s)))]
(lazy-seq (step pred coll))))
(defn cycle
"Returns a lazy (infinite!) sequence of repetitions of the items in coll."
[coll] (lazy-seq
(when-let [s (seq coll)]
(concat s (cycle s)))))
(defn split-at
"Returns a vector of [(take n coll) (drop n coll)]"
[n coll]
[(take n coll) (drop n coll)])
(defn split-with
"Returns a vector of [(take-while pred coll) (drop-while pred coll)]"
[pred coll]
[(take-while pred coll) (drop-while pred coll)])
(defn repeat
"Returns a lazy (infinite!, or length n if supplied) sequence of xs."
([x] (lazy-seq (cons x (repeat x))))
([n x] (take n (repeat x))))
(defn replicate
"Returns a lazy seq of n xs."
[n x] (take n (repeat x)))
(defn iterate
"Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of side-effects"
[f x] (cons x (lazy-seq (iterate f (f x)))))
(defn range
"Returns a lazy seq of nums from start (inclusive) to end
(exclusive), by step, where start defaults to 0 and step to 1."
([end] (range 0 end 1))
([start end] (range start end 1))
([start end step]
(lazy-seq
(let [b (chunk-buffer 32)
comp (if (pos? step) < >)]
(loop [i start]
(if (and (< (count b) 32)
(comp i end))
(do
(chunk-append b i)
(recur (+ i step)))
(chunk-cons (chunk b)
(when (comp i end)
(range i end step)))))))))
(defn merge
"Returns a map that consists of the rest of the maps conj-ed onto
the first. If a key occurs in more than one map, the mapping from
the latter (left-to-right) will be the mapping in the result."
[& maps]
(when (some identity maps)
(reduce #(conj (or %1 {}) %2) maps)))
(defn merge-with
"Returns a map that consists of the rest of the maps conj-ed onto
the first. If a key occurs in more than one map, the mapping(s)
from the latter (left-to-right) will be combined with the mapping in
the result by calling (f val-in-result val-in-latter)."
[f & maps]
(when (some identity maps)
(let [merge-entry (fn [m e]
(let [k (key e) v (val e)]
(if (contains? m k)
(assoc m k (f (m k) v))
(assoc m k v))))
merge2 (fn [m1 m2]
(reduce merge-entry (or m1 {}) (seq m2)))]
(reduce merge2 maps))))
(defn zipmap
"Returns a map with the keys mapped to the corresponding vals."
[keys vals]
(loop [map {}
ks (seq keys)
vs (seq vals)]
(if (and ks vs)
(recur (assoc map (first ks) (first vs))
(next ks)
(next vs))
map)))
(defn line-seq
"Returns the lines of text from rdr as a lazy sequence of strings.
rdr must implement java.io.BufferedReader."
[#^java.io.BufferedReader rdr]
(let [line (. rdr (readLine))]
(when line
(lazy-seq (cons line (line-seq rdr))))))
(defn comparator
"Returns an implementation of java.util.Comparator based upon pred."
[pred]
(fn [x y]
(cond (pred x y) -1 (pred y x) 1 :else 0)))
(defn sort
"Returns a sorted sequence of the items in coll. If no comparator is
supplied, uses compare. comparator must
implement java.util.Comparator."
([coll]
(sort compare coll))
([#^java.util.Comparator comp coll]
(if (seq coll)
(let [a (to-array coll)]
(. java.util.Arrays (sort a comp))
(seq a))
())))
(defn sort-by
"Returns a sorted sequence of the items in coll, where the sort
order is determined by comparing (keyfn item). If no comparator is
supplied, uses compare. comparator must
implement java.util.Comparator."
([keyfn coll]
(sort-by keyfn compare coll))
([keyfn #^java.util.Comparator comp coll]
(sort (fn [x y] (. comp (compare (keyfn x) (keyfn y)))) coll)))
(defn partition
"Returns a lazy sequence of lists of n items each, at offsets step
apart. If step is not supplied, defaults to n, i.e. the partitions
do not overlap. If a pad collection is supplied, use its elements as
necessary to complete last partition upto n items. In case there are
not enough padding elements, return a partition with less than n items."
([n coll]
(partition n n coll))
([n step coll]
(lazy-seq
(when-let [s (seq coll)]
(let [p (take n s)]
(when (= n (count p))
(cons p (partition n step (drop step s))))))))
([n step pad coll]
(lazy-seq
(when-let [s (seq coll)]
(let [p (take n s)]
(if (= n (count p))
(cons p (partition n step pad (drop step s)))
(list (take n (concat p pad)))))))))
;; evaluation
(defn eval
"Evaluates the form data structure (not text!) and returns the result."
[form] (. clojure.lang.Compiler (eval form)))
(defmacro doseq
"Repeatedly executes body (presumably for side-effects) with
bindings and filtering as provided by \"for\". Does not retain
the head of the sequence. Returns nil."
[seq-exprs & body]
(assert-args doseq
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [step (fn step [recform exprs]
(if-not exprs
[true `(do ~@body)]
(let [k (first exprs)
v (second exprs)]
(if (keyword? k)
(let [steppair (step recform (nnext exprs))
needrec (steppair 0)
subform (steppair 1)]
(cond
(= k :let) [needrec `(let ~v ~subform)]
(= k :while) [false `(when ~v
~subform
~@(when needrec [recform]))]
(= k :when) [false `(if ~v
(do
~subform
~@(when needrec [recform]))
~recform)]))
(let [seq- (gensym "seq_")
chunk- (with-meta (gensym "chunk_")
{:tag 'clojure.lang.IChunk})
count- (gensym "count_")
i- (gensym "i_")
recform `(recur (next ~seq-) nil (int 0) (int 0))
steppair (step recform (nnext exprs))
needrec (steppair 0)
subform (steppair 1)
recform-chunk
`(recur ~seq- ~chunk- ~count- (unchecked-inc ~i-))
steppair-chunk (step recform-chunk (nnext exprs))
subform-chunk (steppair-chunk 1)]
[true
`(loop [~seq- (seq ~v), ~chunk- nil,
~count- (int 0), ~i- (int 0)]
(if (< ~i- ~count-)
(let [~k (.nth ~chunk- ~i-)]
~subform-chunk
~@(when needrec [recform-chunk]))
(when-let [~seq- (seq ~seq-)]
(if (chunked-seq? ~seq-)
(let [c# (chunk-first ~seq-)]
(recur (chunk-rest ~seq-) c#
(int (count c#)) (int 0)))
(let [~k (first ~seq-)]
~subform
~@(when needrec [recform]))))))])))))]
(nth (step nil (seq seq-exprs)) 1)))
(defn dorun
"When lazy sequences are produced via functions that have side
effects, any effects other than those needed to produce the first
element in the seq do not occur until the seq is consumed. dorun can
be used to force any effects. Walks through the successive nexts of
the seq, does not retain the head and returns nil."
([coll]
(when (seq coll)
(recur (next coll))))
([n coll]
(when (and (seq coll) (pos? n))
(recur (dec n) (next coll)))))
(defn doall
"When lazy sequences are produced via functions that have side
effects, any effects other than those needed to produce the first
element in the seq do not occur until the seq is consumed. doall can
be used to force any effects. Walks through the successive nexts of
the seq, retains the head and returns it, thus causing the entire
seq to reside in memory at one time."
([coll]
(dorun coll)
coll)
([n coll]
(dorun n coll)
coll))
(defn await
"Blocks the current thread (indefinitely!) until all actions
dispatched thus far, from this thread or agent, to the agent(s) have
occurred."
[& agents]
(io! "await in transaction"
(when *agent*
(throw (new Exception "Can't await in agent action")))
(let [latch (new java.util.concurrent.CountDownLatch (count agents))
count-down (fn [agent] (. latch (countDown)) agent)]
(doseq [agent agents]
(send agent count-down))
(. latch (await)))))
(defn await1 [#^clojure.lang.Agent a]
(when (pos? (.getQueueCount a))
(await a))
a)
(defn await-for
"Blocks the current thread until all actions dispatched thus
far (from this thread or agent) to the agents have occurred, or the
timeout (in milliseconds) has elapsed. Returns nil if returning due
to timeout, non-nil otherwise."
[timeout-ms & agents]
(io! "await-for in transaction"
(when *agent*
(throw (new Exception "Can't await in agent action")))
(let [latch (new java.util.concurrent.CountDownLatch (count agents))
count-down (fn [agent] (. latch (countDown)) agent)]
(doseq [agent agents]
(send agent count-down))
(. latch (await timeout-ms (. java.util.concurrent.TimeUnit MILLISECONDS))))))
(defmacro dotimes
"bindings => name n
Repeatedly executes body (presumably for side-effects) with name
bound to integers from 0 through n-1."
[bindings & body]
(assert-args dotimes
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [i (first bindings)
n (second bindings)]
`(let [n# (int ~n)]
(loop [~i (int 0)]
(when (< ~i n#)
~@body
(recur (unchecked-inc ~i)))))))
(defn into
"Returns a new coll consisting of to-coll with all of the items of
from-coll conjoined."
[to from]
(let [ret to items (seq from)]
(if items
(recur (conj ret (first items)) (next items))
ret)))
(defmacro import
"import-list => (package-symbol class-name-symbols*)
For each name in class-name-symbols, adds a mapping from name to the
class named by package.name to the current namespace. Use :import in the ns
macro in preference to calling this directly."
[& import-symbols-or-lists]
(let [specs (map #(if (and (seq? %) (= 'quote (first %))) (second %) %)
import-symbols-or-lists)]
`(do ~@(map #(list 'clojure.core/import* %)
(reduce (fn [v spec]
(if (symbol? spec)
(conj v (name spec))
(let [p (first spec) cs (rest spec)]
(into v (map #(str p "." %) cs)))))
[] specs)))))
(defn into-array
"Returns an array with components set to the values in aseq. The array's
component type is type if provided, or the type of the first value in
aseq if present, or Object. All values in aseq must be compatible with
the component type. Class objects for the primitive types can be obtained
using, e.g., Integer/TYPE."
([aseq]
(clojure.lang.RT/seqToTypedArray (seq aseq)))
([type aseq]
(clojure.lang.RT/seqToTypedArray type (seq aseq))))
(defn #^{:private true}
array [& items]
(into-array items))
(defn #^Class class
"Returns the Class of x"
[#^Object x] (if (nil? x) x (. x (getClass))))
(defn type
"Returns the :type metadata of x, or its Class if none"
[x]
(or (:type (meta x)) (class x)))
(defn num
"Coerce to Number"
{:tag Number
:inline (fn [x] `(. clojure.lang.Numbers (num ~x)))}
[x] (. clojure.lang.Numbers (num x)))
(defn long
"Coerce to long"
{:tag Long
:inline (fn [x] `(. clojure.lang.RT (longCast ~x)))}
[#^Number x] (. x (longValue)))
(defn float
"Coerce to float"
{:tag Float
:inline (fn [x] `(. clojure.lang.RT (floatCast ~x)))}
[#^Number x] (. x (floatValue)))
(defn double
"Coerce to double"
{:tag Double
:inline (fn [x] `(. clojure.lang.RT (doubleCast ~x)))}
[#^Number x] (. x (doubleValue)))
(defn short
"Coerce to short"
{:tag Short
:inline (fn [x] `(. clojure.lang.RT (shortCast ~x)))}
[#^Number x] (. x (shortValue)))
(defn byte
"Coerce to byte"
{:tag Byte
:inline (fn [x] `(. clojure.lang.RT (byteCast ~x)))}
[#^Number x] (. x (byteValue)))
(defn char
"Coerce to char"
{:tag Character
:inline (fn [x] `(. clojure.lang.RT (charCast ~x)))}
[x] (. clojure.lang.RT (charCast x)))
(defn boolean
"Coerce to boolean"
{:tag Boolean
:inline (fn [x] `(. clojure.lang.RT (booleanCast ~x)))}
[x] (if x true false))
(defn number?
"Returns true if x is a Number"
[x]
(instance? Number x))
(defn integer?
"Returns true if n is an integer"
[n]
(or (instance? Integer n)
(instance? Long n)
(instance? BigInteger n)
(instance? Short n)
(instance? Byte n)))
(defn mod
"Modulus of num and div. Truncates toward negative infinity."
[num div]
(let [m (rem num div)]
(if (or (zero? m) (pos? (* num div)))
m
(+ m div))))
(defn ratio?
"Returns true if n is a Ratio"
[n] (instance? clojure.lang.Ratio n))
(defn decimal?
"Returns true if n is a BigDecimal"
[n] (instance? BigDecimal n))
(defn float?
"Returns true if n is a floating point number"
[n]
(or (instance? Double n)
(instance? Float n)))
(defn rational? [n]
"Returns true if n is a rational number"
(or (integer? n) (ratio? n) (decimal? n)))
(defn bigint
"Coerce to BigInteger"
{:tag BigInteger}
[x] (cond
(instance? BigInteger x) x
(decimal? x) (.toBigInteger #^BigDecimal x)
(number? x) (BigInteger/valueOf (long x))
:else (BigInteger. x)))
(defn bigdec
"Coerce to BigDecimal"
{:tag BigDecimal}
[x] (cond
(decimal? x) x
(float? x) (. BigDecimal valueOf (double x))
(ratio? x) (/ (BigDecimal. (.numerator x)) (.denominator x))
(instance? BigInteger x) (BigDecimal. #^BigInteger x)
(number? x) (BigDecimal/valueOf (long x))
:else (BigDecimal. x)))
(def #^{:private true} print-initialized false)
(defmulti print-method (fn [x writer] (type x)))
(defmulti print-dup (fn [x writer] (class x)))
(defn pr-on
{:private true}
[x w]
(if *print-dup*
(print-dup x w)
(print-method x w))
nil)
(defn pr
"Prints the object(s) to the output stream that is the current value
of *out*. Prints the object(s), separated by spaces if there is
more than one. By default, pr and prn print in a way that objects
can be read by the reader"
([] nil)
([x]
(pr-on x *out*))
([x & more]
(pr x)
(. *out* (append \space))
(apply pr more)))
(defn newline
"Writes a newline to the output stream that is the current value of
*out*"
[]
(. *out* (append \newline))
nil)
(defn flush
"Flushes the output stream that is the current value of
*out*"
[]
(. *out* (flush))
nil)
(defn prn
"Same as pr followed by (newline). Observes *flush-on-newline*"
[& more]
(apply pr more)
(newline)
(when *flush-on-newline*
(flush)))
(defn print
"Prints the object(s) to the output stream that is the current value
of *out*. print and println produce output for human consumption."
[& more]
(binding [*print-readably* nil]
(apply pr more)))
(defn println
"Same as print followed by (newline)"
[& more]
(binding [*print-readably* nil]
(apply prn more)))
(defn read
"Reads the next object from stream, which must be an instance of
java.io.PushbackReader or some derivee. stream defaults to the
current value of *in* ."
([]
(read *in*))
([stream]
(read stream true nil))
([stream eof-error? eof-value]
(read stream eof-error? eof-value false))
([stream eof-error? eof-value recursive?]
(. clojure.lang.LispReader (read stream (boolean eof-error?) eof-value recursive?))))
(defn read-line
"Reads the next line from stream that is the current value of *in* ."
[]
(if (instance? clojure.lang.LineNumberingPushbackReader *in*)
(.readLine #^clojure.lang.LineNumberingPushbackReader *in*)
(.readLine #^java.io.BufferedReader *in*)))
(defn read-string
"Reads one object from the string s"
[s] (clojure.lang.RT/readString s))
(defn subvec
"Returns a persistent vector of the items in vector from
start (inclusive) to end (exclusive). If end is not supplied,
defaults to (count vector). This operation is O(1) and very fast, as
the resulting vector shares structure with the original and no
trimming is done."
([v start]
(subvec v start (count v)))
([v start end]
(. clojure.lang.RT (subvec v start end))))
(defmacro with-open
"bindings => [name init ...]
Evaluates body in a try expression with names bound to the values
of the inits, and a finally clause that calls (.close name) on each
name in reverse order."
[bindings & body]
(assert-args with-open
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(cond
(= (count bindings) 0) `(do ~@body)
(symbol? (bindings 0)) `(let ~(subvec bindings 0 2)
(try
(with-open ~(subvec bindings 2) ~@body)
(finally
(. ~(bindings 0) close))))
:else (throw (IllegalArgumentException.
"with-open only allows Symbols in bindings"))))
(defmacro doto
"Evaluates x then calls all of the methods and functions with the
value of x supplied at the from of the given arguments. The forms
are evaluated in order. Returns x.
(doto (new java.util.HashMap) (.put \"a\" 1) (.put \"b\" 2))"
[x & forms]
(let [gx (gensym)]
`(let [~gx ~x]
~@(map (fn [f]
(if (seq? f)
`(~(first f) ~gx ~@(next f))
`(~f ~gx)))
forms)
~gx)))
(defmacro memfn
"Expands into code that creates a fn that expects to be passed an
object and any args and calls the named instance method on the
object passing the args. Use when you want to treat a Java method as
a first-class fn."
[name & args]
`(fn [target# ~@args]
(. target# (~name ~@args))))
(defmacro time
"Evaluates expr and prints the time it took. Returns the value of
expr."
[expr]
`(let [start# (. System (nanoTime))
ret# ~expr]
(prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " msecs"))
ret#))
(import '(java.lang.reflect Array))
(defn alength
"Returns the length of the Java array. Works on arrays of all
types."
{:inline (fn [a] `(. clojure.lang.RT (alength ~a)))}
[array] (. clojure.lang.RT (alength array)))
(defn aclone
"Returns a clone of the Java array. Works on arrays of known
types."
{:inline (fn [a] `(. clojure.lang.RT (aclone ~a)))}
[array] (. clojure.lang.RT (aclone array)))
(defn aget
"Returns the value at the index/indices. Works on Java arrays of all
types."
{:inline (fn [a i] `(. clojure.lang.RT (aget ~a ~i)))
:inline-arities #{2}}
([array idx]
(clojure.lang.Reflector/prepRet (. Array (get array idx))))
([array idx & idxs]
(apply aget (aget array idx) idxs)))
(defn aset
"Sets the value at the index/indices. Works on Java arrays of
reference types. Returns val."
{:inline (fn [a i v] `(. clojure.lang.RT (aset ~a ~i ~v)))
:inline-arities #{3}}
([array idx val]
(. Array (set array idx val))
val)
([array idx idx2 & idxv]
(apply aset (aget array idx) idx2 idxv)))
(defmacro
#^{:private true}
def-aset [name method coerce]
`(defn ~name
{:arglists '([~'array ~'idx ~'val] [~'array ~'idx ~'idx2 & ~'idxv])}
([array# idx# val#]
(. Array (~method array# idx# (~coerce val#)))
val#)
([array# idx# idx2# & idxv#]
(apply ~name (aget array# idx#) idx2# idxv#))))
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of int. Returns val."}
aset-int setInt int)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of long. Returns val."}
aset-long setLong long)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of boolean. Returns val."}
aset-boolean setBoolean boolean)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of float. Returns val."}
aset-float setFloat float)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of double. Returns val."}
aset-double setDouble double)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of short. Returns val."}
aset-short setShort short)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of byte. Returns val."}
aset-byte setByte byte)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of char. Returns val."}
aset-char setChar char)
(defn make-array
"Creates and returns an array of instances of the specified class of
the specified dimension(s). Note that a class object is required.
Class objects can be obtained by using their imported or
fully-qualified name. Class objects for the primitive types can be
obtained using, e.g., Integer/TYPE."
([#^Class type len]
(. Array (newInstance type (int len))))
([#^Class type dim & more-dims]
(let [dims (cons dim more-dims)
#^"[I" dimarray (make-array (. Integer TYPE) (count dims))]
(dotimes [i (alength dimarray)]
(aset-int dimarray i (nth dims i)))
(. Array (newInstance type dimarray)))))
(defn to-array-2d
"Returns a (potentially-ragged) 2-dimensional array of Objects
containing the contents of coll, which can be any Collection of any
Collection."
{:tag "[[Ljava.lang.Object;"}
[#^java.util.Collection coll]
(let [ret (make-array (. Class (forName "[Ljava.lang.Object;")) (. coll (size)))]
(loop [i 0 xs (seq coll)]
(when xs
(aset ret i (to-array (first xs)))
(recur (inc i) (next xs))))
ret))
(defn macroexpand-1
"If form represents a macro form, returns its expansion,
else returns form."
[form]
(. clojure.lang.Compiler (macroexpand1 form)))
(defn macroexpand
"Repeatedly calls macroexpand-1 on form until it no longer
represents a macro form, then returns it. Note neither
macroexpand-1 nor macroexpand expand macros in subforms."
[form]
(let [ex (macroexpand-1 form)]
(if (identical? ex form)
form
(macroexpand ex))))
(defn create-struct
"Returns a structure basis object."
[& keys]
(. clojure.lang.PersistentStructMap (createSlotMap keys)))
(defmacro defstruct
"Same as (def name (create-struct keys...))"
[name & keys]
`(def ~name (create-struct ~@keys)))
(defn struct-map
"Returns a new structmap instance with the keys of the
structure-basis. keyvals may contain all, some or none of the basis
keys - where values are not supplied they will default to nil.
keyvals can also contain keys not in the basis."
[s & inits]
(. clojure.lang.PersistentStructMap (create s inits)))
(defn struct
"Returns a new structmap instance with the keys of the
structure-basis. vals must be supplied for basis keys in order -
where values are not supplied they will default to nil."
[s & vals]
(. clojure.lang.PersistentStructMap (construct s vals)))
(defn accessor
"Returns a fn that, given an instance of a structmap with the basis,
returns the value at the key. The key must be in the basis. The
returned function should be (slightly) more efficient than using
get, but such use of accessors should be limited to known
performance-critical areas."
[s key]
(. clojure.lang.PersistentStructMap (getAccessor s key)))
(defn load-reader
"Sequentially read and evaluate the set of forms contained in the
stream/file"
[rdr] (. clojure.lang.Compiler (load rdr)))
(defn load-string
"Sequentially read and evaluate the set of forms contained in the
string"
[s]
(let [rdr (-> (java.io.StringReader. s)
(clojure.lang.LineNumberingPushbackReader.))]
(load-reader rdr)))
(defn set
"Returns a set of the distinct elements of coll."
[coll] (apply hash-set coll))
(defn #^{:private true}
filter-key [keyfn pred amap]
(loop [ret {} es (seq amap)]
(if es
(if (pred (keyfn (first es)))
(recur (assoc ret (key (first es)) (val (first es))) (next es))
(recur ret (next es)))
ret)))
(defn find-ns
"Returns the namespace named by the symbol or nil if it doesn't exist."
[sym] (clojure.lang.Namespace/find sym))
(defn create-ns
"Create a new namespace named by the symbol if one doesn't already
exist, returns it or the already-existing namespace of the same
name."
[sym] (clojure.lang.Namespace/findOrCreate sym))
(defn remove-ns
"Removes the namespace named by the symbol. Use with caution.
Cannot be used to remove the clojure namespace."
[sym] (clojure.lang.Namespace/remove sym))
(defn all-ns
"Returns a sequence of all namespaces."
[] (clojure.lang.Namespace/all))
(defn #^clojure.lang.Namespace the-ns
"If passed a namespace, returns it. Else, when passed a symbol,
returns the namespace named by it, throwing an exception if not
found."
[x]
(if (instance? clojure.lang.Namespace x)
x
(or (find-ns x) (throw (Exception. (str "No namespace: " x " found"))))))
(defn ns-name
"Returns the name of the namespace, a symbol."
[ns]
(.getName (the-ns ns)))
(defn ns-map
"Returns a map of all the mappings for the namespace."
[ns]
(.getMappings (the-ns ns)))
(defn ns-unmap
"Removes the mappings for the symbol from the namespace."
[ns sym]
(.unmap (the-ns ns) sym))
;(defn export [syms]
; (doseq [sym syms]
; (.. *ns* (intern sym) (setExported true))))
(defn ns-publics
"Returns a map of the public intern mappings for the namespace."
[ns]
(let [ns (the-ns ns)]
(filter-key val (fn [#^clojure.lang.Var v] (and (instance? clojure.lang.Var v)
(= ns (.ns v))
(.isPublic v)))
(ns-map ns))))
(defn ns-imports
"Returns a map of the import mappings for the namespace."
[ns]
(filter-key val (partial instance? Class) (ns-map ns)))
(defn refer
"refers to all public vars of ns, subject to filters.
filters can include at most one each of:
:exclude list-of-symbols
:only list-of-symbols
:rename map-of-fromsymbol-tosymbol
For each public interned var in the namespace named by the symbol,
adds a mapping from the name of the var to the var to the current
namespace. Throws an exception if name is already mapped to
something else in the current namespace. Filters can be used to
select a subset, via inclusion or exclusion, or to provide a mapping
to a symbol different from the var's name, in order to prevent
clashes. Use :use in the ns macro in preference to calling this directly."
[ns-sym & filters]
(let [ns (or (find-ns ns-sym) (throw (new Exception (str "No namespace: " ns-sym))))
fs (apply hash-map filters)
nspublics (ns-publics ns)
rename (or (:rename fs) {})
exclude (set (:exclude fs))
to-do (or (:only fs) (keys nspublics))]
(doseq [sym to-do]
(when-not (exclude sym)
(let [v (nspublics sym)]
(when-not v
(throw (new java.lang.IllegalAccessError (str sym " is not public"))))
(. *ns* (refer (or (rename sym) sym) v)))))))
(defn ns-refers
"Returns a map of the refer mappings for the namespace."
[ns]
(let [ns (the-ns ns)]
(filter-key val (fn [#^clojure.lang.Var v] (and (instance? clojure.lang.Var v)
(not= ns (.ns v))))
(ns-map ns))))
(defn ns-interns
"Returns a map of the intern mappings for the namespace."
[ns]
(let [ns (the-ns ns)]
(filter-key val (fn [#^clojure.lang.Var v] (and (instance? clojure.lang.Var v)
(= ns (.ns v))))
(ns-map ns))))
(defn alias
"Add an alias in the current namespace to another
namespace. Arguments are two symbols: the alias to be used, and
the symbolic name of the target namespace. Use :as in the ns macro in preference
to calling this directly."
[alias namespace-sym]
(.addAlias *ns* alias (find-ns namespace-sym)))
(defn ns-aliases
"Returns a map of the aliases for the namespace."
[ns]
(.getAliases (the-ns ns)))
(defn ns-unalias
"Removes the alias for the symbol from the namespace."
[ns sym]
(.removeAlias (the-ns ns) sym))
(defn take-nth
"Returns a lazy seq of every nth item in coll."
[n coll]
(lazy-seq
(when-let [s (seq coll)]
(cons (first s) (take-nth n (drop n s))))))
(defn interleave
"Returns a lazy seq of the first item in each coll, then the second etc."
([c1 c2]
(lazy-seq
(let [s1 (seq c1) s2 (seq c2)]
(when (and s1 s2)
(cons (first s1) (cons (first s2)
(interleave (rest s1) (rest s2))))))))
([c1 c2 & colls]
(lazy-seq
(let [ss (map seq (conj colls c2 c1))]
(when (every? identity ss)
(concat (map first ss) (apply interleave (map rest ss))))))))
(defn var-get
"Gets the value in the var object"
[#^clojure.lang.Var x] (. x (get)))
(defn var-set
"Sets the value in the var object to val. The var must be
thread-locally bound."
[#^clojure.lang.Var x val] (. x (set val)))
(defmacro with-local-vars
"varbinding=> symbol init-expr
Executes the exprs in a context in which the symbols are bound to
vars with per-thread bindings to the init-exprs. The symbols refer
to the var objects themselves, and must be accessed with var-get and
var-set"
[name-vals-vec & body]
(assert-args with-local-vars
(vector? name-vals-vec) "a vector for its binding"
(even? (count name-vals-vec)) "an even number of forms in binding vector")
`(let [~@(interleave (take-nth 2 name-vals-vec)
(repeat '(. clojure.lang.Var (create))))]
(. clojure.lang.Var (pushThreadBindings (hash-map ~@name-vals-vec)))
(try
~@body
(finally (. clojure.lang.Var (popThreadBindings))))))
(defn ns-resolve
"Returns the var or Class to which a symbol will be resolved in the
namespace, else nil. Note that if the symbol is fully qualified,
the var/Class to which it resolves need not be present in the
namespace."
[ns sym]
(clojure.lang.Compiler/maybeResolveIn (the-ns ns) sym))
(defn resolve
"same as (ns-resolve *ns* symbol)"
[sym] (ns-resolve *ns* sym))
(defn array-map
"Constructs an array-map."
([] (. clojure.lang.PersistentArrayMap EMPTY))
([& keyvals] (new clojure.lang.PersistentArrayMap (to-array keyvals))))
(defn nthnext
"Returns the nth next of coll, (seq coll) when n is 0."
[coll n]
(loop [n n xs (seq coll)]
(if (and xs (pos? n))
(recur (dec n) (next xs))
xs)))
;redefine let and loop with destructuring
(defn destructure [bindings]
(let [bmap (apply array-map bindings)
pb (fn pb [bvec b v]
(let [pvec
(fn [bvec b val]
(let [gvec (gensym "vec__")]
(loop [ret (-> bvec (conj gvec) (conj val))
n 0
bs b
seen-rest? false]
(if (seq bs)
(let [firstb (first bs)]
(cond
(= firstb '&) (recur (pb ret (second bs) (list `nthnext gvec n))
n
(nnext bs)
true)
(= firstb :as) (pb ret (second bs) gvec)
:else (if seen-rest?
(throw (new Exception "Unsupported binding form, only :as can follow & parameter"))
(recur (pb ret firstb (list `nth gvec n nil))
(inc n)
(next bs)
seen-rest?))))
ret))))
pmap
(fn [bvec b v]
(let [gmap (or (:as b) (gensym "map__"))
defaults (:or b)]
(loop [ret (-> bvec (conj gmap) (conj v))
bes (reduce
(fn [bes entry]
(reduce #(assoc %1 %2 ((val entry) %2))
(dissoc bes (key entry))
((key entry) bes)))
(dissoc b :as :or)
{:keys #(keyword (str %)), :strs str, :syms #(list `quote %)})]
(if (seq bes)
(let [bb (key (first bes))
bk (val (first bes))
has-default (contains? defaults bb)]
(recur (pb ret bb (if has-default
(list `get gmap bk (defaults bb))
(list `get gmap bk)))
(next bes)))
ret))))]
(cond
(symbol? b) (-> bvec (conj b) (conj v))
(vector? b) (pvec bvec b v)
(map? b) (pmap bvec b v)
:else (throw (new Exception (str "Unsupported binding form: " b))))))
process-entry (fn [bvec b] (pb bvec (key b) (val b)))]
(if (every? symbol? (keys bmap))
bindings
(reduce process-entry [] bmap))))
(defmacro let
"Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein."
[bindings & body]
(assert-args let
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
`(let* ~(destructure bindings) ~@body))
;redefine fn with destructuring and pre/post conditions
(defmacro fn
"(fn name? [params* ] exprs*)
(fn name? ([params* ] exprs*)+)
params => positional-params* , or positional-params* & next-param
positional-param => binding-form
next-param => binding-form
name => symbol
Defines a function"
[& sigs]
(let [name (if (symbol? (first sigs)) (first sigs) nil)
sigs (if name (next sigs) sigs)
sigs (if (vector? (first sigs)) (list sigs) sigs)
psig (fn [sig]
(let [[params & body] sig
conds (when (and (next body) (map? (first body)))
(first body))
body (if conds (next body) body)
conds (or conds (meta params))
pre (:pre conds)
post (:post conds)
body (if post
`((let [~'% ~(if (< 1 (count body))
`(do ~@body)
(first body))]
~@(map (fn [c] `(assert ~c)) post)
~'%))
body)
body (if pre
(concat (map (fn [c] `(assert ~c)) pre)
body)
body)]
(if (every? symbol? params)
(cons params body)
(loop [params params
new-params []
lets []]
(if params
(if (symbol? (first params))
(recur (next params) (conj new-params (first params)) lets)
(let [gparam (gensym "p__")]
(recur (next params) (conj new-params gparam)
(-> lets (conj (first params)) (conj gparam)))))
`(~new-params
(let ~lets
~@body)))))))
new-sigs (map psig sigs)]
(with-meta
(if name
(list* 'fn* name new-sigs)
(cons 'fn* new-sigs))
*macro-meta*)))
(defmacro loop
"Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein. Acts as a recur target."
[bindings & body]
(assert-args loop
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(let [db (destructure bindings)]
(if (= db bindings)
`(loop* ~bindings ~@body)
(let [vs (take-nth 2 (drop 1 bindings))
bs (take-nth 2 bindings)
gs (map (fn [b] (if (symbol? b) b (gensym))) bs)
bfs (reduce (fn [ret [b v g]]
(if (symbol? b)
(conj ret g v)
(conj ret g v b g)))
[] (map vector bs vs gs))]
`(let ~bfs
(loop* ~(vec (interleave gs gs))
(let ~(vec (interleave bs gs))
~@body)))))))
(defmacro when-first
"bindings => x xs
Same as (when (seq xs) (let [x (first xs)] body))"
[bindings & body]
(assert-args when-first
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [[x xs] bindings]
`(when (seq ~xs)
(let [~x (first ~xs)]
~@body))))
(defmacro lazy-cat
"Expands to code which yields a lazy sequence of the concatenation
of the supplied colls. Each coll expr is not evaluated until it is
needed.
(lazy-cat xs ys zs) === (concat (lazy-seq xs) (lazy-seq ys) (lazy-seq zs))"
[& colls]
`(concat ~@(map #(list `lazy-seq %) colls)))
(defmacro for
"List comprehension. Takes a vector of one or more
binding-form/collection-expr pairs, each followed by zero or more
modifiers, and yields a lazy sequence of evaluations of expr.
Collections are iterated in a nested fashion, rightmost fastest,
and nested coll-exprs can refer to bindings created in prior
binding-forms. Supported modifiers are: :let [binding-form expr ...],
:while test, :when test.
(take 100 (for [x (range 100000000) y (range 1000000) :while (< y x)] [x y]))"
[seq-exprs body-expr]
(assert-args for
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [to-groups (fn [seq-exprs]
(reduce (fn [groups [k v]]
(if (keyword? k)
(conj (pop groups) (conj (peek groups) [k v]))
(conj groups [k v])))
[] (partition 2 seq-exprs)))
err (fn [& msg] (throw (IllegalArgumentException. #^String (apply str msg))))
emit-bind (fn emit-bind [[[bind expr & mod-pairs]
& [[_ next-expr] :as next-groups]]]
(let [giter (gensym "iter__")
gxs (gensym "s__")
do-mod (fn do-mod [[[k v :as pair] & etc]]
(cond
(= k :let) `(let ~v ~(do-mod etc))
(= k :while) `(when ~v ~(do-mod etc))
(= k :when) `(if ~v
~(do-mod etc)
(recur (rest ~gxs)))
(keyword? k) (err "Invalid 'for' keyword " k)
next-groups
`(let [iterys# ~(emit-bind next-groups)
fs# (seq (iterys# ~next-expr))]
(if fs#
(concat fs# (~giter (rest ~gxs)))
(recur (rest ~gxs))))
:else `(cons ~body-expr
(~giter (rest ~gxs)))))]
(if next-groups
#_"not the inner-most loop"
`(fn ~giter [~gxs]
(lazy-seq
(loop [~gxs ~gxs]
(when-first [~bind ~gxs]
~(do-mod mod-pairs)))))
#_"inner-most loop"
(let [gi (gensym "i__")
gb (gensym "b__")
do-cmod (fn do-cmod [[[k v :as pair] & etc]]
(cond
(= k :let) `(let ~v ~(do-cmod etc))
(= k :while) `(when ~v ~(do-cmod etc))
(= k :when) `(if ~v
~(do-cmod etc)
(recur
(unchecked-inc ~gi)))
(keyword? k)
(err "Invalid 'for' keyword " k)
:else
`(do (chunk-append ~gb ~body-expr)
(recur (unchecked-inc ~gi)))))]
`(fn ~giter [~gxs]
(lazy-seq
(loop [~gxs ~gxs]
(when-let [~gxs (seq ~gxs)]
(if (chunked-seq? ~gxs)
(let [c# (chunk-first ~gxs)
size# (int (count c#))
~gb (chunk-buffer size#)]
(if (loop [~gi (int 0)]
(if (< ~gi size#)
(let [~bind (.nth c# ~gi)]
~(do-cmod mod-pairs))
true))
(chunk-cons
(chunk ~gb)
(~giter (chunk-rest ~gxs)))
(chunk-cons (chunk ~gb) nil)))
(let [~bind (first ~gxs)]
~(do-mod mod-pairs)))))))))))]
`(let [iter# ~(emit-bind (to-groups seq-exprs))]
(iter# ~(second seq-exprs)))))
(defmacro comment
"Ignores body, yields nil"
[& body])
(defmacro with-out-str
"Evaluates exprs in a context in which *out* is bound to a fresh
StringWriter. Returns the string created by any nested printing
calls."
[& body]
`(let [s# (new java.io.StringWriter)]
(binding [*out* s#]
~@body
(str s#))))
(defmacro with-in-str
"Evaluates body in a context in which *in* is bound to a fresh
StringReader initialized with the string s."
[s & body]
`(with-open [s# (-> (java.io.StringReader. ~s) clojure.lang.LineNumberingPushbackReader.)]
(binding [*in* s#]
~@body)))
(defn pr-str
"pr to a string, returning it"
{:tag String}
[& xs]
(with-out-str
(apply pr xs)))
(defn prn-str
"prn to a string, returning it"
{:tag String}
[& xs]
(with-out-str
(apply prn xs)))
(defn print-str
"print to a string, returning it"
{:tag String}
[& xs]
(with-out-str
(apply print xs)))
(defn println-str
"println to a string, returning it"
{:tag String}
[& xs]
(with-out-str
(apply println xs)))
(defmacro assert
"Evaluates expr and throws an exception if it does not evaluate to
logical true."
[x]
(when *assert*
`(when-not ~x
(throw (new AssertionError (str "Assert failed: " (pr-str '~x)))))))
(defn test
"test [v] finds fn at key :test in var metadata and calls it,
presuming failure will throw exception"
[v]
(let [f (:test (meta v))]
(if f
(do (f) :ok)
:no-test)))
(defn re-pattern
"Returns an instance of java.util.regex.Pattern, for use, e.g. in
re-matcher."
{:tag java.util.regex.Pattern}
[s] (if (instance? java.util.regex.Pattern s)
s
(. java.util.regex.Pattern (compile s))))
(defn re-matcher
"Returns an instance of java.util.regex.Matcher, for use, e.g. in
re-find."
{:tag java.util.regex.Matcher}
[#^java.util.regex.Pattern re s]
(. re (matcher s)))
(defn re-groups
"Returns the groups from the most recent match/find. If there are no
nested groups, returns a string of the entire match. If there are
nested groups, returns a vector of the groups, the first element
being the entire match."
[#^java.util.regex.Matcher m]
(let [gc (. m (groupCount))]
(if (zero? gc)
(. m (group))
(loop [ret [] c 0]
(if (<= c gc)
(recur (conj ret (. m (group c))) (inc c))
ret)))))
(defn re-seq
"Returns a lazy sequence of successive matches of pattern in string,
using java.util.regex.Matcher.find(), each such match processed with
re-groups."
[#^java.util.regex.Pattern re s]
(let [m (re-matcher re s)]
((fn step []
(when (. m (find))
(lazy-seq (cons (re-groups m) (step))))))))
(defn re-matches
"Returns the match, if any, of string to pattern, using
java.util.regex.Matcher.matches(). Uses re-groups to return the
groups."
[#^java.util.regex.Pattern re s]
(let [m (re-matcher re s)]
(when (. m (matches))
(re-groups m))))
(defn re-find
"Returns the next regex match, if any, of string to pattern, using
java.util.regex.Matcher.find(). Uses re-groups to return the
groups."
([#^java.util.regex.Matcher m]
(when (. m (find))
(re-groups m)))
([#^java.util.regex.Pattern re s]
(let [m (re-matcher re s)]
(re-find m))))
(defn rand
"Returns a random floating point number between 0 (inclusive) and
n (default 1) (exclusive)."
([] (. Math (random)))
([n] (* n (rand))))
(defn rand-int
"Returns a random integer between 0 (inclusive) and n (exclusive)."
[n] (int (rand n)))
(defmacro defn-
"same as defn, yielding non-public def"
[name & decls]
(list* `defn (with-meta name (assoc (meta name) :private true)) decls))
(defn print-doc [v]
(println "-------------------------")
(println (str (ns-name (:ns (meta v))) "/" (:name (meta v))))
(prn (:arglists (meta v)))
(when (:macro (meta v))
(println "Macro"))
(println " " (:doc (meta v))))
(defn find-doc
"Prints documentation for any var whose documentation or name
contains a match for re-string-or-pattern"
[re-string-or-pattern]
(let [re (re-pattern re-string-or-pattern)]
(doseq [ns (all-ns)
v (sort-by (comp :name meta) (vals (ns-interns ns)))
:when (and (:doc (meta v))
(or (re-find (re-matcher re (:doc (meta v))))
(re-find (re-matcher re (str (:name (meta v)))))))]
(print-doc v))))
(defn special-form-anchor
"Returns the anchor tag on http://clojure.org/special_forms for the
special form x, or nil"
[x]
(#{'. 'def 'do 'fn 'if 'let 'loop 'monitor-enter 'monitor-exit 'new
'quote 'recur 'set! 'throw 'try 'var} x))
(defn syntax-symbol-anchor
"Returns the anchor tag on http://clojure.org/special_forms for the
special form that uses syntax symbol x, or nil"
[x]
({'& 'fn 'catch 'try 'finally 'try} x))
(defn print-special-doc
[name type anchor]
(println "-------------------------")
(println name)
(println type)
(println (str " Please see http://clojure.org/special_forms#" anchor)))
(defn print-namespace-doc
"Print the documentation string of a Namespace."
[nspace]
(println "-------------------------")
(println (str (ns-name nspace)))
(println " " (:doc (meta nspace))))
(defmacro doc
"Prints documentation for a var or special form given its name"
[name]
(cond
(special-form-anchor `~name)
`(print-special-doc '~name "Special Form" (special-form-anchor '~name))
(syntax-symbol-anchor `~name)
`(print-special-doc '~name "Syntax Symbol" (syntax-symbol-anchor '~name))
:else
(let [nspace (find-ns name)]
(if nspace
`(print-namespace-doc ~nspace)
`(print-doc (var ~name))))))
(defn tree-seq
"Returns a lazy sequence of the nodes in a tree, via a depth-first walk.
branch? must be a fn of one arg that returns true if passed a node
that can have children (but may not). children must be a fn of one
arg that returns a sequence of the children. Will only be called on
nodes for which branch? returns true. Root is the root node of the
tree."
[branch? children root]
(let [walk (fn walk [node]
(lazy-seq
(cons node
(when (branch? node)
(mapcat walk (children node))))))]
(walk root)))
(defn file-seq
"A tree seq on java.io.Files"
[dir]
(tree-seq
(fn [#^java.io.File f] (. f (isDirectory)))
(fn [#^java.io.File d] (seq (. d (listFiles))))
dir))
(defn xml-seq
"A tree seq on the xml elements as per xml/parse"
[root]
(tree-seq
(complement string?)
(comp seq :content)
root))
(defn special-symbol?
"Returns true if s names a special form"
[s]
(contains? (. clojure.lang.Compiler specials) s))
(defn var?
"Returns true if v is of type clojure.lang.Var"
[v] (instance? clojure.lang.Var v))
(defn slurp
"Reads the file named by f using the encoding enc into a string
and returns it."
([f] (slurp f (.name (java.nio.charset.Charset/defaultCharset))))
([#^String f #^String enc]
(with-open [r (new java.io.BufferedReader
(new java.io.InputStreamReader
(new java.io.FileInputStream f) enc))]
(let [sb (new StringBuilder)]
(loop [c (.read r)]
(if (neg? c)
(str sb)
(do
(.append sb (char c))
(recur (.read r)))))))))
(defn subs
"Returns the substring of s beginning at start inclusive, and ending
at end (defaults to length of string), exclusive."
([#^String s start] (. s (substring start)))
([#^String s start end] (. s (substring start end))))
(defn max-key
"Returns the x for which (k x), a number, is greatest."
([k x] x)
([k x y] (if (> (k x) (k y)) x y))
([k x y & more]
(reduce #(max-key k %1 %2) (max-key k x y) more)))
(defn min-key
"Returns the x for which (k x), a number, is least."
([k x] x)
([k x y] (if (< (k x) (k y)) x y))
([k x y & more]
(reduce #(min-key k %1 %2) (min-key k x y) more)))
(defn distinct
"Returns a lazy sequence of the elements of coll with duplicates removed"
[coll]
(let [step (fn step [xs seen]
(lazy-seq
((fn [[f :as xs] seen]
(when-let [s (seq xs)]
(if (contains? seen f)
(recur (rest s) seen)
(cons f (step (rest s) (conj seen f))))))
xs seen)))]
(step coll #{})))
(defn replace
"Given a map of replacement pairs and a vector/collection, returns a
vector/seq with any elements = a key in smap replaced with the
corresponding val in smap"
[smap coll]
(if (vector? coll)
(reduce (fn [v i]
(if-let [e (find smap (nth v i))]
(assoc v i (val e))
v))
coll (range (count coll)))
(map #(if-let [e (find smap %)] (val e) %) coll)))
(defmacro dosync
"Runs the exprs (in an implicit do) in a transaction that encompasses
exprs and any nested calls. Starts a transaction if none is already
running on this thread. Any uncaught exception will abort the
transaction and flow out of dosync. The exprs may be run more than
once, but any effects on Refs will be atomic."
[& exprs]
`(sync nil ~@exprs))
(defmacro with-precision
"Sets the precision and rounding mode to be used for BigDecimal operations.
Usage: (with-precision 10 (/ 1M 3))
or: (with-precision 10 :rounding HALF_DOWN (/ 1M 3))
The rounding mode is one of CEILING, FLOOR, HALF_UP, HALF_DOWN,
HALF_EVEN, UP, DOWN and UNNECESSARY; it defaults to HALF_UP."
[precision & exprs]
(let [[body rm] (if (= (first exprs) :rounding)
[(next (next exprs))
`((. java.math.RoundingMode ~(second exprs)))]
[exprs nil])]
`(binding [*math-context* (java.math.MathContext. ~precision ~@rm)]
~@body)))
(defn mk-bound-fn
{:private true}
[#^clojure.lang.Sorted sc test key]
(fn [e]
(test (.. sc comparator (compare (. sc entryKey e) key)) 0)))
(defn subseq
"sc must be a sorted collection, test(s) one of <, <=, > or
>=. Returns a seq of those entries with keys ek for
which (test (.. sc comparator (compare ek key)) 0) is true"
([#^clojure.lang.Sorted sc test key]
(let [include (mk-bound-fn sc test key)]
(if (#{> >=} test)
(when-let [[e :as s] (. sc seqFrom key true)]
(if (include e) s (next s)))
(take-while include (. sc seq true)))))
([#^clojure.lang.Sorted sc start-test start-key end-test end-key]
(when-let [[e :as s] (. sc seqFrom start-key true)]
(take-while (mk-bound-fn sc end-test end-key)
(if ((mk-bound-fn sc start-test start-key) e) s (next s))))))
(defn rsubseq
"sc must be a sorted collection, test(s) one of <, <=, > or
>=. Returns a reverse seq of those entries with keys ek for
which (test (.. sc comparator (compare ek key)) 0) is true"
([#^clojure.lang.Sorted sc test key]
(let [include (mk-bound-fn sc test key)]
(if (#{< <=} test)
(when-let [[e :as s] (. sc seqFrom key false)]
(if (include e) s (next s)))
(take-while include (. sc seq false)))))
([#^clojure.lang.Sorted sc start-test start-key end-test end-key]
(when-let [[e :as s] (. sc seqFrom end-key false)]
(take-while (mk-bound-fn sc start-test start-key)
(if ((mk-bound-fn sc end-test end-key) e) s (next s))))))
(defn repeatedly
"Takes a function of no args, presumably with side effects, and returns an infinite
lazy sequence of calls to it"
[f] (lazy-seq (cons (f) (repeatedly f))))
(defn add-classpath
"DEPRECATED
Adds the url (String or URL object) to the classpath per
URLClassLoader.addURL"
[url]
(println "WARNING: add-classpath is deprecated")
(clojure.lang.RT/addURL url))
(defn hash
"Returns the hash code of its argument"
[x] (. clojure.lang.Util (hash x)))
(defn interpose
"Returns a lazy seq of the elements of coll separated by sep"
[sep coll] (drop 1 (interleave (repeat sep) coll)))
(defmacro definline
"Experimental - like defmacro, except defines a named function whose
body is the expansion, calls to which may be expanded inline as if
it were a macro. Cannot be used with variadic (&) args."
[name & decl]
(let [[pre-args [args expr]] (split-with (comp not vector?) decl)]
`(do
(defn ~name ~@pre-args ~args ~(apply (eval (list `fn args expr)) args))
(alter-meta! (var ~name) assoc :inline (fn ~name ~args ~expr))
(var ~name))))
(defn empty
"Returns an empty collection of the same category as coll, or nil"
[coll]
(when (instance? clojure.lang.IPersistentCollection coll)
(.empty #^clojure.lang.IPersistentCollection coll)))
(defmacro amap
"Maps an expression across an array a, using an index named idx, and
return value named ret, initialized to a clone of a, then setting
each element of ret to the evaluation of expr, returning the new
array ret."
[a idx ret expr]
`(let [a# ~a
~ret (aclone a#)]
(loop [~idx (int 0)]
(if (< ~idx (alength a#))
(do
(aset ~ret ~idx ~expr)
(recur (unchecked-inc ~idx)))
~ret))))
(defmacro areduce
"Reduces an expression across an array a, using an index named idx,
and return value named ret, initialized to init, setting ret to the
evaluation of expr at each step, returning ret."
[a idx ret init expr]
`(let [a# ~a]
(loop [~idx (int 0) ~ret ~init]
(if (< ~idx (alength a#))
(recur (unchecked-inc ~idx) ~expr)
~ret))))
(defn float-array
"Creates an array of floats"
{:inline (fn [& args] `(. clojure.lang.Numbers float_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers float_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers float_array size init-val-or-seq)))
(defn boolean-array
"Creates an array of booleans"
{:inline (fn [& args] `(. clojure.lang.Numbers boolean_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers boolean_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers boolean_array size init-val-or-seq)))
(defn byte-array
"Creates an array of bytes"
{:inline (fn [& args] `(. clojure.lang.Numbers byte_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers byte_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers byte_array size init-val-or-seq)))
(defn char-array
"Creates an array of chars"
{:inline (fn [& args] `(. clojure.lang.Numbers char_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers char_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers char_array size init-val-or-seq)))
(defn short-array
"Creates an array of shorts"
{:inline (fn [& args] `(. clojure.lang.Numbers short_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers short_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers short_array size init-val-or-seq)))
(defn double-array
"Creates an array of doubles"
{:inline (fn [& args] `(. clojure.lang.Numbers double_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers double_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers double_array size init-val-or-seq)))
(defn int-array
"Creates an array of ints"
{:inline (fn [& args] `(. clojure.lang.Numbers int_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers int_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers int_array size init-val-or-seq)))
(defn long-array
"Creates an array of longs"
{:inline (fn [& args] `(. clojure.lang.Numbers long_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers long_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers long_array size init-val-or-seq)))
(definline booleans
"Casts to boolean[]"
[xs] `(. clojure.lang.Numbers booleans ~xs))
(definline bytes
"Casts to bytes[]"
[xs] `(. clojure.lang.Numbers bytes ~xs))
(definline chars
"Casts to chars[]"
[xs] `(. clojure.lang.Numbers chars ~xs))
(definline shorts
"Casts to shorts[]"
[xs] `(. clojure.lang.Numbers shorts ~xs))
(definline floats
"Casts to float[]"
[xs] `(. clojure.lang.Numbers floats ~xs))
(definline ints
"Casts to int[]"
[xs] `(. clojure.lang.Numbers ints ~xs))
(definline doubles
"Casts to double[]"
[xs] `(. clojure.lang.Numbers doubles ~xs))
(definline longs
"Casts to long[]"
[xs] `(. clojure.lang.Numbers longs ~xs))
(import '(java.util.concurrent BlockingQueue LinkedBlockingQueue))
(defn seque
"Creates a queued seq on another (presumably lazy) seq s. The queued
seq will produce a concrete seq in the background, and can get up to
n items ahead of the consumer. n-or-q can be an integer n buffer
size, or an instance of java.util.concurrent BlockingQueue. Note
that reading from a seque can block if the reader gets ahead of the
producer."
([s] (seque 100 s))
([n-or-q s]
(let [#^BlockingQueue q (if (instance? BlockingQueue n-or-q)
n-or-q
(LinkedBlockingQueue. (int n-or-q)))
NIL (Object.) ;nil sentinel since LBQ doesn't support nils
agt (agent (seq s))
fill (fn [s]
(try
(loop [[x & xs :as s] s]
(if s
(if (.offer q (if (nil? x) NIL x))
(recur xs)
s)
(.put q q))) ; q itself is eos sentinel
(catch Exception e
(.put q q)
(throw e))))
drain (fn drain []
(lazy-seq
(let [x (.take q)]
(if (identical? x q) ;q itself is eos sentinel
(do @agt nil) ;touch agent just to propagate errors
(do
(send-off agt fill)
(cons (if (identical? x NIL) nil x) (drain)))))))]
(send-off agt fill)
(drain))))
(defn class?
"Returns true if x is an instance of Class"
[x] (instance? Class x))
(defn alter-var-root
"Atomically alters the root binding of var v by applying f to its
current value plus any args"
[#^clojure.lang.Var v f & args] (.alterRoot v f args))
(defn make-hierarchy
"Creates a hierarchy object for use with derive, isa? etc."
[] {:parents {} :descendants {} :ancestors {}})
(def #^{:private true}
global-hierarchy (make-hierarchy))
(defn not-empty
"If coll is empty, returns nil, else coll"
[coll] (when (seq coll) coll))
(defn bases
"Returns the immediate superclass and direct interfaces of c, if any"
[#^Class c]
(let [i (.getInterfaces c)
s (.getSuperclass c)]
(not-empty
(if s (cons s i) i))))
(defn supers
"Returns the immediate and indirect superclasses and interfaces of c, if any"
[#^Class class]
(loop [ret (set (bases class)) cs ret]
(if (seq cs)
(let [c (first cs) bs (bases c)]
(recur (into ret bs) (into (disj cs c) bs)))
(not-empty ret))))
(defn isa?
"Returns true if (= child parent), or child is directly or indirectly derived from
parent, either via a Java type inheritance relationship or a
relationship established via derive. h must be a hierarchy obtained
from make-hierarchy, if not supplied defaults to the global
hierarchy"
([child parent] (isa? global-hierarchy child parent))
([h child parent]
(or (= child parent)
(and (class? parent) (class? child)
(. #^Class parent isAssignableFrom child))
(contains? ((:ancestors h) child) parent)
(and (class? child) (some #(contains? ((:ancestors h) %) parent) (supers child)))
(and (vector? parent) (vector? child)
(= (count parent) (count child))
(loop [ret true i 0]
(if (or (not ret) (= i (count parent)))
ret
(recur (isa? h (child i) (parent i)) (inc i))))))))
(defn parents
"Returns the immediate parents of tag, either via a Java type
inheritance relationship or a relationship established via derive. h
must be a hierarchy obtained from make-hierarchy, if not supplied
defaults to the global hierarchy"
([tag] (parents global-hierarchy tag))
([h tag] (not-empty
(let [tp (get (:parents h) tag)]
(if (class? tag)
(into (set (bases tag)) tp)
tp)))))
(defn ancestors
"Returns the immediate and indirect parents of tag, either via a Java type
inheritance relationship or a relationship established via derive. h
must be a hierarchy obtained from make-hierarchy, if not supplied
defaults to the global hierarchy"
([tag] (ancestors global-hierarchy tag))
([h tag] (not-empty
(let [ta (get (:ancestors h) tag)]
(if (class? tag)
(let [superclasses (set (supers tag))]
(reduce into superclasses
(cons ta
(map #(get (:ancestors h) %) superclasses))))
ta)))))
(defn descendants
"Returns the immediate and indirect children of tag, through a
relationship established via derive. h must be a hierarchy obtained
from make-hierarchy, if not supplied defaults to the global
hierarchy. Note: does not work on Java type inheritance
relationships."
([tag] (descendants global-hierarchy tag))
([h tag] (if (class? tag)
(throw (java.lang.UnsupportedOperationException. "Can't get descendants of classes"))
(not-empty (get (:descendants h) tag)))))
(defn derive
"Establishes a parent/child relationship between parent and
tag. Parent must be a namespace-qualified symbol or keyword and
child can be either a namespace-qualified symbol or keyword or a
class. h must be a hierarchy obtained from make-hierarchy, if not
supplied defaults to, and modifies, the global hierarchy."
([tag parent]
(assert (namespace parent))
(assert (or (class? tag) (and (instance? clojure.lang.Named tag) (namespace tag))))
(alter-var-root #'global-hierarchy derive tag parent) nil)
([h tag parent]
(assert (not= tag parent))
(assert (or (class? tag) (instance? clojure.lang.Named tag)))
(assert (instance? clojure.lang.Named parent))
(let [tp (:parents h)
td (:descendants h)
ta (:ancestors h)
tf (fn [m source sources target targets]
(reduce (fn [ret k]
(assoc ret k
(reduce conj (get targets k #{}) (cons target (targets target)))))
m (cons source (sources source))))]
(or
(when-not (contains? (tp tag) parent)
(when (contains? (ta tag) parent)
(throw (Exception. (print-str tag "already has" parent "as ancestor"))))
(when (contains? (ta parent) tag)
(throw (Exception. (print-str "Cyclic derivation:" parent "has" tag "as ancestor"))))
{:parents (assoc (:parents h) tag (conj (get tp tag #{}) parent))
:ancestors (tf (:ancestors h) tag td parent ta)
:descendants (tf (:descendants h) parent ta tag td)})
h))))
(defn underive
"Removes a parent/child relationship between parent and
tag. h must be a hierarchy obtained from make-hierarchy, if not
supplied defaults to, and modifies, the global hierarchy."
([tag parent] (alter-var-root #'global-hierarchy underive tag parent) nil)
([h tag parent]
(let [tp (:parents h)
td (:descendants h)
ta (:ancestors h)
tf (fn [m source sources target targets]
(reduce
(fn [ret k]
(assoc ret k
(reduce disj (get targets k) (cons target (targets target)))))
m (cons source (sources source))))]
(if (contains? (tp tag) parent)
{:parent (assoc (:parents h) tag (disj (get tp tag) parent))
:ancestors (tf (:ancestors h) tag td parent ta)
:descendants (tf (:descendants h) parent ta tag td)}
h))))
(defn distinct?
"Returns true if no two of the arguments are ="
{:tag Boolean}
([x] true)
([x y] (not (= x y)))
([x y & more]
(if (not= x y)
(loop [s #{x y} [x & etc :as xs] more]
(if xs
(if (contains? s x)
false
(recur (conj s x) etc))
true))
false)))
(defn resultset-seq
"Creates and returns a lazy sequence of structmaps corresponding to
the rows in the java.sql.ResultSet rs"
[#^java.sql.ResultSet rs]
(let [rsmeta (. rs (getMetaData))
idxs (range 1 (inc (. rsmeta (getColumnCount))))
keys (map (comp keyword #(.toLowerCase #^String %))
(map (fn [i] (. rsmeta (getColumnLabel i))) idxs))
check-keys
(or (apply distinct? keys)
(throw (Exception. "ResultSet must have unique column labels")))
row-struct (apply create-struct keys)
row-values (fn [] (map (fn [#^Integer i] (. rs (getObject i))) idxs))
rows (fn thisfn []
(when (. rs (next))
(lazy-seq (cons (apply struct row-struct (row-values)) (thisfn)))))]
(rows)))
(defn iterator-seq
"Returns a seq on a java.util.Iterator. Note that most collections
providing iterators implement Iterable and thus support seq directly."
[iter]
(clojure.lang.IteratorSeq/create iter))
(defn enumeration-seq
"Returns a seq on a java.util.Enumeration"
[e]
(clojure.lang.EnumerationSeq/create e))
(defn format
"Formats a string using java.lang.String.format, see java.util.Formatter for format
string syntax"
{:tag String}
[fmt & args]
(String/format fmt (to-array args)))
(defn printf
"Prints formatted output, as per format"
[fmt & args]
(print (apply format fmt args)))
(def gen-class)
(defmacro with-loading-context [& body]
`((fn loading# []
(. clojure.lang.Var (pushThreadBindings {clojure.lang.Compiler/LOADER
(.getClassLoader (.getClass #^Object loading#))}))
(try
~@body
(finally
(. clojure.lang.Var (popThreadBindings)))))))
(defmacro ns
"Sets *ns* to the namespace named by name (unevaluated), creating it
if needed. references can be zero or more of: (:refer-clojure ...)
(:require ...) (:use ...) (:import ...) (:load ...) (:gen-class)
with the syntax of refer-clojure/require/use/import/load/gen-class
respectively, except the arguments are unevaluated and need not be
quoted. (:gen-class ...), when supplied, defaults to :name
corresponding to the ns name, :main true, :impl-ns same as ns, and
:init-impl-ns true. All options of gen-class are
supported. The :gen-class directive is ignored when not
compiling. If :gen-class is not supplied, when compiled only an
nsname__init.class will be generated. If :refer-clojure is not used, a
default (refer 'clojure) is used. Use of ns is preferred to
individual calls to in-ns/require/use/import:
(ns foo.bar
(:refer-clojure :exclude [ancestors printf])
(:require (clojure.contrib sql sql.tests))
(:use (my.lib this that))
(:import (java.util Date Timer Random)
(java.sql Connection Statement)))"
[name & references]
(let [process-reference
(fn [[kname & args]]
`(~(symbol "clojure.core" (clojure.core/name kname))
~@(map #(list 'quote %) args)))
docstring (when (string? (first references)) (first references))
references (if docstring (next references) references)
name (if docstring
(with-meta name (assoc (meta name)
:doc docstring))
name)
gen-class-clause (first (filter #(= :gen-class (first %)) references))
gen-class-call
(when gen-class-clause
(list* `gen-class :name (.replace (str name) \- \_) :impl-ns name :main true (next gen-class-clause)))
references (remove #(= :gen-class (first %)) references)
;ns-effect (clojure.core/in-ns name)
]
`(do
(clojure.core/in-ns '~name)
(with-loading-context
~@(when gen-class-call (list gen-class-call))
~@(when (and (not= name 'clojure.core) (not-any? #(= :refer-clojure (first %)) references))
`((clojure.core/refer '~'clojure.core)))
~@(map process-reference references)))))
(defmacro refer-clojure
"Same as (refer 'clojure.core <filters>)"
[& filters]
`(clojure.core/refer '~'clojure.core ~@filters))
(defmacro defonce
"defs name to have the root value of the expr iff the named var has no root value,
else expr is unevaluated"
[name expr]
`(let [v# (def ~name)]
(when-not (.hasRoot v#)
(def ~name ~expr))))
;;;;;;;;;;; require/use/load, contributed by Stephen C. Gilardi ;;;;;;;;;;;;;;;;;;
(defonce
#^{:private true
:doc "A ref to a sorted set of symbols representing loaded libs"}
*loaded-libs* (ref (sorted-set)))
(defonce
#^{:private true
:doc "the set of paths currently being loaded by this thread"}
*pending-paths* #{})
(defonce
#^{:private true :doc
"True while a verbose load is pending"}
*loading-verbosely* false)
(defn- throw-if
"Throws an exception with a message if pred is true"
[pred fmt & args]
(when pred
(let [#^String message (apply format fmt args)
exception (Exception. message)
raw-trace (.getStackTrace exception)
boring? #(not= (.getMethodName #^StackTraceElement %) "doInvoke")
trace (into-array (drop 2 (drop-while boring? raw-trace)))]
(.setStackTrace exception trace)
(throw exception))))
(defn- libspec?
"Returns true if x is a libspec"
[x]
(or (symbol? x)
(and (vector? x)
(or
(nil? (second x))
(keyword? (second x))))))
(defn- prependss
"Prepends a symbol or a seq to coll"
[x coll]
(if (symbol? x)
(cons x coll)
(concat x coll)))
(defn- root-resource
"Returns the root directory path for a lib"
{:tag String}
[lib]
(str \/
(.. (name lib)
(replace \- \_)
(replace \. \/))))
(defn- root-directory
"Returns the root resource path for a lib"
[lib]
(let [d (root-resource lib)]
(subs d 0 (.lastIndexOf d "/"))))
(def load)
(defn- load-one
"Loads a lib given its name. If need-ns, ensures that the associated
namespace exists after loading. If require, records the load so any
duplicate loads can be skipped."
[lib need-ns require]
(load (root-resource lib))
(throw-if (and need-ns (not (find-ns lib)))
"namespace '%s' not found after loading '%s'"
lib (root-resource lib))
(when require
(dosync
(commute *loaded-libs* conj lib))))
(defn- load-all
"Loads a lib given its name and forces a load of any libs it directly or
indirectly loads. If need-ns, ensures that the associated namespace
exists after loading. If require, records the load so any duplicate loads
can be skipped."
[lib need-ns require]
(dosync
(commute *loaded-libs* #(reduce conj %1 %2)
(binding [*loaded-libs* (ref (sorted-set))]
(load-one lib need-ns require)
@*loaded-libs*))))
(defn- load-lib
"Loads a lib with options"
[prefix lib & options]
(throw-if (and prefix (pos? (.indexOf (name lib) (int \.))))
"lib names inside prefix lists must not contain periods")
(let [lib (if prefix (symbol (str prefix \. lib)) lib)
opts (apply hash-map options)
{:keys [as reload reload-all require use verbose]} opts
loaded (contains? @*loaded-libs* lib)
load (cond reload-all
load-all
(or reload (not require) (not loaded))
load-one)
need-ns (or as use)
filter-opts (select-keys opts '(:exclude :only :rename))]
(binding [*loading-verbosely* (or *loading-verbosely* verbose)]
(if load
(load lib need-ns require)
(throw-if (and need-ns (not (find-ns lib)))
"namespace '%s' not found" lib))
(when (and need-ns *loading-verbosely*)
(printf "(clojure.core/in-ns '%s)\n" (ns-name *ns*)))
(when as
(when *loading-verbosely*
(printf "(clojure.core/alias '%s '%s)\n" as lib))
(alias as lib))
(when use
(when *loading-verbosely*
(printf "(clojure.core/refer '%s" lib)
(doseq [opt filter-opts]
(printf " %s '%s" (key opt) (print-str (val opt))))
(printf ")\n"))
(apply refer lib (mapcat seq filter-opts))))))
(defn- load-libs
"Loads libs, interpreting libspecs, prefix lists, and flags for
forwarding to load-lib"
[& args]
(let [flags (filter keyword? args)
opts (interleave flags (repeat true))
args (filter (complement keyword?) args)]
(doseq [arg args]
(if (libspec? arg)
(apply load-lib nil (prependss arg opts))
(let [[prefix & args] arg]
(throw-if (nil? prefix) "prefix cannot be nil")
(doseq [arg args]
(apply load-lib prefix (prependss arg opts))))))))
;; Public
(defn require
"Loads libs, skipping any that are already loaded. Each argument is
either a libspec that identifies a lib, a prefix list that identifies
multiple libs whose names share a common prefix, or a flag that modifies
how all the identified libs are loaded. Use :require in the ns macro
in preference to calling this directly.
Libs
A 'lib' is a named set of resources in classpath whose contents define a
library of Clojure code. Lib names are symbols and each lib is associated
with a Clojure namespace and a Java package that share its name. A lib's
name also locates its root directory within classpath using Java's
package name to classpath-relative path mapping. All resources in a lib
should be contained in the directory structure under its root directory.
All definitions a lib makes should be in its associated namespace.
'require loads a lib by loading its root resource. The root resource path
is derived from the lib name in the following manner:
Consider a lib named by the symbol 'x.y.z; it has the root directory
<classpath>/x/y/, and its root resource is <classpath>/x/y/z.clj. The root
resource should contain code to create the lib's namespace (usually by using
the ns macro) and load any additional lib resources.
Libspecs
A libspec is a lib name or a vector containing a lib name followed by
options expressed as sequential keywords and arguments.
Recognized options: :as
:as takes a symbol as its argument and makes that symbol an alias to the
lib's namespace in the current namespace.
Prefix Lists
It's common for Clojure code to depend on several libs whose names have
the same prefix. When specifying libs, prefix lists can be used to reduce
repetition. A prefix list contains the shared prefix followed by libspecs
with the shared prefix removed from the lib names. After removing the
prefix, the names that remain must not contain any periods.
Flags
A flag is a keyword.
Recognized flags: :reload, :reload-all, :verbose
:reload forces loading of all the identified libs even if they are
already loaded
:reload-all implies :reload and also forces loading of all libs that the
identified libs directly or indirectly load via require or use
:verbose triggers printing information about each load, alias, and refer
Example:
The following would load the libraries clojure.zip and clojure.set
abbreviated as 's'.
(require '(clojure zip [set :as s]))"
[& args]
(apply load-libs :require args))
(defn use
"Like 'require, but also refers to each lib's namespace using
clojure.core/refer. Use :use in the ns macro in preference to calling
this directly.
'use accepts additional options in libspecs: :exclude, :only, :rename.
The arguments and semantics for :exclude, :only, and :rename are the same
as those documented for clojure.core/refer."
[& args] (apply load-libs :require :use args))
(defn loaded-libs
"Returns a sorted set of symbols naming the currently loaded libs"
[] @*loaded-libs*)
(defn load
"Loads Clojure code from resources in classpath. A path is interpreted as
classpath-relative if it begins with a slash or relative to the root
directory for the current namespace otherwise."
[& paths]
(doseq [#^String path paths]
(let [#^String path (if (.startsWith path "/")
path
(str (root-directory (ns-name *ns*)) \/ path))]
(when *loading-verbosely*
(printf "(clojure.core/load \"%s\")\n" path)
(flush))
; (throw-if (*pending-paths* path)
; "cannot load '%s' again while it is loading"
; path)
(when-not (*pending-paths* path)
(binding [*pending-paths* (conj *pending-paths* path)]
(clojure.lang.RT/load (.substring path 1)))))))
(defn compile
"Compiles the namespace named by the symbol lib into a set of
classfiles. The source for the lib must be in a proper
classpath-relative directory. The output files will go into the
directory specified by *compile-path*, and that directory too must
be in the classpath."
[lib]
(binding [*compile-files* true]
(load-one lib true true))
lib)
;;;;;;;;;;;;; nested associative ops ;;;;;;;;;;;
(defn get-in
"returns the value in a nested associative structure, where ks is a sequence of keys"
[m ks]
(reduce get m ks))
(defn assoc-in
"Associates a value in a nested associative structure, where ks is a
sequence of keys and v is the new value and returns a new nested structure.
If any levels do not exist, hash-maps will be created."
[m [k & ks] v]
(if ks
(assoc m k (assoc-in (get m k) ks v))
(assoc m k v)))
(defn update-in
"'Updates' a value in a nested associative structure, where ks is a
sequence of keys and f is a function that will take the old value
and any supplied args and return the new value, and returns a new
nested structure. If any levels do not exist, hash-maps will be
created."
([m [k & ks] f & args]
(if ks
(assoc m k (apply update-in (get m k) ks f args))
(assoc m k (apply f (get m k) args)))))
(defn empty?
"Returns true if coll has no items - same as (not (seq coll)).
Please use the idiom (seq x) rather than (not (empty? x))"
[coll] (not (seq coll)))
(defn coll?
"Returns true if x implements IPersistentCollection"
[x] (instance? clojure.lang.IPersistentCollection x))
(defn list?
"Returns true if x implements IPersistentList"
[x] (instance? clojure.lang.IPersistentList x))
(defn set?
"Returns true if x implements IPersistentSet"
[x] (instance? clojure.lang.IPersistentSet x))
(defn ifn?
"Returns true if x implements IFn. Note that many data structures
(e.g. sets and maps) implement IFn"
[x] (instance? clojure.lang.IFn x))
(defn fn?
"Returns true if x implements Fn, i.e. is an object created via fn."
[x] (instance? clojure.lang.Fn x))
(defn associative?
"Returns true if coll implements Associative"
[coll] (instance? clojure.lang.Associative coll))
(defn sequential?
"Returns true if coll implements Sequential"
[coll] (instance? clojure.lang.Sequential coll))
(defn sorted?
"Returns true if coll implements Sorted"
[coll] (instance? clojure.lang.Sorted coll))
(defn counted?
"Returns true if coll implements count in constant time"
[coll] (instance? clojure.lang.Counted coll))
(defn reversible?
"Returns true if coll implements Reversible"
[coll] (instance? clojure.lang.Reversible coll))
(def
#^{:doc "bound in a repl thread to the most recent value printed"}
*1)
(def
#^{:doc "bound in a repl thread to the second most recent value printed"}
*2)
(def
#^{:doc "bound in a repl thread to the third most recent value printed"}
*3)
(def
#^{:doc "bound in a repl thread to the most recent exception caught by the repl"}
*e)
(defmacro declare
"defs the supplied var names with no bindings, useful for making forward declarations."
[& names] `(do ~@(map #(list 'def %) names)))
(defn trampoline
"trampoline can be used to convert algorithms requiring mutual
recursion without stack consumption. Calls f with supplied args, if
any. If f returns a fn, calls that fn with no arguments, and
continues to repeat, until the return value is not a fn, then
returns that non-fn value. Note that if you want to return a fn as a
final value, you must wrap it in some data structure and unpack it
after trampoline returns."
([f]
(let [ret (f)]
(if (fn? ret)
(recur ret)
ret)))
([f & args]
(trampoline #(apply f args))))
(defn intern
"Finds or creates a var named by the symbol name in the namespace
ns (which can be a symbol or a namespace), setting its root binding
to val if supplied. The namespace must exist. The var will adopt any
metadata from the name symbol. Returns the var."
([ns #^clojure.lang.Symbol name]
(let [v (clojure.lang.Var/intern (the-ns ns) name)]
(when (meta name) (.setMeta v (meta name)))
v))
([ns name val]
(let [v (clojure.lang.Var/intern (the-ns ns) name val)]
(when (meta name) (.setMeta v (meta name)))
v)))
(defmacro while
"Repeatedly executes body while test expression is true. Presumes
some side-effect will cause test to become false/nil. Returns nil"
[test & body]
`(loop []
(when ~test
~@body
(recur))))
(defn memoize
"Returns a memoized version of a referentially transparent function. The
memoized version of the function keeps a cache of the mapping from arguments
to results and, when calls with the same arguments are repeated often, has
higher performance at the expense of higher memory use."
[f]
(let [mem (atom {})]
(fn [& args]
(if-let [e (find @mem args)]
(val e)
(let [ret (apply f args)]
(swap! mem assoc args ret)
ret)))))
(defmacro condp
"Takes a binary predicate, an expression, and a set of clauses.
Each clause can take the form of either:
test-expr result-expr
test-expr :>> result-fn
Note :>> is an ordinary keyword.
For each clause, (pred test-expr expr) is evaluated. If it returns
logical true, the clause is a match. If a binary clause matches, the
result-expr is returned, if a ternary clause matches, its result-fn,
which must be a unary function, is called with the result of the
predicate as its argument, the result of that call being the return
value of condp. A single default expression can follow the clauses,
and its value will be returned if no clause matches. If no default
expression is provided and no clause matches, an
IllegalArgumentException is thrown."
[pred expr & clauses]
(let [gpred (gensym "pred__")
gexpr (gensym "expr__")
emit (fn emit [pred expr args]
(let [[[a b c :as clause] more]
(split-at (if (= :>> (second args)) 3 2) args)
n (count clause)]
(cond
(= 0 n) `(throw (IllegalArgumentException. (str "No matching clause: " ~expr)))
(= 1 n) a
(= 2 n) `(if (~pred ~a ~expr)
~b
~(emit pred expr more))
:else `(if-let [p# (~pred ~a ~expr)]
(~c p#)
~(emit pred expr more)))))
gres (gensym "res__")]
`(let [~gpred ~pred
~gexpr ~expr]
~(emit gpred gexpr clauses))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; var documentation ;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro add-doc {:private true} [name docstring]
`(alter-meta! (var ~name) assoc :doc ~docstring))
(add-doc *file*
"The path of the file being evaluated, as a String.
Evaluates to nil when there is no file, eg. in the REPL.")
(add-doc *command-line-args*
"A sequence of the supplied command line arguments, or nil if
none were supplied")
(add-doc *warn-on-reflection*
"When set to true, the compiler will emit warnings when reflection is
needed to resolve Java method calls or field accesses.
Defaults to false.")
(add-doc *compile-path*
"Specifies the directory where 'compile' will write out .class
files. This directory must be in the classpath for 'compile' to
work.
Defaults to \"classes\"")
(add-doc *compile-files*
"Set to true when compiling files, false otherwise.")
(add-doc *ns*
"A clojure.lang.Namespace object representing the current namespace.")
(add-doc *in*
"A java.io.Reader object representing standard input for read operations.
Defaults to System/in, wrapped in a LineNumberingPushbackReader")
(add-doc *out*
"A java.io.Writer object representing standard output for print operations.
Defaults to System/out")
(add-doc *err*
"A java.io.Writer object representing standard error for print operations.
Defaults to System/err, wrapped in a PrintWriter")
(add-doc *flush-on-newline*
"When set to true, output will be flushed whenever a newline is printed.
Defaults to true.")
(add-doc *print-meta*
"If set to logical true, when printing an object, its metadata will also
be printed in a form that can be read back by the reader.
Defaults to false.")
(add-doc *print-dup*
"When set to logical true, objects will be printed in a way that preserves
their type when read in later.
Defaults to false.")
(add-doc *print-readably*
"When set to logical false, strings and characters will be printed with
non-alphanumeric characters converted to the appropriate escape sequences.
Defaults to true")
(add-doc *read-eval*
"When set to logical false, the EvalReader (#=(...)) is disabled in the
read/load in the thread-local binding.
Example: (binding [*read-eval* false] (read-string \"#=(eval (def x 3))\"))
Defaults to true")
(defn future?
"Returns true if x is a future"
[x] (instance? java.util.concurrent.Future x))
(defn future-done?
"Returns true if future f is done"
[#^java.util.concurrent.Future f] (.isDone f))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; helper files ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(alter-meta! (find-ns 'clojure.core) assoc :doc "Fundamental library of the Clojure language")
(load "core_proxy")
(load "core_print")
(load "genclass")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; futures (needs proxy);;;;;;;;;;;;;;;;;;
(defn future-call
"Takes a function of no args and yields a future object that will
invoke the function in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block."
[#^Callable f]
(let [fut (.submit clojure.lang.Agent/soloExecutor f)]
(proxy [clojure.lang.IDeref java.util.concurrent.Future] []
(deref [] (.get fut))
(get ([] (.get fut))
([timeout unit] (.get fut timeout unit)))
(isCancelled [] (.isCancelled fut))
(isDone [] (.isDone fut))
(cancel [interrupt?] (.cancel fut interrupt?)))))
(defmacro future
"Takes a body of expressions and yields a future object that will
invoke the body in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block."
[& body] `(future-call (fn [] ~@body)))
(defn future-cancel
"Cancels the future, if possible."
[#^java.util.concurrent.Future f] (.cancel f true))
(defn future-cancelled?
"Returns true if future f is cancelled"
[#^java.util.concurrent.Future f] (.isCancelled f))
(defn pmap
"Like map, except f is applied in parallel. Semi-lazy in that the
parallel computation stays ahead of the consumption, but doesn't
realize the entire result unless required. Only useful for
computationally intensive functions where the time of f dominates
the coordination overhead."
([f coll]
(let [n (+ 2 (.. Runtime getRuntime availableProcessors))
rets (map #(future (f %)) coll)
step (fn step [[x & xs :as vs] fs]
(lazy-seq
(if-let [s (seq fs)]
(cons (deref x) (step xs (rest s)))
(map deref vs))))]
(step rets (drop n rets))))
([f coll & colls]
(let [step (fn step [cs]
(lazy-seq
(let [ss (map seq cs)]
(when (every? identity ss)
(cons (map first ss) (step (map rest ss)))))))]
(pmap #(apply f %) (step (cons coll colls))))))
(defn pcalls
"Executes the no-arg fns in parallel, returning a lazy sequence of
their values"
[& fns] (pmap #(%) fns))
(defmacro pvalues
"Returns a lazy sequence of the values of the exprs, which are
evaluated in parallel"
[& exprs]
`(pcalls ~@(map #(list `fn [] %) exprs)))
(defmacro letfn
"Takes a vector of function specs and a body, and generates a set of
bindings of functions to their names. All of the names are available
in all of the definitions of the functions, as well as the body.
fnspec ==> (fname [params*] exprs) or (fname ([params*] exprs)+)"
[fnspecs & body]
`(letfn* ~(vec (interleave (map first fnspecs)
(map #(cons `fn %) fnspecs)))
~@body))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; clojure version number ;;;;;;;;;;;;;;;;;;;;;;
(let [version-stream (.getResourceAsStream (clojure.lang.RT/baseLoader)
"clojure/version.properties")
properties (doto (new java.util.Properties) (.load version-stream))
prop (fn [k] (.getProperty properties (str "clojure.version." k)))
clojure-version {:major (Integer/valueOf #^String (prop "major"))
:minor (Integer/valueOf #^String (prop "minor"))
:incremental (Integer/valueOf #^String (prop "incremental"))
:qualifier (prop "qualifier")}]
(def *clojure-version*
(if (not (= (prop "interim") "false"))
(clojure.lang.RT/assoc clojure-version :interim true)
clojure-version)))
(add-doc *clojure-version*
"The version info for Clojure core, as a map containing :major :minor
:incremental and :qualifier keys. Feature releases may increment
:minor and/or :major, bugfix releases will increment :incremental.
Possible values of :qualifier include \"GA\", \"SNAPSHOT\", \"RC-x\" \"BETA-x\"")
(defn
clojure-version
"Returns clojure version as a printable string."
[]
(str (:major *clojure-version*)
"."
(:minor *clojure-version*)
(when-let [i (:incremental *clojure-version*)]
(str "." i))
(when-let [q (:qualifier *clojure-version*)]
(when (pos? (count q)) (str "-" q)))
(when (:interim *clojure-version*)
"-SNAPSHOT")))
(defn promise
"Alpha - subject to change.
Returns a promise object that can be read with deref/@, and set,
once only, with deliver. Calls to deref/@ prior to delivery will
block. All subsequent derefs will return the same delivered value
without blocking."
[]
(let [d (java.util.concurrent.CountDownLatch. 1)
v (atom nil)]
(proxy [clojure.lang.AFn clojure.lang.IDeref] []
(deref [] (.await d) @v)
(invoke [x]
(locking d
(if (pos? (.getCount d))
(do (reset! v x)
(.countDown d)
this)
(throw (IllegalStateException. "Multiple deliver calls to a promise"))))))))
(defn deliver
"Alpha - subject to change.
Delivers the supplied value to the promise, releasing any pending
derefs. A subsequent call to deliver on a promise will throw an exception."
[promise val] (promise val))
;;;;;;;;;;;;;;;;;;;;; editable collections ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn transient
"Alpha - subject to change.
Returns a new, transient version of the collection, in constant time."
[#^clojure.lang.IEditableCollection coll]
(.asTransient coll))
(defn persistent!
"Alpha - subject to change.
Returns a new, persistent version of the transient collection, in
constant time. The transient collection cannot be used after this
call, any such use will throw an exception."
[#^clojure.lang.ITransientCollection coll]
(.persistent coll))
(defn conj!
"Alpha - subject to change.
Adds x to the transient collection, and return coll. The 'addition'
may happen at different 'places' depending on the concrete type."
[#^clojure.lang.ITransientCollection coll x]
(.conj coll x))
(defn assoc!
"Alpha - subject to change.
When applied to a transient map, adds mapping of key(s) to
val(s). When applied to a transient vector, sets the val at index.
Note - index must be <= (count vector). Returns coll."
([#^clojure.lang.ITransientAssociative coll key val] (.assoc coll key val))
([#^clojure.lang.ITransientAssociative coll key val & kvs]
(let [ret (.assoc coll key val)]
(if kvs
(recur ret (first kvs) (second kvs) (nnext kvs))
ret))))
(defn dissoc!
"Alpha - subject to change.
Returns a transient map that doesn't contain a mapping for key(s)."
([#^clojure.lang.ITransientMap map key] (.without map key))
([#^clojure.lang.ITransientMap map key & ks]
(let [ret (.without map key)]
(if ks
(recur ret (first ks) (next ks))
ret))))
(defn pop!
"Alpha - subject to change.
Removes the last item from a transient vector. If
the collection is empty, throws an exception. Returns coll"
[#^clojure.lang.ITransientVector coll]
(.pop coll))
(defn disj!
"Alpha - subject to change.
disj[oin]. Returns a transient set of the same (hashed/sorted) type, that
does not contain key(s)."
([set] set)
([#^clojure.lang.ITransientSet set key]
(. set (disjoin key)))
([set key & ks]
(let [ret (disj set key)]
(if ks
(recur ret (first ks) (next ks))
ret))))
;redef into with batch support
(defn into
"Returns a new coll consisting of to-coll with all of the items of
from-coll conjoined."
[to from]
(if (instance? clojure.lang.IEditableCollection to)
(#(loop [ret (transient to) items (seq from)]
(if items
(recur (conj! ret (first items)) (next items))
(persistent! ret))))
(#(loop [ret to items (seq from)]
(if items
(recur (conj ret (first items)) (next items))
ret)))))
| 121580 | ; Copyright (c) <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns #^{:doc "The core Clojure language."
:author "<NAME>"}
clojure.core)
(def unquote)
(def unquote-splicing)
(def
#^{:arglists '([& items])
:doc "Creates a new list containing the items."}
list (. clojure.lang.PersistentList creator))
(def
#^{:arglists '([x seq])
:doc "Returns a new seq where x is the first element and seq is
the rest."}
cons (fn* cons [x seq] (. clojure.lang.RT (cons x seq))))
;during bootstrap we don't have destructuring let, loop or fn, will redefine later
(def
#^{:macro true}
let (fn* let [& decl] (cons 'let* decl)))
(def
#^{:macro true}
loop (fn* loop [& decl] (cons 'loop* decl)))
(def
#^{:macro true}
fn (fn* fn [& decl] (cons 'fn* decl)))
(def
#^{:arglists '([coll])
:doc "Returns the first item in the collection. Calls seq on its
argument. If coll is nil, returns nil."}
first (fn first [coll] (. clojure.lang.RT (first coll))))
(def
#^{:arglists '([coll])
:tag clojure.lang.ISeq
:doc "Returns a seq of the items after the first. Calls seq on its
argument. If there are no more items, returns nil."}
next (fn next [x] (. clojure.lang.RT (next x))))
(def
#^{:arglists '([coll])
:tag clojure.lang.ISeq
:doc "Returns a possibly empty seq of the items after the first. Calls seq on its
argument."}
rest (fn rest [x] (. clojure.lang.RT (more x))))
(def
#^{:arglists '([coll x] [coll x & xs])
:doc "conj[oin]. Returns a new collection with the xs
'added'. (conj nil item) returns (item). The 'addition' may
happen at different 'places' depending on the concrete type."}
conj (fn conj
([coll x] (. clojure.lang.RT (conj coll x)))
([coll x & xs]
(if xs
(recur (conj coll x) (first xs) (next xs))
(conj coll x)))))
(def
#^{:doc "Same as (first (next x))"
:arglists '([x])}
second (fn second [x] (first (next x))))
(def
#^{:doc "Same as (first (first x))"
:arglists '([x])}
ffirst (fn ffirst [x] (first (first x))))
(def
#^{:doc "Same as (next (first x))"
:arglists '([x])}
nfirst (fn nfirst [x] (next (first x))))
(def
#^{:doc "Same as (first (next x))"
:arglists '([x])}
fnext (fn fnext [x] (first (next x))))
(def
#^{:doc "Same as (next (next x))"
:arglists '([x])}
nnext (fn nnext [x] (next (next x))))
(def
#^{:arglists '([coll])
:doc "Returns a seq on the collection. If the collection is
empty, returns nil. (seq nil) returns nil. seq also works on
Strings, native Java arrays (of reference types) and any objects
that implement Iterable."
:tag clojure.lang.ISeq}
seq (fn seq [coll] (. clojure.lang.RT (seq coll))))
(def
#^{:arglists '([#^Class c x])
:doc "Evaluates x and tests if it is an instance of the class
c. Returns true or false"}
instance? (fn instance? [#^Class c x] (. c (isInstance x))))
(def
#^{:arglists '([x])
:doc "Return true if x implements ISeq"}
seq? (fn seq? [x] (instance? clojure.lang.ISeq x)))
(def
#^{:arglists '([x])
:doc "Return true if x is a Character"}
char? (fn char? [x] (instance? Character x)))
(def
#^{:arglists '([x])
:doc "Return true if x is a String"}
string? (fn string? [x] (instance? String x)))
(def
#^{:arglists '([x])
:doc "Return true if x implements IPersistentMap"}
map? (fn map? [x] (instance? clojure.lang.IPersistentMap x)))
(def
#^{:arglists '([x])
:doc "Return true if x implements IPersistentVector "}
vector? (fn vector? [x] (instance? clojure.lang.IPersistentVector x)))
(def
#^{:arglists '([map key val] [map key val & kvs])
:doc "assoc[iate]. When applied to a map, returns a new map of the
same (hashed/sorted) type, that contains the mapping of key(s) to
val(s). When applied to a vector, returns a new vector that
contains val at index. Note - index must be <= (count vector)."}
assoc
(fn assoc
([map key val] (. clojure.lang.RT (assoc map key val)))
([map key val & kvs]
(let [ret (assoc map key val)]
(if kvs
(recur ret (first kvs) (second kvs) (nnext kvs))
ret)))))
;;;;;;;;;;;;;;;;; metadata ;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def
#^{:arglists '([obj])
:doc "Returns the metadata of obj, returns nil if there is no metadata."}
meta (fn meta [x]
(if (instance? clojure.lang.IMeta x)
(. #^clojure.lang.IMeta x (meta)))))
(def
#^{:arglists '([#^clojure.lang.IObj obj m])
:doc "Returns an object of the same type and value as obj, with
map m as its metadata."}
with-meta (fn with-meta [#^clojure.lang.IObj x m]
(. x (withMeta m))))
(def
#^{:private true}
sigs
(fn [fdecl]
(let [asig
(fn [fdecl]
(let [arglist (first fdecl)
body (next fdecl)]
(if (map? (first body))
(if (next body)
(with-meta arglist (conj (if (meta arglist) (meta arglist) {}) (first body)))
arglist)
arglist)))]
(if (seq? (first fdecl))
(loop [ret [] fdecls fdecl]
(if fdecls
(recur (conj ret (asig (first fdecls))) (next fdecls))
(seq ret)))
(list (asig fdecl))))))
(def
#^{:arglists '([coll])
:doc "Return the last item in coll, in linear time"}
last (fn last [s]
(if (next s)
(recur (next s))
(first s))))
(def
#^{:arglists '([coll])
:doc "Return a seq of all but the last item in coll, in linear time"}
butlast (fn butlast [s]
(loop [ret [] s s]
(if (next s)
(recur (conj ret (first s)) (next s))
(seq ret)))))
(def
#^{:doc "Same as (def name (fn [params* ] exprs*)) or (def
name (fn ([params* ] exprs*)+)) with any doc-string or attrs added
to the var metadata"
:arglists '([name doc-string? attr-map? [params*] body]
[name doc-string? attr-map? ([params*] body)+ attr-map?])}
defn (fn defn [name & fdecl]
(let [m (if (string? (first fdecl))
{:doc (first fdecl)}
{})
fdecl (if (string? (first fdecl))
(next fdecl)
fdecl)
m (if (map? (first fdecl))
(conj m (first fdecl))
m)
fdecl (if (map? (first fdecl))
(next fdecl)
fdecl)
fdecl (if (vector? (first fdecl))
(list fdecl)
fdecl)
m (if (map? (last fdecl))
(conj m (last fdecl))
m)
fdecl (if (map? (last fdecl))
(butlast fdecl)
fdecl)
m (conj {:arglists (list 'quote (sigs fdecl))} m)
m (let [inline (:inline m)
ifn (first inline)
iname (second inline)]
;; same as: (if (and (= 'fn ifn) (not (symbol? iname))) ...)
(if (if (clojure.lang.Util/equiv 'fn ifn)
(if (instance? clojure.lang.Symbol iname) false true))
;; inserts the same fn name to the inline fn if it does not have one
(assoc m :inline (cons ifn (cons name (next inline))))
m))]
(list 'def (with-meta name (conj (if (meta name) (meta name) {}) m))
(cons `fn fdecl)))))
(. (var defn) (setMacro))
(defn cast
"Throws a ClassCastException if x is not a c, else returns x."
[#^Class c x]
(. c (cast x)))
(defn to-array
"Returns an array of Objects containing the contents of coll, which
can be any Collection. Maps to java.util.Collection.toArray()."
{:tag "[Ljava.lang.Object;"}
[coll] (. clojure.lang.RT (toArray coll)))
(defn vector
"Creates a new vector containing the args."
([] [])
([& args]
(. clojure.lang.LazilyPersistentVector (create args))))
(defn vec
"Creates a new vector containing the contents of coll."
([coll]
(if (instance? java.util.Collection coll)
(clojure.lang.LazilyPersistentVector/create coll)
(. clojure.lang.LazilyPersistentVector (createOwning (to-array coll))))))
(defn hash-map
"keyval => key val
Returns a new hash map with supplied mappings."
([] {})
([& keyvals]
(. clojure.lang.PersistentHashMap (create keyvals))))
(defn hash-set
"Returns a new hash set with supplied keys."
([] #{})
([& keys]
(clojure.lang.PersistentHashSet/create keys)))
(defn sorted-map
"keyval => key val
Returns a new sorted map with supplied mappings."
([& keyvals]
(clojure.lang.PersistentTreeMap/create keyvals)))
(defn sorted-map-by
"keyval => key val
Returns a new sorted map with supplied mappings, using the supplied comparator."
([comparator & keyvals]
(clojure.lang.PersistentTreeMap/create comparator keyvals)))
(defn sorted-set
"Returns a new sorted set with supplied keys."
([& keys]
(clojure.lang.PersistentTreeSet/create keys)))
(defn sorted-set-by
"Returns a new sorted set with supplied keys, using the supplied comparator."
([comparator & keys]
(clojure.lang.PersistentTreeSet/create comparator keys)))
;;;;;;;;;;;;;;;;;;;;
(def
#^{:doc "Like defn, but the resulting function name is declared as a
macro and will be used as a macro by the compiler when it is
called."
:arglists '([name doc-string? attr-map? [params*] body]
[name doc-string? attr-map? ([params*] body)+ attr-map?])}
defmacro (fn [name & args]
(list 'do
(cons `defn (cons name args))
(list '. (list 'var name) '(setMacro))
(list 'var name))))
(. (var defmacro) (setMacro))
(defmacro when
"Evaluates test. If logical true, evaluates body in an implicit do."
[test & body]
(list 'if test (cons 'do body)))
(defmacro when-not
"Evaluates test. If logical false, evaluates body in an implicit do."
[test & body]
(list 'if test nil (cons 'do body)))
(defn nil?
"Returns true if x is nil, false otherwise."
{:tag Boolean}
[x] (identical? x nil))
(defn false?
"Returns true if x is the value false, false otherwise."
{:tag Boolean}
[x] (identical? x false))
(defn true?
"Returns true if x is the value true, false otherwise."
{:tag Boolean}
[x] (identical? x true))
(defn not
"Returns true if x is logical false, false otherwise."
{:tag Boolean}
[x] (if x false true))
(defn str
"With no args, returns the empty string. With one arg x, returns
x.toString(). (str nil) returns the empty string. With more than
one arg, returns the concatenation of the str values of the args."
{:tag String}
([] "")
([#^Object x]
(if (nil? x) "" (. x (toString))))
([x & ys]
((fn [#^StringBuilder sb more]
(if more
(recur (. sb (append (str (first more)))) (next more))
(str sb)))
(new StringBuilder #^String (str x)) ys)))
(defn symbol?
"Return true if x is a Symbol"
[x] (instance? clojure.lang.Symbol x))
(defn keyword?
"Return true if x is a Keyword"
[x] (instance? clojure.lang.Keyword x))
(defn symbol
"Returns a Symbol with the given namespace and name."
{:tag clojure.lang.Symbol}
([name] (if (symbol? name) name (clojure.lang.Symbol/intern name)))
([ns name] (clojure.lang.Symbol/intern ns name)))
(defn keyword
"Returns a Keyword with the given namespace and name. Do not use :
in the keyword strings, it will be added automatically."
{:tag clojure.lang.Keyword}
([name] (if (keyword? name) name (clojure.lang.Keyword/intern name)))
([ns name] (clojure.lang.Keyword/intern ns name)))
(defn gensym
"Returns a new symbol with a unique name. If a prefix string is
supplied, the name is prefix# where # is some unique number. If
prefix is not supplied, the prefix is 'G__'."
([] (gensym "G__"))
([prefix-string] (. clojure.lang.Symbol (intern (str prefix-string (str (. clojure.lang.RT (nextID))))))))
(defmacro cond
"Takes a set of test/expr pairs. It evaluates each test one at a
time. If a test returns logical true, cond evaluates and returns
the value of the corresponding expr and doesn't evaluate any of the
other tests or exprs. (cond) returns nil."
[& clauses]
(when clauses
(list 'if (first clauses)
(if (next clauses)
(second clauses)
(throw (IllegalArgumentException.
"cond requires an even number of forms")))
(cons 'clojure.core/cond (next (next clauses))))))
(defn spread
{:private true}
[arglist]
(cond
(nil? arglist) nil
(nil? (next arglist)) (seq (first arglist))
:else (cons (first arglist) (spread (next arglist)))))
(defn list*
"Creates a new list containing the items prepended to the rest, the
last of which will be treated as a sequence."
([args] (seq args))
([a args] (cons a args))
([a b args] (cons a (cons b args)))
([a b c args] (cons a (cons b (cons c args))))
([a b c d & more]
(cons a (cons b (cons c (cons d (spread more)))))))
(defn apply
"Applies fn f to the argument list formed by prepending args to argseq."
{:arglists '([f args* argseq])}
([#^clojure.lang.IFn f args]
(. f (applyTo (seq args))))
([#^clojure.lang.IFn f x args]
(. f (applyTo (list* x args))))
([#^clojure.lang.IFn f x y args]
(. f (applyTo (list* x y args))))
([#^clojure.lang.IFn f x y z args]
(. f (applyTo (list* x y z args))))
([#^clojure.lang.IFn f a b c d & args]
(. f (applyTo (cons a (cons b (cons c (cons d (spread args)))))))))
(defn vary-meta
"Returns an object of the same type and value as obj, with
(apply f (meta obj) args) as its metadata."
[obj f & args]
(with-meta obj (apply f (meta obj) args)))
(defmacro lazy-seq
"Takes a body of expressions that returns an ISeq or nil, and yields
a Seqable object that will invoke the body only the first time seq
is called, and will cache the result and return it on all subsequent
seq calls."
[& body]
(list 'new 'clojure.lang.LazySeq (list* '#^{:once true} fn* [] body)))
(defn #^clojure.lang.ChunkBuffer chunk-buffer [capacity]
(clojure.lang.ChunkBuffer. capacity))
(defn chunk-append [#^clojure.lang.ChunkBuffer b x]
(.add b x))
(defn chunk [#^clojure.lang.ChunkBuffer b]
(.chunk b))
(defn #^clojure.lang.IChunk chunk-first [#^clojure.lang.IChunkedSeq s]
(.chunkedFirst s))
(defn #^clojure.lang.ISeq chunk-rest [#^clojure.lang.IChunkedSeq s]
(.chunkedMore s))
(defn #^clojure.lang.ISeq chunk-next [#^clojure.lang.IChunkedSeq s]
(.chunkedNext s))
(defn chunk-cons [chunk rest]
(if (clojure.lang.Numbers/isZero (clojure.lang.RT/count chunk))
rest
(clojure.lang.ChunkedCons. chunk rest)))
(defn chunked-seq? [s]
(instance? clojure.lang.IChunkedSeq s))
(defn concat
"Returns a lazy seq representing the concatenation of the elements in the supplied colls."
([] (lazy-seq nil))
([x] (lazy-seq x))
([x y]
(lazy-seq
(let [s (seq x)]
(if s
(if (chunked-seq? s)
(chunk-cons (chunk-first s) (concat (chunk-rest s) y))
(cons (first s) (concat (rest s) y)))
y))))
([x y & zs]
(let [cat (fn cat [xys zs]
(lazy-seq
(let [xys (seq xys)]
(if xys
(if (chunked-seq? xys)
(chunk-cons (chunk-first xys)
(cat (chunk-rest xys) zs))
(cons (first xys) (cat (rest xys) zs)))
(when zs
(cat (first zs) (next zs)))))))]
(cat (concat x y) zs))))
;;;;;;;;;;;;;;;;at this point all the support for syntax-quote exists;;;;;;;;;;;;;;;;;;;;;;
(defmacro delay
"Takes a body of expressions and yields a Delay object that will
invoke the body only the first time it is forced (with force), and
will cache the result and return it on all subsequent force
calls."
[& body]
(list 'new 'clojure.lang.Delay (list* `#^{:once true} fn* [] body)))
(defn delay?
"returns true if x is a Delay created with delay"
[x] (instance? clojure.lang.Delay x))
(defn force
"If x is a Delay, returns the (possibly cached) value of its expression, else returns x"
[x] (. clojure.lang.Delay (force x)))
(defmacro if-not
"Evaluates test. If logical false, evaluates and returns then expr,
otherwise else expr, if supplied, else nil."
([test then] `(if-not ~test ~then nil))
([test then else]
`(if (not ~test) ~then ~else)))
(defn =
"Equality. Returns true if x equals y, false if not. Same as
Java x.equals(y) except it also works for nil, and compares
numbers and collections in a type-independent manner. Clojure's immutable data
structures define equals() (and thus =) as a value, not an identity,
comparison."
{:tag Boolean
:inline (fn [x y] `(. clojure.lang.Util equiv ~x ~y))
:inline-arities #{2}}
([x] true)
([x y] (clojure.lang.Util/equiv x y))
([x y & more]
(if (= x y)
(if (next more)
(recur y (first more) (next more))
(= y (first more)))
false)))
(defn not=
"Same as (not (= obj1 obj2))"
{:tag Boolean}
([x] false)
([x y] (not (= x y)))
([x y & more]
(not (apply = x y more))))
(defn compare
"Comparator. Returns a negative number, zero, or a positive number
when x is logically 'less than', 'equal to', or 'greater than'
y. Same as Java x.compareTo(y) except it also works for nil, and
compares numbers and collections in a type-independent manner. x
must implement Comparable"
{:tag Integer
:inline (fn [x y] `(. clojure.lang.Util compare ~x ~y))}
[x y] (. clojure.lang.Util (compare x y)))
(defmacro and
"Evaluates exprs one at a time, from left to right. If a form
returns logical false (nil or false), and returns that value and
doesn't evaluate any of the other expressions, otherwise it returns
the value of the last expr. (and) returns true."
([] true)
([x] x)
([x & next]
`(let [and# ~x]
(if and# (and ~@next) and#))))
(defmacro or
"Evaluates exprs one at a time, from left to right. If a form
returns a logical true value, or returns that value and doesn't
evaluate any of the other expressions, otherwise it returns the
value of the last expression. (or) returns nil."
([] nil)
([x] x)
([x & next]
`(let [or# ~x]
(if or# or# (or ~@next)))))
;;;;;;;;;;;;;;;;;;; sequence fns ;;;;;;;;;;;;;;;;;;;;;;;
(defn zero?
"Returns true if num is zero, else false"
{:tag Boolean
:inline (fn [x] `(. clojure.lang.Numbers (isZero ~x)))}
[x] (. clojure.lang.Numbers (isZero x)))
(defn count
"Returns the number of items in the collection. (count nil) returns
0. Also works on strings, arrays, and Java Collections and Maps"
[coll] (clojure.lang.RT/count coll))
(defn int
"Coerce to int"
{:tag Integer
:inline (fn [x] `(. clojure.lang.RT (intCast ~x)))}
[x] (. clojure.lang.RT (intCast x)))
(defn nth
"Returns the value at the index. get returns nil if index out of
bounds, nth throws an exception unless not-found is supplied. nth
also works for strings, Java arrays, regex Matchers and Lists, and,
in O(n) time, for sequences."
{:inline (fn [c i & nf] `(. clojure.lang.RT (nth ~c ~i ~@nf)))
:inline-arities #{2 3}}
([coll index] (. clojure.lang.RT (nth coll index)))
([coll index not-found] (. clojure.lang.RT (nth coll index not-found))))
(defn <
"Returns non-nil if nums are in monotonically increasing order,
otherwise false."
{:inline (fn [x y] `(. clojure.lang.Numbers (lt ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (lt x y)))
([x y & more]
(if (< x y)
(if (next more)
(recur y (first more) (next more))
(< y (first more)))
false)))
(defn inc
"Returns a number one greater than num."
{:inline (fn [x] `(. clojure.lang.Numbers (inc ~x)))}
[x] (. clojure.lang.Numbers (inc x)))
(defn reduce
"f should be a function of 2 arguments. If val is not supplied,
returns the result of applying f to the first 2 items in coll, then
applying f to that result and the 3rd item, etc. If coll contains no
items, f must accept no arguments as well, and reduce returns the
result of calling f with no arguments. If coll has only 1 item, it
is returned and f is not called. If val is supplied, returns the
result of applying f to val and the first item in coll, then
applying f to that result and the 2nd item, etc. If coll contains no
items, returns val and f is not called."
([f coll]
(let [s (seq coll)]
(if s
(reduce f (first s) (next s))
(f))))
([f val coll]
(let [s (seq coll)]
(if s
(if (chunked-seq? s)
(recur f
(.reduce (chunk-first s) f val)
(chunk-next s))
(recur f (f val (first s)) (next s)))
val))))
(defn reverse
"Returns a seq of the items in coll in reverse order. Not lazy."
[coll]
(reduce conj () coll))
;;math stuff
(defn +
"Returns the sum of nums. (+) returns 0."
{:inline (fn [x y] `(. clojure.lang.Numbers (add ~x ~y)))
:inline-arities #{2}}
([] 0)
([x] (cast Number x))
([x y] (. clojure.lang.Numbers (add x y)))
([x y & more]
(reduce + (+ x y) more)))
(defn *
"Returns the product of nums. (*) returns 1."
{:inline (fn [x y] `(. clojure.lang.Numbers (multiply ~x ~y)))
:inline-arities #{2}}
([] 1)
([x] (cast Number x))
([x y] (. clojure.lang.Numbers (multiply x y)))
([x y & more]
(reduce * (* x y) more)))
(defn /
"If no denominators are supplied, returns 1/numerator,
else returns numerator divided by all of the denominators."
{:inline (fn [x y] `(. clojure.lang.Numbers (divide ~x ~y)))
:inline-arities #{2}}
([x] (/ 1 x))
([x y] (. clojure.lang.Numbers (divide x y)))
([x y & more]
(reduce / (/ x y) more)))
(defn -
"If no ys are supplied, returns the negation of x, else subtracts
the ys from x and returns the result."
{:inline (fn [& args] `(. clojure.lang.Numbers (minus ~@args)))
:inline-arities #{1 2}}
([x] (. clojure.lang.Numbers (minus x)))
([x y] (. clojure.lang.Numbers (minus x y)))
([x y & more]
(reduce - (- x y) more)))
(defn <=
"Returns non-nil if nums are in monotonically non-decreasing order,
otherwise false."
{:inline (fn [x y] `(. clojure.lang.Numbers (lte ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (lte x y)))
([x y & more]
(if (<= x y)
(if (next more)
(recur y (first more) (next more))
(<= y (first more)))
false)))
(defn >
"Returns non-nil if nums are in monotonically decreasing order,
otherwise false."
{:inline (fn [x y] `(. clojure.lang.Numbers (gt ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (gt x y)))
([x y & more]
(if (> x y)
(if (next more)
(recur y (first more) (next more))
(> y (first more)))
false)))
(defn >=
"Returns non-nil if nums are in monotonically non-increasing order,
otherwise false."
{:inline (fn [x y] `(. clojure.lang.Numbers (gte ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (gte x y)))
([x y & more]
(if (>= x y)
(if (next more)
(recur y (first more) (next more))
(>= y (first more)))
false)))
(defn ==
"Returns non-nil if nums all have the same value, otherwise false"
{:inline (fn [x y] `(. clojure.lang.Numbers (equiv ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (equiv x y)))
([x y & more]
(if (== x y)
(if (next more)
(recur y (first more) (next more))
(== y (first more)))
false)))
(defn max
"Returns the greatest of the nums."
([x] x)
([x y] (if (> x y) x y))
([x y & more]
(reduce max (max x y) more)))
(defn min
"Returns the least of the nums."
([x] x)
([x y] (if (< x y) x y))
([x y & more]
(reduce min (min x y) more)))
(defn dec
"Returns a number one less than num."
{:inline (fn [x] `(. clojure.lang.Numbers (dec ~x)))}
[x] (. clojure.lang.Numbers (dec x)))
(defn unchecked-inc
"Returns a number one greater than x, an int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x] `(. clojure.lang.Numbers (unchecked_inc ~x)))}
[x] (. clojure.lang.Numbers (unchecked_inc x)))
(defn unchecked-dec
"Returns a number one less than x, an int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x] `(. clojure.lang.Numbers (unchecked_dec ~x)))}
[x] (. clojure.lang.Numbers (unchecked_dec x)))
(defn unchecked-negate
"Returns the negation of x, an int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x] `(. clojure.lang.Numbers (unchecked_negate ~x)))}
[x] (. clojure.lang.Numbers (unchecked_negate x)))
(defn unchecked-add
"Returns the sum of x and y, both int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_add ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_add x y)))
(defn unchecked-subtract
"Returns the difference of x and y, both int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_subtract ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_subtract x y)))
(defn unchecked-multiply
"Returns the product of x and y, both int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_multiply ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_multiply x y)))
(defn unchecked-divide
"Returns the division of x by y, both int or long.
Note - uses a primitive operator subject to truncation."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_divide ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_divide x y)))
(defn unchecked-remainder
"Returns the remainder of division of x by y, both int or long.
Note - uses a primitive operator subject to truncation."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_remainder ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_remainder x y)))
(defn pos?
"Returns true if num is greater than zero, else false"
{:tag Boolean
:inline (fn [x] `(. clojure.lang.Numbers (isPos ~x)))}
[x] (. clojure.lang.Numbers (isPos x)))
(defn neg?
"Returns true if num is less than zero, else false"
{:tag Boolean
:inline (fn [x] `(. clojure.lang.Numbers (isNeg ~x)))}
[x] (. clojure.lang.Numbers (isNeg x)))
(defn quot
"quot[ient] of dividing numerator by denominator."
[num div]
(. clojure.lang.Numbers (quotient num div)))
(defn rem
"remainder of dividing numerator by denominator."
[num div]
(. clojure.lang.Numbers (remainder num div)))
(defn rationalize
"returns the rational value of num"
[num]
(. clojure.lang.Numbers (rationalize num)))
;;Bit ops
(defn bit-not
"Bitwise complement"
{:inline (fn [x] `(. clojure.lang.Numbers (not ~x)))}
[x] (. clojure.lang.Numbers not x))
(defn bit-and
"Bitwise and"
{:inline (fn [x y] `(. clojure.lang.Numbers (and ~x ~y)))}
[x y] (. clojure.lang.Numbers and x y))
(defn bit-or
"Bitwise or"
{:inline (fn [x y] `(. clojure.lang.Numbers (or ~x ~y)))}
[x y] (. clojure.lang.Numbers or x y))
(defn bit-xor
"Bitwise exclusive or"
{:inline (fn [x y] `(. clojure.lang.Numbers (xor ~x ~y)))}
[x y] (. clojure.lang.Numbers xor x y))
(defn bit-and-not
"Bitwise and with complement"
[x y] (. clojure.lang.Numbers andNot x y))
(defn bit-clear
"Clear bit at index n"
[x n] (. clojure.lang.Numbers clearBit x n))
(defn bit-set
"Set bit at index n"
[x n] (. clojure.lang.Numbers setBit x n))
(defn bit-flip
"Flip bit at index n"
[x n] (. clojure.lang.Numbers flipBit x n))
(defn bit-test
"Test bit at index n"
[x n] (. clojure.lang.Numbers testBit x n))
(defn bit-shift-left
"Bitwise shift left"
[x n] (. clojure.lang.Numbers shiftLeft x n))
(defn bit-shift-right
"Bitwise shift right"
[x n] (. clojure.lang.Numbers shiftRight x n))
(defn even?
"Returns true if n is even, throws an exception if n is not an integer"
[n] (zero? (bit-and n 1)))
(defn odd?
"Returns true if n is odd, throws an exception if n is not an integer"
[n] (not (even? n)))
;;
(defn complement
"Takes a fn f and returns a fn that takes the same arguments as f,
has the same effects, if any, and returns the opposite truth value."
[f]
(fn
([] (not (f)))
([x] (not (f x)))
([x y] (not (f x y)))
([x y & zs] (not (apply f x y zs)))))
(defn constantly
"Returns a function that takes any number of arguments and returns x."
[x] (fn [& args] x))
(defn identity
"Returns its argument."
[x] x)
;;Collection stuff
;;list stuff
(defn peek
"For a list or queue, same as first, for a vector, same as, but much
more efficient than, last. If the collection is empty, returns nil."
[coll] (. clojure.lang.RT (peek coll)))
(defn pop
"For a list or queue, returns a new list/queue without the first
item, for a vector, returns a new vector without the last item. If
the collection is empty, throws an exception. Note - not the same
as next/butlast."
[coll] (. clojure.lang.RT (pop coll)))
;;map stuff
(defn contains?
"Returns true if key is present in the given collection, otherwise
returns false. Note that for numerically indexed collections like
vectors and Java arrays, this tests if the numeric key is within the
range of indexes. 'contains?' operates constant or logarithmic time;
it will not perform a linear search for a value. See also 'some'."
[coll key] (. clojure.lang.RT (contains coll key)))
(defn get
"Returns the value mapped to key, not-found or nil if key not present."
([map key]
(. clojure.lang.RT (get map key)))
([map key not-found]
(. clojure.lang.RT (get map key not-found))))
(defn dissoc
"dissoc[iate]. Returns a new map of the same (hashed/sorted) type,
that does not contain a mapping for key(s)."
([map] map)
([map key]
(. clojure.lang.RT (dissoc map key)))
([map key & ks]
(let [ret (dissoc map key)]
(if ks
(recur ret (first ks) (next ks))
ret))))
(defn disj
"disj[oin]. Returns a new set of the same (hashed/sorted) type, that
does not contain key(s)."
([set] set)
([#^clojure.lang.IPersistentSet set key]
(. set (disjoin key)))
([set key & ks]
(let [ret (disj set key)]
(if ks
(recur ret (first ks) (next ks))
ret))))
(defn find
"Returns the map entry for key, or nil if key not present."
[map key] (. clojure.lang.RT (find map key)))
(defn select-keys
"Returns a map containing only those entries in map whose key is in keys"
[map keyseq]
(loop [ret {} keys (seq keyseq)]
(if keys
(let [entry (. clojure.lang.RT (find map (first keys)))]
(recur
(if entry
(conj ret entry)
ret)
(next keys)))
ret)))
(defn keys
"Returns a sequence of the map's keys."
[map] (. clojure.lang.RT (keys map)))
(defn vals
"Returns a sequence of the map's values."
[map] (. clojure.lang.RT (vals map)))
(defn key
"Returns the key of the map entry."
[#^java.util.Map$Entry e]
(. e (getKey)))
(defn val
"Returns the value in the map entry."
[#^java.util.Map$Entry e]
(. e (getValue)))
(defn rseq
"Returns, in constant time, a seq of the items in rev (which
can be a vector or sorted-map), in reverse order. If rev is empty returns nil"
[#^clojure.lang.Reversible rev]
(. rev (rseq)))
(defn name
"Returns the name String of a symbol or keyword."
{:tag String}
[#^clojure.lang.Named x]
(. x (getName)))
(defn namespace
"Returns the namespace String of a symbol or keyword, or nil if not present."
{:tag String}
[#^clojure.lang.Named x]
(. x (getNamespace)))
(defmacro locking
"Executes exprs in an implicit do, while holding the monitor of x.
Will release the monitor of x in all circumstances."
[x & body]
`(let [lockee# ~x]
(try
(monitor-enter lockee#)
~@body
(finally
(monitor-exit lockee#)))))
(defmacro ..
"form => fieldName-symbol or (instanceMethodName-symbol args*)
Expands into a member access (.) of the first member on the first
argument, followed by the next member on the result, etc. For
instance:
(.. System (getProperties) (get \"os.name\"))
expands to:
(. (. System (getProperties)) (get \"os.name\"))
but is easier to write, read, and understand."
([x form] `(. ~x ~form))
([x form & more] `(.. (. ~x ~form) ~@more)))
(defmacro ->
"Threads the expr through the forms. Inserts x as the
second item in the first form, making a list of it if it is not a
list already. If there are more forms, inserts the first form as the
second item in second form, etc."
([x] x)
([x form] (if (seq? form)
(with-meta `(~(first form) ~x ~@(next form)) (meta form))
(list form x)))
([x form & more] `(-> (-> ~x ~form) ~@more)))
(defmacro ->>
"Threads the expr through the forms. Inserts x as the
last item in the first form, making a list of it if it is not a
list already. If there are more forms, inserts the first form as the
last item in second form, etc."
([x form] (if (seq? form)
(with-meta `(~(first form) ~@(next form) ~x) (meta form))
(list form x)))
([x form & more] `(->> (->> ~x ~form) ~@more)))
;;multimethods
(def global-hierarchy)
(defmacro defmulti
"Creates a new multimethod with the associated dispatch function.
The docstring and attribute-map are optional.
Options are key-value pairs and may be one of:
:default the default dispatch value, defaults to :default
:hierarchy the isa? hierarchy to use for dispatching
defaults to the global hierarchy"
{:arglists '([name docstring? attr-map? dispatch-fn & options])}
[mm-name & options]
(let [docstring (if (string? (first options))
(first options)
nil)
options (if (string? (first options))
(next options)
options)
m (if (map? (first options))
(first options)
{})
options (if (map? (first options))
(next options)
options)
dispatch-fn (first options)
options (next options)
m (assoc m :tag 'clojure.lang.MultiFn)
m (if docstring
(assoc m :doc docstring)
m)
m (if (meta mm-name)
(conj (meta mm-name) m)
m)]
(when (= (count options) 1)
(throw (Exception. "The syntax for defmulti has changed. Example: (defmulti name dispatch-fn :default dispatch-value)")))
(let [options (apply hash-map options)
default (get options :default :default)
hierarchy (get options :hierarchy #'global-hierarchy)]
`(def ~(with-meta mm-name m)
(new clojure.lang.MultiFn ~(name mm-name) ~dispatch-fn ~default ~hierarchy)))))
(defmacro defmethod
"Creates and installs a new method of multimethod associated with dispatch-value. "
[multifn dispatch-val & fn-tail]
`(. ~(with-meta multifn {:tag 'clojure.lang.MultiFn}) addMethod ~dispatch-val (fn ~@fn-tail)))
(defn remove-method
"Removes the method of multimethod associated with dispatch-value."
[#^clojure.lang.MultiFn multifn dispatch-val]
(. multifn removeMethod dispatch-val))
(defn prefer-method
"Causes the multimethod to prefer matches of dispatch-val-x over dispatch-val-y
when there is a conflict"
[#^clojure.lang.MultiFn multifn dispatch-val-x dispatch-val-y]
(. multifn preferMethod dispatch-val-x dispatch-val-y))
(defn methods
"Given a multimethod, returns a map of dispatch values -> dispatch fns"
[#^clojure.lang.MultiFn multifn] (.getMethodTable multifn))
(defn get-method
"Given a multimethod and a dispatch value, returns the dispatch fn
that would apply to that value, or nil if none apply and no default"
[#^clojure.lang.MultiFn multifn dispatch-val] (.getMethod multifn dispatch-val))
(defn prefers
"Given a multimethod, returns a map of preferred value -> set of other values"
[#^clojure.lang.MultiFn multifn] (.getPreferTable multifn))
;;;;;;;;; var stuff
(defmacro #^{:private true} assert-args [fnname & pairs]
`(do (when-not ~(first pairs)
(throw (IllegalArgumentException.
~(str fnname " requires " (second pairs)))))
~(let [more (nnext pairs)]
(when more
(list* `assert-args fnname more)))))
(defmacro if-let
"bindings => binding-form test
If test is true, evaluates then with binding-form bound to the value of
test, if not, yields else"
([bindings then]
`(if-let ~bindings ~then nil))
([bindings then else & oldform]
(assert-args if-let
(and (vector? bindings) (nil? oldform)) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [form (bindings 0) tst (bindings 1)]
`(let [temp# ~tst]
(if temp#
(let [~form temp#]
~then)
~else)))))
(defmacro when-let
"bindings => binding-form test
When test is true, evaluates body with binding-form bound to the value of test"
[bindings & body]
(assert-args when-let
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [form (bindings 0) tst (bindings 1)]
`(let [temp# ~tst]
(when temp#
(let [~form temp#]
~@body)))))
(defn push-thread-bindings
"WARNING: This is a low-level function. Prefer high-level macros like
binding where ever possible.
Takes a map of Var/value pairs. Binds each Var to the associated value for
the current thread. Each call *MUST* be accompanied by a matching call to
pop-thread-bindings wrapped in a try-finally!
(push-thread-bindings bindings)
(try
...
(finally
(pop-thread-bindings)))"
[bindings]
(clojure.lang.Var/pushThreadBindings bindings))
(defn pop-thread-bindings
"Pop one set of bindings pushed with push-binding before. It is an error to
pop bindings without pushing before."
[]
(clojure.lang.Var/popThreadBindings))
(defn get-thread-bindings
"Get a map with the Var/value pairs which is currently in effect for the
current thread."
[]
(clojure.lang.Var/getThreadBindings))
(defmacro binding
"binding => var-symbol init-expr
Creates new bindings for the (already-existing) vars, with the
supplied initial values, executes the exprs in an implicit do, then
re-establishes the bindings that existed before. The new bindings
are made in parallel (unlike let); all init-exprs are evaluated
before the vars are bound to their new values."
[bindings & body]
(assert-args binding
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(let [var-ize (fn [var-vals]
(loop [ret [] vvs (seq var-vals)]
(if vvs
(recur (conj (conj ret `(var ~(first vvs))) (second vvs))
(next (next vvs)))
(seq ret))))]
`(let []
(push-thread-bindings (hash-map ~@(var-ize bindings)))
(try
~@body
(finally
(pop-thread-bindings))))))
(defn with-bindings*
"Takes a map of Var/value pairs. Installs for the given Vars the associated
values as thread-local bindings. Then calls f with the supplied arguments.
Pops the installed bindings after f returned. Returns whatever f returns."
[binding-map f & args]
(push-thread-bindings binding-map)
(try
(apply f args)
(finally
(pop-thread-bindings))))
(defmacro with-bindings
"Takes a map of Var/value pairs. Installs for the given Vars the associated
values as thread-local bindings. The executes body. Pops the installed
bindings after body was evaluated. Returns the value of body."
[binding-map & body]
`(with-bindings* ~binding-map (fn [] ~@body)))
(defn bound-fn*
"Returns a function, which will install the same bindings in effect as in
the thread at the time bound-fn* was called and then call f with any given
arguments. This may be used to define a helper function which runs on a
different thread, but needs the same bindings in place."
[f]
(let [bindings (get-thread-bindings)]
(fn [& args]
(apply with-bindings* bindings f args))))
(defmacro bound-fn
"Returns a function defined by the given fntail, which will install the
same bindings in effect as in the thread at the time bound-fn was called.
This may be used to define a helper function which runs on a different
thread, but needs the same bindings in place."
[& fntail]
`(bound-fn* (fn ~@fntail)))
(defn find-var
"Returns the global var named by the namespace-qualified symbol, or
nil if no var with that name."
[sym] (. clojure.lang.Var (find sym)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Refs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn #^{:private true}
setup-reference [#^clojure.lang.ARef r options]
(let [opts (apply hash-map options)]
(when (:meta opts)
(.resetMeta r (:meta opts)))
(when (:validator opts)
(.setValidator r (:validator opts)))
r))
(defn agent
"Creates and returns an agent with an initial value of state and
zero or more options (in any order):
:meta metadata-map
:validator validate-fn
If metadata-map is supplied, it will be come the metadata on the
agent. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception."
([state] (new clojure.lang.Agent state))
([state & options]
(setup-reference (agent state) options)))
(defn send
"Dispatch an action to an agent. Returns the agent immediately.
Subsequently, in a thread from a thread pool, the state of the agent
will be set to the value of:
(apply action-fn state-of-agent args)"
[#^clojure.lang.Agent a f & args]
(. a (dispatch f args false)))
(defn send-off
"Dispatch a potentially blocking action to an agent. Returns the
agent immediately. Subsequently, in a separate thread, the state of
the agent will be set to the value of:
(apply action-fn state-of-agent args)"
[#^clojure.lang.Agent a f & args]
(. a (dispatch f args true)))
(defn release-pending-sends
"Normally, actions sent directly or indirectly during another action
are held until the action completes (changes the agent's
state). This function can be used to dispatch any pending sent
actions immediately. This has no impact on actions sent during a
transaction, which are still held until commit. If no action is
occurring, does nothing. Returns the number of actions dispatched."
[] (clojure.lang.Agent/releasePendingSends))
(defn add-watch
"Alpha - subject to change.
Adds a watch function to an agent/atom/var/ref reference. The watch
fn must be a fn of 4 args: a key, the reference, its old-state, its
new-state. Whenever the reference's state might have been changed,
any registered watches will have their functions called. The watch fn
will be called synchronously, on the agent's thread if an agent,
before any pending sends if agent or ref. Note that an atom's or
ref's state may have changed again prior to the fn call, so use
old/new-state rather than derefing the reference. Note also that watch
fns may be called from multiple threads simultaneously. Var watchers
are triggered only by root binding changes, not thread-local
set!s. Keys must be unique per reference, and can be used to remove
the watch with remove-watch, but are otherwise considered opaque by
the watch mechanism."
[#^clojure.lang.IRef reference key fn] (.addWatch reference key fn))
(defn remove-watch
"Alpha - subject to change.
Removes a watch (set by add-watch) from a reference"
[#^clojure.lang.IRef reference key]
(.removeWatch reference key))
(defn agent-errors
"Returns a sequence of the exceptions thrown during asynchronous
actions of the agent."
[#^clojure.lang.Agent a] (. a (getErrors)))
(defn clear-agent-errors
"Clears any exceptions thrown during asynchronous actions of the
agent, allowing subsequent actions to occur."
[#^clojure.lang.Agent a] (. a (clearErrors)))
(defn shutdown-agents
"Initiates a shutdown of the thread pools that back the agent
system. Running actions will complete, but no new actions will be
accepted"
[] (. clojure.lang.Agent shutdown))
(defn ref
"Creates and returns a Ref with an initial value of x and zero or
more options (in any order):
:meta metadata-map
:validator validate-fn
:min-history (default 0)
:max-history (default 10)
If metadata-map is supplied, it will be come the metadata on the
ref. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception. validate-fn will be called on
transaction commit, when all refs have their final values.
Normally refs accumulate history dynamically as needed to deal with
read demands. If you know in advance you will need history you can
set :min-history to ensure it will be available when first needed (instead
of after a read fault). History is limited, and the limit can be set
with :max-history."
([x] (new clojure.lang.Ref x))
([x & options]
(let [r #^clojure.lang.Ref (setup-reference (ref x) options)
opts (apply hash-map options)]
(when (:max-history opts)
(.setMaxHistory r (:max-history opts)))
(when (:min-history opts)
(.setMinHistory r (:min-history opts)))
r)))
(defn deref
"Also reader macro: @ref/@agent/@var/@atom/@delay/@future. Within a transaction,
returns the in-transaction-value of ref, else returns the
most-recently-committed value of ref. When applied to a var, agent
or atom, returns its current state. When applied to a delay, forces
it if not already forced. When applied to a future, will block if
computation not complete"
[#^clojure.lang.IDeref ref] (.deref ref))
(defn atom
"Creates and returns an Atom with an initial value of x and zero or
more options (in any order):
:meta metadata-map
:validator validate-fn
If metadata-map is supplied, it will be come the metadata on the
atom. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception."
([x] (new clojure.lang.Atom x))
([x & options] (setup-reference (atom x) options)))
(defn swap!
"Atomically swaps the value of atom to be:
(apply f current-value-of-atom args). Note that f may be called
multiple times, and thus should be free of side effects. Returns
the value that was swapped in."
([#^clojure.lang.Atom atom f] (.swap atom f))
([#^clojure.lang.Atom atom f x] (.swap atom f x))
([#^clojure.lang.Atom atom f x y] (.swap atom f x y))
([#^clojure.lang.Atom atom f x y & args] (.swap atom f x y args)))
(defn compare-and-set!
"Atomically sets the value of atom to newval if and only if the
current value of the atom is identical to oldval. Returns true if
set happened, else false"
[#^clojure.lang.Atom atom oldval newval] (.compareAndSet atom oldval newval))
(defn reset!
"Sets the value of atom to newval without regard for the
current value. Returns newval."
[#^clojure.lang.Atom atom newval] (.reset atom newval))
(defn set-validator!
"Sets the validator-fn for a var/ref/agent/atom. validator-fn must be nil or a
side-effect-free fn of one argument, which will be passed the intended
new state on any state change. If the new state is unacceptable, the
validator-fn should return false or throw an exception. If the current state (root
value if var) is not acceptable to the new validator, an exception
will be thrown and the validator will not be changed."
[#^clojure.lang.IRef iref validator-fn] (. iref (setValidator validator-fn)))
(defn get-validator
"Gets the validator-fn for a var/ref/agent/atom."
[#^clojure.lang.IRef iref] (. iref (getValidator)))
(defn alter-meta!
"Atomically sets the metadata for a namespace/var/ref/agent/atom to be:
(apply f its-current-meta args)
f must be free of side-effects"
[#^clojure.lang.IReference iref f & args] (.alterMeta iref f args))
(defn reset-meta!
"Atomically resets the metadata for a namespace/var/ref/agent/atom"
[#^clojure.lang.IReference iref metadata-map] (.resetMeta iref metadata-map))
(defn commute
"Must be called in a transaction. Sets the in-transaction-value of
ref to:
(apply fun in-transaction-value-of-ref args)
and returns the in-transaction-value of ref.
At the commit point of the transaction, sets the value of ref to be:
(apply fun most-recently-committed-value-of-ref args)
Thus fun should be commutative, or, failing that, you must accept
last-one-in-wins behavior. commute allows for more concurrency than
ref-set."
[#^clojure.lang.Ref ref fun & args]
(. ref (commute fun args)))
(defn alter
"Must be called in a transaction. Sets the in-transaction-value of
ref to:
(apply fun in-transaction-value-of-ref args)
and returns the in-transaction-value of ref."
[#^clojure.lang.Ref ref fun & args]
(. ref (alter fun args)))
(defn ref-set
"Must be called in a transaction. Sets the value of ref.
Returns val."
[#^clojure.lang.Ref ref val]
(. ref (set val)))
(defn ref-history-count
"Returns the history count of a ref"
[#^clojure.lang.Ref ref]
(.getHistoryCount ref))
(defn ref-min-history
"Gets the min-history of a ref, or sets it and returns the ref"
([#^clojure.lang.Ref ref]
(.getMinHistory ref))
([#^clojure.lang.Ref ref n]
(.setMinHistory ref n)))
(defn ref-max-history
"Gets the max-history of a ref, or sets it and returns the ref"
([#^clojure.lang.Ref ref]
(.getMaxHistory ref))
([#^clojure.lang.Ref ref n]
(.setMaxHistory ref n)))
(defn ensure
"Must be called in a transaction. Protects the ref from modification
by other transactions. Returns the in-transaction-value of
ref. Allows for more concurrency than (ref-set ref @ref)"
[#^clojure.lang.Ref ref]
(. ref (touch))
(. ref (deref)))
(defmacro sync
"transaction-flags => TBD, pass nil for now
Runs the exprs (in an implicit do) in a transaction that encompasses
exprs and any nested calls. Starts a transaction if none is already
running on this thread. Any uncaught exception will abort the
transaction and flow out of sync. The exprs may be run more than
once, but any effects on Refs will be atomic."
[flags-ignored-for-now & body]
`(. clojure.lang.LockingTransaction
(runInTransaction (fn [] ~@body))))
(defmacro io!
"If an io! block occurs in a transaction, throws an
IllegalStateException, else runs body in an implicit do. If the
first expression in body is a literal string, will use that as the
exception message."
[& body]
(let [message (when (string? (first body)) (first body))
body (if message (next body) body)]
`(if (clojure.lang.LockingTransaction/isRunning)
(throw (new IllegalStateException ~(or message "I/O in transaction")))
(do ~@body))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; fn stuff ;;;;;;;;;;;;;;;;
(defn comp
"Takes a set of functions and returns a fn that is the composition
of those fns. The returned fn takes a variable number of args,
applies the rightmost of fns to the args, the next
fn (right-to-left) to the result, etc."
([f] f)
([f g]
(fn
([] (f (g)))
([x] (f (g x)))
([x y] (f (g x y)))
([x y z] (f (g x y z)))
([x y z & args] (f (apply g x y z args)))))
([f g h]
(fn
([] (f (g (h))))
([x] (f (g (h x))))
([x y] (f (g (h x y))))
([x y z] (f (g (h x y z))))
([x y z & args] (f (g (apply h x y z args))))))
([f1 f2 f3 & fs]
(let [fs (reverse (list* f1 f2 f3 fs))]
(fn [& args]
(loop [ret (apply (first fs) args) fs (next fs)]
(if fs
(recur ((first fs) ret) (next fs))
ret))))))
(defn juxt
"Alpha - name subject to change.
Takes a set of functions and returns a fn that is the juxtaposition
of those fns. The returned fn takes a variable number of args, and
returns a vector containing the result of applying each fn to the
args (left-to-right).
((juxt a b c) x) => [(a x) (b x) (c x)]"
([f]
(fn
([] [(f)])
([x] [(f x)])
([x y] [(f x y)])
([x y z] [(f x y z)])
([x y z & args] [(apply f x y z args)])))
([f g]
(fn
([] [(f) (g)])
([x] [(f x) (g x)])
([x y] [(f x y) (g x y)])
([x y z] [(f x y z) (g x y z)])
([x y z & args] [(apply f x y z args) (apply g x y z args)])))
([f g h]
(fn
([] [(f) (g) (h)])
([x] [(f x) (g x) (h x)])
([x y] [(f x y) (g x y) (h x y)])
([x y z] [(f x y z) (g x y z) (h x y z)])
([x y z & args] [(apply f x y z args) (apply g x y z args) (apply h x y z args)])))
([f g h & fs]
(let [fs (list* f g h fs)]
(fn
([] (reduce #(conj %1 (%2)) [] fs))
([x] (reduce #(conj %1 (%2 x)) [] fs))
([x y] (reduce #(conj %1 (%2 x y)) [] fs))
([x y z] (reduce #(conj %1 (%2 x y z)) [] fs))
([x y z & args] (reduce #(conj %1 (apply %2 x y z args)) [] fs))))))
(defn partial
"Takes a function f and fewer than the normal arguments to f, and
returns a fn that takes a variable number of additional args. When
called, the returned function calls f with args + additional args."
([f arg1]
(fn [& args] (apply f arg1 args)))
([f arg1 arg2]
(fn [& args] (apply f arg1 arg2 args)))
([f arg1 arg2 arg3]
(fn [& args] (apply f arg1 arg2 arg3 args)))
([f arg1 arg2 arg3 & more]
(fn [& args] (apply f arg1 arg2 arg3 (concat more args)))))
;;;;;;;;;;;;;;;;;;; sequence fns ;;;;;;;;;;;;;;;;;;;;;;;
(defn stream?
"Returns true if x is an instance of Stream"
[x] (instance? clojure.lang.Stream x))
(defn sequence
"Coerces coll to a (possibly empty) sequence, if it is not already
one. Will not force a lazy seq. (sequence nil) yields ()"
[coll]
(cond
(seq? coll) coll
(stream? coll) (.sequence #^clojure.lang.Stream coll)
:else (or (seq coll) ())))
(defn every?
"Returns true if (pred x) is logical true for every x in coll, else
false."
{:tag Boolean}
[pred coll]
(cond
(nil? (seq coll)) true
(pred (first coll)) (recur pred (next coll))
:else false))
(def
#^{:tag Boolean
:doc "Returns false if (pred x) is logical true for every x in
coll, else true."
:arglists '([pred coll])}
not-every? (comp not every?))
(defn some
"Returns the first logical true value of (pred x) for any x in coll,
else nil. One common idiom is to use a set as pred, for example
this will return :fred if :fred is in the sequence, otherwise nil:
(some #{:fred} coll)"
[pred coll]
(when (seq coll)
(or (pred (first coll)) (recur pred (next coll)))))
(def
#^{:tag Boolean
:doc "Returns false if (pred x) is logical true for any x in coll,
else true."
:arglists '([pred coll])}
not-any? (comp not some))
;will be redefed later with arg checks
(defmacro dotimes
"bindings => name n
Repeatedly executes body (presumably for side-effects) with name
bound to integers from 0 through n-1."
[bindings & body]
(let [i (first bindings)
n (second bindings)]
`(let [n# (int ~n)]
(loop [~i (int 0)]
(when (< ~i n#)
~@body
(recur (inc ~i)))))))
(defn map
"Returns a lazy sequence consisting of the result of applying f to the
set of first items of each coll, followed by applying f to the set
of second items in each coll, until any one of the colls is
exhausted. Any remaining items in other colls are ignored. Function
f should accept number-of-colls arguments."
([f coll]
(lazy-seq
(when-let [s (seq coll)]
(if (chunked-seq? s)
(let [c (chunk-first s)
size (int (count c))
b (chunk-buffer size)]
(dotimes [i size]
(chunk-append b (f (.nth c i))))
(chunk-cons (chunk b) (map f (chunk-rest s))))
(cons (f (first s)) (map f (rest s)))))))
([f c1 c2]
(lazy-seq
(let [s1 (seq c1) s2 (seq c2)]
(when (and s1 s2)
(cons (f (first s1) (first s2))
(map f (rest s1) (rest s2)))))))
([f c1 c2 c3]
(lazy-seq
(let [s1 (seq c1) s2 (seq c2) s3 (seq c3)]
(when (and s1 s2 s3)
(cons (f (first s1) (first s2) (first s3))
(map f (rest s1) (rest s2) (rest s3)))))))
([f c1 c2 c3 & colls]
(let [step (fn step [cs]
(lazy-seq
(let [ss (map seq cs)]
(when (every? identity ss)
(cons (map first ss) (step (map rest ss)))))))]
(map #(apply f %) (step (conj colls c3 c2 c1))))))
(defn mapcat
"Returns the result of applying concat to the result of applying map
to f and colls. Thus function f should return a collection."
[f & colls]
(apply concat (apply map f colls)))
(defn filter
"Returns a lazy sequence of the items in coll for which
(pred item) returns true. pred must be free of side-effects."
([pred coll]
(lazy-seq
(when-let [s (seq coll)]
(if (chunked-seq? s)
(let [c (chunk-first s)
size (count c)
b (chunk-buffer size)]
(dotimes [i size]
(when (pred (.nth c i))
(chunk-append b (.nth c i))))
(chunk-cons (chunk b) (filter pred (chunk-rest s))))
(let [f (first s) r (rest s)]
(if (pred f)
(cons f (filter pred r))
(filter pred r))))))))
(defn remove
"Returns a lazy sequence of the items in coll for which
(pred item) returns false. pred must be free of side-effects."
[pred coll]
(filter (complement pred) coll))
(defn take
"Returns a lazy sequence of the first n items in coll, or all items if
there are fewer than n."
[n coll]
(lazy-seq
(when (pos? n)
(when-let [s (seq coll)]
(cons (first s) (take (dec n) (rest s)))))))
(defn take-while
"Returns a lazy sequence of successive items from coll while
(pred item) returns true. pred must be free of side-effects."
[pred coll]
(lazy-seq
(when-let [s (seq coll)]
(when (pred (first s))
(cons (first s) (take-while pred (rest s)))))))
(defn drop
"Returns a lazy sequence of all but the first n items in coll."
[n coll]
(let [step (fn [n coll]
(let [s (seq coll)]
(if (and (pos? n) s)
(recur (dec n) (rest s))
s)))]
(lazy-seq (step n coll))))
(defn drop-last
"Return a lazy sequence of all but the last n (default 1) items in coll"
([s] (drop-last 1 s))
([n s] (map (fn [x _] x) s (drop n s))))
(defn take-last
"Returns a seq of the last n items in coll. Depending on the type
of coll may be no better than linear time. For vectors, see also subvec."
[n coll]
(loop [s (seq coll), lead (seq (drop n coll))]
(if lead
(recur (next s) (next lead))
s)))
(defn drop-while
"Returns a lazy sequence of the items in coll starting from the first
item for which (pred item) returns nil."
[pred coll]
(let [step (fn [pred coll]
(let [s (seq coll)]
(if (and s (pred (first s)))
(recur pred (rest s))
s)))]
(lazy-seq (step pred coll))))
(defn cycle
"Returns a lazy (infinite!) sequence of repetitions of the items in coll."
[coll] (lazy-seq
(when-let [s (seq coll)]
(concat s (cycle s)))))
(defn split-at
"Returns a vector of [(take n coll) (drop n coll)]"
[n coll]
[(take n coll) (drop n coll)])
(defn split-with
"Returns a vector of [(take-while pred coll) (drop-while pred coll)]"
[pred coll]
[(take-while pred coll) (drop-while pred coll)])
(defn repeat
"Returns a lazy (infinite!, or length n if supplied) sequence of xs."
([x] (lazy-seq (cons x (repeat x))))
([n x] (take n (repeat x))))
(defn replicate
"Returns a lazy seq of n xs."
[n x] (take n (repeat x)))
(defn iterate
"Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of side-effects"
[f x] (cons x (lazy-seq (iterate f (f x)))))
(defn range
"Returns a lazy seq of nums from start (inclusive) to end
(exclusive), by step, where start defaults to 0 and step to 1."
([end] (range 0 end 1))
([start end] (range start end 1))
([start end step]
(lazy-seq
(let [b (chunk-buffer 32)
comp (if (pos? step) < >)]
(loop [i start]
(if (and (< (count b) 32)
(comp i end))
(do
(chunk-append b i)
(recur (+ i step)))
(chunk-cons (chunk b)
(when (comp i end)
(range i end step)))))))))
(defn merge
"Returns a map that consists of the rest of the maps conj-ed onto
the first. If a key occurs in more than one map, the mapping from
the latter (left-to-right) will be the mapping in the result."
[& maps]
(when (some identity maps)
(reduce #(conj (or %1 {}) %2) maps)))
(defn merge-with
"Returns a map that consists of the rest of the maps conj-ed onto
the first. If a key occurs in more than one map, the mapping(s)
from the latter (left-to-right) will be combined with the mapping in
the result by calling (f val-in-result val-in-latter)."
[f & maps]
(when (some identity maps)
(let [merge-entry (fn [m e]
(let [k (key e) v (val e)]
(if (contains? m k)
(assoc m k (f (m k) v))
(assoc m k v))))
merge2 (fn [m1 m2]
(reduce merge-entry (or m1 {}) (seq m2)))]
(reduce merge2 maps))))
(defn zipmap
"Returns a map with the keys mapped to the corresponding vals."
[keys vals]
(loop [map {}
ks (seq keys)
vs (seq vals)]
(if (and ks vs)
(recur (assoc map (first ks) (first vs))
(next ks)
(next vs))
map)))
(defn line-seq
"Returns the lines of text from rdr as a lazy sequence of strings.
rdr must implement java.io.BufferedReader."
[#^java.io.BufferedReader rdr]
(let [line (. rdr (readLine))]
(when line
(lazy-seq (cons line (line-seq rdr))))))
(defn comparator
"Returns an implementation of java.util.Comparator based upon pred."
[pred]
(fn [x y]
(cond (pred x y) -1 (pred y x) 1 :else 0)))
(defn sort
"Returns a sorted sequence of the items in coll. If no comparator is
supplied, uses compare. comparator must
implement java.util.Comparator."
([coll]
(sort compare coll))
([#^java.util.Comparator comp coll]
(if (seq coll)
(let [a (to-array coll)]
(. java.util.Arrays (sort a comp))
(seq a))
())))
(defn sort-by
"Returns a sorted sequence of the items in coll, where the sort
order is determined by comparing (keyfn item). If no comparator is
supplied, uses compare. comparator must
implement java.util.Comparator."
([keyfn coll]
(sort-by keyfn compare coll))
([keyfn #^java.util.Comparator comp coll]
(sort (fn [x y] (. comp (compare (keyfn x) (keyfn y)))) coll)))
(defn partition
"Returns a lazy sequence of lists of n items each, at offsets step
apart. If step is not supplied, defaults to n, i.e. the partitions
do not overlap. If a pad collection is supplied, use its elements as
necessary to complete last partition upto n items. In case there are
not enough padding elements, return a partition with less than n items."
([n coll]
(partition n n coll))
([n step coll]
(lazy-seq
(when-let [s (seq coll)]
(let [p (take n s)]
(when (= n (count p))
(cons p (partition n step (drop step s))))))))
([n step pad coll]
(lazy-seq
(when-let [s (seq coll)]
(let [p (take n s)]
(if (= n (count p))
(cons p (partition n step pad (drop step s)))
(list (take n (concat p pad)))))))))
;; evaluation
(defn eval
"Evaluates the form data structure (not text!) and returns the result."
[form] (. clojure.lang.Compiler (eval form)))
(defmacro doseq
"Repeatedly executes body (presumably for side-effects) with
bindings and filtering as provided by \"for\". Does not retain
the head of the sequence. Returns nil."
[seq-exprs & body]
(assert-args doseq
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [step (fn step [recform exprs]
(if-not exprs
[true `(do ~@body)]
(let [k (first exprs)
v (second exprs)]
(if (keyword? k)
(let [steppair (step recform (nnext exprs))
needrec (steppair 0)
subform (steppair 1)]
(cond
(= k :let) [needrec `(let ~v ~subform)]
(= k :while) [false `(when ~v
~subform
~@(when needrec [recform]))]
(= k :when) [false `(if ~v
(do
~subform
~@(when needrec [recform]))
~recform)]))
(let [seq- (gensym "seq_")
chunk- (with-meta (gensym "chunk_")
{:tag 'clojure.lang.IChunk})
count- (gensym "count_")
i- (gensym "i_")
recform `(recur (next ~seq-) nil (int 0) (int 0))
steppair (step recform (nnext exprs))
needrec (steppair 0)
subform (steppair 1)
recform-chunk
`(recur ~seq- ~chunk- ~count- (unchecked-inc ~i-))
steppair-chunk (step recform-chunk (nnext exprs))
subform-chunk (steppair-chunk 1)]
[true
`(loop [~seq- (seq ~v), ~chunk- nil,
~count- (int 0), ~i- (int 0)]
(if (< ~i- ~count-)
(let [~k (.nth ~chunk- ~i-)]
~subform-chunk
~@(when needrec [recform-chunk]))
(when-let [~seq- (seq ~seq-)]
(if (chunked-seq? ~seq-)
(let [c# (chunk-first ~seq-)]
(recur (chunk-rest ~seq-) c#
(int (count c#)) (int 0)))
(let [~k (first ~seq-)]
~subform
~@(when needrec [recform]))))))])))))]
(nth (step nil (seq seq-exprs)) 1)))
(defn dorun
"When lazy sequences are produced via functions that have side
effects, any effects other than those needed to produce the first
element in the seq do not occur until the seq is consumed. dorun can
be used to force any effects. Walks through the successive nexts of
the seq, does not retain the head and returns nil."
([coll]
(when (seq coll)
(recur (next coll))))
([n coll]
(when (and (seq coll) (pos? n))
(recur (dec n) (next coll)))))
(defn doall
"When lazy sequences are produced via functions that have side
effects, any effects other than those needed to produce the first
element in the seq do not occur until the seq is consumed. doall can
be used to force any effects. Walks through the successive nexts of
the seq, retains the head and returns it, thus causing the entire
seq to reside in memory at one time."
([coll]
(dorun coll)
coll)
([n coll]
(dorun n coll)
coll))
(defn await
"Blocks the current thread (indefinitely!) until all actions
dispatched thus far, from this thread or agent, to the agent(s) have
occurred."
[& agents]
(io! "await in transaction"
(when *agent*
(throw (new Exception "Can't await in agent action")))
(let [latch (new java.util.concurrent.CountDownLatch (count agents))
count-down (fn [agent] (. latch (countDown)) agent)]
(doseq [agent agents]
(send agent count-down))
(. latch (await)))))
(defn await1 [#^clojure.lang.Agent a]
(when (pos? (.getQueueCount a))
(await a))
a)
(defn await-for
"Blocks the current thread until all actions dispatched thus
far (from this thread or agent) to the agents have occurred, or the
timeout (in milliseconds) has elapsed. Returns nil if returning due
to timeout, non-nil otherwise."
[timeout-ms & agents]
(io! "await-for in transaction"
(when *agent*
(throw (new Exception "Can't await in agent action")))
(let [latch (new java.util.concurrent.CountDownLatch (count agents))
count-down (fn [agent] (. latch (countDown)) agent)]
(doseq [agent agents]
(send agent count-down))
(. latch (await timeout-ms (. java.util.concurrent.TimeUnit MILLISECONDS))))))
(defmacro dotimes
"bindings => name n
Repeatedly executes body (presumably for side-effects) with name
bound to integers from 0 through n-1."
[bindings & body]
(assert-args dotimes
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [i (first bindings)
n (second bindings)]
`(let [n# (int ~n)]
(loop [~i (int 0)]
(when (< ~i n#)
~@body
(recur (unchecked-inc ~i)))))))
(defn into
"Returns a new coll consisting of to-coll with all of the items of
from-coll conjoined."
[to from]
(let [ret to items (seq from)]
(if items
(recur (conj ret (first items)) (next items))
ret)))
(defmacro import
"import-list => (package-symbol class-name-symbols*)
For each name in class-name-symbols, adds a mapping from name to the
class named by package.name to the current namespace. Use :import in the ns
macro in preference to calling this directly."
[& import-symbols-or-lists]
(let [specs (map #(if (and (seq? %) (= 'quote (first %))) (second %) %)
import-symbols-or-lists)]
`(do ~@(map #(list 'clojure.core/import* %)
(reduce (fn [v spec]
(if (symbol? spec)
(conj v (name spec))
(let [p (first spec) cs (rest spec)]
(into v (map #(str p "." %) cs)))))
[] specs)))))
(defn into-array
"Returns an array with components set to the values in aseq. The array's
component type is type if provided, or the type of the first value in
aseq if present, or Object. All values in aseq must be compatible with
the component type. Class objects for the primitive types can be obtained
using, e.g., Integer/TYPE."
([aseq]
(clojure.lang.RT/seqToTypedArray (seq aseq)))
([type aseq]
(clojure.lang.RT/seqToTypedArray type (seq aseq))))
(defn #^{:private true}
array [& items]
(into-array items))
(defn #^Class class
"Returns the Class of x"
[#^Object x] (if (nil? x) x (. x (getClass))))
(defn type
"Returns the :type metadata of x, or its Class if none"
[x]
(or (:type (meta x)) (class x)))
(defn num
"Coerce to Number"
{:tag Number
:inline (fn [x] `(. clojure.lang.Numbers (num ~x)))}
[x] (. clojure.lang.Numbers (num x)))
(defn long
"Coerce to long"
{:tag Long
:inline (fn [x] `(. clojure.lang.RT (longCast ~x)))}
[#^Number x] (. x (longValue)))
(defn float
"Coerce to float"
{:tag Float
:inline (fn [x] `(. clojure.lang.RT (floatCast ~x)))}
[#^Number x] (. x (floatValue)))
(defn double
"Coerce to double"
{:tag Double
:inline (fn [x] `(. clojure.lang.RT (doubleCast ~x)))}
[#^Number x] (. x (doubleValue)))
(defn short
"Coerce to short"
{:tag Short
:inline (fn [x] `(. clojure.lang.RT (shortCast ~x)))}
[#^Number x] (. x (shortValue)))
(defn byte
"Coerce to byte"
{:tag Byte
:inline (fn [x] `(. clojure.lang.RT (byteCast ~x)))}
[#^Number x] (. x (byteValue)))
(defn char
"Coerce to char"
{:tag Character
:inline (fn [x] `(. clojure.lang.RT (charCast ~x)))}
[x] (. clojure.lang.RT (charCast x)))
(defn boolean
"Coerce to boolean"
{:tag Boolean
:inline (fn [x] `(. clojure.lang.RT (booleanCast ~x)))}
[x] (if x true false))
(defn number?
"Returns true if x is a Number"
[x]
(instance? Number x))
(defn integer?
"Returns true if n is an integer"
[n]
(or (instance? Integer n)
(instance? Long n)
(instance? BigInteger n)
(instance? Short n)
(instance? Byte n)))
(defn mod
"Modulus of num and div. Truncates toward negative infinity."
[num div]
(let [m (rem num div)]
(if (or (zero? m) (pos? (* num div)))
m
(+ m div))))
(defn ratio?
"Returns true if n is a Ratio"
[n] (instance? clojure.lang.Ratio n))
(defn decimal?
"Returns true if n is a BigDecimal"
[n] (instance? BigDecimal n))
(defn float?
"Returns true if n is a floating point number"
[n]
(or (instance? Double n)
(instance? Float n)))
(defn rational? [n]
"Returns true if n is a rational number"
(or (integer? n) (ratio? n) (decimal? n)))
(defn bigint
"Coerce to BigInteger"
{:tag BigInteger}
[x] (cond
(instance? BigInteger x) x
(decimal? x) (.toBigInteger #^BigDecimal x)
(number? x) (BigInteger/valueOf (long x))
:else (BigInteger. x)))
(defn bigdec
"Coerce to BigDecimal"
{:tag BigDecimal}
[x] (cond
(decimal? x) x
(float? x) (. BigDecimal valueOf (double x))
(ratio? x) (/ (BigDecimal. (.numerator x)) (.denominator x))
(instance? BigInteger x) (BigDecimal. #^BigInteger x)
(number? x) (BigDecimal/valueOf (long x))
:else (BigDecimal. x)))
(def #^{:private true} print-initialized false)
(defmulti print-method (fn [x writer] (type x)))
(defmulti print-dup (fn [x writer] (class x)))
(defn pr-on
{:private true}
[x w]
(if *print-dup*
(print-dup x w)
(print-method x w))
nil)
(defn pr
"Prints the object(s) to the output stream that is the current value
of *out*. Prints the object(s), separated by spaces if there is
more than one. By default, pr and prn print in a way that objects
can be read by the reader"
([] nil)
([x]
(pr-on x *out*))
([x & more]
(pr x)
(. *out* (append \space))
(apply pr more)))
(defn newline
"Writes a newline to the output stream that is the current value of
*out*"
[]
(. *out* (append \newline))
nil)
(defn flush
"Flushes the output stream that is the current value of
*out*"
[]
(. *out* (flush))
nil)
(defn prn
"Same as pr followed by (newline). Observes *flush-on-newline*"
[& more]
(apply pr more)
(newline)
(when *flush-on-newline*
(flush)))
(defn print
"Prints the object(s) to the output stream that is the current value
of *out*. print and println produce output for human consumption."
[& more]
(binding [*print-readably* nil]
(apply pr more)))
(defn println
"Same as print followed by (newline)"
[& more]
(binding [*print-readably* nil]
(apply prn more)))
(defn read
"Reads the next object from stream, which must be an instance of
java.io.PushbackReader or some derivee. stream defaults to the
current value of *in* ."
([]
(read *in*))
([stream]
(read stream true nil))
([stream eof-error? eof-value]
(read stream eof-error? eof-value false))
([stream eof-error? eof-value recursive?]
(. clojure.lang.LispReader (read stream (boolean eof-error?) eof-value recursive?))))
(defn read-line
"Reads the next line from stream that is the current value of *in* ."
[]
(if (instance? clojure.lang.LineNumberingPushbackReader *in*)
(.readLine #^clojure.lang.LineNumberingPushbackReader *in*)
(.readLine #^java.io.BufferedReader *in*)))
(defn read-string
"Reads one object from the string s"
[s] (clojure.lang.RT/readString s))
(defn subvec
"Returns a persistent vector of the items in vector from
start (inclusive) to end (exclusive). If end is not supplied,
defaults to (count vector). This operation is O(1) and very fast, as
the resulting vector shares structure with the original and no
trimming is done."
([v start]
(subvec v start (count v)))
([v start end]
(. clojure.lang.RT (subvec v start end))))
(defmacro with-open
"bindings => [name init ...]
Evaluates body in a try expression with names bound to the values
of the inits, and a finally clause that calls (.close name) on each
name in reverse order."
[bindings & body]
(assert-args with-open
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(cond
(= (count bindings) 0) `(do ~@body)
(symbol? (bindings 0)) `(let ~(subvec bindings 0 2)
(try
(with-open ~(subvec bindings 2) ~@body)
(finally
(. ~(bindings 0) close))))
:else (throw (IllegalArgumentException.
"with-open only allows Symbols in bindings"))))
(defmacro doto
"Evaluates x then calls all of the methods and functions with the
value of x supplied at the from of the given arguments. The forms
are evaluated in order. Returns x.
(doto (new java.util.HashMap) (.put \"a\" 1) (.put \"b\" 2))"
[x & forms]
(let [gx (gensym)]
`(let [~gx ~x]
~@(map (fn [f]
(if (seq? f)
`(~(first f) ~gx ~@(next f))
`(~f ~gx)))
forms)
~gx)))
(defmacro memfn
"Expands into code that creates a fn that expects to be passed an
object and any args and calls the named instance method on the
object passing the args. Use when you want to treat a Java method as
a first-class fn."
[name & args]
`(fn [target# ~@args]
(. target# (~name ~@args))))
(defmacro time
"Evaluates expr and prints the time it took. Returns the value of
expr."
[expr]
`(let [start# (. System (nanoTime))
ret# ~expr]
(prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " msecs"))
ret#))
(import '(java.lang.reflect Array))
(defn alength
"Returns the length of the Java array. Works on arrays of all
types."
{:inline (fn [a] `(. clojure.lang.RT (alength ~a)))}
[array] (. clojure.lang.RT (alength array)))
(defn aclone
"Returns a clone of the Java array. Works on arrays of known
types."
{:inline (fn [a] `(. clojure.lang.RT (aclone ~a)))}
[array] (. clojure.lang.RT (aclone array)))
(defn aget
"Returns the value at the index/indices. Works on Java arrays of all
types."
{:inline (fn [a i] `(. clojure.lang.RT (aget ~a ~i)))
:inline-arities #{2}}
([array idx]
(clojure.lang.Reflector/prepRet (. Array (get array idx))))
([array idx & idxs]
(apply aget (aget array idx) idxs)))
(defn aset
"Sets the value at the index/indices. Works on Java arrays of
reference types. Returns val."
{:inline (fn [a i v] `(. clojure.lang.RT (aset ~a ~i ~v)))
:inline-arities #{3}}
([array idx val]
(. Array (set array idx val))
val)
([array idx idx2 & idxv]
(apply aset (aget array idx) idx2 idxv)))
(defmacro
#^{:private true}
def-aset [name method coerce]
`(defn ~name
{:arglists '([~'array ~'idx ~'val] [~'array ~'idx ~'idx2 & ~'idxv])}
([array# idx# val#]
(. Array (~method array# idx# (~coerce val#)))
val#)
([array# idx# idx2# & idxv#]
(apply ~name (aget array# idx#) idx2# idxv#))))
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of int. Returns val."}
aset-int setInt int)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of long. Returns val."}
aset-long setLong long)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of boolean. Returns val."}
aset-boolean setBoolean boolean)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of float. Returns val."}
aset-float setFloat float)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of double. Returns val."}
aset-double setDouble double)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of short. Returns val."}
aset-short setShort short)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of byte. Returns val."}
aset-byte setByte byte)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of char. Returns val."}
aset-char setChar char)
(defn make-array
"Creates and returns an array of instances of the specified class of
the specified dimension(s). Note that a class object is required.
Class objects can be obtained by using their imported or
fully-qualified name. Class objects for the primitive types can be
obtained using, e.g., Integer/TYPE."
([#^Class type len]
(. Array (newInstance type (int len))))
([#^Class type dim & more-dims]
(let [dims (cons dim more-dims)
#^"[I" dimarray (make-array (. Integer TYPE) (count dims))]
(dotimes [i (alength dimarray)]
(aset-int dimarray i (nth dims i)))
(. Array (newInstance type dimarray)))))
(defn to-array-2d
"Returns a (potentially-ragged) 2-dimensional array of Objects
containing the contents of coll, which can be any Collection of any
Collection."
{:tag "[[Ljava.lang.Object;"}
[#^java.util.Collection coll]
(let [ret (make-array (. Class (forName "[Ljava.lang.Object;")) (. coll (size)))]
(loop [i 0 xs (seq coll)]
(when xs
(aset ret i (to-array (first xs)))
(recur (inc i) (next xs))))
ret))
(defn macroexpand-1
"If form represents a macro form, returns its expansion,
else returns form."
[form]
(. clojure.lang.Compiler (macroexpand1 form)))
(defn macroexpand
"Repeatedly calls macroexpand-1 on form until it no longer
represents a macro form, then returns it. Note neither
macroexpand-1 nor macroexpand expand macros in subforms."
[form]
(let [ex (macroexpand-1 form)]
(if (identical? ex form)
form
(macroexpand ex))))
(defn create-struct
"Returns a structure basis object."
[& keys]
(. clojure.lang.PersistentStructMap (createSlotMap keys)))
(defmacro defstruct
"Same as (def name (create-struct keys...))"
[name & keys]
`(def ~name (create-struct ~@keys)))
(defn struct-map
"Returns a new structmap instance with the keys of the
structure-basis. keyvals may contain all, some or none of the basis
keys - where values are not supplied they will default to nil.
keyvals can also contain keys not in the basis."
[s & inits]
(. clojure.lang.PersistentStructMap (create s inits)))
(defn struct
"Returns a new structmap instance with the keys of the
structure-basis. vals must be supplied for basis keys in order -
where values are not supplied they will default to nil."
[s & vals]
(. clojure.lang.PersistentStructMap (construct s vals)))
(defn accessor
"Returns a fn that, given an instance of a structmap with the basis,
returns the value at the key. The key must be in the basis. The
returned function should be (slightly) more efficient than using
get, but such use of accessors should be limited to known
performance-critical areas."
[s key]
(. clojure.lang.PersistentStructMap (getAccessor s key)))
(defn load-reader
"Sequentially read and evaluate the set of forms contained in the
stream/file"
[rdr] (. clojure.lang.Compiler (load rdr)))
(defn load-string
"Sequentially read and evaluate the set of forms contained in the
string"
[s]
(let [rdr (-> (java.io.StringReader. s)
(clojure.lang.LineNumberingPushbackReader.))]
(load-reader rdr)))
(defn set
"Returns a set of the distinct elements of coll."
[coll] (apply hash-set coll))
(defn #^{:private true}
filter-key [keyfn pred amap]
(loop [ret {} es (seq amap)]
(if es
(if (pred (keyfn (first es)))
(recur (assoc ret (key (first es)) (val (first es))) (next es))
(recur ret (next es)))
ret)))
(defn find-ns
"Returns the namespace named by the symbol or nil if it doesn't exist."
[sym] (clojure.lang.Namespace/find sym))
(defn create-ns
"Create a new namespace named by the symbol if one doesn't already
exist, returns it or the already-existing namespace of the same
name."
[sym] (clojure.lang.Namespace/findOrCreate sym))
(defn remove-ns
"Removes the namespace named by the symbol. Use with caution.
Cannot be used to remove the clojure namespace."
[sym] (clojure.lang.Namespace/remove sym))
(defn all-ns
"Returns a sequence of all namespaces."
[] (clojure.lang.Namespace/all))
(defn #^clojure.lang.Namespace the-ns
"If passed a namespace, returns it. Else, when passed a symbol,
returns the namespace named by it, throwing an exception if not
found."
[x]
(if (instance? clojure.lang.Namespace x)
x
(or (find-ns x) (throw (Exception. (str "No namespace: " x " found"))))))
(defn ns-name
"Returns the name of the namespace, a symbol."
[ns]
(.getName (the-ns ns)))
(defn ns-map
"Returns a map of all the mappings for the namespace."
[ns]
(.getMappings (the-ns ns)))
(defn ns-unmap
"Removes the mappings for the symbol from the namespace."
[ns sym]
(.unmap (the-ns ns) sym))
;(defn export [syms]
; (doseq [sym syms]
; (.. *ns* (intern sym) (setExported true))))
(defn ns-publics
"Returns a map of the public intern mappings for the namespace."
[ns]
(let [ns (the-ns ns)]
(filter-key val (fn [#^clojure.lang.Var v] (and (instance? clojure.lang.Var v)
(= ns (.ns v))
(.isPublic v)))
(ns-map ns))))
(defn ns-imports
"Returns a map of the import mappings for the namespace."
[ns]
(filter-key val (partial instance? Class) (ns-map ns)))
(defn refer
"refers to all public vars of ns, subject to filters.
filters can include at most one each of:
:exclude list-of-symbols
:only list-of-symbols
:rename map-of-fromsymbol-tosymbol
For each public interned var in the namespace named by the symbol,
adds a mapping from the name of the var to the var to the current
namespace. Throws an exception if name is already mapped to
something else in the current namespace. Filters can be used to
select a subset, via inclusion or exclusion, or to provide a mapping
to a symbol different from the var's name, in order to prevent
clashes. Use :use in the ns macro in preference to calling this directly."
[ns-sym & filters]
(let [ns (or (find-ns ns-sym) (throw (new Exception (str "No namespace: " ns-sym))))
fs (apply hash-map filters)
nspublics (ns-publics ns)
rename (or (:rename fs) {})
exclude (set (:exclude fs))
to-do (or (:only fs) (keys nspublics))]
(doseq [sym to-do]
(when-not (exclude sym)
(let [v (nspublics sym)]
(when-not v
(throw (new java.lang.IllegalAccessError (str sym " is not public"))))
(. *ns* (refer (or (rename sym) sym) v)))))))
(defn ns-refers
"Returns a map of the refer mappings for the namespace."
[ns]
(let [ns (the-ns ns)]
(filter-key val (fn [#^clojure.lang.Var v] (and (instance? clojure.lang.Var v)
(not= ns (.ns v))))
(ns-map ns))))
(defn ns-interns
"Returns a map of the intern mappings for the namespace."
[ns]
(let [ns (the-ns ns)]
(filter-key val (fn [#^clojure.lang.Var v] (and (instance? clojure.lang.Var v)
(= ns (.ns v))))
(ns-map ns))))
(defn alias
"Add an alias in the current namespace to another
namespace. Arguments are two symbols: the alias to be used, and
the symbolic name of the target namespace. Use :as in the ns macro in preference
to calling this directly."
[alias namespace-sym]
(.addAlias *ns* alias (find-ns namespace-sym)))
(defn ns-aliases
"Returns a map of the aliases for the namespace."
[ns]
(.getAliases (the-ns ns)))
(defn ns-unalias
"Removes the alias for the symbol from the namespace."
[ns sym]
(.removeAlias (the-ns ns) sym))
(defn take-nth
"Returns a lazy seq of every nth item in coll."
[n coll]
(lazy-seq
(when-let [s (seq coll)]
(cons (first s) (take-nth n (drop n s))))))
(defn interleave
"Returns a lazy seq of the first item in each coll, then the second etc."
([c1 c2]
(lazy-seq
(let [s1 (seq c1) s2 (seq c2)]
(when (and s1 s2)
(cons (first s1) (cons (first s2)
(interleave (rest s1) (rest s2))))))))
([c1 c2 & colls]
(lazy-seq
(let [ss (map seq (conj colls c2 c1))]
(when (every? identity ss)
(concat (map first ss) (apply interleave (map rest ss))))))))
(defn var-get
"Gets the value in the var object"
[#^clojure.lang.Var x] (. x (get)))
(defn var-set
"Sets the value in the var object to val. The var must be
thread-locally bound."
[#^clojure.lang.Var x val] (. x (set val)))
(defmacro with-local-vars
"varbinding=> symbol init-expr
Executes the exprs in a context in which the symbols are bound to
vars with per-thread bindings to the init-exprs. The symbols refer
to the var objects themselves, and must be accessed with var-get and
var-set"
[name-vals-vec & body]
(assert-args with-local-vars
(vector? name-vals-vec) "a vector for its binding"
(even? (count name-vals-vec)) "an even number of forms in binding vector")
`(let [~@(interleave (take-nth 2 name-vals-vec)
(repeat '(. clojure.lang.Var (create))))]
(. clojure.lang.Var (pushThreadBindings (hash-map ~@name-vals-vec)))
(try
~@body
(finally (. clojure.lang.Var (popThreadBindings))))))
(defn ns-resolve
"Returns the var or Class to which a symbol will be resolved in the
namespace, else nil. Note that if the symbol is fully qualified,
the var/Class to which it resolves need not be present in the
namespace."
[ns sym]
(clojure.lang.Compiler/maybeResolveIn (the-ns ns) sym))
(defn resolve
"same as (ns-resolve *ns* symbol)"
[sym] (ns-resolve *ns* sym))
(defn array-map
"Constructs an array-map."
([] (. clojure.lang.PersistentArrayMap EMPTY))
([& keyvals] (new clojure.lang.PersistentArrayMap (to-array keyvals))))
(defn nthnext
"Returns the nth next of coll, (seq coll) when n is 0."
[coll n]
(loop [n n xs (seq coll)]
(if (and xs (pos? n))
(recur (dec n) (next xs))
xs)))
;redefine let and loop with destructuring
(defn destructure [bindings]
(let [bmap (apply array-map bindings)
pb (fn pb [bvec b v]
(let [pvec
(fn [bvec b val]
(let [gvec (gensym "vec__")]
(loop [ret (-> bvec (conj gvec) (conj val))
n 0
bs b
seen-rest? false]
(if (seq bs)
(let [firstb (first bs)]
(cond
(= firstb '&) (recur (pb ret (second bs) (list `nthnext gvec n))
n
(nnext bs)
true)
(= firstb :as) (pb ret (second bs) gvec)
:else (if seen-rest?
(throw (new Exception "Unsupported binding form, only :as can follow & parameter"))
(recur (pb ret firstb (list `nth gvec n nil))
(inc n)
(next bs)
seen-rest?))))
ret))))
pmap
(fn [bvec b v]
(let [gmap (or (:as b) (gensym "map__"))
defaults (:or b)]
(loop [ret (-> bvec (conj gmap) (conj v))
bes (reduce
(fn [bes entry]
(reduce #(assoc %1 %2 ((val entry) %2))
(dissoc bes (key entry))
((key entry) bes)))
(dissoc b :as :or)
{:keys #(keyword (str %)), :strs str, :syms #(list `quote %)})]
(if (seq bes)
(let [bb (key (first bes))
bk (val (first bes))
has-default (contains? defaults bb)]
(recur (pb ret bb (if has-default
(list `get gmap bk (defaults bb))
(list `get gmap bk)))
(next bes)))
ret))))]
(cond
(symbol? b) (-> bvec (conj b) (conj v))
(vector? b) (pvec bvec b v)
(map? b) (pmap bvec b v)
:else (throw (new Exception (str "Unsupported binding form: " b))))))
process-entry (fn [bvec b] (pb bvec (key b) (val b)))]
(if (every? symbol? (keys bmap))
bindings
(reduce process-entry [] bmap))))
(defmacro let
"Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein."
[bindings & body]
(assert-args let
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
`(let* ~(destructure bindings) ~@body))
;redefine fn with destructuring and pre/post conditions
(defmacro fn
"(fn name? [params* ] exprs*)
(fn name? ([params* ] exprs*)+)
params => positional-params* , or positional-params* & next-param
positional-param => binding-form
next-param => binding-form
name => symbol
Defines a function"
[& sigs]
(let [name (if (symbol? (first sigs)) (first sigs) nil)
sigs (if name (next sigs) sigs)
sigs (if (vector? (first sigs)) (list sigs) sigs)
psig (fn [sig]
(let [[params & body] sig
conds (when (and (next body) (map? (first body)))
(first body))
body (if conds (next body) body)
conds (or conds (meta params))
pre (:pre conds)
post (:post conds)
body (if post
`((let [~'% ~(if (< 1 (count body))
`(do ~@body)
(first body))]
~@(map (fn [c] `(assert ~c)) post)
~'%))
body)
body (if pre
(concat (map (fn [c] `(assert ~c)) pre)
body)
body)]
(if (every? symbol? params)
(cons params body)
(loop [params params
new-params []
lets []]
(if params
(if (symbol? (first params))
(recur (next params) (conj new-params (first params)) lets)
(let [gparam (gensym "p__")]
(recur (next params) (conj new-params gparam)
(-> lets (conj (first params)) (conj gparam)))))
`(~new-params
(let ~lets
~@body)))))))
new-sigs (map psig sigs)]
(with-meta
(if name
(list* 'fn* name new-sigs)
(cons 'fn* new-sigs))
*macro-meta*)))
(defmacro loop
"Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein. Acts as a recur target."
[bindings & body]
(assert-args loop
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(let [db (destructure bindings)]
(if (= db bindings)
`(loop* ~bindings ~@body)
(let [vs (take-nth 2 (drop 1 bindings))
bs (take-nth 2 bindings)
gs (map (fn [b] (if (symbol? b) b (gensym))) bs)
bfs (reduce (fn [ret [b v g]]
(if (symbol? b)
(conj ret g v)
(conj ret g v b g)))
[] (map vector bs vs gs))]
`(let ~bfs
(loop* ~(vec (interleave gs gs))
(let ~(vec (interleave bs gs))
~@body)))))))
(defmacro when-first
"bindings => x xs
Same as (when (seq xs) (let [x (first xs)] body))"
[bindings & body]
(assert-args when-first
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [[x xs] bindings]
`(when (seq ~xs)
(let [~x (first ~xs)]
~@body))))
(defmacro lazy-cat
"Expands to code which yields a lazy sequence of the concatenation
of the supplied colls. Each coll expr is not evaluated until it is
needed.
(lazy-cat xs ys zs) === (concat (lazy-seq xs) (lazy-seq ys) (lazy-seq zs))"
[& colls]
`(concat ~@(map #(list `lazy-seq %) colls)))
(defmacro for
"List comprehension. Takes a vector of one or more
binding-form/collection-expr pairs, each followed by zero or more
modifiers, and yields a lazy sequence of evaluations of expr.
Collections are iterated in a nested fashion, rightmost fastest,
and nested coll-exprs can refer to bindings created in prior
binding-forms. Supported modifiers are: :let [binding-form expr ...],
:while test, :when test.
(take 100 (for [x (range 100000000) y (range 1000000) :while (< y x)] [x y]))"
[seq-exprs body-expr]
(assert-args for
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [to-groups (fn [seq-exprs]
(reduce (fn [groups [k v]]
(if (keyword? k)
(conj (pop groups) (conj (peek groups) [k v]))
(conj groups [k v])))
[] (partition 2 seq-exprs)))
err (fn [& msg] (throw (IllegalArgumentException. #^String (apply str msg))))
emit-bind (fn emit-bind [[[bind expr & mod-pairs]
& [[_ next-expr] :as next-groups]]]
(let [giter (gensym "iter__")
gxs (gensym "s__")
do-mod (fn do-mod [[[k v :as pair] & etc]]
(cond
(= k :let) `(let ~v ~(do-mod etc))
(= k :while) `(when ~v ~(do-mod etc))
(= k :when) `(if ~v
~(do-mod etc)
(recur (rest ~gxs)))
(keyword? k) (err "Invalid 'for' keyword " k)
next-groups
`(let [iterys# ~(emit-bind next-groups)
fs# (seq (iterys# ~next-expr))]
(if fs#
(concat fs# (~giter (rest ~gxs)))
(recur (rest ~gxs))))
:else `(cons ~body-expr
(~giter (rest ~gxs)))))]
(if next-groups
#_"not the inner-most loop"
`(fn ~giter [~gxs]
(lazy-seq
(loop [~gxs ~gxs]
(when-first [~bind ~gxs]
~(do-mod mod-pairs)))))
#_"inner-most loop"
(let [gi (gensym "i__")
gb (gensym "b__")
do-cmod (fn do-cmod [[[k v :as pair] & etc]]
(cond
(= k :let) `(let ~v ~(do-cmod etc))
(= k :while) `(when ~v ~(do-cmod etc))
(= k :when) `(if ~v
~(do-cmod etc)
(recur
(unchecked-inc ~gi)))
(keyword? k)
(err "Invalid 'for' keyword " k)
:else
`(do (chunk-append ~gb ~body-expr)
(recur (unchecked-inc ~gi)))))]
`(fn ~giter [~gxs]
(lazy-seq
(loop [~gxs ~gxs]
(when-let [~gxs (seq ~gxs)]
(if (chunked-seq? ~gxs)
(let [c# (chunk-first ~gxs)
size# (int (count c#))
~gb (chunk-buffer size#)]
(if (loop [~gi (int 0)]
(if (< ~gi size#)
(let [~bind (.nth c# ~gi)]
~(do-cmod mod-pairs))
true))
(chunk-cons
(chunk ~gb)
(~giter (chunk-rest ~gxs)))
(chunk-cons (chunk ~gb) nil)))
(let [~bind (first ~gxs)]
~(do-mod mod-pairs)))))))))))]
`(let [iter# ~(emit-bind (to-groups seq-exprs))]
(iter# ~(second seq-exprs)))))
(defmacro comment
"Ignores body, yields nil"
[& body])
(defmacro with-out-str
"Evaluates exprs in a context in which *out* is bound to a fresh
StringWriter. Returns the string created by any nested printing
calls."
[& body]
`(let [s# (new java.io.StringWriter)]
(binding [*out* s#]
~@body
(str s#))))
(defmacro with-in-str
"Evaluates body in a context in which *in* is bound to a fresh
StringReader initialized with the string s."
[s & body]
`(with-open [s# (-> (java.io.StringReader. ~s) clojure.lang.LineNumberingPushbackReader.)]
(binding [*in* s#]
~@body)))
(defn pr-str
"pr to a string, returning it"
{:tag String}
[& xs]
(with-out-str
(apply pr xs)))
(defn prn-str
"prn to a string, returning it"
{:tag String}
[& xs]
(with-out-str
(apply prn xs)))
(defn print-str
"print to a string, returning it"
{:tag String}
[& xs]
(with-out-str
(apply print xs)))
(defn println-str
"println to a string, returning it"
{:tag String}
[& xs]
(with-out-str
(apply println xs)))
(defmacro assert
"Evaluates expr and throws an exception if it does not evaluate to
logical true."
[x]
(when *assert*
`(when-not ~x
(throw (new AssertionError (str "Assert failed: " (pr-str '~x)))))))
(defn test
"test [v] finds fn at key :test in var metadata and calls it,
presuming failure will throw exception"
[v]
(let [f (:test (meta v))]
(if f
(do (f) :ok)
:no-test)))
(defn re-pattern
"Returns an instance of java.util.regex.Pattern, for use, e.g. in
re-matcher."
{:tag java.util.regex.Pattern}
[s] (if (instance? java.util.regex.Pattern s)
s
(. java.util.regex.Pattern (compile s))))
(defn re-matcher
"Returns an instance of java.util.regex.Matcher, for use, e.g. in
re-find."
{:tag java.util.regex.Matcher}
[#^java.util.regex.Pattern re s]
(. re (matcher s)))
(defn re-groups
"Returns the groups from the most recent match/find. If there are no
nested groups, returns a string of the entire match. If there are
nested groups, returns a vector of the groups, the first element
being the entire match."
[#^java.util.regex.Matcher m]
(let [gc (. m (groupCount))]
(if (zero? gc)
(. m (group))
(loop [ret [] c 0]
(if (<= c gc)
(recur (conj ret (. m (group c))) (inc c))
ret)))))
(defn re-seq
"Returns a lazy sequence of successive matches of pattern in string,
using java.util.regex.Matcher.find(), each such match processed with
re-groups."
[#^java.util.regex.Pattern re s]
(let [m (re-matcher re s)]
((fn step []
(when (. m (find))
(lazy-seq (cons (re-groups m) (step))))))))
(defn re-matches
"Returns the match, if any, of string to pattern, using
java.util.regex.Matcher.matches(). Uses re-groups to return the
groups."
[#^java.util.regex.Pattern re s]
(let [m (re-matcher re s)]
(when (. m (matches))
(re-groups m))))
(defn re-find
"Returns the next regex match, if any, of string to pattern, using
java.util.regex.Matcher.find(). Uses re-groups to return the
groups."
([#^java.util.regex.Matcher m]
(when (. m (find))
(re-groups m)))
([#^java.util.regex.Pattern re s]
(let [m (re-matcher re s)]
(re-find m))))
(defn rand
"Returns a random floating point number between 0 (inclusive) and
n (default 1) (exclusive)."
([] (. Math (random)))
([n] (* n (rand))))
(defn rand-int
"Returns a random integer between 0 (inclusive) and n (exclusive)."
[n] (int (rand n)))
(defmacro defn-
"same as defn, yielding non-public def"
[name & decls]
(list* `defn (with-meta name (assoc (meta name) :private true)) decls))
(defn print-doc [v]
(println "-------------------------")
(println (str (ns-name (:ns (meta v))) "/" (:name (meta v))))
(prn (:arglists (meta v)))
(when (:macro (meta v))
(println "Macro"))
(println " " (:doc (meta v))))
(defn find-doc
"Prints documentation for any var whose documentation or name
contains a match for re-string-or-pattern"
[re-string-or-pattern]
(let [re (re-pattern re-string-or-pattern)]
(doseq [ns (all-ns)
v (sort-by (comp :name meta) (vals (ns-interns ns)))
:when (and (:doc (meta v))
(or (re-find (re-matcher re (:doc (meta v))))
(re-find (re-matcher re (str (:name (meta v)))))))]
(print-doc v))))
(defn special-form-anchor
"Returns the anchor tag on http://clojure.org/special_forms for the
special form x, or nil"
[x]
(#{'. 'def 'do 'fn 'if 'let 'loop 'monitor-enter 'monitor-exit 'new
'quote 'recur 'set! 'throw 'try 'var} x))
(defn syntax-symbol-anchor
"Returns the anchor tag on http://clojure.org/special_forms for the
special form that uses syntax symbol x, or nil"
[x]
({'& 'fn 'catch 'try 'finally 'try} x))
(defn print-special-doc
[name type anchor]
(println "-------------------------")
(println name)
(println type)
(println (str " Please see http://clojure.org/special_forms#" anchor)))
(defn print-namespace-doc
"Print the documentation string of a Namespace."
[nspace]
(println "-------------------------")
(println (str (ns-name nspace)))
(println " " (:doc (meta nspace))))
(defmacro doc
"Prints documentation for a var or special form given its name"
[name]
(cond
(special-form-anchor `~name)
`(print-special-doc '~name "Special Form" (special-form-anchor '~name))
(syntax-symbol-anchor `~name)
`(print-special-doc '~name "Syntax Symbol" (syntax-symbol-anchor '~name))
:else
(let [nspace (find-ns name)]
(if nspace
`(print-namespace-doc ~nspace)
`(print-doc (var ~name))))))
(defn tree-seq
"Returns a lazy sequence of the nodes in a tree, via a depth-first walk.
branch? must be a fn of one arg that returns true if passed a node
that can have children (but may not). children must be a fn of one
arg that returns a sequence of the children. Will only be called on
nodes for which branch? returns true. Root is the root node of the
tree."
[branch? children root]
(let [walk (fn walk [node]
(lazy-seq
(cons node
(when (branch? node)
(mapcat walk (children node))))))]
(walk root)))
(defn file-seq
"A tree seq on java.io.Files"
[dir]
(tree-seq
(fn [#^java.io.File f] (. f (isDirectory)))
(fn [#^java.io.File d] (seq (. d (listFiles))))
dir))
(defn xml-seq
"A tree seq on the xml elements as per xml/parse"
[root]
(tree-seq
(complement string?)
(comp seq :content)
root))
(defn special-symbol?
"Returns true if s names a special form"
[s]
(contains? (. clojure.lang.Compiler specials) s))
(defn var?
"Returns true if v is of type clojure.lang.Var"
[v] (instance? clojure.lang.Var v))
(defn slurp
"Reads the file named by f using the encoding enc into a string
and returns it."
([f] (slurp f (.name (java.nio.charset.Charset/defaultCharset))))
([#^String f #^String enc]
(with-open [r (new java.io.BufferedReader
(new java.io.InputStreamReader
(new java.io.FileInputStream f) enc))]
(let [sb (new StringBuilder)]
(loop [c (.read r)]
(if (neg? c)
(str sb)
(do
(.append sb (char c))
(recur (.read r)))))))))
(defn subs
"Returns the substring of s beginning at start inclusive, and ending
at end (defaults to length of string), exclusive."
([#^String s start] (. s (substring start)))
([#^String s start end] (. s (substring start end))))
(defn max-key
"Returns the x for which (k x), a number, is greatest."
([k x] x)
([k x y] (if (> (k x) (k y)) x y))
([k x y & more]
(reduce #(max-key k %1 %2) (max-key k x y) more)))
(defn min-key
"Returns the x for which (k x), a number, is least."
([k x] x)
([k x y] (if (< (k x) (k y)) x y))
([k x y & more]
(reduce #(min-key k %1 %2) (min-key k x y) more)))
(defn distinct
"Returns a lazy sequence of the elements of coll with duplicates removed"
[coll]
(let [step (fn step [xs seen]
(lazy-seq
((fn [[f :as xs] seen]
(when-let [s (seq xs)]
(if (contains? seen f)
(recur (rest s) seen)
(cons f (step (rest s) (conj seen f))))))
xs seen)))]
(step coll #{})))
(defn replace
"Given a map of replacement pairs and a vector/collection, returns a
vector/seq with any elements = a key in smap replaced with the
corresponding val in smap"
[smap coll]
(if (vector? coll)
(reduce (fn [v i]
(if-let [e (find smap (nth v i))]
(assoc v i (val e))
v))
coll (range (count coll)))
(map #(if-let [e (find smap %)] (val e) %) coll)))
(defmacro dosync
"Runs the exprs (in an implicit do) in a transaction that encompasses
exprs and any nested calls. Starts a transaction if none is already
running on this thread. Any uncaught exception will abort the
transaction and flow out of dosync. The exprs may be run more than
once, but any effects on Refs will be atomic."
[& exprs]
`(sync nil ~@exprs))
(defmacro with-precision
"Sets the precision and rounding mode to be used for BigDecimal operations.
Usage: (with-precision 10 (/ 1M 3))
or: (with-precision 10 :rounding HALF_DOWN (/ 1M 3))
The rounding mode is one of CEILING, FLOOR, HALF_UP, HALF_DOWN,
HALF_EVEN, UP, DOWN and UNNECESSARY; it defaults to HALF_UP."
[precision & exprs]
(let [[body rm] (if (= (first exprs) :rounding)
[(next (next exprs))
`((. java.math.RoundingMode ~(second exprs)))]
[exprs nil])]
`(binding [*math-context* (java.math.MathContext. ~precision ~@rm)]
~@body)))
(defn mk-bound-fn
{:private true}
[#^clojure.lang.Sorted sc test key]
(fn [e]
(test (.. sc comparator (compare (. sc entryKey e) key)) 0)))
(defn subseq
"sc must be a sorted collection, test(s) one of <, <=, > or
>=. Returns a seq of those entries with keys ek for
which (test (.. sc comparator (compare ek key)) 0) is true"
([#^clojure.lang.Sorted sc test key]
(let [include (mk-bound-fn sc test key)]
(if (#{> >=} test)
(when-let [[e :as s] (. sc seqFrom key true)]
(if (include e) s (next s)))
(take-while include (. sc seq true)))))
([#^clojure.lang.Sorted sc start-test start-key end-test end-key]
(when-let [[e :as s] (. sc seqFrom start-key true)]
(take-while (mk-bound-fn sc end-test end-key)
(if ((mk-bound-fn sc start-test start-key) e) s (next s))))))
(defn rsubseq
"sc must be a sorted collection, test(s) one of <, <=, > or
>=. Returns a reverse seq of those entries with keys ek for
which (test (.. sc comparator (compare ek key)) 0) is true"
([#^clojure.lang.Sorted sc test key]
(let [include (mk-bound-fn sc test key)]
(if (#{< <=} test)
(when-let [[e :as s] (. sc seqFrom key false)]
(if (include e) s (next s)))
(take-while include (. sc seq false)))))
([#^clojure.lang.Sorted sc start-test start-key end-test end-key]
(when-let [[e :as s] (. sc seqFrom end-key false)]
(take-while (mk-bound-fn sc start-test start-key)
(if ((mk-bound-fn sc end-test end-key) e) s (next s))))))
(defn repeatedly
"Takes a function of no args, presumably with side effects, and returns an infinite
lazy sequence of calls to it"
[f] (lazy-seq (cons (f) (repeatedly f))))
(defn add-classpath
"DEPRECATED
Adds the url (String or URL object) to the classpath per
URLClassLoader.addURL"
[url]
(println "WARNING: add-classpath is deprecated")
(clojure.lang.RT/addURL url))
(defn hash
"Returns the hash code of its argument"
[x] (. clojure.lang.Util (hash x)))
(defn interpose
"Returns a lazy seq of the elements of coll separated by sep"
[sep coll] (drop 1 (interleave (repeat sep) coll)))
(defmacro definline
"Experimental - like defmacro, except defines a named function whose
body is the expansion, calls to which may be expanded inline as if
it were a macro. Cannot be used with variadic (&) args."
[name & decl]
(let [[pre-args [args expr]] (split-with (comp not vector?) decl)]
`(do
(defn ~name ~@pre-args ~args ~(apply (eval (list `fn args expr)) args))
(alter-meta! (var ~name) assoc :inline (fn ~name ~args ~expr))
(var ~name))))
(defn empty
"Returns an empty collection of the same category as coll, or nil"
[coll]
(when (instance? clojure.lang.IPersistentCollection coll)
(.empty #^clojure.lang.IPersistentCollection coll)))
(defmacro amap
"Maps an expression across an array a, using an index named idx, and
return value named ret, initialized to a clone of a, then setting
each element of ret to the evaluation of expr, returning the new
array ret."
[a idx ret expr]
`(let [a# ~a
~ret (aclone a#)]
(loop [~idx (int 0)]
(if (< ~idx (alength a#))
(do
(aset ~ret ~idx ~expr)
(recur (unchecked-inc ~idx)))
~ret))))
(defmacro areduce
"Reduces an expression across an array a, using an index named idx,
and return value named ret, initialized to init, setting ret to the
evaluation of expr at each step, returning ret."
[a idx ret init expr]
`(let [a# ~a]
(loop [~idx (int 0) ~ret ~init]
(if (< ~idx (alength a#))
(recur (unchecked-inc ~idx) ~expr)
~ret))))
(defn float-array
"Creates an array of floats"
{:inline (fn [& args] `(. clojure.lang.Numbers float_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers float_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers float_array size init-val-or-seq)))
(defn boolean-array
"Creates an array of booleans"
{:inline (fn [& args] `(. clojure.lang.Numbers boolean_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers boolean_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers boolean_array size init-val-or-seq)))
(defn byte-array
"Creates an array of bytes"
{:inline (fn [& args] `(. clojure.lang.Numbers byte_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers byte_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers byte_array size init-val-or-seq)))
(defn char-array
"Creates an array of chars"
{:inline (fn [& args] `(. clojure.lang.Numbers char_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers char_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers char_array size init-val-or-seq)))
(defn short-array
"Creates an array of shorts"
{:inline (fn [& args] `(. clojure.lang.Numbers short_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers short_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers short_array size init-val-or-seq)))
(defn double-array
"Creates an array of doubles"
{:inline (fn [& args] `(. clojure.lang.Numbers double_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers double_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers double_array size init-val-or-seq)))
(defn int-array
"Creates an array of ints"
{:inline (fn [& args] `(. clojure.lang.Numbers int_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers int_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers int_array size init-val-or-seq)))
(defn long-array
"Creates an array of longs"
{:inline (fn [& args] `(. clojure.lang.Numbers long_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers long_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers long_array size init-val-or-seq)))
(definline booleans
"Casts to boolean[]"
[xs] `(. clojure.lang.Numbers booleans ~xs))
(definline bytes
"Casts to bytes[]"
[xs] `(. clojure.lang.Numbers bytes ~xs))
(definline chars
"Casts to chars[]"
[xs] `(. clojure.lang.Numbers chars ~xs))
(definline shorts
"Casts to shorts[]"
[xs] `(. clojure.lang.Numbers shorts ~xs))
(definline floats
"Casts to float[]"
[xs] `(. clojure.lang.Numbers floats ~xs))
(definline ints
"Casts to int[]"
[xs] `(. clojure.lang.Numbers ints ~xs))
(definline doubles
"Casts to double[]"
[xs] `(. clojure.lang.Numbers doubles ~xs))
(definline longs
"Casts to long[]"
[xs] `(. clojure.lang.Numbers longs ~xs))
(import '(java.util.concurrent BlockingQueue LinkedBlockingQueue))
(defn seque
"Creates a queued seq on another (presumably lazy) seq s. The queued
seq will produce a concrete seq in the background, and can get up to
n items ahead of the consumer. n-or-q can be an integer n buffer
size, or an instance of java.util.concurrent BlockingQueue. Note
that reading from a seque can block if the reader gets ahead of the
producer."
([s] (seque 100 s))
([n-or-q s]
(let [#^BlockingQueue q (if (instance? BlockingQueue n-or-q)
n-or-q
(LinkedBlockingQueue. (int n-or-q)))
NIL (Object.) ;nil sentinel since LBQ doesn't support nils
agt (agent (seq s))
fill (fn [s]
(try
(loop [[x & xs :as s] s]
(if s
(if (.offer q (if (nil? x) NIL x))
(recur xs)
s)
(.put q q))) ; q itself is eos sentinel
(catch Exception e
(.put q q)
(throw e))))
drain (fn drain []
(lazy-seq
(let [x (.take q)]
(if (identical? x q) ;q itself is eos sentinel
(do @agt nil) ;touch agent just to propagate errors
(do
(send-off agt fill)
(cons (if (identical? x NIL) nil x) (drain)))))))]
(send-off agt fill)
(drain))))
(defn class?
"Returns true if x is an instance of Class"
[x] (instance? Class x))
(defn alter-var-root
"Atomically alters the root binding of var v by applying f to its
current value plus any args"
[#^clojure.lang.Var v f & args] (.alterRoot v f args))
(defn make-hierarchy
"Creates a hierarchy object for use with derive, isa? etc."
[] {:parents {} :descendants {} :ancestors {}})
(def #^{:private true}
global-hierarchy (make-hierarchy))
(defn not-empty
"If coll is empty, returns nil, else coll"
[coll] (when (seq coll) coll))
(defn bases
"Returns the immediate superclass and direct interfaces of c, if any"
[#^Class c]
(let [i (.getInterfaces c)
s (.getSuperclass c)]
(not-empty
(if s (cons s i) i))))
(defn supers
"Returns the immediate and indirect superclasses and interfaces of c, if any"
[#^Class class]
(loop [ret (set (bases class)) cs ret]
(if (seq cs)
(let [c (first cs) bs (bases c)]
(recur (into ret bs) (into (disj cs c) bs)))
(not-empty ret))))
(defn isa?
"Returns true if (= child parent), or child is directly or indirectly derived from
parent, either via a Java type inheritance relationship or a
relationship established via derive. h must be a hierarchy obtained
from make-hierarchy, if not supplied defaults to the global
hierarchy"
([child parent] (isa? global-hierarchy child parent))
([h child parent]
(or (= child parent)
(and (class? parent) (class? child)
(. #^Class parent isAssignableFrom child))
(contains? ((:ancestors h) child) parent)
(and (class? child) (some #(contains? ((:ancestors h) %) parent) (supers child)))
(and (vector? parent) (vector? child)
(= (count parent) (count child))
(loop [ret true i 0]
(if (or (not ret) (= i (count parent)))
ret
(recur (isa? h (child i) (parent i)) (inc i))))))))
(defn parents
"Returns the immediate parents of tag, either via a Java type
inheritance relationship or a relationship established via derive. h
must be a hierarchy obtained from make-hierarchy, if not supplied
defaults to the global hierarchy"
([tag] (parents global-hierarchy tag))
([h tag] (not-empty
(let [tp (get (:parents h) tag)]
(if (class? tag)
(into (set (bases tag)) tp)
tp)))))
(defn ancestors
"Returns the immediate and indirect parents of tag, either via a Java type
inheritance relationship or a relationship established via derive. h
must be a hierarchy obtained from make-hierarchy, if not supplied
defaults to the global hierarchy"
([tag] (ancestors global-hierarchy tag))
([h tag] (not-empty
(let [ta (get (:ancestors h) tag)]
(if (class? tag)
(let [superclasses (set (supers tag))]
(reduce into superclasses
(cons ta
(map #(get (:ancestors h) %) superclasses))))
ta)))))
(defn descendants
"Returns the immediate and indirect children of tag, through a
relationship established via derive. h must be a hierarchy obtained
from make-hierarchy, if not supplied defaults to the global
hierarchy. Note: does not work on Java type inheritance
relationships."
([tag] (descendants global-hierarchy tag))
([h tag] (if (class? tag)
(throw (java.lang.UnsupportedOperationException. "Can't get descendants of classes"))
(not-empty (get (:descendants h) tag)))))
(defn derive
"Establishes a parent/child relationship between parent and
tag. Parent must be a namespace-qualified symbol or keyword and
child can be either a namespace-qualified symbol or keyword or a
class. h must be a hierarchy obtained from make-hierarchy, if not
supplied defaults to, and modifies, the global hierarchy."
([tag parent]
(assert (namespace parent))
(assert (or (class? tag) (and (instance? clojure.lang.Named tag) (namespace tag))))
(alter-var-root #'global-hierarchy derive tag parent) nil)
([h tag parent]
(assert (not= tag parent))
(assert (or (class? tag) (instance? clojure.lang.Named tag)))
(assert (instance? clojure.lang.Named parent))
(let [tp (:parents h)
td (:descendants h)
ta (:ancestors h)
tf (fn [m source sources target targets]
(reduce (fn [ret k]
(assoc ret k
(reduce conj (get targets k #{}) (cons target (targets target)))))
m (cons source (sources source))))]
(or
(when-not (contains? (tp tag) parent)
(when (contains? (ta tag) parent)
(throw (Exception. (print-str tag "already has" parent "as ancestor"))))
(when (contains? (ta parent) tag)
(throw (Exception. (print-str "Cyclic derivation:" parent "has" tag "as ancestor"))))
{:parents (assoc (:parents h) tag (conj (get tp tag #{}) parent))
:ancestors (tf (:ancestors h) tag td parent ta)
:descendants (tf (:descendants h) parent ta tag td)})
h))))
(defn underive
"Removes a parent/child relationship between parent and
tag. h must be a hierarchy obtained from make-hierarchy, if not
supplied defaults to, and modifies, the global hierarchy."
([tag parent] (alter-var-root #'global-hierarchy underive tag parent) nil)
([h tag parent]
(let [tp (:parents h)
td (:descendants h)
ta (:ancestors h)
tf (fn [m source sources target targets]
(reduce
(fn [ret k]
(assoc ret k
(reduce disj (get targets k) (cons target (targets target)))))
m (cons source (sources source))))]
(if (contains? (tp tag) parent)
{:parent (assoc (:parents h) tag (disj (get tp tag) parent))
:ancestors (tf (:ancestors h) tag td parent ta)
:descendants (tf (:descendants h) parent ta tag td)}
h))))
(defn distinct?
"Returns true if no two of the arguments are ="
{:tag Boolean}
([x] true)
([x y] (not (= x y)))
([x y & more]
(if (not= x y)
(loop [s #{x y} [x & etc :as xs] more]
(if xs
(if (contains? s x)
false
(recur (conj s x) etc))
true))
false)))
(defn resultset-seq
"Creates and returns a lazy sequence of structmaps corresponding to
the rows in the java.sql.ResultSet rs"
[#^java.sql.ResultSet rs]
(let [rsmeta (. rs (getMetaData))
idxs (range 1 (inc (. rsmeta (getColumnCount))))
keys (map (comp keyword #(.toLowerCase #^String %))
(map (fn [i] (. rsmeta (getColumnLabel i))) idxs))
check-keys
(or (apply distinct? keys)
(throw (Exception. "ResultSet must have unique column labels")))
row-struct (apply create-struct keys)
row-values (fn [] (map (fn [#^Integer i] (. rs (getObject i))) idxs))
rows (fn thisfn []
(when (. rs (next))
(lazy-seq (cons (apply struct row-struct (row-values)) (thisfn)))))]
(rows)))
(defn iterator-seq
"Returns a seq on a java.util.Iterator. Note that most collections
providing iterators implement Iterable and thus support seq directly."
[iter]
(clojure.lang.IteratorSeq/create iter))
(defn enumeration-seq
"Returns a seq on a java.util.Enumeration"
[e]
(clojure.lang.EnumerationSeq/create e))
(defn format
"Formats a string using java.lang.String.format, see java.util.Formatter for format
string syntax"
{:tag String}
[fmt & args]
(String/format fmt (to-array args)))
(defn printf
"Prints formatted output, as per format"
[fmt & args]
(print (apply format fmt args)))
(def gen-class)
(defmacro with-loading-context [& body]
`((fn loading# []
(. clojure.lang.Var (pushThreadBindings {clojure.lang.Compiler/LOADER
(.getClassLoader (.getClass #^Object loading#))}))
(try
~@body
(finally
(. clojure.lang.Var (popThreadBindings)))))))
(defmacro ns
"Sets *ns* to the namespace named by name (unevaluated), creating it
if needed. references can be zero or more of: (:refer-clojure ...)
(:require ...) (:use ...) (:import ...) (:load ...) (:gen-class)
with the syntax of refer-clojure/require/use/import/load/gen-class
respectively, except the arguments are unevaluated and need not be
quoted. (:gen-class ...), when supplied, defaults to :name
corresponding to the ns name, :main true, :impl-ns same as ns, and
:init-impl-ns true. All options of gen-class are
supported. The :gen-class directive is ignored when not
compiling. If :gen-class is not supplied, when compiled only an
nsname__init.class will be generated. If :refer-clojure is not used, a
default (refer 'clojure) is used. Use of ns is preferred to
individual calls to in-ns/require/use/import:
(ns foo.bar
(:refer-clojure :exclude [ancestors printf])
(:require (clojure.contrib sql sql.tests))
(:use (my.lib this that))
(:import (java.util Date Timer Random)
(java.sql Connection Statement)))"
[name & references]
(let [process-reference
(fn [[kname & args]]
`(~(symbol "clojure.core" (clojure.core/name kname))
~@(map #(list 'quote %) args)))
docstring (when (string? (first references)) (first references))
references (if docstring (next references) references)
name (if docstring
(with-meta name (assoc (meta name)
:doc docstring))
name)
gen-class-clause (first (filter #(= :gen-class (first %)) references))
gen-class-call
(when gen-class-clause
(list* `gen-class :name (.replace (str name) \- \_) :impl-ns name :main true (next gen-class-clause)))
references (remove #(= :gen-class (first %)) references)
;ns-effect (clojure.core/in-ns name)
]
`(do
(clojure.core/in-ns '~name)
(with-loading-context
~@(when gen-class-call (list gen-class-call))
~@(when (and (not= name 'clojure.core) (not-any? #(= :refer-clojure (first %)) references))
`((clojure.core/refer '~'clojure.core)))
~@(map process-reference references)))))
(defmacro refer-clojure
"Same as (refer 'clojure.core <filters>)"
[& filters]
`(clojure.core/refer '~'clojure.core ~@filters))
(defmacro defonce
"defs name to have the root value of the expr iff the named var has no root value,
else expr is unevaluated"
[name expr]
`(let [v# (def ~name)]
(when-not (.hasRoot v#)
(def ~name ~expr))))
;;;;;;;;;;; require/use/load, contributed by <NAME> ;;;;;;;;;;;;;;;;;;
(defonce
#^{:private true
:doc "A ref to a sorted set of symbols representing loaded libs"}
*loaded-libs* (ref (sorted-set)))
(defonce
#^{:private true
:doc "the set of paths currently being loaded by this thread"}
*pending-paths* #{})
(defonce
#^{:private true :doc
"True while a verbose load is pending"}
*loading-verbosely* false)
(defn- throw-if
"Throws an exception with a message if pred is true"
[pred fmt & args]
(when pred
(let [#^String message (apply format fmt args)
exception (Exception. message)
raw-trace (.getStackTrace exception)
boring? #(not= (.getMethodName #^StackTraceElement %) "doInvoke")
trace (into-array (drop 2 (drop-while boring? raw-trace)))]
(.setStackTrace exception trace)
(throw exception))))
(defn- libspec?
"Returns true if x is a libspec"
[x]
(or (symbol? x)
(and (vector? x)
(or
(nil? (second x))
(keyword? (second x))))))
(defn- prependss
"Prepends a symbol or a seq to coll"
[x coll]
(if (symbol? x)
(cons x coll)
(concat x coll)))
(defn- root-resource
"Returns the root directory path for a lib"
{:tag String}
[lib]
(str \/
(.. (name lib)
(replace \- \_)
(replace \. \/))))
(defn- root-directory
"Returns the root resource path for a lib"
[lib]
(let [d (root-resource lib)]
(subs d 0 (.lastIndexOf d "/"))))
(def load)
(defn- load-one
"Loads a lib given its name. If need-ns, ensures that the associated
namespace exists after loading. If require, records the load so any
duplicate loads can be skipped."
[lib need-ns require]
(load (root-resource lib))
(throw-if (and need-ns (not (find-ns lib)))
"namespace '%s' not found after loading '%s'"
lib (root-resource lib))
(when require
(dosync
(commute *loaded-libs* conj lib))))
(defn- load-all
"Loads a lib given its name and forces a load of any libs it directly or
indirectly loads. If need-ns, ensures that the associated namespace
exists after loading. If require, records the load so any duplicate loads
can be skipped."
[lib need-ns require]
(dosync
(commute *loaded-libs* #(reduce conj %1 %2)
(binding [*loaded-libs* (ref (sorted-set))]
(load-one lib need-ns require)
@*loaded-libs*))))
(defn- load-lib
"Loads a lib with options"
[prefix lib & options]
(throw-if (and prefix (pos? (.indexOf (name lib) (int \.))))
"lib names inside prefix lists must not contain periods")
(let [lib (if prefix (symbol (str prefix \. lib)) lib)
opts (apply hash-map options)
{:keys [as reload reload-all require use verbose]} opts
loaded (contains? @*loaded-libs* lib)
load (cond reload-all
load-all
(or reload (not require) (not loaded))
load-one)
need-ns (or as use)
filter-opts (select-keys opts '(:exclude :only :rename))]
(binding [*loading-verbosely* (or *loading-verbosely* verbose)]
(if load
(load lib need-ns require)
(throw-if (and need-ns (not (find-ns lib)))
"namespace '%s' not found" lib))
(when (and need-ns *loading-verbosely*)
(printf "(clojure.core/in-ns '%s)\n" (ns-name *ns*)))
(when as
(when *loading-verbosely*
(printf "(clojure.core/alias '%s '%s)\n" as lib))
(alias as lib))
(when use
(when *loading-verbosely*
(printf "(clojure.core/refer '%s" lib)
(doseq [opt filter-opts]
(printf " %s '%s" (key opt) (print-str (val opt))))
(printf ")\n"))
(apply refer lib (mapcat seq filter-opts))))))
(defn- load-libs
"Loads libs, interpreting libspecs, prefix lists, and flags for
forwarding to load-lib"
[& args]
(let [flags (filter keyword? args)
opts (interleave flags (repeat true))
args (filter (complement keyword?) args)]
(doseq [arg args]
(if (libspec? arg)
(apply load-lib nil (prependss arg opts))
(let [[prefix & args] arg]
(throw-if (nil? prefix) "prefix cannot be nil")
(doseq [arg args]
(apply load-lib prefix (prependss arg opts))))))))
;; Public
(defn require
"Loads libs, skipping any that are already loaded. Each argument is
either a libspec that identifies a lib, a prefix list that identifies
multiple libs whose names share a common prefix, or a flag that modifies
how all the identified libs are loaded. Use :require in the ns macro
in preference to calling this directly.
Libs
A 'lib' is a named set of resources in classpath whose contents define a
library of Clojure code. Lib names are symbols and each lib is associated
with a Clojure namespace and a Java package that share its name. A lib's
name also locates its root directory within classpath using Java's
package name to classpath-relative path mapping. All resources in a lib
should be contained in the directory structure under its root directory.
All definitions a lib makes should be in its associated namespace.
'require loads a lib by loading its root resource. The root resource path
is derived from the lib name in the following manner:
Consider a lib named by the symbol 'x.y.z; it has the root directory
<classpath>/x/y/, and its root resource is <classpath>/x/y/z.clj. The root
resource should contain code to create the lib's namespace (usually by using
the ns macro) and load any additional lib resources.
Libspecs
A libspec is a lib name or a vector containing a lib name followed by
options expressed as sequential keywords and arguments.
Recognized options: :as
:as takes a symbol as its argument and makes that symbol an alias to the
lib's namespace in the current namespace.
Prefix Lists
It's common for Clojure code to depend on several libs whose names have
the same prefix. When specifying libs, prefix lists can be used to reduce
repetition. A prefix list contains the shared prefix followed by libspecs
with the shared prefix removed from the lib names. After removing the
prefix, the names that remain must not contain any periods.
Flags
A flag is a keyword.
Recognized flags: :reload, :reload-all, :verbose
:reload forces loading of all the identified libs even if they are
already loaded
:reload-all implies :reload and also forces loading of all libs that the
identified libs directly or indirectly load via require or use
:verbose triggers printing information about each load, alias, and refer
Example:
The following would load the libraries clojure.zip and clojure.set
abbreviated as 's'.
(require '(clojure zip [set :as s]))"
[& args]
(apply load-libs :require args))
(defn use
"Like 'require, but also refers to each lib's namespace using
clojure.core/refer. Use :use in the ns macro in preference to calling
this directly.
'use accepts additional options in libspecs: :exclude, :only, :rename.
The arguments and semantics for :exclude, :only, and :rename are the same
as those documented for clojure.core/refer."
[& args] (apply load-libs :require :use args))
(defn loaded-libs
"Returns a sorted set of symbols naming the currently loaded libs"
[] @*loaded-libs*)
(defn load
"Loads Clojure code from resources in classpath. A path is interpreted as
classpath-relative if it begins with a slash or relative to the root
directory for the current namespace otherwise."
[& paths]
(doseq [#^String path paths]
(let [#^String path (if (.startsWith path "/")
path
(str (root-directory (ns-name *ns*)) \/ path))]
(when *loading-verbosely*
(printf "(clojure.core/load \"%s\")\n" path)
(flush))
; (throw-if (*pending-paths* path)
; "cannot load '%s' again while it is loading"
; path)
(when-not (*pending-paths* path)
(binding [*pending-paths* (conj *pending-paths* path)]
(clojure.lang.RT/load (.substring path 1)))))))
(defn compile
"Compiles the namespace named by the symbol lib into a set of
classfiles. The source for the lib must be in a proper
classpath-relative directory. The output files will go into the
directory specified by *compile-path*, and that directory too must
be in the classpath."
[lib]
(binding [*compile-files* true]
(load-one lib true true))
lib)
;;;;;;;;;;;;; nested associative ops ;;;;;;;;;;;
(defn get-in
"returns the value in a nested associative structure, where ks is a sequence of keys"
[m ks]
(reduce get m ks))
(defn assoc-in
"Associates a value in a nested associative structure, where ks is a
sequence of keys and v is the new value and returns a new nested structure.
If any levels do not exist, hash-maps will be created."
[m [k & ks] v]
(if ks
(assoc m k (assoc-in (get m k) ks v))
(assoc m k v)))
(defn update-in
"'Updates' a value in a nested associative structure, where ks is a
sequence of keys and f is a function that will take the old value
and any supplied args and return the new value, and returns a new
nested structure. If any levels do not exist, hash-maps will be
created."
([m [k & ks] f & args]
(if ks
(assoc m k (apply update-in (get m k) ks f args))
(assoc m k (apply f (get m k) args)))))
(defn empty?
"Returns true if coll has no items - same as (not (seq coll)).
Please use the idiom (seq x) rather than (not (empty? x))"
[coll] (not (seq coll)))
(defn coll?
"Returns true if x implements IPersistentCollection"
[x] (instance? clojure.lang.IPersistentCollection x))
(defn list?
"Returns true if x implements IPersistentList"
[x] (instance? clojure.lang.IPersistentList x))
(defn set?
"Returns true if x implements IPersistentSet"
[x] (instance? clojure.lang.IPersistentSet x))
(defn ifn?
"Returns true if x implements IFn. Note that many data structures
(e.g. sets and maps) implement IFn"
[x] (instance? clojure.lang.IFn x))
(defn fn?
"Returns true if x implements Fn, i.e. is an object created via fn."
[x] (instance? clojure.lang.Fn x))
(defn associative?
"Returns true if coll implements Associative"
[coll] (instance? clojure.lang.Associative coll))
(defn sequential?
"Returns true if coll implements Sequential"
[coll] (instance? clojure.lang.Sequential coll))
(defn sorted?
"Returns true if coll implements Sorted"
[coll] (instance? clojure.lang.Sorted coll))
(defn counted?
"Returns true if coll implements count in constant time"
[coll] (instance? clojure.lang.Counted coll))
(defn reversible?
"Returns true if coll implements Reversible"
[coll] (instance? clojure.lang.Reversible coll))
(def
#^{:doc "bound in a repl thread to the most recent value printed"}
*1)
(def
#^{:doc "bound in a repl thread to the second most recent value printed"}
*2)
(def
#^{:doc "bound in a repl thread to the third most recent value printed"}
*3)
(def
#^{:doc "bound in a repl thread to the most recent exception caught by the repl"}
*e)
(defmacro declare
"defs the supplied var names with no bindings, useful for making forward declarations."
[& names] `(do ~@(map #(list 'def %) names)))
(defn trampoline
"trampoline can be used to convert algorithms requiring mutual
recursion without stack consumption. Calls f with supplied args, if
any. If f returns a fn, calls that fn with no arguments, and
continues to repeat, until the return value is not a fn, then
returns that non-fn value. Note that if you want to return a fn as a
final value, you must wrap it in some data structure and unpack it
after trampoline returns."
([f]
(let [ret (f)]
(if (fn? ret)
(recur ret)
ret)))
([f & args]
(trampoline #(apply f args))))
(defn intern
"Finds or creates a var named by the symbol name in the namespace
ns (which can be a symbol or a namespace), setting its root binding
to val if supplied. The namespace must exist. The var will adopt any
metadata from the name symbol. Returns the var."
([ns #^clojure.lang.Symbol name]
(let [v (clojure.lang.Var/intern (the-ns ns) name)]
(when (meta name) (.setMeta v (meta name)))
v))
([ns name val]
(let [v (clojure.lang.Var/intern (the-ns ns) name val)]
(when (meta name) (.setMeta v (meta name)))
v)))
(defmacro while
"Repeatedly executes body while test expression is true. Presumes
some side-effect will cause test to become false/nil. Returns nil"
[test & body]
`(loop []
(when ~test
~@body
(recur))))
(defn memoize
"Returns a memoized version of a referentially transparent function. The
memoized version of the function keeps a cache of the mapping from arguments
to results and, when calls with the same arguments are repeated often, has
higher performance at the expense of higher memory use."
[f]
(let [mem (atom {})]
(fn [& args]
(if-let [e (find @mem args)]
(val e)
(let [ret (apply f args)]
(swap! mem assoc args ret)
ret)))))
(defmacro condp
"Takes a binary predicate, an expression, and a set of clauses.
Each clause can take the form of either:
test-expr result-expr
test-expr :>> result-fn
Note :>> is an ordinary keyword.
For each clause, (pred test-expr expr) is evaluated. If it returns
logical true, the clause is a match. If a binary clause matches, the
result-expr is returned, if a ternary clause matches, its result-fn,
which must be a unary function, is called with the result of the
predicate as its argument, the result of that call being the return
value of condp. A single default expression can follow the clauses,
and its value will be returned if no clause matches. If no default
expression is provided and no clause matches, an
IllegalArgumentException is thrown."
[pred expr & clauses]
(let [gpred (gensym "pred__")
gexpr (gensym "expr__")
emit (fn emit [pred expr args]
(let [[[a b c :as clause] more]
(split-at (if (= :>> (second args)) 3 2) args)
n (count clause)]
(cond
(= 0 n) `(throw (IllegalArgumentException. (str "No matching clause: " ~expr)))
(= 1 n) a
(= 2 n) `(if (~pred ~a ~expr)
~b
~(emit pred expr more))
:else `(if-let [p# (~pred ~a ~expr)]
(~c p#)
~(emit pred expr more)))))
gres (gensym "res__")]
`(let [~gpred ~pred
~gexpr ~expr]
~(emit gpred gexpr clauses))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; var documentation ;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro add-doc {:private true} [name docstring]
`(alter-meta! (var ~name) assoc :doc ~docstring))
(add-doc *file*
"The path of the file being evaluated, as a String.
Evaluates to nil when there is no file, eg. in the REPL.")
(add-doc *command-line-args*
"A sequence of the supplied command line arguments, or nil if
none were supplied")
(add-doc *warn-on-reflection*
"When set to true, the compiler will emit warnings when reflection is
needed to resolve Java method calls or field accesses.
Defaults to false.")
(add-doc *compile-path*
"Specifies the directory where 'compile' will write out .class
files. This directory must be in the classpath for 'compile' to
work.
Defaults to \"classes\"")
(add-doc *compile-files*
"Set to true when compiling files, false otherwise.")
(add-doc *ns*
"A clojure.lang.Namespace object representing the current namespace.")
(add-doc *in*
"A java.io.Reader object representing standard input for read operations.
Defaults to System/in, wrapped in a LineNumberingPushbackReader")
(add-doc *out*
"A java.io.Writer object representing standard output for print operations.
Defaults to System/out")
(add-doc *err*
"A java.io.Writer object representing standard error for print operations.
Defaults to System/err, wrapped in a PrintWriter")
(add-doc *flush-on-newline*
"When set to true, output will be flushed whenever a newline is printed.
Defaults to true.")
(add-doc *print-meta*
"If set to logical true, when printing an object, its metadata will also
be printed in a form that can be read back by the reader.
Defaults to false.")
(add-doc *print-dup*
"When set to logical true, objects will be printed in a way that preserves
their type when read in later.
Defaults to false.")
(add-doc *print-readably*
"When set to logical false, strings and characters will be printed with
non-alphanumeric characters converted to the appropriate escape sequences.
Defaults to true")
(add-doc *read-eval*
"When set to logical false, the EvalReader (#=(...)) is disabled in the
read/load in the thread-local binding.
Example: (binding [*read-eval* false] (read-string \"#=(eval (def x 3))\"))
Defaults to true")
(defn future?
"Returns true if x is a future"
[x] (instance? java.util.concurrent.Future x))
(defn future-done?
"Returns true if future f is done"
[#^java.util.concurrent.Future f] (.isDone f))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; helper files ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(alter-meta! (find-ns 'clojure.core) assoc :doc "Fundamental library of the Clojure language")
(load "core_proxy")
(load "core_print")
(load "genclass")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; futures (needs proxy);;;;;;;;;;;;;;;;;;
(defn future-call
"Takes a function of no args and yields a future object that will
invoke the function in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block."
[#^Callable f]
(let [fut (.submit clojure.lang.Agent/soloExecutor f)]
(proxy [clojure.lang.IDeref java.util.concurrent.Future] []
(deref [] (.get fut))
(get ([] (.get fut))
([timeout unit] (.get fut timeout unit)))
(isCancelled [] (.isCancelled fut))
(isDone [] (.isDone fut))
(cancel [interrupt?] (.cancel fut interrupt?)))))
(defmacro future
"Takes a body of expressions and yields a future object that will
invoke the body in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block."
[& body] `(future-call (fn [] ~@body)))
(defn future-cancel
"Cancels the future, if possible."
[#^java.util.concurrent.Future f] (.cancel f true))
(defn future-cancelled?
"Returns true if future f is cancelled"
[#^java.util.concurrent.Future f] (.isCancelled f))
(defn pmap
"Like map, except f is applied in parallel. Semi-lazy in that the
parallel computation stays ahead of the consumption, but doesn't
realize the entire result unless required. Only useful for
computationally intensive functions where the time of f dominates
the coordination overhead."
([f coll]
(let [n (+ 2 (.. Runtime getRuntime availableProcessors))
rets (map #(future (f %)) coll)
step (fn step [[x & xs :as vs] fs]
(lazy-seq
(if-let [s (seq fs)]
(cons (deref x) (step xs (rest s)))
(map deref vs))))]
(step rets (drop n rets))))
([f coll & colls]
(let [step (fn step [cs]
(lazy-seq
(let [ss (map seq cs)]
(when (every? identity ss)
(cons (map first ss) (step (map rest ss)))))))]
(pmap #(apply f %) (step (cons coll colls))))))
(defn pcalls
"Executes the no-arg fns in parallel, returning a lazy sequence of
their values"
[& fns] (pmap #(%) fns))
(defmacro pvalues
"Returns a lazy sequence of the values of the exprs, which are
evaluated in parallel"
[& exprs]
`(pcalls ~@(map #(list `fn [] %) exprs)))
(defmacro letfn
"Takes a vector of function specs and a body, and generates a set of
bindings of functions to their names. All of the names are available
in all of the definitions of the functions, as well as the body.
fnspec ==> (fname [params*] exprs) or (fname ([params*] exprs)+)"
[fnspecs & body]
`(letfn* ~(vec (interleave (map first fnspecs)
(map #(cons `fn %) fnspecs)))
~@body))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; clojure version number ;;;;;;;;;;;;;;;;;;;;;;
(let [version-stream (.getResourceAsStream (clojure.lang.RT/baseLoader)
"clojure/version.properties")
properties (doto (new java.util.Properties) (.load version-stream))
prop (fn [k] (.getProperty properties (str "clojure.version." k)))
clojure-version {:major (Integer/valueOf #^String (prop "major"))
:minor (Integer/valueOf #^String (prop "minor"))
:incremental (Integer/valueOf #^String (prop "incremental"))
:qualifier (prop "qualifier")}]
(def *clojure-version*
(if (not (= (prop "interim") "false"))
(clojure.lang.RT/assoc clojure-version :interim true)
clojure-version)))
(add-doc *clojure-version*
"The version info for Clojure core, as a map containing :major :minor
:incremental and :qualifier keys. Feature releases may increment
:minor and/or :major, bugfix releases will increment :incremental.
Possible values of :qualifier include \"GA\", \"SNAPSHOT\", \"RC-x\" \"BETA-x\"")
(defn
clojure-version
"Returns clojure version as a printable string."
[]
(str (:major *clojure-version*)
"."
(:minor *clojure-version*)
(when-let [i (:incremental *clojure-version*)]
(str "." i))
(when-let [q (:qualifier *clojure-version*)]
(when (pos? (count q)) (str "-" q)))
(when (:interim *clojure-version*)
"-SNAPSHOT")))
(defn promise
"Alpha - subject to change.
Returns a promise object that can be read with deref/@, and set,
once only, with deliver. Calls to deref/@ prior to delivery will
block. All subsequent derefs will return the same delivered value
without blocking."
[]
(let [d (java.util.concurrent.CountDownLatch. 1)
v (atom nil)]
(proxy [clojure.lang.AFn clojure.lang.IDeref] []
(deref [] (.await d) @v)
(invoke [x]
(locking d
(if (pos? (.getCount d))
(do (reset! v x)
(.countDown d)
this)
(throw (IllegalStateException. "Multiple deliver calls to a promise"))))))))
(defn deliver
"Alpha - subject to change.
Delivers the supplied value to the promise, releasing any pending
derefs. A subsequent call to deliver on a promise will throw an exception."
[promise val] (promise val))
;;;;;;;;;;;;;;;;;;;;; editable collections ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn transient
"Alpha - subject to change.
Returns a new, transient version of the collection, in constant time."
[#^clojure.lang.IEditableCollection coll]
(.asTransient coll))
(defn persistent!
"Alpha - subject to change.
Returns a new, persistent version of the transient collection, in
constant time. The transient collection cannot be used after this
call, any such use will throw an exception."
[#^clojure.lang.ITransientCollection coll]
(.persistent coll))
(defn conj!
"Alpha - subject to change.
Adds x to the transient collection, and return coll. The 'addition'
may happen at different 'places' depending on the concrete type."
[#^clojure.lang.ITransientCollection coll x]
(.conj coll x))
(defn assoc!
"Alpha - subject to change.
When applied to a transient map, adds mapping of key(s) to
val(s). When applied to a transient vector, sets the val at index.
Note - index must be <= (count vector). Returns coll."
([#^clojure.lang.ITransientAssociative coll key val] (.assoc coll key val))
([#^clojure.lang.ITransientAssociative coll key val & kvs]
(let [ret (.assoc coll key val)]
(if kvs
(recur ret (first kvs) (second kvs) (nnext kvs))
ret))))
(defn dissoc!
"Alpha - subject to change.
Returns a transient map that doesn't contain a mapping for key(s)."
([#^clojure.lang.ITransientMap map key] (.without map key))
([#^clojure.lang.ITransientMap map key & ks]
(let [ret (.without map key)]
(if ks
(recur ret (first ks) (next ks))
ret))))
(defn pop!
"Alpha - subject to change.
Removes the last item from a transient vector. If
the collection is empty, throws an exception. Returns coll"
[#^clojure.lang.ITransientVector coll]
(.pop coll))
(defn disj!
"Alpha - subject to change.
disj[oin]. Returns a transient set of the same (hashed/sorted) type, that
does not contain key(s)."
([set] set)
([#^clojure.lang.ITransientSet set key]
(. set (disjoin key)))
([set key & ks]
(let [ret (disj set key)]
(if ks
(recur ret (first ks) (next ks))
ret))))
;redef into with batch support
(defn into
"Returns a new coll consisting of to-coll with all of the items of
from-coll conjoined."
[to from]
(if (instance? clojure.lang.IEditableCollection to)
(#(loop [ret (transient to) items (seq from)]
(if items
(recur (conj! ret (first items)) (next items))
(persistent! ret))))
(#(loop [ret to items (seq from)]
(if items
(recur (conj ret (first items)) (next items))
ret)))))
| true | ; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns #^{:doc "The core Clojure language."
:author "PI:NAME:<NAME>END_PI"}
clojure.core)
(def unquote)
(def unquote-splicing)
(def
#^{:arglists '([& items])
:doc "Creates a new list containing the items."}
list (. clojure.lang.PersistentList creator))
(def
#^{:arglists '([x seq])
:doc "Returns a new seq where x is the first element and seq is
the rest."}
cons (fn* cons [x seq] (. clojure.lang.RT (cons x seq))))
;during bootstrap we don't have destructuring let, loop or fn, will redefine later
(def
#^{:macro true}
let (fn* let [& decl] (cons 'let* decl)))
(def
#^{:macro true}
loop (fn* loop [& decl] (cons 'loop* decl)))
(def
#^{:macro true}
fn (fn* fn [& decl] (cons 'fn* decl)))
(def
#^{:arglists '([coll])
:doc "Returns the first item in the collection. Calls seq on its
argument. If coll is nil, returns nil."}
first (fn first [coll] (. clojure.lang.RT (first coll))))
(def
#^{:arglists '([coll])
:tag clojure.lang.ISeq
:doc "Returns a seq of the items after the first. Calls seq on its
argument. If there are no more items, returns nil."}
next (fn next [x] (. clojure.lang.RT (next x))))
(def
#^{:arglists '([coll])
:tag clojure.lang.ISeq
:doc "Returns a possibly empty seq of the items after the first. Calls seq on its
argument."}
rest (fn rest [x] (. clojure.lang.RT (more x))))
(def
#^{:arglists '([coll x] [coll x & xs])
:doc "conj[oin]. Returns a new collection with the xs
'added'. (conj nil item) returns (item). The 'addition' may
happen at different 'places' depending on the concrete type."}
conj (fn conj
([coll x] (. clojure.lang.RT (conj coll x)))
([coll x & xs]
(if xs
(recur (conj coll x) (first xs) (next xs))
(conj coll x)))))
(def
#^{:doc "Same as (first (next x))"
:arglists '([x])}
second (fn second [x] (first (next x))))
(def
#^{:doc "Same as (first (first x))"
:arglists '([x])}
ffirst (fn ffirst [x] (first (first x))))
(def
#^{:doc "Same as (next (first x))"
:arglists '([x])}
nfirst (fn nfirst [x] (next (first x))))
(def
#^{:doc "Same as (first (next x))"
:arglists '([x])}
fnext (fn fnext [x] (first (next x))))
(def
#^{:doc "Same as (next (next x))"
:arglists '([x])}
nnext (fn nnext [x] (next (next x))))
(def
#^{:arglists '([coll])
:doc "Returns a seq on the collection. If the collection is
empty, returns nil. (seq nil) returns nil. seq also works on
Strings, native Java arrays (of reference types) and any objects
that implement Iterable."
:tag clojure.lang.ISeq}
seq (fn seq [coll] (. clojure.lang.RT (seq coll))))
(def
#^{:arglists '([#^Class c x])
:doc "Evaluates x and tests if it is an instance of the class
c. Returns true or false"}
instance? (fn instance? [#^Class c x] (. c (isInstance x))))
(def
#^{:arglists '([x])
:doc "Return true if x implements ISeq"}
seq? (fn seq? [x] (instance? clojure.lang.ISeq x)))
(def
#^{:arglists '([x])
:doc "Return true if x is a Character"}
char? (fn char? [x] (instance? Character x)))
(def
#^{:arglists '([x])
:doc "Return true if x is a String"}
string? (fn string? [x] (instance? String x)))
(def
#^{:arglists '([x])
:doc "Return true if x implements IPersistentMap"}
map? (fn map? [x] (instance? clojure.lang.IPersistentMap x)))
(def
#^{:arglists '([x])
:doc "Return true if x implements IPersistentVector "}
vector? (fn vector? [x] (instance? clojure.lang.IPersistentVector x)))
(def
#^{:arglists '([map key val] [map key val & kvs])
:doc "assoc[iate]. When applied to a map, returns a new map of the
same (hashed/sorted) type, that contains the mapping of key(s) to
val(s). When applied to a vector, returns a new vector that
contains val at index. Note - index must be <= (count vector)."}
assoc
(fn assoc
([map key val] (. clojure.lang.RT (assoc map key val)))
([map key val & kvs]
(let [ret (assoc map key val)]
(if kvs
(recur ret (first kvs) (second kvs) (nnext kvs))
ret)))))
;;;;;;;;;;;;;;;;; metadata ;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def
#^{:arglists '([obj])
:doc "Returns the metadata of obj, returns nil if there is no metadata."}
meta (fn meta [x]
(if (instance? clojure.lang.IMeta x)
(. #^clojure.lang.IMeta x (meta)))))
(def
#^{:arglists '([#^clojure.lang.IObj obj m])
:doc "Returns an object of the same type and value as obj, with
map m as its metadata."}
with-meta (fn with-meta [#^clojure.lang.IObj x m]
(. x (withMeta m))))
(def
#^{:private true}
sigs
(fn [fdecl]
(let [asig
(fn [fdecl]
(let [arglist (first fdecl)
body (next fdecl)]
(if (map? (first body))
(if (next body)
(with-meta arglist (conj (if (meta arglist) (meta arglist) {}) (first body)))
arglist)
arglist)))]
(if (seq? (first fdecl))
(loop [ret [] fdecls fdecl]
(if fdecls
(recur (conj ret (asig (first fdecls))) (next fdecls))
(seq ret)))
(list (asig fdecl))))))
(def
#^{:arglists '([coll])
:doc "Return the last item in coll, in linear time"}
last (fn last [s]
(if (next s)
(recur (next s))
(first s))))
(def
#^{:arglists '([coll])
:doc "Return a seq of all but the last item in coll, in linear time"}
butlast (fn butlast [s]
(loop [ret [] s s]
(if (next s)
(recur (conj ret (first s)) (next s))
(seq ret)))))
(def
#^{:doc "Same as (def name (fn [params* ] exprs*)) or (def
name (fn ([params* ] exprs*)+)) with any doc-string or attrs added
to the var metadata"
:arglists '([name doc-string? attr-map? [params*] body]
[name doc-string? attr-map? ([params*] body)+ attr-map?])}
defn (fn defn [name & fdecl]
(let [m (if (string? (first fdecl))
{:doc (first fdecl)}
{})
fdecl (if (string? (first fdecl))
(next fdecl)
fdecl)
m (if (map? (first fdecl))
(conj m (first fdecl))
m)
fdecl (if (map? (first fdecl))
(next fdecl)
fdecl)
fdecl (if (vector? (first fdecl))
(list fdecl)
fdecl)
m (if (map? (last fdecl))
(conj m (last fdecl))
m)
fdecl (if (map? (last fdecl))
(butlast fdecl)
fdecl)
m (conj {:arglists (list 'quote (sigs fdecl))} m)
m (let [inline (:inline m)
ifn (first inline)
iname (second inline)]
;; same as: (if (and (= 'fn ifn) (not (symbol? iname))) ...)
(if (if (clojure.lang.Util/equiv 'fn ifn)
(if (instance? clojure.lang.Symbol iname) false true))
;; inserts the same fn name to the inline fn if it does not have one
(assoc m :inline (cons ifn (cons name (next inline))))
m))]
(list 'def (with-meta name (conj (if (meta name) (meta name) {}) m))
(cons `fn fdecl)))))
(. (var defn) (setMacro))
(defn cast
"Throws a ClassCastException if x is not a c, else returns x."
[#^Class c x]
(. c (cast x)))
(defn to-array
"Returns an array of Objects containing the contents of coll, which
can be any Collection. Maps to java.util.Collection.toArray()."
{:tag "[Ljava.lang.Object;"}
[coll] (. clojure.lang.RT (toArray coll)))
(defn vector
"Creates a new vector containing the args."
([] [])
([& args]
(. clojure.lang.LazilyPersistentVector (create args))))
(defn vec
"Creates a new vector containing the contents of coll."
([coll]
(if (instance? java.util.Collection coll)
(clojure.lang.LazilyPersistentVector/create coll)
(. clojure.lang.LazilyPersistentVector (createOwning (to-array coll))))))
(defn hash-map
"keyval => key val
Returns a new hash map with supplied mappings."
([] {})
([& keyvals]
(. clojure.lang.PersistentHashMap (create keyvals))))
(defn hash-set
"Returns a new hash set with supplied keys."
([] #{})
([& keys]
(clojure.lang.PersistentHashSet/create keys)))
(defn sorted-map
"keyval => key val
Returns a new sorted map with supplied mappings."
([& keyvals]
(clojure.lang.PersistentTreeMap/create keyvals)))
(defn sorted-map-by
"keyval => key val
Returns a new sorted map with supplied mappings, using the supplied comparator."
([comparator & keyvals]
(clojure.lang.PersistentTreeMap/create comparator keyvals)))
(defn sorted-set
"Returns a new sorted set with supplied keys."
([& keys]
(clojure.lang.PersistentTreeSet/create keys)))
(defn sorted-set-by
"Returns a new sorted set with supplied keys, using the supplied comparator."
([comparator & keys]
(clojure.lang.PersistentTreeSet/create comparator keys)))
;;;;;;;;;;;;;;;;;;;;
(def
#^{:doc "Like defn, but the resulting function name is declared as a
macro and will be used as a macro by the compiler when it is
called."
:arglists '([name doc-string? attr-map? [params*] body]
[name doc-string? attr-map? ([params*] body)+ attr-map?])}
defmacro (fn [name & args]
(list 'do
(cons `defn (cons name args))
(list '. (list 'var name) '(setMacro))
(list 'var name))))
(. (var defmacro) (setMacro))
(defmacro when
"Evaluates test. If logical true, evaluates body in an implicit do."
[test & body]
(list 'if test (cons 'do body)))
(defmacro when-not
"Evaluates test. If logical false, evaluates body in an implicit do."
[test & body]
(list 'if test nil (cons 'do body)))
(defn nil?
"Returns true if x is nil, false otherwise."
{:tag Boolean}
[x] (identical? x nil))
(defn false?
"Returns true if x is the value false, false otherwise."
{:tag Boolean}
[x] (identical? x false))
(defn true?
"Returns true if x is the value true, false otherwise."
{:tag Boolean}
[x] (identical? x true))
(defn not
"Returns true if x is logical false, false otherwise."
{:tag Boolean}
[x] (if x false true))
(defn str
"With no args, returns the empty string. With one arg x, returns
x.toString(). (str nil) returns the empty string. With more than
one arg, returns the concatenation of the str values of the args."
{:tag String}
([] "")
([#^Object x]
(if (nil? x) "" (. x (toString))))
([x & ys]
((fn [#^StringBuilder sb more]
(if more
(recur (. sb (append (str (first more)))) (next more))
(str sb)))
(new StringBuilder #^String (str x)) ys)))
(defn symbol?
"Return true if x is a Symbol"
[x] (instance? clojure.lang.Symbol x))
(defn keyword?
"Return true if x is a Keyword"
[x] (instance? clojure.lang.Keyword x))
(defn symbol
"Returns a Symbol with the given namespace and name."
{:tag clojure.lang.Symbol}
([name] (if (symbol? name) name (clojure.lang.Symbol/intern name)))
([ns name] (clojure.lang.Symbol/intern ns name)))
(defn keyword
"Returns a Keyword with the given namespace and name. Do not use :
in the keyword strings, it will be added automatically."
{:tag clojure.lang.Keyword}
([name] (if (keyword? name) name (clojure.lang.Keyword/intern name)))
([ns name] (clojure.lang.Keyword/intern ns name)))
(defn gensym
"Returns a new symbol with a unique name. If a prefix string is
supplied, the name is prefix# where # is some unique number. If
prefix is not supplied, the prefix is 'G__'."
([] (gensym "G__"))
([prefix-string] (. clojure.lang.Symbol (intern (str prefix-string (str (. clojure.lang.RT (nextID))))))))
(defmacro cond
"Takes a set of test/expr pairs. It evaluates each test one at a
time. If a test returns logical true, cond evaluates and returns
the value of the corresponding expr and doesn't evaluate any of the
other tests or exprs. (cond) returns nil."
[& clauses]
(when clauses
(list 'if (first clauses)
(if (next clauses)
(second clauses)
(throw (IllegalArgumentException.
"cond requires an even number of forms")))
(cons 'clojure.core/cond (next (next clauses))))))
(defn spread
{:private true}
[arglist]
(cond
(nil? arglist) nil
(nil? (next arglist)) (seq (first arglist))
:else (cons (first arglist) (spread (next arglist)))))
(defn list*
"Creates a new list containing the items prepended to the rest, the
last of which will be treated as a sequence."
([args] (seq args))
([a args] (cons a args))
([a b args] (cons a (cons b args)))
([a b c args] (cons a (cons b (cons c args))))
([a b c d & more]
(cons a (cons b (cons c (cons d (spread more)))))))
(defn apply
"Applies fn f to the argument list formed by prepending args to argseq."
{:arglists '([f args* argseq])}
([#^clojure.lang.IFn f args]
(. f (applyTo (seq args))))
([#^clojure.lang.IFn f x args]
(. f (applyTo (list* x args))))
([#^clojure.lang.IFn f x y args]
(. f (applyTo (list* x y args))))
([#^clojure.lang.IFn f x y z args]
(. f (applyTo (list* x y z args))))
([#^clojure.lang.IFn f a b c d & args]
(. f (applyTo (cons a (cons b (cons c (cons d (spread args)))))))))
(defn vary-meta
"Returns an object of the same type and value as obj, with
(apply f (meta obj) args) as its metadata."
[obj f & args]
(with-meta obj (apply f (meta obj) args)))
(defmacro lazy-seq
"Takes a body of expressions that returns an ISeq or nil, and yields
a Seqable object that will invoke the body only the first time seq
is called, and will cache the result and return it on all subsequent
seq calls."
[& body]
(list 'new 'clojure.lang.LazySeq (list* '#^{:once true} fn* [] body)))
(defn #^clojure.lang.ChunkBuffer chunk-buffer [capacity]
(clojure.lang.ChunkBuffer. capacity))
(defn chunk-append [#^clojure.lang.ChunkBuffer b x]
(.add b x))
(defn chunk [#^clojure.lang.ChunkBuffer b]
(.chunk b))
(defn #^clojure.lang.IChunk chunk-first [#^clojure.lang.IChunkedSeq s]
(.chunkedFirst s))
(defn #^clojure.lang.ISeq chunk-rest [#^clojure.lang.IChunkedSeq s]
(.chunkedMore s))
(defn #^clojure.lang.ISeq chunk-next [#^clojure.lang.IChunkedSeq s]
(.chunkedNext s))
(defn chunk-cons [chunk rest]
(if (clojure.lang.Numbers/isZero (clojure.lang.RT/count chunk))
rest
(clojure.lang.ChunkedCons. chunk rest)))
(defn chunked-seq? [s]
(instance? clojure.lang.IChunkedSeq s))
(defn concat
"Returns a lazy seq representing the concatenation of the elements in the supplied colls."
([] (lazy-seq nil))
([x] (lazy-seq x))
([x y]
(lazy-seq
(let [s (seq x)]
(if s
(if (chunked-seq? s)
(chunk-cons (chunk-first s) (concat (chunk-rest s) y))
(cons (first s) (concat (rest s) y)))
y))))
([x y & zs]
(let [cat (fn cat [xys zs]
(lazy-seq
(let [xys (seq xys)]
(if xys
(if (chunked-seq? xys)
(chunk-cons (chunk-first xys)
(cat (chunk-rest xys) zs))
(cons (first xys) (cat (rest xys) zs)))
(when zs
(cat (first zs) (next zs)))))))]
(cat (concat x y) zs))))
;;;;;;;;;;;;;;;;at this point all the support for syntax-quote exists;;;;;;;;;;;;;;;;;;;;;;
(defmacro delay
"Takes a body of expressions and yields a Delay object that will
invoke the body only the first time it is forced (with force), and
will cache the result and return it on all subsequent force
calls."
[& body]
(list 'new 'clojure.lang.Delay (list* `#^{:once true} fn* [] body)))
(defn delay?
"returns true if x is a Delay created with delay"
[x] (instance? clojure.lang.Delay x))
(defn force
"If x is a Delay, returns the (possibly cached) value of its expression, else returns x"
[x] (. clojure.lang.Delay (force x)))
(defmacro if-not
"Evaluates test. If logical false, evaluates and returns then expr,
otherwise else expr, if supplied, else nil."
([test then] `(if-not ~test ~then nil))
([test then else]
`(if (not ~test) ~then ~else)))
(defn =
"Equality. Returns true if x equals y, false if not. Same as
Java x.equals(y) except it also works for nil, and compares
numbers and collections in a type-independent manner. Clojure's immutable data
structures define equals() (and thus =) as a value, not an identity,
comparison."
{:tag Boolean
:inline (fn [x y] `(. clojure.lang.Util equiv ~x ~y))
:inline-arities #{2}}
([x] true)
([x y] (clojure.lang.Util/equiv x y))
([x y & more]
(if (= x y)
(if (next more)
(recur y (first more) (next more))
(= y (first more)))
false)))
(defn not=
"Same as (not (= obj1 obj2))"
{:tag Boolean}
([x] false)
([x y] (not (= x y)))
([x y & more]
(not (apply = x y more))))
(defn compare
"Comparator. Returns a negative number, zero, or a positive number
when x is logically 'less than', 'equal to', or 'greater than'
y. Same as Java x.compareTo(y) except it also works for nil, and
compares numbers and collections in a type-independent manner. x
must implement Comparable"
{:tag Integer
:inline (fn [x y] `(. clojure.lang.Util compare ~x ~y))}
[x y] (. clojure.lang.Util (compare x y)))
(defmacro and
"Evaluates exprs one at a time, from left to right. If a form
returns logical false (nil or false), and returns that value and
doesn't evaluate any of the other expressions, otherwise it returns
the value of the last expr. (and) returns true."
([] true)
([x] x)
([x & next]
`(let [and# ~x]
(if and# (and ~@next) and#))))
(defmacro or
"Evaluates exprs one at a time, from left to right. If a form
returns a logical true value, or returns that value and doesn't
evaluate any of the other expressions, otherwise it returns the
value of the last expression. (or) returns nil."
([] nil)
([x] x)
([x & next]
`(let [or# ~x]
(if or# or# (or ~@next)))))
;;;;;;;;;;;;;;;;;;; sequence fns ;;;;;;;;;;;;;;;;;;;;;;;
(defn zero?
"Returns true if num is zero, else false"
{:tag Boolean
:inline (fn [x] `(. clojure.lang.Numbers (isZero ~x)))}
[x] (. clojure.lang.Numbers (isZero x)))
(defn count
"Returns the number of items in the collection. (count nil) returns
0. Also works on strings, arrays, and Java Collections and Maps"
[coll] (clojure.lang.RT/count coll))
(defn int
"Coerce to int"
{:tag Integer
:inline (fn [x] `(. clojure.lang.RT (intCast ~x)))}
[x] (. clojure.lang.RT (intCast x)))
(defn nth
"Returns the value at the index. get returns nil if index out of
bounds, nth throws an exception unless not-found is supplied. nth
also works for strings, Java arrays, regex Matchers and Lists, and,
in O(n) time, for sequences."
{:inline (fn [c i & nf] `(. clojure.lang.RT (nth ~c ~i ~@nf)))
:inline-arities #{2 3}}
([coll index] (. clojure.lang.RT (nth coll index)))
([coll index not-found] (. clojure.lang.RT (nth coll index not-found))))
(defn <
"Returns non-nil if nums are in monotonically increasing order,
otherwise false."
{:inline (fn [x y] `(. clojure.lang.Numbers (lt ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (lt x y)))
([x y & more]
(if (< x y)
(if (next more)
(recur y (first more) (next more))
(< y (first more)))
false)))
(defn inc
"Returns a number one greater than num."
{:inline (fn [x] `(. clojure.lang.Numbers (inc ~x)))}
[x] (. clojure.lang.Numbers (inc x)))
(defn reduce
"f should be a function of 2 arguments. If val is not supplied,
returns the result of applying f to the first 2 items in coll, then
applying f to that result and the 3rd item, etc. If coll contains no
items, f must accept no arguments as well, and reduce returns the
result of calling f with no arguments. If coll has only 1 item, it
is returned and f is not called. If val is supplied, returns the
result of applying f to val and the first item in coll, then
applying f to that result and the 2nd item, etc. If coll contains no
items, returns val and f is not called."
([f coll]
(let [s (seq coll)]
(if s
(reduce f (first s) (next s))
(f))))
([f val coll]
(let [s (seq coll)]
(if s
(if (chunked-seq? s)
(recur f
(.reduce (chunk-first s) f val)
(chunk-next s))
(recur f (f val (first s)) (next s)))
val))))
(defn reverse
"Returns a seq of the items in coll in reverse order. Not lazy."
[coll]
(reduce conj () coll))
;;math stuff
(defn +
"Returns the sum of nums. (+) returns 0."
{:inline (fn [x y] `(. clojure.lang.Numbers (add ~x ~y)))
:inline-arities #{2}}
([] 0)
([x] (cast Number x))
([x y] (. clojure.lang.Numbers (add x y)))
([x y & more]
(reduce + (+ x y) more)))
(defn *
"Returns the product of nums. (*) returns 1."
{:inline (fn [x y] `(. clojure.lang.Numbers (multiply ~x ~y)))
:inline-arities #{2}}
([] 1)
([x] (cast Number x))
([x y] (. clojure.lang.Numbers (multiply x y)))
([x y & more]
(reduce * (* x y) more)))
(defn /
"If no denominators are supplied, returns 1/numerator,
else returns numerator divided by all of the denominators."
{:inline (fn [x y] `(. clojure.lang.Numbers (divide ~x ~y)))
:inline-arities #{2}}
([x] (/ 1 x))
([x y] (. clojure.lang.Numbers (divide x y)))
([x y & more]
(reduce / (/ x y) more)))
(defn -
"If no ys are supplied, returns the negation of x, else subtracts
the ys from x and returns the result."
{:inline (fn [& args] `(. clojure.lang.Numbers (minus ~@args)))
:inline-arities #{1 2}}
([x] (. clojure.lang.Numbers (minus x)))
([x y] (. clojure.lang.Numbers (minus x y)))
([x y & more]
(reduce - (- x y) more)))
(defn <=
"Returns non-nil if nums are in monotonically non-decreasing order,
otherwise false."
{:inline (fn [x y] `(. clojure.lang.Numbers (lte ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (lte x y)))
([x y & more]
(if (<= x y)
(if (next more)
(recur y (first more) (next more))
(<= y (first more)))
false)))
(defn >
"Returns non-nil if nums are in monotonically decreasing order,
otherwise false."
{:inline (fn [x y] `(. clojure.lang.Numbers (gt ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (gt x y)))
([x y & more]
(if (> x y)
(if (next more)
(recur y (first more) (next more))
(> y (first more)))
false)))
(defn >=
"Returns non-nil if nums are in monotonically non-increasing order,
otherwise false."
{:inline (fn [x y] `(. clojure.lang.Numbers (gte ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (gte x y)))
([x y & more]
(if (>= x y)
(if (next more)
(recur y (first more) (next more))
(>= y (first more)))
false)))
(defn ==
"Returns non-nil if nums all have the same value, otherwise false"
{:inline (fn [x y] `(. clojure.lang.Numbers (equiv ~x ~y)))
:inline-arities #{2}}
([x] true)
([x y] (. clojure.lang.Numbers (equiv x y)))
([x y & more]
(if (== x y)
(if (next more)
(recur y (first more) (next more))
(== y (first more)))
false)))
(defn max
"Returns the greatest of the nums."
([x] x)
([x y] (if (> x y) x y))
([x y & more]
(reduce max (max x y) more)))
(defn min
"Returns the least of the nums."
([x] x)
([x y] (if (< x y) x y))
([x y & more]
(reduce min (min x y) more)))
(defn dec
"Returns a number one less than num."
{:inline (fn [x] `(. clojure.lang.Numbers (dec ~x)))}
[x] (. clojure.lang.Numbers (dec x)))
(defn unchecked-inc
"Returns a number one greater than x, an int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x] `(. clojure.lang.Numbers (unchecked_inc ~x)))}
[x] (. clojure.lang.Numbers (unchecked_inc x)))
(defn unchecked-dec
"Returns a number one less than x, an int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x] `(. clojure.lang.Numbers (unchecked_dec ~x)))}
[x] (. clojure.lang.Numbers (unchecked_dec x)))
(defn unchecked-negate
"Returns the negation of x, an int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x] `(. clojure.lang.Numbers (unchecked_negate ~x)))}
[x] (. clojure.lang.Numbers (unchecked_negate x)))
(defn unchecked-add
"Returns the sum of x and y, both int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_add ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_add x y)))
(defn unchecked-subtract
"Returns the difference of x and y, both int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_subtract ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_subtract x y)))
(defn unchecked-multiply
"Returns the product of x and y, both int or long.
Note - uses a primitive operator subject to overflow."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_multiply ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_multiply x y)))
(defn unchecked-divide
"Returns the division of x by y, both int or long.
Note - uses a primitive operator subject to truncation."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_divide ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_divide x y)))
(defn unchecked-remainder
"Returns the remainder of division of x by y, both int or long.
Note - uses a primitive operator subject to truncation."
{:inline (fn [x y] `(. clojure.lang.Numbers (unchecked_remainder ~x ~y)))}
[x y] (. clojure.lang.Numbers (unchecked_remainder x y)))
(defn pos?
"Returns true if num is greater than zero, else false"
{:tag Boolean
:inline (fn [x] `(. clojure.lang.Numbers (isPos ~x)))}
[x] (. clojure.lang.Numbers (isPos x)))
(defn neg?
"Returns true if num is less than zero, else false"
{:tag Boolean
:inline (fn [x] `(. clojure.lang.Numbers (isNeg ~x)))}
[x] (. clojure.lang.Numbers (isNeg x)))
(defn quot
"quot[ient] of dividing numerator by denominator."
[num div]
(. clojure.lang.Numbers (quotient num div)))
(defn rem
"remainder of dividing numerator by denominator."
[num div]
(. clojure.lang.Numbers (remainder num div)))
(defn rationalize
"returns the rational value of num"
[num]
(. clojure.lang.Numbers (rationalize num)))
;;Bit ops
(defn bit-not
"Bitwise complement"
{:inline (fn [x] `(. clojure.lang.Numbers (not ~x)))}
[x] (. clojure.lang.Numbers not x))
(defn bit-and
"Bitwise and"
{:inline (fn [x y] `(. clojure.lang.Numbers (and ~x ~y)))}
[x y] (. clojure.lang.Numbers and x y))
(defn bit-or
"Bitwise or"
{:inline (fn [x y] `(. clojure.lang.Numbers (or ~x ~y)))}
[x y] (. clojure.lang.Numbers or x y))
(defn bit-xor
"Bitwise exclusive or"
{:inline (fn [x y] `(. clojure.lang.Numbers (xor ~x ~y)))}
[x y] (. clojure.lang.Numbers xor x y))
(defn bit-and-not
"Bitwise and with complement"
[x y] (. clojure.lang.Numbers andNot x y))
(defn bit-clear
"Clear bit at index n"
[x n] (. clojure.lang.Numbers clearBit x n))
(defn bit-set
"Set bit at index n"
[x n] (. clojure.lang.Numbers setBit x n))
(defn bit-flip
"Flip bit at index n"
[x n] (. clojure.lang.Numbers flipBit x n))
(defn bit-test
"Test bit at index n"
[x n] (. clojure.lang.Numbers testBit x n))
(defn bit-shift-left
"Bitwise shift left"
[x n] (. clojure.lang.Numbers shiftLeft x n))
(defn bit-shift-right
"Bitwise shift right"
[x n] (. clojure.lang.Numbers shiftRight x n))
(defn even?
"Returns true if n is even, throws an exception if n is not an integer"
[n] (zero? (bit-and n 1)))
(defn odd?
"Returns true if n is odd, throws an exception if n is not an integer"
[n] (not (even? n)))
;;
(defn complement
"Takes a fn f and returns a fn that takes the same arguments as f,
has the same effects, if any, and returns the opposite truth value."
[f]
(fn
([] (not (f)))
([x] (not (f x)))
([x y] (not (f x y)))
([x y & zs] (not (apply f x y zs)))))
(defn constantly
"Returns a function that takes any number of arguments and returns x."
[x] (fn [& args] x))
(defn identity
"Returns its argument."
[x] x)
;;Collection stuff
;;list stuff
(defn peek
"For a list or queue, same as first, for a vector, same as, but much
more efficient than, last. If the collection is empty, returns nil."
[coll] (. clojure.lang.RT (peek coll)))
(defn pop
"For a list or queue, returns a new list/queue without the first
item, for a vector, returns a new vector without the last item. If
the collection is empty, throws an exception. Note - not the same
as next/butlast."
[coll] (. clojure.lang.RT (pop coll)))
;;map stuff
(defn contains?
"Returns true if key is present in the given collection, otherwise
returns false. Note that for numerically indexed collections like
vectors and Java arrays, this tests if the numeric key is within the
range of indexes. 'contains?' operates constant or logarithmic time;
it will not perform a linear search for a value. See also 'some'."
[coll key] (. clojure.lang.RT (contains coll key)))
(defn get
"Returns the value mapped to key, not-found or nil if key not present."
([map key]
(. clojure.lang.RT (get map key)))
([map key not-found]
(. clojure.lang.RT (get map key not-found))))
(defn dissoc
"dissoc[iate]. Returns a new map of the same (hashed/sorted) type,
that does not contain a mapping for key(s)."
([map] map)
([map key]
(. clojure.lang.RT (dissoc map key)))
([map key & ks]
(let [ret (dissoc map key)]
(if ks
(recur ret (first ks) (next ks))
ret))))
(defn disj
"disj[oin]. Returns a new set of the same (hashed/sorted) type, that
does not contain key(s)."
([set] set)
([#^clojure.lang.IPersistentSet set key]
(. set (disjoin key)))
([set key & ks]
(let [ret (disj set key)]
(if ks
(recur ret (first ks) (next ks))
ret))))
(defn find
"Returns the map entry for key, or nil if key not present."
[map key] (. clojure.lang.RT (find map key)))
(defn select-keys
"Returns a map containing only those entries in map whose key is in keys"
[map keyseq]
(loop [ret {} keys (seq keyseq)]
(if keys
(let [entry (. clojure.lang.RT (find map (first keys)))]
(recur
(if entry
(conj ret entry)
ret)
(next keys)))
ret)))
(defn keys
"Returns a sequence of the map's keys."
[map] (. clojure.lang.RT (keys map)))
(defn vals
"Returns a sequence of the map's values."
[map] (. clojure.lang.RT (vals map)))
(defn key
"Returns the key of the map entry."
[#^java.util.Map$Entry e]
(. e (getKey)))
(defn val
"Returns the value in the map entry."
[#^java.util.Map$Entry e]
(. e (getValue)))
(defn rseq
"Returns, in constant time, a seq of the items in rev (which
can be a vector or sorted-map), in reverse order. If rev is empty returns nil"
[#^clojure.lang.Reversible rev]
(. rev (rseq)))
(defn name
"Returns the name String of a symbol or keyword."
{:tag String}
[#^clojure.lang.Named x]
(. x (getName)))
(defn namespace
"Returns the namespace String of a symbol or keyword, or nil if not present."
{:tag String}
[#^clojure.lang.Named x]
(. x (getNamespace)))
(defmacro locking
"Executes exprs in an implicit do, while holding the monitor of x.
Will release the monitor of x in all circumstances."
[x & body]
`(let [lockee# ~x]
(try
(monitor-enter lockee#)
~@body
(finally
(monitor-exit lockee#)))))
(defmacro ..
"form => fieldName-symbol or (instanceMethodName-symbol args*)
Expands into a member access (.) of the first member on the first
argument, followed by the next member on the result, etc. For
instance:
(.. System (getProperties) (get \"os.name\"))
expands to:
(. (. System (getProperties)) (get \"os.name\"))
but is easier to write, read, and understand."
([x form] `(. ~x ~form))
([x form & more] `(.. (. ~x ~form) ~@more)))
(defmacro ->
"Threads the expr through the forms. Inserts x as the
second item in the first form, making a list of it if it is not a
list already. If there are more forms, inserts the first form as the
second item in second form, etc."
([x] x)
([x form] (if (seq? form)
(with-meta `(~(first form) ~x ~@(next form)) (meta form))
(list form x)))
([x form & more] `(-> (-> ~x ~form) ~@more)))
(defmacro ->>
"Threads the expr through the forms. Inserts x as the
last item in the first form, making a list of it if it is not a
list already. If there are more forms, inserts the first form as the
last item in second form, etc."
([x form] (if (seq? form)
(with-meta `(~(first form) ~@(next form) ~x) (meta form))
(list form x)))
([x form & more] `(->> (->> ~x ~form) ~@more)))
;;multimethods
(def global-hierarchy)
(defmacro defmulti
"Creates a new multimethod with the associated dispatch function.
The docstring and attribute-map are optional.
Options are key-value pairs and may be one of:
:default the default dispatch value, defaults to :default
:hierarchy the isa? hierarchy to use for dispatching
defaults to the global hierarchy"
{:arglists '([name docstring? attr-map? dispatch-fn & options])}
[mm-name & options]
(let [docstring (if (string? (first options))
(first options)
nil)
options (if (string? (first options))
(next options)
options)
m (if (map? (first options))
(first options)
{})
options (if (map? (first options))
(next options)
options)
dispatch-fn (first options)
options (next options)
m (assoc m :tag 'clojure.lang.MultiFn)
m (if docstring
(assoc m :doc docstring)
m)
m (if (meta mm-name)
(conj (meta mm-name) m)
m)]
(when (= (count options) 1)
(throw (Exception. "The syntax for defmulti has changed. Example: (defmulti name dispatch-fn :default dispatch-value)")))
(let [options (apply hash-map options)
default (get options :default :default)
hierarchy (get options :hierarchy #'global-hierarchy)]
`(def ~(with-meta mm-name m)
(new clojure.lang.MultiFn ~(name mm-name) ~dispatch-fn ~default ~hierarchy)))))
(defmacro defmethod
"Creates and installs a new method of multimethod associated with dispatch-value. "
[multifn dispatch-val & fn-tail]
`(. ~(with-meta multifn {:tag 'clojure.lang.MultiFn}) addMethod ~dispatch-val (fn ~@fn-tail)))
(defn remove-method
"Removes the method of multimethod associated with dispatch-value."
[#^clojure.lang.MultiFn multifn dispatch-val]
(. multifn removeMethod dispatch-val))
(defn prefer-method
"Causes the multimethod to prefer matches of dispatch-val-x over dispatch-val-y
when there is a conflict"
[#^clojure.lang.MultiFn multifn dispatch-val-x dispatch-val-y]
(. multifn preferMethod dispatch-val-x dispatch-val-y))
(defn methods
"Given a multimethod, returns a map of dispatch values -> dispatch fns"
[#^clojure.lang.MultiFn multifn] (.getMethodTable multifn))
(defn get-method
"Given a multimethod and a dispatch value, returns the dispatch fn
that would apply to that value, or nil if none apply and no default"
[#^clojure.lang.MultiFn multifn dispatch-val] (.getMethod multifn dispatch-val))
(defn prefers
"Given a multimethod, returns a map of preferred value -> set of other values"
[#^clojure.lang.MultiFn multifn] (.getPreferTable multifn))
;;;;;;;;; var stuff
(defmacro #^{:private true} assert-args [fnname & pairs]
`(do (when-not ~(first pairs)
(throw (IllegalArgumentException.
~(str fnname " requires " (second pairs)))))
~(let [more (nnext pairs)]
(when more
(list* `assert-args fnname more)))))
(defmacro if-let
"bindings => binding-form test
If test is true, evaluates then with binding-form bound to the value of
test, if not, yields else"
([bindings then]
`(if-let ~bindings ~then nil))
([bindings then else & oldform]
(assert-args if-let
(and (vector? bindings) (nil? oldform)) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [form (bindings 0) tst (bindings 1)]
`(let [temp# ~tst]
(if temp#
(let [~form temp#]
~then)
~else)))))
(defmacro when-let
"bindings => binding-form test
When test is true, evaluates body with binding-form bound to the value of test"
[bindings & body]
(assert-args when-let
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [form (bindings 0) tst (bindings 1)]
`(let [temp# ~tst]
(when temp#
(let [~form temp#]
~@body)))))
(defn push-thread-bindings
"WARNING: This is a low-level function. Prefer high-level macros like
binding where ever possible.
Takes a map of Var/value pairs. Binds each Var to the associated value for
the current thread. Each call *MUST* be accompanied by a matching call to
pop-thread-bindings wrapped in a try-finally!
(push-thread-bindings bindings)
(try
...
(finally
(pop-thread-bindings)))"
[bindings]
(clojure.lang.Var/pushThreadBindings bindings))
(defn pop-thread-bindings
"Pop one set of bindings pushed with push-binding before. It is an error to
pop bindings without pushing before."
[]
(clojure.lang.Var/popThreadBindings))
(defn get-thread-bindings
"Get a map with the Var/value pairs which is currently in effect for the
current thread."
[]
(clojure.lang.Var/getThreadBindings))
(defmacro binding
"binding => var-symbol init-expr
Creates new bindings for the (already-existing) vars, with the
supplied initial values, executes the exprs in an implicit do, then
re-establishes the bindings that existed before. The new bindings
are made in parallel (unlike let); all init-exprs are evaluated
before the vars are bound to their new values."
[bindings & body]
(assert-args binding
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(let [var-ize (fn [var-vals]
(loop [ret [] vvs (seq var-vals)]
(if vvs
(recur (conj (conj ret `(var ~(first vvs))) (second vvs))
(next (next vvs)))
(seq ret))))]
`(let []
(push-thread-bindings (hash-map ~@(var-ize bindings)))
(try
~@body
(finally
(pop-thread-bindings))))))
(defn with-bindings*
"Takes a map of Var/value pairs. Installs for the given Vars the associated
values as thread-local bindings. Then calls f with the supplied arguments.
Pops the installed bindings after f returned. Returns whatever f returns."
[binding-map f & args]
(push-thread-bindings binding-map)
(try
(apply f args)
(finally
(pop-thread-bindings))))
(defmacro with-bindings
"Takes a map of Var/value pairs. Installs for the given Vars the associated
values as thread-local bindings. The executes body. Pops the installed
bindings after body was evaluated. Returns the value of body."
[binding-map & body]
`(with-bindings* ~binding-map (fn [] ~@body)))
(defn bound-fn*
"Returns a function, which will install the same bindings in effect as in
the thread at the time bound-fn* was called and then call f with any given
arguments. This may be used to define a helper function which runs on a
different thread, but needs the same bindings in place."
[f]
(let [bindings (get-thread-bindings)]
(fn [& args]
(apply with-bindings* bindings f args))))
(defmacro bound-fn
"Returns a function defined by the given fntail, which will install the
same bindings in effect as in the thread at the time bound-fn was called.
This may be used to define a helper function which runs on a different
thread, but needs the same bindings in place."
[& fntail]
`(bound-fn* (fn ~@fntail)))
(defn find-var
"Returns the global var named by the namespace-qualified symbol, or
nil if no var with that name."
[sym] (. clojure.lang.Var (find sym)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Refs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn #^{:private true}
setup-reference [#^clojure.lang.ARef r options]
(let [opts (apply hash-map options)]
(when (:meta opts)
(.resetMeta r (:meta opts)))
(when (:validator opts)
(.setValidator r (:validator opts)))
r))
(defn agent
"Creates and returns an agent with an initial value of state and
zero or more options (in any order):
:meta metadata-map
:validator validate-fn
If metadata-map is supplied, it will be come the metadata on the
agent. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception."
([state] (new clojure.lang.Agent state))
([state & options]
(setup-reference (agent state) options)))
(defn send
"Dispatch an action to an agent. Returns the agent immediately.
Subsequently, in a thread from a thread pool, the state of the agent
will be set to the value of:
(apply action-fn state-of-agent args)"
[#^clojure.lang.Agent a f & args]
(. a (dispatch f args false)))
(defn send-off
"Dispatch a potentially blocking action to an agent. Returns the
agent immediately. Subsequently, in a separate thread, the state of
the agent will be set to the value of:
(apply action-fn state-of-agent args)"
[#^clojure.lang.Agent a f & args]
(. a (dispatch f args true)))
(defn release-pending-sends
"Normally, actions sent directly or indirectly during another action
are held until the action completes (changes the agent's
state). This function can be used to dispatch any pending sent
actions immediately. This has no impact on actions sent during a
transaction, which are still held until commit. If no action is
occurring, does nothing. Returns the number of actions dispatched."
[] (clojure.lang.Agent/releasePendingSends))
(defn add-watch
"Alpha - subject to change.
Adds a watch function to an agent/atom/var/ref reference. The watch
fn must be a fn of 4 args: a key, the reference, its old-state, its
new-state. Whenever the reference's state might have been changed,
any registered watches will have their functions called. The watch fn
will be called synchronously, on the agent's thread if an agent,
before any pending sends if agent or ref. Note that an atom's or
ref's state may have changed again prior to the fn call, so use
old/new-state rather than derefing the reference. Note also that watch
fns may be called from multiple threads simultaneously. Var watchers
are triggered only by root binding changes, not thread-local
set!s. Keys must be unique per reference, and can be used to remove
the watch with remove-watch, but are otherwise considered opaque by
the watch mechanism."
[#^clojure.lang.IRef reference key fn] (.addWatch reference key fn))
(defn remove-watch
"Alpha - subject to change.
Removes a watch (set by add-watch) from a reference"
[#^clojure.lang.IRef reference key]
(.removeWatch reference key))
(defn agent-errors
"Returns a sequence of the exceptions thrown during asynchronous
actions of the agent."
[#^clojure.lang.Agent a] (. a (getErrors)))
(defn clear-agent-errors
"Clears any exceptions thrown during asynchronous actions of the
agent, allowing subsequent actions to occur."
[#^clojure.lang.Agent a] (. a (clearErrors)))
(defn shutdown-agents
"Initiates a shutdown of the thread pools that back the agent
system. Running actions will complete, but no new actions will be
accepted"
[] (. clojure.lang.Agent shutdown))
(defn ref
"Creates and returns a Ref with an initial value of x and zero or
more options (in any order):
:meta metadata-map
:validator validate-fn
:min-history (default 0)
:max-history (default 10)
If metadata-map is supplied, it will be come the metadata on the
ref. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception. validate-fn will be called on
transaction commit, when all refs have their final values.
Normally refs accumulate history dynamically as needed to deal with
read demands. If you know in advance you will need history you can
set :min-history to ensure it will be available when first needed (instead
of after a read fault). History is limited, and the limit can be set
with :max-history."
([x] (new clojure.lang.Ref x))
([x & options]
(let [r #^clojure.lang.Ref (setup-reference (ref x) options)
opts (apply hash-map options)]
(when (:max-history opts)
(.setMaxHistory r (:max-history opts)))
(when (:min-history opts)
(.setMinHistory r (:min-history opts)))
r)))
(defn deref
"Also reader macro: @ref/@agent/@var/@atom/@delay/@future. Within a transaction,
returns the in-transaction-value of ref, else returns the
most-recently-committed value of ref. When applied to a var, agent
or atom, returns its current state. When applied to a delay, forces
it if not already forced. When applied to a future, will block if
computation not complete"
[#^clojure.lang.IDeref ref] (.deref ref))
(defn atom
"Creates and returns an Atom with an initial value of x and zero or
more options (in any order):
:meta metadata-map
:validator validate-fn
If metadata-map is supplied, it will be come the metadata on the
atom. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception."
([x] (new clojure.lang.Atom x))
([x & options] (setup-reference (atom x) options)))
(defn swap!
"Atomically swaps the value of atom to be:
(apply f current-value-of-atom args). Note that f may be called
multiple times, and thus should be free of side effects. Returns
the value that was swapped in."
([#^clojure.lang.Atom atom f] (.swap atom f))
([#^clojure.lang.Atom atom f x] (.swap atom f x))
([#^clojure.lang.Atom atom f x y] (.swap atom f x y))
([#^clojure.lang.Atom atom f x y & args] (.swap atom f x y args)))
(defn compare-and-set!
"Atomically sets the value of atom to newval if and only if the
current value of the atom is identical to oldval. Returns true if
set happened, else false"
[#^clojure.lang.Atom atom oldval newval] (.compareAndSet atom oldval newval))
(defn reset!
"Sets the value of atom to newval without regard for the
current value. Returns newval."
[#^clojure.lang.Atom atom newval] (.reset atom newval))
(defn set-validator!
"Sets the validator-fn for a var/ref/agent/atom. validator-fn must be nil or a
side-effect-free fn of one argument, which will be passed the intended
new state on any state change. If the new state is unacceptable, the
validator-fn should return false or throw an exception. If the current state (root
value if var) is not acceptable to the new validator, an exception
will be thrown and the validator will not be changed."
[#^clojure.lang.IRef iref validator-fn] (. iref (setValidator validator-fn)))
(defn get-validator
"Gets the validator-fn for a var/ref/agent/atom."
[#^clojure.lang.IRef iref] (. iref (getValidator)))
(defn alter-meta!
"Atomically sets the metadata for a namespace/var/ref/agent/atom to be:
(apply f its-current-meta args)
f must be free of side-effects"
[#^clojure.lang.IReference iref f & args] (.alterMeta iref f args))
(defn reset-meta!
"Atomically resets the metadata for a namespace/var/ref/agent/atom"
[#^clojure.lang.IReference iref metadata-map] (.resetMeta iref metadata-map))
(defn commute
"Must be called in a transaction. Sets the in-transaction-value of
ref to:
(apply fun in-transaction-value-of-ref args)
and returns the in-transaction-value of ref.
At the commit point of the transaction, sets the value of ref to be:
(apply fun most-recently-committed-value-of-ref args)
Thus fun should be commutative, or, failing that, you must accept
last-one-in-wins behavior. commute allows for more concurrency than
ref-set."
[#^clojure.lang.Ref ref fun & args]
(. ref (commute fun args)))
(defn alter
"Must be called in a transaction. Sets the in-transaction-value of
ref to:
(apply fun in-transaction-value-of-ref args)
and returns the in-transaction-value of ref."
[#^clojure.lang.Ref ref fun & args]
(. ref (alter fun args)))
(defn ref-set
"Must be called in a transaction. Sets the value of ref.
Returns val."
[#^clojure.lang.Ref ref val]
(. ref (set val)))
(defn ref-history-count
"Returns the history count of a ref"
[#^clojure.lang.Ref ref]
(.getHistoryCount ref))
(defn ref-min-history
"Gets the min-history of a ref, or sets it and returns the ref"
([#^clojure.lang.Ref ref]
(.getMinHistory ref))
([#^clojure.lang.Ref ref n]
(.setMinHistory ref n)))
(defn ref-max-history
"Gets the max-history of a ref, or sets it and returns the ref"
([#^clojure.lang.Ref ref]
(.getMaxHistory ref))
([#^clojure.lang.Ref ref n]
(.setMaxHistory ref n)))
(defn ensure
"Must be called in a transaction. Protects the ref from modification
by other transactions. Returns the in-transaction-value of
ref. Allows for more concurrency than (ref-set ref @ref)"
[#^clojure.lang.Ref ref]
(. ref (touch))
(. ref (deref)))
(defmacro sync
"transaction-flags => TBD, pass nil for now
Runs the exprs (in an implicit do) in a transaction that encompasses
exprs and any nested calls. Starts a transaction if none is already
running on this thread. Any uncaught exception will abort the
transaction and flow out of sync. The exprs may be run more than
once, but any effects on Refs will be atomic."
[flags-ignored-for-now & body]
`(. clojure.lang.LockingTransaction
(runInTransaction (fn [] ~@body))))
(defmacro io!
"If an io! block occurs in a transaction, throws an
IllegalStateException, else runs body in an implicit do. If the
first expression in body is a literal string, will use that as the
exception message."
[& body]
(let [message (when (string? (first body)) (first body))
body (if message (next body) body)]
`(if (clojure.lang.LockingTransaction/isRunning)
(throw (new IllegalStateException ~(or message "I/O in transaction")))
(do ~@body))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; fn stuff ;;;;;;;;;;;;;;;;
(defn comp
"Takes a set of functions and returns a fn that is the composition
of those fns. The returned fn takes a variable number of args,
applies the rightmost of fns to the args, the next
fn (right-to-left) to the result, etc."
([f] f)
([f g]
(fn
([] (f (g)))
([x] (f (g x)))
([x y] (f (g x y)))
([x y z] (f (g x y z)))
([x y z & args] (f (apply g x y z args)))))
([f g h]
(fn
([] (f (g (h))))
([x] (f (g (h x))))
([x y] (f (g (h x y))))
([x y z] (f (g (h x y z))))
([x y z & args] (f (g (apply h x y z args))))))
([f1 f2 f3 & fs]
(let [fs (reverse (list* f1 f2 f3 fs))]
(fn [& args]
(loop [ret (apply (first fs) args) fs (next fs)]
(if fs
(recur ((first fs) ret) (next fs))
ret))))))
(defn juxt
"Alpha - name subject to change.
Takes a set of functions and returns a fn that is the juxtaposition
of those fns. The returned fn takes a variable number of args, and
returns a vector containing the result of applying each fn to the
args (left-to-right).
((juxt a b c) x) => [(a x) (b x) (c x)]"
([f]
(fn
([] [(f)])
([x] [(f x)])
([x y] [(f x y)])
([x y z] [(f x y z)])
([x y z & args] [(apply f x y z args)])))
([f g]
(fn
([] [(f) (g)])
([x] [(f x) (g x)])
([x y] [(f x y) (g x y)])
([x y z] [(f x y z) (g x y z)])
([x y z & args] [(apply f x y z args) (apply g x y z args)])))
([f g h]
(fn
([] [(f) (g) (h)])
([x] [(f x) (g x) (h x)])
([x y] [(f x y) (g x y) (h x y)])
([x y z] [(f x y z) (g x y z) (h x y z)])
([x y z & args] [(apply f x y z args) (apply g x y z args) (apply h x y z args)])))
([f g h & fs]
(let [fs (list* f g h fs)]
(fn
([] (reduce #(conj %1 (%2)) [] fs))
([x] (reduce #(conj %1 (%2 x)) [] fs))
([x y] (reduce #(conj %1 (%2 x y)) [] fs))
([x y z] (reduce #(conj %1 (%2 x y z)) [] fs))
([x y z & args] (reduce #(conj %1 (apply %2 x y z args)) [] fs))))))
(defn partial
"Takes a function f and fewer than the normal arguments to f, and
returns a fn that takes a variable number of additional args. When
called, the returned function calls f with args + additional args."
([f arg1]
(fn [& args] (apply f arg1 args)))
([f arg1 arg2]
(fn [& args] (apply f arg1 arg2 args)))
([f arg1 arg2 arg3]
(fn [& args] (apply f arg1 arg2 arg3 args)))
([f arg1 arg2 arg3 & more]
(fn [& args] (apply f arg1 arg2 arg3 (concat more args)))))
;;;;;;;;;;;;;;;;;;; sequence fns ;;;;;;;;;;;;;;;;;;;;;;;
(defn stream?
"Returns true if x is an instance of Stream"
[x] (instance? clojure.lang.Stream x))
(defn sequence
"Coerces coll to a (possibly empty) sequence, if it is not already
one. Will not force a lazy seq. (sequence nil) yields ()"
[coll]
(cond
(seq? coll) coll
(stream? coll) (.sequence #^clojure.lang.Stream coll)
:else (or (seq coll) ())))
(defn every?
"Returns true if (pred x) is logical true for every x in coll, else
false."
{:tag Boolean}
[pred coll]
(cond
(nil? (seq coll)) true
(pred (first coll)) (recur pred (next coll))
:else false))
(def
#^{:tag Boolean
:doc "Returns false if (pred x) is logical true for every x in
coll, else true."
:arglists '([pred coll])}
not-every? (comp not every?))
(defn some
"Returns the first logical true value of (pred x) for any x in coll,
else nil. One common idiom is to use a set as pred, for example
this will return :fred if :fred is in the sequence, otherwise nil:
(some #{:fred} coll)"
[pred coll]
(when (seq coll)
(or (pred (first coll)) (recur pred (next coll)))))
(def
#^{:tag Boolean
:doc "Returns false if (pred x) is logical true for any x in coll,
else true."
:arglists '([pred coll])}
not-any? (comp not some))
;will be redefed later with arg checks
(defmacro dotimes
"bindings => name n
Repeatedly executes body (presumably for side-effects) with name
bound to integers from 0 through n-1."
[bindings & body]
(let [i (first bindings)
n (second bindings)]
`(let [n# (int ~n)]
(loop [~i (int 0)]
(when (< ~i n#)
~@body
(recur (inc ~i)))))))
(defn map
"Returns a lazy sequence consisting of the result of applying f to the
set of first items of each coll, followed by applying f to the set
of second items in each coll, until any one of the colls is
exhausted. Any remaining items in other colls are ignored. Function
f should accept number-of-colls arguments."
([f coll]
(lazy-seq
(when-let [s (seq coll)]
(if (chunked-seq? s)
(let [c (chunk-first s)
size (int (count c))
b (chunk-buffer size)]
(dotimes [i size]
(chunk-append b (f (.nth c i))))
(chunk-cons (chunk b) (map f (chunk-rest s))))
(cons (f (first s)) (map f (rest s)))))))
([f c1 c2]
(lazy-seq
(let [s1 (seq c1) s2 (seq c2)]
(when (and s1 s2)
(cons (f (first s1) (first s2))
(map f (rest s1) (rest s2)))))))
([f c1 c2 c3]
(lazy-seq
(let [s1 (seq c1) s2 (seq c2) s3 (seq c3)]
(when (and s1 s2 s3)
(cons (f (first s1) (first s2) (first s3))
(map f (rest s1) (rest s2) (rest s3)))))))
([f c1 c2 c3 & colls]
(let [step (fn step [cs]
(lazy-seq
(let [ss (map seq cs)]
(when (every? identity ss)
(cons (map first ss) (step (map rest ss)))))))]
(map #(apply f %) (step (conj colls c3 c2 c1))))))
(defn mapcat
"Returns the result of applying concat to the result of applying map
to f and colls. Thus function f should return a collection."
[f & colls]
(apply concat (apply map f colls)))
(defn filter
"Returns a lazy sequence of the items in coll for which
(pred item) returns true. pred must be free of side-effects."
([pred coll]
(lazy-seq
(when-let [s (seq coll)]
(if (chunked-seq? s)
(let [c (chunk-first s)
size (count c)
b (chunk-buffer size)]
(dotimes [i size]
(when (pred (.nth c i))
(chunk-append b (.nth c i))))
(chunk-cons (chunk b) (filter pred (chunk-rest s))))
(let [f (first s) r (rest s)]
(if (pred f)
(cons f (filter pred r))
(filter pred r))))))))
(defn remove
"Returns a lazy sequence of the items in coll for which
(pred item) returns false. pred must be free of side-effects."
[pred coll]
(filter (complement pred) coll))
(defn take
"Returns a lazy sequence of the first n items in coll, or all items if
there are fewer than n."
[n coll]
(lazy-seq
(when (pos? n)
(when-let [s (seq coll)]
(cons (first s) (take (dec n) (rest s)))))))
(defn take-while
"Returns a lazy sequence of successive items from coll while
(pred item) returns true. pred must be free of side-effects."
[pred coll]
(lazy-seq
(when-let [s (seq coll)]
(when (pred (first s))
(cons (first s) (take-while pred (rest s)))))))
(defn drop
"Returns a lazy sequence of all but the first n items in coll."
[n coll]
(let [step (fn [n coll]
(let [s (seq coll)]
(if (and (pos? n) s)
(recur (dec n) (rest s))
s)))]
(lazy-seq (step n coll))))
(defn drop-last
"Return a lazy sequence of all but the last n (default 1) items in coll"
([s] (drop-last 1 s))
([n s] (map (fn [x _] x) s (drop n s))))
(defn take-last
"Returns a seq of the last n items in coll. Depending on the type
of coll may be no better than linear time. For vectors, see also subvec."
[n coll]
(loop [s (seq coll), lead (seq (drop n coll))]
(if lead
(recur (next s) (next lead))
s)))
(defn drop-while
"Returns a lazy sequence of the items in coll starting from the first
item for which (pred item) returns nil."
[pred coll]
(let [step (fn [pred coll]
(let [s (seq coll)]
(if (and s (pred (first s)))
(recur pred (rest s))
s)))]
(lazy-seq (step pred coll))))
(defn cycle
"Returns a lazy (infinite!) sequence of repetitions of the items in coll."
[coll] (lazy-seq
(when-let [s (seq coll)]
(concat s (cycle s)))))
(defn split-at
"Returns a vector of [(take n coll) (drop n coll)]"
[n coll]
[(take n coll) (drop n coll)])
(defn split-with
"Returns a vector of [(take-while pred coll) (drop-while pred coll)]"
[pred coll]
[(take-while pred coll) (drop-while pred coll)])
(defn repeat
"Returns a lazy (infinite!, or length n if supplied) sequence of xs."
([x] (lazy-seq (cons x (repeat x))))
([n x] (take n (repeat x))))
(defn replicate
"Returns a lazy seq of n xs."
[n x] (take n (repeat x)))
(defn iterate
"Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of side-effects"
[f x] (cons x (lazy-seq (iterate f (f x)))))
(defn range
"Returns a lazy seq of nums from start (inclusive) to end
(exclusive), by step, where start defaults to 0 and step to 1."
([end] (range 0 end 1))
([start end] (range start end 1))
([start end step]
(lazy-seq
(let [b (chunk-buffer 32)
comp (if (pos? step) < >)]
(loop [i start]
(if (and (< (count b) 32)
(comp i end))
(do
(chunk-append b i)
(recur (+ i step)))
(chunk-cons (chunk b)
(when (comp i end)
(range i end step)))))))))
(defn merge
"Returns a map that consists of the rest of the maps conj-ed onto
the first. If a key occurs in more than one map, the mapping from
the latter (left-to-right) will be the mapping in the result."
[& maps]
(when (some identity maps)
(reduce #(conj (or %1 {}) %2) maps)))
(defn merge-with
"Returns a map that consists of the rest of the maps conj-ed onto
the first. If a key occurs in more than one map, the mapping(s)
from the latter (left-to-right) will be combined with the mapping in
the result by calling (f val-in-result val-in-latter)."
[f & maps]
(when (some identity maps)
(let [merge-entry (fn [m e]
(let [k (key e) v (val e)]
(if (contains? m k)
(assoc m k (f (m k) v))
(assoc m k v))))
merge2 (fn [m1 m2]
(reduce merge-entry (or m1 {}) (seq m2)))]
(reduce merge2 maps))))
(defn zipmap
"Returns a map with the keys mapped to the corresponding vals."
[keys vals]
(loop [map {}
ks (seq keys)
vs (seq vals)]
(if (and ks vs)
(recur (assoc map (first ks) (first vs))
(next ks)
(next vs))
map)))
(defn line-seq
"Returns the lines of text from rdr as a lazy sequence of strings.
rdr must implement java.io.BufferedReader."
[#^java.io.BufferedReader rdr]
(let [line (. rdr (readLine))]
(when line
(lazy-seq (cons line (line-seq rdr))))))
(defn comparator
"Returns an implementation of java.util.Comparator based upon pred."
[pred]
(fn [x y]
(cond (pred x y) -1 (pred y x) 1 :else 0)))
(defn sort
"Returns a sorted sequence of the items in coll. If no comparator is
supplied, uses compare. comparator must
implement java.util.Comparator."
([coll]
(sort compare coll))
([#^java.util.Comparator comp coll]
(if (seq coll)
(let [a (to-array coll)]
(. java.util.Arrays (sort a comp))
(seq a))
())))
(defn sort-by
"Returns a sorted sequence of the items in coll, where the sort
order is determined by comparing (keyfn item). If no comparator is
supplied, uses compare. comparator must
implement java.util.Comparator."
([keyfn coll]
(sort-by keyfn compare coll))
([keyfn #^java.util.Comparator comp coll]
(sort (fn [x y] (. comp (compare (keyfn x) (keyfn y)))) coll)))
(defn partition
"Returns a lazy sequence of lists of n items each, at offsets step
apart. If step is not supplied, defaults to n, i.e. the partitions
do not overlap. If a pad collection is supplied, use its elements as
necessary to complete last partition upto n items. In case there are
not enough padding elements, return a partition with less than n items."
([n coll]
(partition n n coll))
([n step coll]
(lazy-seq
(when-let [s (seq coll)]
(let [p (take n s)]
(when (= n (count p))
(cons p (partition n step (drop step s))))))))
([n step pad coll]
(lazy-seq
(when-let [s (seq coll)]
(let [p (take n s)]
(if (= n (count p))
(cons p (partition n step pad (drop step s)))
(list (take n (concat p pad)))))))))
;; evaluation
(defn eval
"Evaluates the form data structure (not text!) and returns the result."
[form] (. clojure.lang.Compiler (eval form)))
(defmacro doseq
"Repeatedly executes body (presumably for side-effects) with
bindings and filtering as provided by \"for\". Does not retain
the head of the sequence. Returns nil."
[seq-exprs & body]
(assert-args doseq
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [step (fn step [recform exprs]
(if-not exprs
[true `(do ~@body)]
(let [k (first exprs)
v (second exprs)]
(if (keyword? k)
(let [steppair (step recform (nnext exprs))
needrec (steppair 0)
subform (steppair 1)]
(cond
(= k :let) [needrec `(let ~v ~subform)]
(= k :while) [false `(when ~v
~subform
~@(when needrec [recform]))]
(= k :when) [false `(if ~v
(do
~subform
~@(when needrec [recform]))
~recform)]))
(let [seq- (gensym "seq_")
chunk- (with-meta (gensym "chunk_")
{:tag 'clojure.lang.IChunk})
count- (gensym "count_")
i- (gensym "i_")
recform `(recur (next ~seq-) nil (int 0) (int 0))
steppair (step recform (nnext exprs))
needrec (steppair 0)
subform (steppair 1)
recform-chunk
`(recur ~seq- ~chunk- ~count- (unchecked-inc ~i-))
steppair-chunk (step recform-chunk (nnext exprs))
subform-chunk (steppair-chunk 1)]
[true
`(loop [~seq- (seq ~v), ~chunk- nil,
~count- (int 0), ~i- (int 0)]
(if (< ~i- ~count-)
(let [~k (.nth ~chunk- ~i-)]
~subform-chunk
~@(when needrec [recform-chunk]))
(when-let [~seq- (seq ~seq-)]
(if (chunked-seq? ~seq-)
(let [c# (chunk-first ~seq-)]
(recur (chunk-rest ~seq-) c#
(int (count c#)) (int 0)))
(let [~k (first ~seq-)]
~subform
~@(when needrec [recform]))))))])))))]
(nth (step nil (seq seq-exprs)) 1)))
(defn dorun
"When lazy sequences are produced via functions that have side
effects, any effects other than those needed to produce the first
element in the seq do not occur until the seq is consumed. dorun can
be used to force any effects. Walks through the successive nexts of
the seq, does not retain the head and returns nil."
([coll]
(when (seq coll)
(recur (next coll))))
([n coll]
(when (and (seq coll) (pos? n))
(recur (dec n) (next coll)))))
(defn doall
"When lazy sequences are produced via functions that have side
effects, any effects other than those needed to produce the first
element in the seq do not occur until the seq is consumed. doall can
be used to force any effects. Walks through the successive nexts of
the seq, retains the head and returns it, thus causing the entire
seq to reside in memory at one time."
([coll]
(dorun coll)
coll)
([n coll]
(dorun n coll)
coll))
(defn await
"Blocks the current thread (indefinitely!) until all actions
dispatched thus far, from this thread or agent, to the agent(s) have
occurred."
[& agents]
(io! "await in transaction"
(when *agent*
(throw (new Exception "Can't await in agent action")))
(let [latch (new java.util.concurrent.CountDownLatch (count agents))
count-down (fn [agent] (. latch (countDown)) agent)]
(doseq [agent agents]
(send agent count-down))
(. latch (await)))))
(defn await1 [#^clojure.lang.Agent a]
(when (pos? (.getQueueCount a))
(await a))
a)
(defn await-for
"Blocks the current thread until all actions dispatched thus
far (from this thread or agent) to the agents have occurred, or the
timeout (in milliseconds) has elapsed. Returns nil if returning due
to timeout, non-nil otherwise."
[timeout-ms & agents]
(io! "await-for in transaction"
(when *agent*
(throw (new Exception "Can't await in agent action")))
(let [latch (new java.util.concurrent.CountDownLatch (count agents))
count-down (fn [agent] (. latch (countDown)) agent)]
(doseq [agent agents]
(send agent count-down))
(. latch (await timeout-ms (. java.util.concurrent.TimeUnit MILLISECONDS))))))
(defmacro dotimes
"bindings => name n
Repeatedly executes body (presumably for side-effects) with name
bound to integers from 0 through n-1."
[bindings & body]
(assert-args dotimes
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [i (first bindings)
n (second bindings)]
`(let [n# (int ~n)]
(loop [~i (int 0)]
(when (< ~i n#)
~@body
(recur (unchecked-inc ~i)))))))
(defn into
"Returns a new coll consisting of to-coll with all of the items of
from-coll conjoined."
[to from]
(let [ret to items (seq from)]
(if items
(recur (conj ret (first items)) (next items))
ret)))
(defmacro import
"import-list => (package-symbol class-name-symbols*)
For each name in class-name-symbols, adds a mapping from name to the
class named by package.name to the current namespace. Use :import in the ns
macro in preference to calling this directly."
[& import-symbols-or-lists]
(let [specs (map #(if (and (seq? %) (= 'quote (first %))) (second %) %)
import-symbols-or-lists)]
`(do ~@(map #(list 'clojure.core/import* %)
(reduce (fn [v spec]
(if (symbol? spec)
(conj v (name spec))
(let [p (first spec) cs (rest spec)]
(into v (map #(str p "." %) cs)))))
[] specs)))))
(defn into-array
"Returns an array with components set to the values in aseq. The array's
component type is type if provided, or the type of the first value in
aseq if present, or Object. All values in aseq must be compatible with
the component type. Class objects for the primitive types can be obtained
using, e.g., Integer/TYPE."
([aseq]
(clojure.lang.RT/seqToTypedArray (seq aseq)))
([type aseq]
(clojure.lang.RT/seqToTypedArray type (seq aseq))))
(defn #^{:private true}
array [& items]
(into-array items))
(defn #^Class class
"Returns the Class of x"
[#^Object x] (if (nil? x) x (. x (getClass))))
(defn type
"Returns the :type metadata of x, or its Class if none"
[x]
(or (:type (meta x)) (class x)))
(defn num
"Coerce to Number"
{:tag Number
:inline (fn [x] `(. clojure.lang.Numbers (num ~x)))}
[x] (. clojure.lang.Numbers (num x)))
(defn long
"Coerce to long"
{:tag Long
:inline (fn [x] `(. clojure.lang.RT (longCast ~x)))}
[#^Number x] (. x (longValue)))
(defn float
"Coerce to float"
{:tag Float
:inline (fn [x] `(. clojure.lang.RT (floatCast ~x)))}
[#^Number x] (. x (floatValue)))
(defn double
"Coerce to double"
{:tag Double
:inline (fn [x] `(. clojure.lang.RT (doubleCast ~x)))}
[#^Number x] (. x (doubleValue)))
(defn short
"Coerce to short"
{:tag Short
:inline (fn [x] `(. clojure.lang.RT (shortCast ~x)))}
[#^Number x] (. x (shortValue)))
(defn byte
"Coerce to byte"
{:tag Byte
:inline (fn [x] `(. clojure.lang.RT (byteCast ~x)))}
[#^Number x] (. x (byteValue)))
(defn char
"Coerce to char"
{:tag Character
:inline (fn [x] `(. clojure.lang.RT (charCast ~x)))}
[x] (. clojure.lang.RT (charCast x)))
(defn boolean
"Coerce to boolean"
{:tag Boolean
:inline (fn [x] `(. clojure.lang.RT (booleanCast ~x)))}
[x] (if x true false))
(defn number?
"Returns true if x is a Number"
[x]
(instance? Number x))
(defn integer?
"Returns true if n is an integer"
[n]
(or (instance? Integer n)
(instance? Long n)
(instance? BigInteger n)
(instance? Short n)
(instance? Byte n)))
(defn mod
"Modulus of num and div. Truncates toward negative infinity."
[num div]
(let [m (rem num div)]
(if (or (zero? m) (pos? (* num div)))
m
(+ m div))))
(defn ratio?
"Returns true if n is a Ratio"
[n] (instance? clojure.lang.Ratio n))
(defn decimal?
"Returns true if n is a BigDecimal"
[n] (instance? BigDecimal n))
(defn float?
"Returns true if n is a floating point number"
[n]
(or (instance? Double n)
(instance? Float n)))
(defn rational? [n]
"Returns true if n is a rational number"
(or (integer? n) (ratio? n) (decimal? n)))
(defn bigint
"Coerce to BigInteger"
{:tag BigInteger}
[x] (cond
(instance? BigInteger x) x
(decimal? x) (.toBigInteger #^BigDecimal x)
(number? x) (BigInteger/valueOf (long x))
:else (BigInteger. x)))
(defn bigdec
"Coerce to BigDecimal"
{:tag BigDecimal}
[x] (cond
(decimal? x) x
(float? x) (. BigDecimal valueOf (double x))
(ratio? x) (/ (BigDecimal. (.numerator x)) (.denominator x))
(instance? BigInteger x) (BigDecimal. #^BigInteger x)
(number? x) (BigDecimal/valueOf (long x))
:else (BigDecimal. x)))
(def #^{:private true} print-initialized false)
(defmulti print-method (fn [x writer] (type x)))
(defmulti print-dup (fn [x writer] (class x)))
(defn pr-on
{:private true}
[x w]
(if *print-dup*
(print-dup x w)
(print-method x w))
nil)
(defn pr
"Prints the object(s) to the output stream that is the current value
of *out*. Prints the object(s), separated by spaces if there is
more than one. By default, pr and prn print in a way that objects
can be read by the reader"
([] nil)
([x]
(pr-on x *out*))
([x & more]
(pr x)
(. *out* (append \space))
(apply pr more)))
(defn newline
"Writes a newline to the output stream that is the current value of
*out*"
[]
(. *out* (append \newline))
nil)
(defn flush
"Flushes the output stream that is the current value of
*out*"
[]
(. *out* (flush))
nil)
(defn prn
"Same as pr followed by (newline). Observes *flush-on-newline*"
[& more]
(apply pr more)
(newline)
(when *flush-on-newline*
(flush)))
(defn print
"Prints the object(s) to the output stream that is the current value
of *out*. print and println produce output for human consumption."
[& more]
(binding [*print-readably* nil]
(apply pr more)))
(defn println
"Same as print followed by (newline)"
[& more]
(binding [*print-readably* nil]
(apply prn more)))
(defn read
"Reads the next object from stream, which must be an instance of
java.io.PushbackReader or some derivee. stream defaults to the
current value of *in* ."
([]
(read *in*))
([stream]
(read stream true nil))
([stream eof-error? eof-value]
(read stream eof-error? eof-value false))
([stream eof-error? eof-value recursive?]
(. clojure.lang.LispReader (read stream (boolean eof-error?) eof-value recursive?))))
(defn read-line
"Reads the next line from stream that is the current value of *in* ."
[]
(if (instance? clojure.lang.LineNumberingPushbackReader *in*)
(.readLine #^clojure.lang.LineNumberingPushbackReader *in*)
(.readLine #^java.io.BufferedReader *in*)))
(defn read-string
"Reads one object from the string s"
[s] (clojure.lang.RT/readString s))
(defn subvec
"Returns a persistent vector of the items in vector from
start (inclusive) to end (exclusive). If end is not supplied,
defaults to (count vector). This operation is O(1) and very fast, as
the resulting vector shares structure with the original and no
trimming is done."
([v start]
(subvec v start (count v)))
([v start end]
(. clojure.lang.RT (subvec v start end))))
(defmacro with-open
"bindings => [name init ...]
Evaluates body in a try expression with names bound to the values
of the inits, and a finally clause that calls (.close name) on each
name in reverse order."
[bindings & body]
(assert-args with-open
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(cond
(= (count bindings) 0) `(do ~@body)
(symbol? (bindings 0)) `(let ~(subvec bindings 0 2)
(try
(with-open ~(subvec bindings 2) ~@body)
(finally
(. ~(bindings 0) close))))
:else (throw (IllegalArgumentException.
"with-open only allows Symbols in bindings"))))
(defmacro doto
"Evaluates x then calls all of the methods and functions with the
value of x supplied at the from of the given arguments. The forms
are evaluated in order. Returns x.
(doto (new java.util.HashMap) (.put \"a\" 1) (.put \"b\" 2))"
[x & forms]
(let [gx (gensym)]
`(let [~gx ~x]
~@(map (fn [f]
(if (seq? f)
`(~(first f) ~gx ~@(next f))
`(~f ~gx)))
forms)
~gx)))
(defmacro memfn
"Expands into code that creates a fn that expects to be passed an
object and any args and calls the named instance method on the
object passing the args. Use when you want to treat a Java method as
a first-class fn."
[name & args]
`(fn [target# ~@args]
(. target# (~name ~@args))))
(defmacro time
"Evaluates expr and prints the time it took. Returns the value of
expr."
[expr]
`(let [start# (. System (nanoTime))
ret# ~expr]
(prn (str "Elapsed time: " (/ (double (- (. System (nanoTime)) start#)) 1000000.0) " msecs"))
ret#))
(import '(java.lang.reflect Array))
(defn alength
"Returns the length of the Java array. Works on arrays of all
types."
{:inline (fn [a] `(. clojure.lang.RT (alength ~a)))}
[array] (. clojure.lang.RT (alength array)))
(defn aclone
"Returns a clone of the Java array. Works on arrays of known
types."
{:inline (fn [a] `(. clojure.lang.RT (aclone ~a)))}
[array] (. clojure.lang.RT (aclone array)))
(defn aget
"Returns the value at the index/indices. Works on Java arrays of all
types."
{:inline (fn [a i] `(. clojure.lang.RT (aget ~a ~i)))
:inline-arities #{2}}
([array idx]
(clojure.lang.Reflector/prepRet (. Array (get array idx))))
([array idx & idxs]
(apply aget (aget array idx) idxs)))
(defn aset
"Sets the value at the index/indices. Works on Java arrays of
reference types. Returns val."
{:inline (fn [a i v] `(. clojure.lang.RT (aset ~a ~i ~v)))
:inline-arities #{3}}
([array idx val]
(. Array (set array idx val))
val)
([array idx idx2 & idxv]
(apply aset (aget array idx) idx2 idxv)))
(defmacro
#^{:private true}
def-aset [name method coerce]
`(defn ~name
{:arglists '([~'array ~'idx ~'val] [~'array ~'idx ~'idx2 & ~'idxv])}
([array# idx# val#]
(. Array (~method array# idx# (~coerce val#)))
val#)
([array# idx# idx2# & idxv#]
(apply ~name (aget array# idx#) idx2# idxv#))))
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of int. Returns val."}
aset-int setInt int)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of long. Returns val."}
aset-long setLong long)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of boolean. Returns val."}
aset-boolean setBoolean boolean)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of float. Returns val."}
aset-float setFloat float)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of double. Returns val."}
aset-double setDouble double)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of short. Returns val."}
aset-short setShort short)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of byte. Returns val."}
aset-byte setByte byte)
(def-aset
#^{:doc "Sets the value at the index/indices. Works on arrays of char. Returns val."}
aset-char setChar char)
(defn make-array
"Creates and returns an array of instances of the specified class of
the specified dimension(s). Note that a class object is required.
Class objects can be obtained by using their imported or
fully-qualified name. Class objects for the primitive types can be
obtained using, e.g., Integer/TYPE."
([#^Class type len]
(. Array (newInstance type (int len))))
([#^Class type dim & more-dims]
(let [dims (cons dim more-dims)
#^"[I" dimarray (make-array (. Integer TYPE) (count dims))]
(dotimes [i (alength dimarray)]
(aset-int dimarray i (nth dims i)))
(. Array (newInstance type dimarray)))))
(defn to-array-2d
"Returns a (potentially-ragged) 2-dimensional array of Objects
containing the contents of coll, which can be any Collection of any
Collection."
{:tag "[[Ljava.lang.Object;"}
[#^java.util.Collection coll]
(let [ret (make-array (. Class (forName "[Ljava.lang.Object;")) (. coll (size)))]
(loop [i 0 xs (seq coll)]
(when xs
(aset ret i (to-array (first xs)))
(recur (inc i) (next xs))))
ret))
(defn macroexpand-1
"If form represents a macro form, returns its expansion,
else returns form."
[form]
(. clojure.lang.Compiler (macroexpand1 form)))
(defn macroexpand
"Repeatedly calls macroexpand-1 on form until it no longer
represents a macro form, then returns it. Note neither
macroexpand-1 nor macroexpand expand macros in subforms."
[form]
(let [ex (macroexpand-1 form)]
(if (identical? ex form)
form
(macroexpand ex))))
(defn create-struct
"Returns a structure basis object."
[& keys]
(. clojure.lang.PersistentStructMap (createSlotMap keys)))
(defmacro defstruct
"Same as (def name (create-struct keys...))"
[name & keys]
`(def ~name (create-struct ~@keys)))
(defn struct-map
"Returns a new structmap instance with the keys of the
structure-basis. keyvals may contain all, some or none of the basis
keys - where values are not supplied they will default to nil.
keyvals can also contain keys not in the basis."
[s & inits]
(. clojure.lang.PersistentStructMap (create s inits)))
(defn struct
"Returns a new structmap instance with the keys of the
structure-basis. vals must be supplied for basis keys in order -
where values are not supplied they will default to nil."
[s & vals]
(. clojure.lang.PersistentStructMap (construct s vals)))
(defn accessor
"Returns a fn that, given an instance of a structmap with the basis,
returns the value at the key. The key must be in the basis. The
returned function should be (slightly) more efficient than using
get, but such use of accessors should be limited to known
performance-critical areas."
[s key]
(. clojure.lang.PersistentStructMap (getAccessor s key)))
(defn load-reader
"Sequentially read and evaluate the set of forms contained in the
stream/file"
[rdr] (. clojure.lang.Compiler (load rdr)))
(defn load-string
"Sequentially read and evaluate the set of forms contained in the
string"
[s]
(let [rdr (-> (java.io.StringReader. s)
(clojure.lang.LineNumberingPushbackReader.))]
(load-reader rdr)))
(defn set
"Returns a set of the distinct elements of coll."
[coll] (apply hash-set coll))
(defn #^{:private true}
filter-key [keyfn pred amap]
(loop [ret {} es (seq amap)]
(if es
(if (pred (keyfn (first es)))
(recur (assoc ret (key (first es)) (val (first es))) (next es))
(recur ret (next es)))
ret)))
(defn find-ns
"Returns the namespace named by the symbol or nil if it doesn't exist."
[sym] (clojure.lang.Namespace/find sym))
(defn create-ns
"Create a new namespace named by the symbol if one doesn't already
exist, returns it or the already-existing namespace of the same
name."
[sym] (clojure.lang.Namespace/findOrCreate sym))
(defn remove-ns
"Removes the namespace named by the symbol. Use with caution.
Cannot be used to remove the clojure namespace."
[sym] (clojure.lang.Namespace/remove sym))
(defn all-ns
"Returns a sequence of all namespaces."
[] (clojure.lang.Namespace/all))
(defn #^clojure.lang.Namespace the-ns
"If passed a namespace, returns it. Else, when passed a symbol,
returns the namespace named by it, throwing an exception if not
found."
[x]
(if (instance? clojure.lang.Namespace x)
x
(or (find-ns x) (throw (Exception. (str "No namespace: " x " found"))))))
(defn ns-name
"Returns the name of the namespace, a symbol."
[ns]
(.getName (the-ns ns)))
(defn ns-map
"Returns a map of all the mappings for the namespace."
[ns]
(.getMappings (the-ns ns)))
(defn ns-unmap
"Removes the mappings for the symbol from the namespace."
[ns sym]
(.unmap (the-ns ns) sym))
;(defn export [syms]
; (doseq [sym syms]
; (.. *ns* (intern sym) (setExported true))))
(defn ns-publics
"Returns a map of the public intern mappings for the namespace."
[ns]
(let [ns (the-ns ns)]
(filter-key val (fn [#^clojure.lang.Var v] (and (instance? clojure.lang.Var v)
(= ns (.ns v))
(.isPublic v)))
(ns-map ns))))
(defn ns-imports
"Returns a map of the import mappings for the namespace."
[ns]
(filter-key val (partial instance? Class) (ns-map ns)))
(defn refer
"refers to all public vars of ns, subject to filters.
filters can include at most one each of:
:exclude list-of-symbols
:only list-of-symbols
:rename map-of-fromsymbol-tosymbol
For each public interned var in the namespace named by the symbol,
adds a mapping from the name of the var to the var to the current
namespace. Throws an exception if name is already mapped to
something else in the current namespace. Filters can be used to
select a subset, via inclusion or exclusion, or to provide a mapping
to a symbol different from the var's name, in order to prevent
clashes. Use :use in the ns macro in preference to calling this directly."
[ns-sym & filters]
(let [ns (or (find-ns ns-sym) (throw (new Exception (str "No namespace: " ns-sym))))
fs (apply hash-map filters)
nspublics (ns-publics ns)
rename (or (:rename fs) {})
exclude (set (:exclude fs))
to-do (or (:only fs) (keys nspublics))]
(doseq [sym to-do]
(when-not (exclude sym)
(let [v (nspublics sym)]
(when-not v
(throw (new java.lang.IllegalAccessError (str sym " is not public"))))
(. *ns* (refer (or (rename sym) sym) v)))))))
(defn ns-refers
"Returns a map of the refer mappings for the namespace."
[ns]
(let [ns (the-ns ns)]
(filter-key val (fn [#^clojure.lang.Var v] (and (instance? clojure.lang.Var v)
(not= ns (.ns v))))
(ns-map ns))))
(defn ns-interns
"Returns a map of the intern mappings for the namespace."
[ns]
(let [ns (the-ns ns)]
(filter-key val (fn [#^clojure.lang.Var v] (and (instance? clojure.lang.Var v)
(= ns (.ns v))))
(ns-map ns))))
(defn alias
"Add an alias in the current namespace to another
namespace. Arguments are two symbols: the alias to be used, and
the symbolic name of the target namespace. Use :as in the ns macro in preference
to calling this directly."
[alias namespace-sym]
(.addAlias *ns* alias (find-ns namespace-sym)))
(defn ns-aliases
"Returns a map of the aliases for the namespace."
[ns]
(.getAliases (the-ns ns)))
(defn ns-unalias
"Removes the alias for the symbol from the namespace."
[ns sym]
(.removeAlias (the-ns ns) sym))
(defn take-nth
"Returns a lazy seq of every nth item in coll."
[n coll]
(lazy-seq
(when-let [s (seq coll)]
(cons (first s) (take-nth n (drop n s))))))
(defn interleave
"Returns a lazy seq of the first item in each coll, then the second etc."
([c1 c2]
(lazy-seq
(let [s1 (seq c1) s2 (seq c2)]
(when (and s1 s2)
(cons (first s1) (cons (first s2)
(interleave (rest s1) (rest s2))))))))
([c1 c2 & colls]
(lazy-seq
(let [ss (map seq (conj colls c2 c1))]
(when (every? identity ss)
(concat (map first ss) (apply interleave (map rest ss))))))))
(defn var-get
"Gets the value in the var object"
[#^clojure.lang.Var x] (. x (get)))
(defn var-set
"Sets the value in the var object to val. The var must be
thread-locally bound."
[#^clojure.lang.Var x val] (. x (set val)))
(defmacro with-local-vars
"varbinding=> symbol init-expr
Executes the exprs in a context in which the symbols are bound to
vars with per-thread bindings to the init-exprs. The symbols refer
to the var objects themselves, and must be accessed with var-get and
var-set"
[name-vals-vec & body]
(assert-args with-local-vars
(vector? name-vals-vec) "a vector for its binding"
(even? (count name-vals-vec)) "an even number of forms in binding vector")
`(let [~@(interleave (take-nth 2 name-vals-vec)
(repeat '(. clojure.lang.Var (create))))]
(. clojure.lang.Var (pushThreadBindings (hash-map ~@name-vals-vec)))
(try
~@body
(finally (. clojure.lang.Var (popThreadBindings))))))
(defn ns-resolve
"Returns the var or Class to which a symbol will be resolved in the
namespace, else nil. Note that if the symbol is fully qualified,
the var/Class to which it resolves need not be present in the
namespace."
[ns sym]
(clojure.lang.Compiler/maybeResolveIn (the-ns ns) sym))
(defn resolve
"same as (ns-resolve *ns* symbol)"
[sym] (ns-resolve *ns* sym))
(defn array-map
"Constructs an array-map."
([] (. clojure.lang.PersistentArrayMap EMPTY))
([& keyvals] (new clojure.lang.PersistentArrayMap (to-array keyvals))))
(defn nthnext
"Returns the nth next of coll, (seq coll) when n is 0."
[coll n]
(loop [n n xs (seq coll)]
(if (and xs (pos? n))
(recur (dec n) (next xs))
xs)))
;redefine let and loop with destructuring
(defn destructure [bindings]
(let [bmap (apply array-map bindings)
pb (fn pb [bvec b v]
(let [pvec
(fn [bvec b val]
(let [gvec (gensym "vec__")]
(loop [ret (-> bvec (conj gvec) (conj val))
n 0
bs b
seen-rest? false]
(if (seq bs)
(let [firstb (first bs)]
(cond
(= firstb '&) (recur (pb ret (second bs) (list `nthnext gvec n))
n
(nnext bs)
true)
(= firstb :as) (pb ret (second bs) gvec)
:else (if seen-rest?
(throw (new Exception "Unsupported binding form, only :as can follow & parameter"))
(recur (pb ret firstb (list `nth gvec n nil))
(inc n)
(next bs)
seen-rest?))))
ret))))
pmap
(fn [bvec b v]
(let [gmap (or (:as b) (gensym "map__"))
defaults (:or b)]
(loop [ret (-> bvec (conj gmap) (conj v))
bes (reduce
(fn [bes entry]
(reduce #(assoc %1 %2 ((val entry) %2))
(dissoc bes (key entry))
((key entry) bes)))
(dissoc b :as :or)
{:keys #(keyword (str %)), :strs str, :syms #(list `quote %)})]
(if (seq bes)
(let [bb (key (first bes))
bk (val (first bes))
has-default (contains? defaults bb)]
(recur (pb ret bb (if has-default
(list `get gmap bk (defaults bb))
(list `get gmap bk)))
(next bes)))
ret))))]
(cond
(symbol? b) (-> bvec (conj b) (conj v))
(vector? b) (pvec bvec b v)
(map? b) (pmap bvec b v)
:else (throw (new Exception (str "Unsupported binding form: " b))))))
process-entry (fn [bvec b] (pb bvec (key b) (val b)))]
(if (every? symbol? (keys bmap))
bindings
(reduce process-entry [] bmap))))
(defmacro let
"Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein."
[bindings & body]
(assert-args let
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
`(let* ~(destructure bindings) ~@body))
;redefine fn with destructuring and pre/post conditions
(defmacro fn
"(fn name? [params* ] exprs*)
(fn name? ([params* ] exprs*)+)
params => positional-params* , or positional-params* & next-param
positional-param => binding-form
next-param => binding-form
name => symbol
Defines a function"
[& sigs]
(let [name (if (symbol? (first sigs)) (first sigs) nil)
sigs (if name (next sigs) sigs)
sigs (if (vector? (first sigs)) (list sigs) sigs)
psig (fn [sig]
(let [[params & body] sig
conds (when (and (next body) (map? (first body)))
(first body))
body (if conds (next body) body)
conds (or conds (meta params))
pre (:pre conds)
post (:post conds)
body (if post
`((let [~'% ~(if (< 1 (count body))
`(do ~@body)
(first body))]
~@(map (fn [c] `(assert ~c)) post)
~'%))
body)
body (if pre
(concat (map (fn [c] `(assert ~c)) pre)
body)
body)]
(if (every? symbol? params)
(cons params body)
(loop [params params
new-params []
lets []]
(if params
(if (symbol? (first params))
(recur (next params) (conj new-params (first params)) lets)
(let [gparam (gensym "p__")]
(recur (next params) (conj new-params gparam)
(-> lets (conj (first params)) (conj gparam)))))
`(~new-params
(let ~lets
~@body)))))))
new-sigs (map psig sigs)]
(with-meta
(if name
(list* 'fn* name new-sigs)
(cons 'fn* new-sigs))
*macro-meta*)))
(defmacro loop
"Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein. Acts as a recur target."
[bindings & body]
(assert-args loop
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(let [db (destructure bindings)]
(if (= db bindings)
`(loop* ~bindings ~@body)
(let [vs (take-nth 2 (drop 1 bindings))
bs (take-nth 2 bindings)
gs (map (fn [b] (if (symbol? b) b (gensym))) bs)
bfs (reduce (fn [ret [b v g]]
(if (symbol? b)
(conj ret g v)
(conj ret g v b g)))
[] (map vector bs vs gs))]
`(let ~bfs
(loop* ~(vec (interleave gs gs))
(let ~(vec (interleave bs gs))
~@body)))))))
(defmacro when-first
"bindings => x xs
Same as (when (seq xs) (let [x (first xs)] body))"
[bindings & body]
(assert-args when-first
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [[x xs] bindings]
`(when (seq ~xs)
(let [~x (first ~xs)]
~@body))))
(defmacro lazy-cat
"Expands to code which yields a lazy sequence of the concatenation
of the supplied colls. Each coll expr is not evaluated until it is
needed.
(lazy-cat xs ys zs) === (concat (lazy-seq xs) (lazy-seq ys) (lazy-seq zs))"
[& colls]
`(concat ~@(map #(list `lazy-seq %) colls)))
(defmacro for
"List comprehension. Takes a vector of one or more
binding-form/collection-expr pairs, each followed by zero or more
modifiers, and yields a lazy sequence of evaluations of expr.
Collections are iterated in a nested fashion, rightmost fastest,
and nested coll-exprs can refer to bindings created in prior
binding-forms. Supported modifiers are: :let [binding-form expr ...],
:while test, :when test.
(take 100 (for [x (range 100000000) y (range 1000000) :while (< y x)] [x y]))"
[seq-exprs body-expr]
(assert-args for
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [to-groups (fn [seq-exprs]
(reduce (fn [groups [k v]]
(if (keyword? k)
(conj (pop groups) (conj (peek groups) [k v]))
(conj groups [k v])))
[] (partition 2 seq-exprs)))
err (fn [& msg] (throw (IllegalArgumentException. #^String (apply str msg))))
emit-bind (fn emit-bind [[[bind expr & mod-pairs]
& [[_ next-expr] :as next-groups]]]
(let [giter (gensym "iter__")
gxs (gensym "s__")
do-mod (fn do-mod [[[k v :as pair] & etc]]
(cond
(= k :let) `(let ~v ~(do-mod etc))
(= k :while) `(when ~v ~(do-mod etc))
(= k :when) `(if ~v
~(do-mod etc)
(recur (rest ~gxs)))
(keyword? k) (err "Invalid 'for' keyword " k)
next-groups
`(let [iterys# ~(emit-bind next-groups)
fs# (seq (iterys# ~next-expr))]
(if fs#
(concat fs# (~giter (rest ~gxs)))
(recur (rest ~gxs))))
:else `(cons ~body-expr
(~giter (rest ~gxs)))))]
(if next-groups
#_"not the inner-most loop"
`(fn ~giter [~gxs]
(lazy-seq
(loop [~gxs ~gxs]
(when-first [~bind ~gxs]
~(do-mod mod-pairs)))))
#_"inner-most loop"
(let [gi (gensym "i__")
gb (gensym "b__")
do-cmod (fn do-cmod [[[k v :as pair] & etc]]
(cond
(= k :let) `(let ~v ~(do-cmod etc))
(= k :while) `(when ~v ~(do-cmod etc))
(= k :when) `(if ~v
~(do-cmod etc)
(recur
(unchecked-inc ~gi)))
(keyword? k)
(err "Invalid 'for' keyword " k)
:else
`(do (chunk-append ~gb ~body-expr)
(recur (unchecked-inc ~gi)))))]
`(fn ~giter [~gxs]
(lazy-seq
(loop [~gxs ~gxs]
(when-let [~gxs (seq ~gxs)]
(if (chunked-seq? ~gxs)
(let [c# (chunk-first ~gxs)
size# (int (count c#))
~gb (chunk-buffer size#)]
(if (loop [~gi (int 0)]
(if (< ~gi size#)
(let [~bind (.nth c# ~gi)]
~(do-cmod mod-pairs))
true))
(chunk-cons
(chunk ~gb)
(~giter (chunk-rest ~gxs)))
(chunk-cons (chunk ~gb) nil)))
(let [~bind (first ~gxs)]
~(do-mod mod-pairs)))))))))))]
`(let [iter# ~(emit-bind (to-groups seq-exprs))]
(iter# ~(second seq-exprs)))))
(defmacro comment
"Ignores body, yields nil"
[& body])
(defmacro with-out-str
"Evaluates exprs in a context in which *out* is bound to a fresh
StringWriter. Returns the string created by any nested printing
calls."
[& body]
`(let [s# (new java.io.StringWriter)]
(binding [*out* s#]
~@body
(str s#))))
(defmacro with-in-str
"Evaluates body in a context in which *in* is bound to a fresh
StringReader initialized with the string s."
[s & body]
`(with-open [s# (-> (java.io.StringReader. ~s) clojure.lang.LineNumberingPushbackReader.)]
(binding [*in* s#]
~@body)))
(defn pr-str
"pr to a string, returning it"
{:tag String}
[& xs]
(with-out-str
(apply pr xs)))
(defn prn-str
"prn to a string, returning it"
{:tag String}
[& xs]
(with-out-str
(apply prn xs)))
(defn print-str
"print to a string, returning it"
{:tag String}
[& xs]
(with-out-str
(apply print xs)))
(defn println-str
"println to a string, returning it"
{:tag String}
[& xs]
(with-out-str
(apply println xs)))
(defmacro assert
"Evaluates expr and throws an exception if it does not evaluate to
logical true."
[x]
(when *assert*
`(when-not ~x
(throw (new AssertionError (str "Assert failed: " (pr-str '~x)))))))
(defn test
"test [v] finds fn at key :test in var metadata and calls it,
presuming failure will throw exception"
[v]
(let [f (:test (meta v))]
(if f
(do (f) :ok)
:no-test)))
(defn re-pattern
"Returns an instance of java.util.regex.Pattern, for use, e.g. in
re-matcher."
{:tag java.util.regex.Pattern}
[s] (if (instance? java.util.regex.Pattern s)
s
(. java.util.regex.Pattern (compile s))))
(defn re-matcher
"Returns an instance of java.util.regex.Matcher, for use, e.g. in
re-find."
{:tag java.util.regex.Matcher}
[#^java.util.regex.Pattern re s]
(. re (matcher s)))
(defn re-groups
"Returns the groups from the most recent match/find. If there are no
nested groups, returns a string of the entire match. If there are
nested groups, returns a vector of the groups, the first element
being the entire match."
[#^java.util.regex.Matcher m]
(let [gc (. m (groupCount))]
(if (zero? gc)
(. m (group))
(loop [ret [] c 0]
(if (<= c gc)
(recur (conj ret (. m (group c))) (inc c))
ret)))))
(defn re-seq
"Returns a lazy sequence of successive matches of pattern in string,
using java.util.regex.Matcher.find(), each such match processed with
re-groups."
[#^java.util.regex.Pattern re s]
(let [m (re-matcher re s)]
((fn step []
(when (. m (find))
(lazy-seq (cons (re-groups m) (step))))))))
(defn re-matches
"Returns the match, if any, of string to pattern, using
java.util.regex.Matcher.matches(). Uses re-groups to return the
groups."
[#^java.util.regex.Pattern re s]
(let [m (re-matcher re s)]
(when (. m (matches))
(re-groups m))))
(defn re-find
"Returns the next regex match, if any, of string to pattern, using
java.util.regex.Matcher.find(). Uses re-groups to return the
groups."
([#^java.util.regex.Matcher m]
(when (. m (find))
(re-groups m)))
([#^java.util.regex.Pattern re s]
(let [m (re-matcher re s)]
(re-find m))))
(defn rand
"Returns a random floating point number between 0 (inclusive) and
n (default 1) (exclusive)."
([] (. Math (random)))
([n] (* n (rand))))
(defn rand-int
"Returns a random integer between 0 (inclusive) and n (exclusive)."
[n] (int (rand n)))
(defmacro defn-
"same as defn, yielding non-public def"
[name & decls]
(list* `defn (with-meta name (assoc (meta name) :private true)) decls))
(defn print-doc [v]
(println "-------------------------")
(println (str (ns-name (:ns (meta v))) "/" (:name (meta v))))
(prn (:arglists (meta v)))
(when (:macro (meta v))
(println "Macro"))
(println " " (:doc (meta v))))
(defn find-doc
"Prints documentation for any var whose documentation or name
contains a match for re-string-or-pattern"
[re-string-or-pattern]
(let [re (re-pattern re-string-or-pattern)]
(doseq [ns (all-ns)
v (sort-by (comp :name meta) (vals (ns-interns ns)))
:when (and (:doc (meta v))
(or (re-find (re-matcher re (:doc (meta v))))
(re-find (re-matcher re (str (:name (meta v)))))))]
(print-doc v))))
(defn special-form-anchor
"Returns the anchor tag on http://clojure.org/special_forms for the
special form x, or nil"
[x]
(#{'. 'def 'do 'fn 'if 'let 'loop 'monitor-enter 'monitor-exit 'new
'quote 'recur 'set! 'throw 'try 'var} x))
(defn syntax-symbol-anchor
"Returns the anchor tag on http://clojure.org/special_forms for the
special form that uses syntax symbol x, or nil"
[x]
({'& 'fn 'catch 'try 'finally 'try} x))
(defn print-special-doc
[name type anchor]
(println "-------------------------")
(println name)
(println type)
(println (str " Please see http://clojure.org/special_forms#" anchor)))
(defn print-namespace-doc
"Print the documentation string of a Namespace."
[nspace]
(println "-------------------------")
(println (str (ns-name nspace)))
(println " " (:doc (meta nspace))))
(defmacro doc
"Prints documentation for a var or special form given its name"
[name]
(cond
(special-form-anchor `~name)
`(print-special-doc '~name "Special Form" (special-form-anchor '~name))
(syntax-symbol-anchor `~name)
`(print-special-doc '~name "Syntax Symbol" (syntax-symbol-anchor '~name))
:else
(let [nspace (find-ns name)]
(if nspace
`(print-namespace-doc ~nspace)
`(print-doc (var ~name))))))
(defn tree-seq
"Returns a lazy sequence of the nodes in a tree, via a depth-first walk.
branch? must be a fn of one arg that returns true if passed a node
that can have children (but may not). children must be a fn of one
arg that returns a sequence of the children. Will only be called on
nodes for which branch? returns true. Root is the root node of the
tree."
[branch? children root]
(let [walk (fn walk [node]
(lazy-seq
(cons node
(when (branch? node)
(mapcat walk (children node))))))]
(walk root)))
(defn file-seq
"A tree seq on java.io.Files"
[dir]
(tree-seq
(fn [#^java.io.File f] (. f (isDirectory)))
(fn [#^java.io.File d] (seq (. d (listFiles))))
dir))
(defn xml-seq
"A tree seq on the xml elements as per xml/parse"
[root]
(tree-seq
(complement string?)
(comp seq :content)
root))
(defn special-symbol?
"Returns true if s names a special form"
[s]
(contains? (. clojure.lang.Compiler specials) s))
(defn var?
"Returns true if v is of type clojure.lang.Var"
[v] (instance? clojure.lang.Var v))
(defn slurp
"Reads the file named by f using the encoding enc into a string
and returns it."
([f] (slurp f (.name (java.nio.charset.Charset/defaultCharset))))
([#^String f #^String enc]
(with-open [r (new java.io.BufferedReader
(new java.io.InputStreamReader
(new java.io.FileInputStream f) enc))]
(let [sb (new StringBuilder)]
(loop [c (.read r)]
(if (neg? c)
(str sb)
(do
(.append sb (char c))
(recur (.read r)))))))))
(defn subs
"Returns the substring of s beginning at start inclusive, and ending
at end (defaults to length of string), exclusive."
([#^String s start] (. s (substring start)))
([#^String s start end] (. s (substring start end))))
(defn max-key
"Returns the x for which (k x), a number, is greatest."
([k x] x)
([k x y] (if (> (k x) (k y)) x y))
([k x y & more]
(reduce #(max-key k %1 %2) (max-key k x y) more)))
(defn min-key
"Returns the x for which (k x), a number, is least."
([k x] x)
([k x y] (if (< (k x) (k y)) x y))
([k x y & more]
(reduce #(min-key k %1 %2) (min-key k x y) more)))
(defn distinct
"Returns a lazy sequence of the elements of coll with duplicates removed"
[coll]
(let [step (fn step [xs seen]
(lazy-seq
((fn [[f :as xs] seen]
(when-let [s (seq xs)]
(if (contains? seen f)
(recur (rest s) seen)
(cons f (step (rest s) (conj seen f))))))
xs seen)))]
(step coll #{})))
(defn replace
"Given a map of replacement pairs and a vector/collection, returns a
vector/seq with any elements = a key in smap replaced with the
corresponding val in smap"
[smap coll]
(if (vector? coll)
(reduce (fn [v i]
(if-let [e (find smap (nth v i))]
(assoc v i (val e))
v))
coll (range (count coll)))
(map #(if-let [e (find smap %)] (val e) %) coll)))
(defmacro dosync
"Runs the exprs (in an implicit do) in a transaction that encompasses
exprs and any nested calls. Starts a transaction if none is already
running on this thread. Any uncaught exception will abort the
transaction and flow out of dosync. The exprs may be run more than
once, but any effects on Refs will be atomic."
[& exprs]
`(sync nil ~@exprs))
(defmacro with-precision
"Sets the precision and rounding mode to be used for BigDecimal operations.
Usage: (with-precision 10 (/ 1M 3))
or: (with-precision 10 :rounding HALF_DOWN (/ 1M 3))
The rounding mode is one of CEILING, FLOOR, HALF_UP, HALF_DOWN,
HALF_EVEN, UP, DOWN and UNNECESSARY; it defaults to HALF_UP."
[precision & exprs]
(let [[body rm] (if (= (first exprs) :rounding)
[(next (next exprs))
`((. java.math.RoundingMode ~(second exprs)))]
[exprs nil])]
`(binding [*math-context* (java.math.MathContext. ~precision ~@rm)]
~@body)))
(defn mk-bound-fn
{:private true}
[#^clojure.lang.Sorted sc test key]
(fn [e]
(test (.. sc comparator (compare (. sc entryKey e) key)) 0)))
(defn subseq
"sc must be a sorted collection, test(s) one of <, <=, > or
>=. Returns a seq of those entries with keys ek for
which (test (.. sc comparator (compare ek key)) 0) is true"
([#^clojure.lang.Sorted sc test key]
(let [include (mk-bound-fn sc test key)]
(if (#{> >=} test)
(when-let [[e :as s] (. sc seqFrom key true)]
(if (include e) s (next s)))
(take-while include (. sc seq true)))))
([#^clojure.lang.Sorted sc start-test start-key end-test end-key]
(when-let [[e :as s] (. sc seqFrom start-key true)]
(take-while (mk-bound-fn sc end-test end-key)
(if ((mk-bound-fn sc start-test start-key) e) s (next s))))))
(defn rsubseq
"sc must be a sorted collection, test(s) one of <, <=, > or
>=. Returns a reverse seq of those entries with keys ek for
which (test (.. sc comparator (compare ek key)) 0) is true"
([#^clojure.lang.Sorted sc test key]
(let [include (mk-bound-fn sc test key)]
(if (#{< <=} test)
(when-let [[e :as s] (. sc seqFrom key false)]
(if (include e) s (next s)))
(take-while include (. sc seq false)))))
([#^clojure.lang.Sorted sc start-test start-key end-test end-key]
(when-let [[e :as s] (. sc seqFrom end-key false)]
(take-while (mk-bound-fn sc start-test start-key)
(if ((mk-bound-fn sc end-test end-key) e) s (next s))))))
(defn repeatedly
"Takes a function of no args, presumably with side effects, and returns an infinite
lazy sequence of calls to it"
[f] (lazy-seq (cons (f) (repeatedly f))))
(defn add-classpath
"DEPRECATED
Adds the url (String or URL object) to the classpath per
URLClassLoader.addURL"
[url]
(println "WARNING: add-classpath is deprecated")
(clojure.lang.RT/addURL url))
(defn hash
"Returns the hash code of its argument"
[x] (. clojure.lang.Util (hash x)))
(defn interpose
"Returns a lazy seq of the elements of coll separated by sep"
[sep coll] (drop 1 (interleave (repeat sep) coll)))
(defmacro definline
"Experimental - like defmacro, except defines a named function whose
body is the expansion, calls to which may be expanded inline as if
it were a macro. Cannot be used with variadic (&) args."
[name & decl]
(let [[pre-args [args expr]] (split-with (comp not vector?) decl)]
`(do
(defn ~name ~@pre-args ~args ~(apply (eval (list `fn args expr)) args))
(alter-meta! (var ~name) assoc :inline (fn ~name ~args ~expr))
(var ~name))))
(defn empty
"Returns an empty collection of the same category as coll, or nil"
[coll]
(when (instance? clojure.lang.IPersistentCollection coll)
(.empty #^clojure.lang.IPersistentCollection coll)))
(defmacro amap
"Maps an expression across an array a, using an index named idx, and
return value named ret, initialized to a clone of a, then setting
each element of ret to the evaluation of expr, returning the new
array ret."
[a idx ret expr]
`(let [a# ~a
~ret (aclone a#)]
(loop [~idx (int 0)]
(if (< ~idx (alength a#))
(do
(aset ~ret ~idx ~expr)
(recur (unchecked-inc ~idx)))
~ret))))
(defmacro areduce
"Reduces an expression across an array a, using an index named idx,
and return value named ret, initialized to init, setting ret to the
evaluation of expr at each step, returning ret."
[a idx ret init expr]
`(let [a# ~a]
(loop [~idx (int 0) ~ret ~init]
(if (< ~idx (alength a#))
(recur (unchecked-inc ~idx) ~expr)
~ret))))
(defn float-array
"Creates an array of floats"
{:inline (fn [& args] `(. clojure.lang.Numbers float_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers float_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers float_array size init-val-or-seq)))
(defn boolean-array
"Creates an array of booleans"
{:inline (fn [& args] `(. clojure.lang.Numbers boolean_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers boolean_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers boolean_array size init-val-or-seq)))
(defn byte-array
"Creates an array of bytes"
{:inline (fn [& args] `(. clojure.lang.Numbers byte_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers byte_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers byte_array size init-val-or-seq)))
(defn char-array
"Creates an array of chars"
{:inline (fn [& args] `(. clojure.lang.Numbers char_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers char_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers char_array size init-val-or-seq)))
(defn short-array
"Creates an array of shorts"
{:inline (fn [& args] `(. clojure.lang.Numbers short_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers short_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers short_array size init-val-or-seq)))
(defn double-array
"Creates an array of doubles"
{:inline (fn [& args] `(. clojure.lang.Numbers double_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers double_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers double_array size init-val-or-seq)))
(defn int-array
"Creates an array of ints"
{:inline (fn [& args] `(. clojure.lang.Numbers int_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers int_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers int_array size init-val-or-seq)))
(defn long-array
"Creates an array of longs"
{:inline (fn [& args] `(. clojure.lang.Numbers long_array ~@args))
:inline-arities #{1 2}}
([size-or-seq] (. clojure.lang.Numbers long_array size-or-seq))
([size init-val-or-seq] (. clojure.lang.Numbers long_array size init-val-or-seq)))
(definline booleans
"Casts to boolean[]"
[xs] `(. clojure.lang.Numbers booleans ~xs))
(definline bytes
"Casts to bytes[]"
[xs] `(. clojure.lang.Numbers bytes ~xs))
(definline chars
"Casts to chars[]"
[xs] `(. clojure.lang.Numbers chars ~xs))
(definline shorts
"Casts to shorts[]"
[xs] `(. clojure.lang.Numbers shorts ~xs))
(definline floats
"Casts to float[]"
[xs] `(. clojure.lang.Numbers floats ~xs))
(definline ints
"Casts to int[]"
[xs] `(. clojure.lang.Numbers ints ~xs))
(definline doubles
"Casts to double[]"
[xs] `(. clojure.lang.Numbers doubles ~xs))
(definline longs
"Casts to long[]"
[xs] `(. clojure.lang.Numbers longs ~xs))
(import '(java.util.concurrent BlockingQueue LinkedBlockingQueue))
(defn seque
"Creates a queued seq on another (presumably lazy) seq s. The queued
seq will produce a concrete seq in the background, and can get up to
n items ahead of the consumer. n-or-q can be an integer n buffer
size, or an instance of java.util.concurrent BlockingQueue. Note
that reading from a seque can block if the reader gets ahead of the
producer."
([s] (seque 100 s))
([n-or-q s]
(let [#^BlockingQueue q (if (instance? BlockingQueue n-or-q)
n-or-q
(LinkedBlockingQueue. (int n-or-q)))
NIL (Object.) ;nil sentinel since LBQ doesn't support nils
agt (agent (seq s))
fill (fn [s]
(try
(loop [[x & xs :as s] s]
(if s
(if (.offer q (if (nil? x) NIL x))
(recur xs)
s)
(.put q q))) ; q itself is eos sentinel
(catch Exception e
(.put q q)
(throw e))))
drain (fn drain []
(lazy-seq
(let [x (.take q)]
(if (identical? x q) ;q itself is eos sentinel
(do @agt nil) ;touch agent just to propagate errors
(do
(send-off agt fill)
(cons (if (identical? x NIL) nil x) (drain)))))))]
(send-off agt fill)
(drain))))
(defn class?
"Returns true if x is an instance of Class"
[x] (instance? Class x))
(defn alter-var-root
"Atomically alters the root binding of var v by applying f to its
current value plus any args"
[#^clojure.lang.Var v f & args] (.alterRoot v f args))
(defn make-hierarchy
"Creates a hierarchy object for use with derive, isa? etc."
[] {:parents {} :descendants {} :ancestors {}})
(def #^{:private true}
global-hierarchy (make-hierarchy))
(defn not-empty
"If coll is empty, returns nil, else coll"
[coll] (when (seq coll) coll))
(defn bases
"Returns the immediate superclass and direct interfaces of c, if any"
[#^Class c]
(let [i (.getInterfaces c)
s (.getSuperclass c)]
(not-empty
(if s (cons s i) i))))
(defn supers
"Returns the immediate and indirect superclasses and interfaces of c, if any"
[#^Class class]
(loop [ret (set (bases class)) cs ret]
(if (seq cs)
(let [c (first cs) bs (bases c)]
(recur (into ret bs) (into (disj cs c) bs)))
(not-empty ret))))
(defn isa?
"Returns true if (= child parent), or child is directly or indirectly derived from
parent, either via a Java type inheritance relationship or a
relationship established via derive. h must be a hierarchy obtained
from make-hierarchy, if not supplied defaults to the global
hierarchy"
([child parent] (isa? global-hierarchy child parent))
([h child parent]
(or (= child parent)
(and (class? parent) (class? child)
(. #^Class parent isAssignableFrom child))
(contains? ((:ancestors h) child) parent)
(and (class? child) (some #(contains? ((:ancestors h) %) parent) (supers child)))
(and (vector? parent) (vector? child)
(= (count parent) (count child))
(loop [ret true i 0]
(if (or (not ret) (= i (count parent)))
ret
(recur (isa? h (child i) (parent i)) (inc i))))))))
(defn parents
"Returns the immediate parents of tag, either via a Java type
inheritance relationship or a relationship established via derive. h
must be a hierarchy obtained from make-hierarchy, if not supplied
defaults to the global hierarchy"
([tag] (parents global-hierarchy tag))
([h tag] (not-empty
(let [tp (get (:parents h) tag)]
(if (class? tag)
(into (set (bases tag)) tp)
tp)))))
(defn ancestors
"Returns the immediate and indirect parents of tag, either via a Java type
inheritance relationship or a relationship established via derive. h
must be a hierarchy obtained from make-hierarchy, if not supplied
defaults to the global hierarchy"
([tag] (ancestors global-hierarchy tag))
([h tag] (not-empty
(let [ta (get (:ancestors h) tag)]
(if (class? tag)
(let [superclasses (set (supers tag))]
(reduce into superclasses
(cons ta
(map #(get (:ancestors h) %) superclasses))))
ta)))))
(defn descendants
"Returns the immediate and indirect children of tag, through a
relationship established via derive. h must be a hierarchy obtained
from make-hierarchy, if not supplied defaults to the global
hierarchy. Note: does not work on Java type inheritance
relationships."
([tag] (descendants global-hierarchy tag))
([h tag] (if (class? tag)
(throw (java.lang.UnsupportedOperationException. "Can't get descendants of classes"))
(not-empty (get (:descendants h) tag)))))
(defn derive
"Establishes a parent/child relationship between parent and
tag. Parent must be a namespace-qualified symbol or keyword and
child can be either a namespace-qualified symbol or keyword or a
class. h must be a hierarchy obtained from make-hierarchy, if not
supplied defaults to, and modifies, the global hierarchy."
([tag parent]
(assert (namespace parent))
(assert (or (class? tag) (and (instance? clojure.lang.Named tag) (namespace tag))))
(alter-var-root #'global-hierarchy derive tag parent) nil)
([h tag parent]
(assert (not= tag parent))
(assert (or (class? tag) (instance? clojure.lang.Named tag)))
(assert (instance? clojure.lang.Named parent))
(let [tp (:parents h)
td (:descendants h)
ta (:ancestors h)
tf (fn [m source sources target targets]
(reduce (fn [ret k]
(assoc ret k
(reduce conj (get targets k #{}) (cons target (targets target)))))
m (cons source (sources source))))]
(or
(when-not (contains? (tp tag) parent)
(when (contains? (ta tag) parent)
(throw (Exception. (print-str tag "already has" parent "as ancestor"))))
(when (contains? (ta parent) tag)
(throw (Exception. (print-str "Cyclic derivation:" parent "has" tag "as ancestor"))))
{:parents (assoc (:parents h) tag (conj (get tp tag #{}) parent))
:ancestors (tf (:ancestors h) tag td parent ta)
:descendants (tf (:descendants h) parent ta tag td)})
h))))
(defn underive
"Removes a parent/child relationship between parent and
tag. h must be a hierarchy obtained from make-hierarchy, if not
supplied defaults to, and modifies, the global hierarchy."
([tag parent] (alter-var-root #'global-hierarchy underive tag parent) nil)
([h tag parent]
(let [tp (:parents h)
td (:descendants h)
ta (:ancestors h)
tf (fn [m source sources target targets]
(reduce
(fn [ret k]
(assoc ret k
(reduce disj (get targets k) (cons target (targets target)))))
m (cons source (sources source))))]
(if (contains? (tp tag) parent)
{:parent (assoc (:parents h) tag (disj (get tp tag) parent))
:ancestors (tf (:ancestors h) tag td parent ta)
:descendants (tf (:descendants h) parent ta tag td)}
h))))
(defn distinct?
"Returns true if no two of the arguments are ="
{:tag Boolean}
([x] true)
([x y] (not (= x y)))
([x y & more]
(if (not= x y)
(loop [s #{x y} [x & etc :as xs] more]
(if xs
(if (contains? s x)
false
(recur (conj s x) etc))
true))
false)))
(defn resultset-seq
"Creates and returns a lazy sequence of structmaps corresponding to
the rows in the java.sql.ResultSet rs"
[#^java.sql.ResultSet rs]
(let [rsmeta (. rs (getMetaData))
idxs (range 1 (inc (. rsmeta (getColumnCount))))
keys (map (comp keyword #(.toLowerCase #^String %))
(map (fn [i] (. rsmeta (getColumnLabel i))) idxs))
check-keys
(or (apply distinct? keys)
(throw (Exception. "ResultSet must have unique column labels")))
row-struct (apply create-struct keys)
row-values (fn [] (map (fn [#^Integer i] (. rs (getObject i))) idxs))
rows (fn thisfn []
(when (. rs (next))
(lazy-seq (cons (apply struct row-struct (row-values)) (thisfn)))))]
(rows)))
(defn iterator-seq
"Returns a seq on a java.util.Iterator. Note that most collections
providing iterators implement Iterable and thus support seq directly."
[iter]
(clojure.lang.IteratorSeq/create iter))
(defn enumeration-seq
"Returns a seq on a java.util.Enumeration"
[e]
(clojure.lang.EnumerationSeq/create e))
(defn format
"Formats a string using java.lang.String.format, see java.util.Formatter for format
string syntax"
{:tag String}
[fmt & args]
(String/format fmt (to-array args)))
(defn printf
"Prints formatted output, as per format"
[fmt & args]
(print (apply format fmt args)))
(def gen-class)
(defmacro with-loading-context [& body]
`((fn loading# []
(. clojure.lang.Var (pushThreadBindings {clojure.lang.Compiler/LOADER
(.getClassLoader (.getClass #^Object loading#))}))
(try
~@body
(finally
(. clojure.lang.Var (popThreadBindings)))))))
(defmacro ns
"Sets *ns* to the namespace named by name (unevaluated), creating it
if needed. references can be zero or more of: (:refer-clojure ...)
(:require ...) (:use ...) (:import ...) (:load ...) (:gen-class)
with the syntax of refer-clojure/require/use/import/load/gen-class
respectively, except the arguments are unevaluated and need not be
quoted. (:gen-class ...), when supplied, defaults to :name
corresponding to the ns name, :main true, :impl-ns same as ns, and
:init-impl-ns true. All options of gen-class are
supported. The :gen-class directive is ignored when not
compiling. If :gen-class is not supplied, when compiled only an
nsname__init.class will be generated. If :refer-clojure is not used, a
default (refer 'clojure) is used. Use of ns is preferred to
individual calls to in-ns/require/use/import:
(ns foo.bar
(:refer-clojure :exclude [ancestors printf])
(:require (clojure.contrib sql sql.tests))
(:use (my.lib this that))
(:import (java.util Date Timer Random)
(java.sql Connection Statement)))"
[name & references]
(let [process-reference
(fn [[kname & args]]
`(~(symbol "clojure.core" (clojure.core/name kname))
~@(map #(list 'quote %) args)))
docstring (when (string? (first references)) (first references))
references (if docstring (next references) references)
name (if docstring
(with-meta name (assoc (meta name)
:doc docstring))
name)
gen-class-clause (first (filter #(= :gen-class (first %)) references))
gen-class-call
(when gen-class-clause
(list* `gen-class :name (.replace (str name) \- \_) :impl-ns name :main true (next gen-class-clause)))
references (remove #(= :gen-class (first %)) references)
;ns-effect (clojure.core/in-ns name)
]
`(do
(clojure.core/in-ns '~name)
(with-loading-context
~@(when gen-class-call (list gen-class-call))
~@(when (and (not= name 'clojure.core) (not-any? #(= :refer-clojure (first %)) references))
`((clojure.core/refer '~'clojure.core)))
~@(map process-reference references)))))
(defmacro refer-clojure
"Same as (refer 'clojure.core <filters>)"
[& filters]
`(clojure.core/refer '~'clojure.core ~@filters))
(defmacro defonce
"defs name to have the root value of the expr iff the named var has no root value,
else expr is unevaluated"
[name expr]
`(let [v# (def ~name)]
(when-not (.hasRoot v#)
(def ~name ~expr))))
;;;;;;;;;;; require/use/load, contributed by PI:NAME:<NAME>END_PI ;;;;;;;;;;;;;;;;;;
(defonce
#^{:private true
:doc "A ref to a sorted set of symbols representing loaded libs"}
*loaded-libs* (ref (sorted-set)))
(defonce
#^{:private true
:doc "the set of paths currently being loaded by this thread"}
*pending-paths* #{})
(defonce
#^{:private true :doc
"True while a verbose load is pending"}
*loading-verbosely* false)
(defn- throw-if
"Throws an exception with a message if pred is true"
[pred fmt & args]
(when pred
(let [#^String message (apply format fmt args)
exception (Exception. message)
raw-trace (.getStackTrace exception)
boring? #(not= (.getMethodName #^StackTraceElement %) "doInvoke")
trace (into-array (drop 2 (drop-while boring? raw-trace)))]
(.setStackTrace exception trace)
(throw exception))))
(defn- libspec?
"Returns true if x is a libspec"
[x]
(or (symbol? x)
(and (vector? x)
(or
(nil? (second x))
(keyword? (second x))))))
(defn- prependss
"Prepends a symbol or a seq to coll"
[x coll]
(if (symbol? x)
(cons x coll)
(concat x coll)))
(defn- root-resource
"Returns the root directory path for a lib"
{:tag String}
[lib]
(str \/
(.. (name lib)
(replace \- \_)
(replace \. \/))))
(defn- root-directory
"Returns the root resource path for a lib"
[lib]
(let [d (root-resource lib)]
(subs d 0 (.lastIndexOf d "/"))))
(def load)
(defn- load-one
"Loads a lib given its name. If need-ns, ensures that the associated
namespace exists after loading. If require, records the load so any
duplicate loads can be skipped."
[lib need-ns require]
(load (root-resource lib))
(throw-if (and need-ns (not (find-ns lib)))
"namespace '%s' not found after loading '%s'"
lib (root-resource lib))
(when require
(dosync
(commute *loaded-libs* conj lib))))
(defn- load-all
"Loads a lib given its name and forces a load of any libs it directly or
indirectly loads. If need-ns, ensures that the associated namespace
exists after loading. If require, records the load so any duplicate loads
can be skipped."
[lib need-ns require]
(dosync
(commute *loaded-libs* #(reduce conj %1 %2)
(binding [*loaded-libs* (ref (sorted-set))]
(load-one lib need-ns require)
@*loaded-libs*))))
(defn- load-lib
"Loads a lib with options"
[prefix lib & options]
(throw-if (and prefix (pos? (.indexOf (name lib) (int \.))))
"lib names inside prefix lists must not contain periods")
(let [lib (if prefix (symbol (str prefix \. lib)) lib)
opts (apply hash-map options)
{:keys [as reload reload-all require use verbose]} opts
loaded (contains? @*loaded-libs* lib)
load (cond reload-all
load-all
(or reload (not require) (not loaded))
load-one)
need-ns (or as use)
filter-opts (select-keys opts '(:exclude :only :rename))]
(binding [*loading-verbosely* (or *loading-verbosely* verbose)]
(if load
(load lib need-ns require)
(throw-if (and need-ns (not (find-ns lib)))
"namespace '%s' not found" lib))
(when (and need-ns *loading-verbosely*)
(printf "(clojure.core/in-ns '%s)\n" (ns-name *ns*)))
(when as
(when *loading-verbosely*
(printf "(clojure.core/alias '%s '%s)\n" as lib))
(alias as lib))
(when use
(when *loading-verbosely*
(printf "(clojure.core/refer '%s" lib)
(doseq [opt filter-opts]
(printf " %s '%s" (key opt) (print-str (val opt))))
(printf ")\n"))
(apply refer lib (mapcat seq filter-opts))))))
(defn- load-libs
"Loads libs, interpreting libspecs, prefix lists, and flags for
forwarding to load-lib"
[& args]
(let [flags (filter keyword? args)
opts (interleave flags (repeat true))
args (filter (complement keyword?) args)]
(doseq [arg args]
(if (libspec? arg)
(apply load-lib nil (prependss arg opts))
(let [[prefix & args] arg]
(throw-if (nil? prefix) "prefix cannot be nil")
(doseq [arg args]
(apply load-lib prefix (prependss arg opts))))))))
;; Public
(defn require
"Loads libs, skipping any that are already loaded. Each argument is
either a libspec that identifies a lib, a prefix list that identifies
multiple libs whose names share a common prefix, or a flag that modifies
how all the identified libs are loaded. Use :require in the ns macro
in preference to calling this directly.
Libs
A 'lib' is a named set of resources in classpath whose contents define a
library of Clojure code. Lib names are symbols and each lib is associated
with a Clojure namespace and a Java package that share its name. A lib's
name also locates its root directory within classpath using Java's
package name to classpath-relative path mapping. All resources in a lib
should be contained in the directory structure under its root directory.
All definitions a lib makes should be in its associated namespace.
'require loads a lib by loading its root resource. The root resource path
is derived from the lib name in the following manner:
Consider a lib named by the symbol 'x.y.z; it has the root directory
<classpath>/x/y/, and its root resource is <classpath>/x/y/z.clj. The root
resource should contain code to create the lib's namespace (usually by using
the ns macro) and load any additional lib resources.
Libspecs
A libspec is a lib name or a vector containing a lib name followed by
options expressed as sequential keywords and arguments.
Recognized options: :as
:as takes a symbol as its argument and makes that symbol an alias to the
lib's namespace in the current namespace.
Prefix Lists
It's common for Clojure code to depend on several libs whose names have
the same prefix. When specifying libs, prefix lists can be used to reduce
repetition. A prefix list contains the shared prefix followed by libspecs
with the shared prefix removed from the lib names. After removing the
prefix, the names that remain must not contain any periods.
Flags
A flag is a keyword.
Recognized flags: :reload, :reload-all, :verbose
:reload forces loading of all the identified libs even if they are
already loaded
:reload-all implies :reload and also forces loading of all libs that the
identified libs directly or indirectly load via require or use
:verbose triggers printing information about each load, alias, and refer
Example:
The following would load the libraries clojure.zip and clojure.set
abbreviated as 's'.
(require '(clojure zip [set :as s]))"
[& args]
(apply load-libs :require args))
(defn use
"Like 'require, but also refers to each lib's namespace using
clojure.core/refer. Use :use in the ns macro in preference to calling
this directly.
'use accepts additional options in libspecs: :exclude, :only, :rename.
The arguments and semantics for :exclude, :only, and :rename are the same
as those documented for clojure.core/refer."
[& args] (apply load-libs :require :use args))
(defn loaded-libs
"Returns a sorted set of symbols naming the currently loaded libs"
[] @*loaded-libs*)
(defn load
"Loads Clojure code from resources in classpath. A path is interpreted as
classpath-relative if it begins with a slash or relative to the root
directory for the current namespace otherwise."
[& paths]
(doseq [#^String path paths]
(let [#^String path (if (.startsWith path "/")
path
(str (root-directory (ns-name *ns*)) \/ path))]
(when *loading-verbosely*
(printf "(clojure.core/load \"%s\")\n" path)
(flush))
; (throw-if (*pending-paths* path)
; "cannot load '%s' again while it is loading"
; path)
(when-not (*pending-paths* path)
(binding [*pending-paths* (conj *pending-paths* path)]
(clojure.lang.RT/load (.substring path 1)))))))
(defn compile
"Compiles the namespace named by the symbol lib into a set of
classfiles. The source for the lib must be in a proper
classpath-relative directory. The output files will go into the
directory specified by *compile-path*, and that directory too must
be in the classpath."
[lib]
(binding [*compile-files* true]
(load-one lib true true))
lib)
;;;;;;;;;;;;; nested associative ops ;;;;;;;;;;;
(defn get-in
"returns the value in a nested associative structure, where ks is a sequence of keys"
[m ks]
(reduce get m ks))
(defn assoc-in
"Associates a value in a nested associative structure, where ks is a
sequence of keys and v is the new value and returns a new nested structure.
If any levels do not exist, hash-maps will be created."
[m [k & ks] v]
(if ks
(assoc m k (assoc-in (get m k) ks v))
(assoc m k v)))
(defn update-in
"'Updates' a value in a nested associative structure, where ks is a
sequence of keys and f is a function that will take the old value
and any supplied args and return the new value, and returns a new
nested structure. If any levels do not exist, hash-maps will be
created."
([m [k & ks] f & args]
(if ks
(assoc m k (apply update-in (get m k) ks f args))
(assoc m k (apply f (get m k) args)))))
(defn empty?
"Returns true if coll has no items - same as (not (seq coll)).
Please use the idiom (seq x) rather than (not (empty? x))"
[coll] (not (seq coll)))
(defn coll?
"Returns true if x implements IPersistentCollection"
[x] (instance? clojure.lang.IPersistentCollection x))
(defn list?
"Returns true if x implements IPersistentList"
[x] (instance? clojure.lang.IPersistentList x))
(defn set?
"Returns true if x implements IPersistentSet"
[x] (instance? clojure.lang.IPersistentSet x))
(defn ifn?
"Returns true if x implements IFn. Note that many data structures
(e.g. sets and maps) implement IFn"
[x] (instance? clojure.lang.IFn x))
(defn fn?
"Returns true if x implements Fn, i.e. is an object created via fn."
[x] (instance? clojure.lang.Fn x))
(defn associative?
"Returns true if coll implements Associative"
[coll] (instance? clojure.lang.Associative coll))
(defn sequential?
"Returns true if coll implements Sequential"
[coll] (instance? clojure.lang.Sequential coll))
(defn sorted?
"Returns true if coll implements Sorted"
[coll] (instance? clojure.lang.Sorted coll))
(defn counted?
"Returns true if coll implements count in constant time"
[coll] (instance? clojure.lang.Counted coll))
(defn reversible?
"Returns true if coll implements Reversible"
[coll] (instance? clojure.lang.Reversible coll))
(def
#^{:doc "bound in a repl thread to the most recent value printed"}
*1)
(def
#^{:doc "bound in a repl thread to the second most recent value printed"}
*2)
(def
#^{:doc "bound in a repl thread to the third most recent value printed"}
*3)
(def
#^{:doc "bound in a repl thread to the most recent exception caught by the repl"}
*e)
(defmacro declare
"defs the supplied var names with no bindings, useful for making forward declarations."
[& names] `(do ~@(map #(list 'def %) names)))
(defn trampoline
"trampoline can be used to convert algorithms requiring mutual
recursion without stack consumption. Calls f with supplied args, if
any. If f returns a fn, calls that fn with no arguments, and
continues to repeat, until the return value is not a fn, then
returns that non-fn value. Note that if you want to return a fn as a
final value, you must wrap it in some data structure and unpack it
after trampoline returns."
([f]
(let [ret (f)]
(if (fn? ret)
(recur ret)
ret)))
([f & args]
(trampoline #(apply f args))))
(defn intern
"Finds or creates a var named by the symbol name in the namespace
ns (which can be a symbol or a namespace), setting its root binding
to val if supplied. The namespace must exist. The var will adopt any
metadata from the name symbol. Returns the var."
([ns #^clojure.lang.Symbol name]
(let [v (clojure.lang.Var/intern (the-ns ns) name)]
(when (meta name) (.setMeta v (meta name)))
v))
([ns name val]
(let [v (clojure.lang.Var/intern (the-ns ns) name val)]
(when (meta name) (.setMeta v (meta name)))
v)))
(defmacro while
"Repeatedly executes body while test expression is true. Presumes
some side-effect will cause test to become false/nil. Returns nil"
[test & body]
`(loop []
(when ~test
~@body
(recur))))
(defn memoize
"Returns a memoized version of a referentially transparent function. The
memoized version of the function keeps a cache of the mapping from arguments
to results and, when calls with the same arguments are repeated often, has
higher performance at the expense of higher memory use."
[f]
(let [mem (atom {})]
(fn [& args]
(if-let [e (find @mem args)]
(val e)
(let [ret (apply f args)]
(swap! mem assoc args ret)
ret)))))
(defmacro condp
"Takes a binary predicate, an expression, and a set of clauses.
Each clause can take the form of either:
test-expr result-expr
test-expr :>> result-fn
Note :>> is an ordinary keyword.
For each clause, (pred test-expr expr) is evaluated. If it returns
logical true, the clause is a match. If a binary clause matches, the
result-expr is returned, if a ternary clause matches, its result-fn,
which must be a unary function, is called with the result of the
predicate as its argument, the result of that call being the return
value of condp. A single default expression can follow the clauses,
and its value will be returned if no clause matches. If no default
expression is provided and no clause matches, an
IllegalArgumentException is thrown."
[pred expr & clauses]
(let [gpred (gensym "pred__")
gexpr (gensym "expr__")
emit (fn emit [pred expr args]
(let [[[a b c :as clause] more]
(split-at (if (= :>> (second args)) 3 2) args)
n (count clause)]
(cond
(= 0 n) `(throw (IllegalArgumentException. (str "No matching clause: " ~expr)))
(= 1 n) a
(= 2 n) `(if (~pred ~a ~expr)
~b
~(emit pred expr more))
:else `(if-let [p# (~pred ~a ~expr)]
(~c p#)
~(emit pred expr more)))))
gres (gensym "res__")]
`(let [~gpred ~pred
~gexpr ~expr]
~(emit gpred gexpr clauses))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; var documentation ;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro add-doc {:private true} [name docstring]
`(alter-meta! (var ~name) assoc :doc ~docstring))
(add-doc *file*
"The path of the file being evaluated, as a String.
Evaluates to nil when there is no file, eg. in the REPL.")
(add-doc *command-line-args*
"A sequence of the supplied command line arguments, or nil if
none were supplied")
(add-doc *warn-on-reflection*
"When set to true, the compiler will emit warnings when reflection is
needed to resolve Java method calls or field accesses.
Defaults to false.")
(add-doc *compile-path*
"Specifies the directory where 'compile' will write out .class
files. This directory must be in the classpath for 'compile' to
work.
Defaults to \"classes\"")
(add-doc *compile-files*
"Set to true when compiling files, false otherwise.")
(add-doc *ns*
"A clojure.lang.Namespace object representing the current namespace.")
(add-doc *in*
"A java.io.Reader object representing standard input for read operations.
Defaults to System/in, wrapped in a LineNumberingPushbackReader")
(add-doc *out*
"A java.io.Writer object representing standard output for print operations.
Defaults to System/out")
(add-doc *err*
"A java.io.Writer object representing standard error for print operations.
Defaults to System/err, wrapped in a PrintWriter")
(add-doc *flush-on-newline*
"When set to true, output will be flushed whenever a newline is printed.
Defaults to true.")
(add-doc *print-meta*
"If set to logical true, when printing an object, its metadata will also
be printed in a form that can be read back by the reader.
Defaults to false.")
(add-doc *print-dup*
"When set to logical true, objects will be printed in a way that preserves
their type when read in later.
Defaults to false.")
(add-doc *print-readably*
"When set to logical false, strings and characters will be printed with
non-alphanumeric characters converted to the appropriate escape sequences.
Defaults to true")
(add-doc *read-eval*
"When set to logical false, the EvalReader (#=(...)) is disabled in the
read/load in the thread-local binding.
Example: (binding [*read-eval* false] (read-string \"#=(eval (def x 3))\"))
Defaults to true")
(defn future?
"Returns true if x is a future"
[x] (instance? java.util.concurrent.Future x))
(defn future-done?
"Returns true if future f is done"
[#^java.util.concurrent.Future f] (.isDone f))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; helper files ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(alter-meta! (find-ns 'clojure.core) assoc :doc "Fundamental library of the Clojure language")
(load "core_proxy")
(load "core_print")
(load "genclass")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; futures (needs proxy);;;;;;;;;;;;;;;;;;
(defn future-call
"Takes a function of no args and yields a future object that will
invoke the function in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block."
[#^Callable f]
(let [fut (.submit clojure.lang.Agent/soloExecutor f)]
(proxy [clojure.lang.IDeref java.util.concurrent.Future] []
(deref [] (.get fut))
(get ([] (.get fut))
([timeout unit] (.get fut timeout unit)))
(isCancelled [] (.isCancelled fut))
(isDone [] (.isDone fut))
(cancel [interrupt?] (.cancel fut interrupt?)))))
(defmacro future
"Takes a body of expressions and yields a future object that will
invoke the body in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block."
[& body] `(future-call (fn [] ~@body)))
(defn future-cancel
"Cancels the future, if possible."
[#^java.util.concurrent.Future f] (.cancel f true))
(defn future-cancelled?
"Returns true if future f is cancelled"
[#^java.util.concurrent.Future f] (.isCancelled f))
(defn pmap
"Like map, except f is applied in parallel. Semi-lazy in that the
parallel computation stays ahead of the consumption, but doesn't
realize the entire result unless required. Only useful for
computationally intensive functions where the time of f dominates
the coordination overhead."
([f coll]
(let [n (+ 2 (.. Runtime getRuntime availableProcessors))
rets (map #(future (f %)) coll)
step (fn step [[x & xs :as vs] fs]
(lazy-seq
(if-let [s (seq fs)]
(cons (deref x) (step xs (rest s)))
(map deref vs))))]
(step rets (drop n rets))))
([f coll & colls]
(let [step (fn step [cs]
(lazy-seq
(let [ss (map seq cs)]
(when (every? identity ss)
(cons (map first ss) (step (map rest ss)))))))]
(pmap #(apply f %) (step (cons coll colls))))))
(defn pcalls
"Executes the no-arg fns in parallel, returning a lazy sequence of
their values"
[& fns] (pmap #(%) fns))
(defmacro pvalues
"Returns a lazy sequence of the values of the exprs, which are
evaluated in parallel"
[& exprs]
`(pcalls ~@(map #(list `fn [] %) exprs)))
(defmacro letfn
"Takes a vector of function specs and a body, and generates a set of
bindings of functions to their names. All of the names are available
in all of the definitions of the functions, as well as the body.
fnspec ==> (fname [params*] exprs) or (fname ([params*] exprs)+)"
[fnspecs & body]
`(letfn* ~(vec (interleave (map first fnspecs)
(map #(cons `fn %) fnspecs)))
~@body))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; clojure version number ;;;;;;;;;;;;;;;;;;;;;;
(let [version-stream (.getResourceAsStream (clojure.lang.RT/baseLoader)
"clojure/version.properties")
properties (doto (new java.util.Properties) (.load version-stream))
prop (fn [k] (.getProperty properties (str "clojure.version." k)))
clojure-version {:major (Integer/valueOf #^String (prop "major"))
:minor (Integer/valueOf #^String (prop "minor"))
:incremental (Integer/valueOf #^String (prop "incremental"))
:qualifier (prop "qualifier")}]
(def *clojure-version*
(if (not (= (prop "interim") "false"))
(clojure.lang.RT/assoc clojure-version :interim true)
clojure-version)))
(add-doc *clojure-version*
"The version info for Clojure core, as a map containing :major :minor
:incremental and :qualifier keys. Feature releases may increment
:minor and/or :major, bugfix releases will increment :incremental.
Possible values of :qualifier include \"GA\", \"SNAPSHOT\", \"RC-x\" \"BETA-x\"")
(defn
clojure-version
"Returns clojure version as a printable string."
[]
(str (:major *clojure-version*)
"."
(:minor *clojure-version*)
(when-let [i (:incremental *clojure-version*)]
(str "." i))
(when-let [q (:qualifier *clojure-version*)]
(when (pos? (count q)) (str "-" q)))
(when (:interim *clojure-version*)
"-SNAPSHOT")))
(defn promise
"Alpha - subject to change.
Returns a promise object that can be read with deref/@, and set,
once only, with deliver. Calls to deref/@ prior to delivery will
block. All subsequent derefs will return the same delivered value
without blocking."
[]
(let [d (java.util.concurrent.CountDownLatch. 1)
v (atom nil)]
(proxy [clojure.lang.AFn clojure.lang.IDeref] []
(deref [] (.await d) @v)
(invoke [x]
(locking d
(if (pos? (.getCount d))
(do (reset! v x)
(.countDown d)
this)
(throw (IllegalStateException. "Multiple deliver calls to a promise"))))))))
(defn deliver
"Alpha - subject to change.
Delivers the supplied value to the promise, releasing any pending
derefs. A subsequent call to deliver on a promise will throw an exception."
[promise val] (promise val))
;;;;;;;;;;;;;;;;;;;;; editable collections ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn transient
"Alpha - subject to change.
Returns a new, transient version of the collection, in constant time."
[#^clojure.lang.IEditableCollection coll]
(.asTransient coll))
(defn persistent!
"Alpha - subject to change.
Returns a new, persistent version of the transient collection, in
constant time. The transient collection cannot be used after this
call, any such use will throw an exception."
[#^clojure.lang.ITransientCollection coll]
(.persistent coll))
(defn conj!
"Alpha - subject to change.
Adds x to the transient collection, and return coll. The 'addition'
may happen at different 'places' depending on the concrete type."
[#^clojure.lang.ITransientCollection coll x]
(.conj coll x))
(defn assoc!
"Alpha - subject to change.
When applied to a transient map, adds mapping of key(s) to
val(s). When applied to a transient vector, sets the val at index.
Note - index must be <= (count vector). Returns coll."
([#^clojure.lang.ITransientAssociative coll key val] (.assoc coll key val))
([#^clojure.lang.ITransientAssociative coll key val & kvs]
(let [ret (.assoc coll key val)]
(if kvs
(recur ret (first kvs) (second kvs) (nnext kvs))
ret))))
(defn dissoc!
"Alpha - subject to change.
Returns a transient map that doesn't contain a mapping for key(s)."
([#^clojure.lang.ITransientMap map key] (.without map key))
([#^clojure.lang.ITransientMap map key & ks]
(let [ret (.without map key)]
(if ks
(recur ret (first ks) (next ks))
ret))))
(defn pop!
"Alpha - subject to change.
Removes the last item from a transient vector. If
the collection is empty, throws an exception. Returns coll"
[#^clojure.lang.ITransientVector coll]
(.pop coll))
(defn disj!
"Alpha - subject to change.
disj[oin]. Returns a transient set of the same (hashed/sorted) type, that
does not contain key(s)."
([set] set)
([#^clojure.lang.ITransientSet set key]
(. set (disjoin key)))
([set key & ks]
(let [ret (disj set key)]
(if ks
(recur ret (first ks) (next ks))
ret))))
;redef into with batch support
(defn into
"Returns a new coll consisting of to-coll with all of the items of
from-coll conjoined."
[to from]
(if (instance? clojure.lang.IEditableCollection to)
(#(loop [ret (transient to) items (seq from)]
(if items
(recur (conj! ret (first items)) (next items))
(persistent! ret))))
(#(loop [ret to items (seq from)]
(if items
(recur (conj ret (first items)) (next items))
ret)))))
|
[
{
"context": "cts, Adaptation and Vulnerability\"\n :authors [\"Nicholls, R.J\" \"P.P. Wong\" \"V.R. Burkett\", \"J.O. Codignotto\", \"",
"end": 8124,
"score": 0.9998821020126343,
"start": 8111,
"tag": "NAME",
"value": "Nicholls, R.J"
},
{
"context": "and Vulnerability\"\n :authors [\"Nicholls, R.J\" \"P.P. Wong\" \"V.R. Burkett\", \"J.O. Codignotto\", \"J.E. Hay\", \"",
"end": 8136,
"score": 0.9998817443847656,
"start": 8127,
"tag": "NAME",
"value": "P.P. Wong"
},
{
"context": "ility\"\n :authors [\"Nicholls, R.J\" \"P.P. Wong\" \"V.R. Burkett\", \"J.O. Codignotto\", \"J.E. Hay\", \"R.F. McLean\",\n ",
"end": 8151,
"score": 0.9998825192451477,
"start": 8139,
"tag": "NAME",
"value": "V.R. Burkett"
},
{
"context": "ors [\"Nicholls, R.J\" \"P.P. Wong\" \"V.R. Burkett\", \"J.O. Codignotto\", \"J.E. Hay\", \"R.F. McLean\",\n \"S. Ra",
"end": 8170,
"score": 0.9998800158500671,
"start": 8155,
"tag": "NAME",
"value": "J.O. Codignotto"
},
{
"context": "\" \"P.P. Wong\" \"V.R. Burkett\", \"J.O. Codignotto\", \"J.E. Hay\", \"R.F. McLean\",\n \"S. Ragoonaden\" \"C",
"end": 8182,
"score": 0.9998515248298645,
"start": 8174,
"tag": "NAME",
"value": "J.E. Hay"
},
{
"context": "\" \"V.R. Burkett\", \"J.O. Codignotto\", \"J.E. Hay\", \"R.F. McLean\",\n \"S. Ragoonaden\" \"C.D. Woodroffe\"]",
"end": 8197,
"score": 0.9998543858528137,
"start": 8186,
"tag": "NAME",
"value": "R.F. McLean"
},
{
"context": "notto\", \"J.E. Hay\", \"R.F. McLean\",\n \"S. Ragoonaden\" \"C.D. Woodroffe\"]\n :published \"Cambridge Univ",
"end": 8228,
"score": 0.9998781085014343,
"start": 8215,
"tag": "NAME",
"value": "S. Ragoonaden"
},
{
"context": "y\", \"R.F. McLean\",\n \"S. Ragoonaden\" \"C.D. Woodroffe\"]\n :published \"Cambridge University Press, Cam",
"end": 8245,
"score": 0.9998652935028076,
"start": 8231,
"tag": "NAME",
"value": "C.D. Woodroffe"
},
{
"context": "for the impacts of sea level rise\"\n :authors [\"Nicholls, R.J\"]}})",
"end": 8488,
"score": 0.9998266100883484,
"start": 8480,
"tag": "NAME",
"value": "Nicholls"
},
{
"context": "mpacts of sea level rise\"\n :authors [\"Nicholls, R.J\"]}})",
"end": 8493,
"score": 0.9900274276733398,
"start": 8490,
"tag": "NAME",
"value": "R.J"
}
] | data/test/clojure/75f0ca13a1f335459f80a35a575d45901882b26bsite.clj | harshp8l/deep-learning-lang-detection | 84 | (ns clad.views.site)
(def
^{:doc
"Sitemap: Structure
Page Title
Sections
Section Title
Headings
Heading Title
From selector
To selector"}
sitemap [{:title "Home" :file "Home.html"
:sections [{:title "Irish Coast and CC" :from :#home_ic}
{:title "How can I use this site?" :from :#home_how}
{:title "News and Events" :from :#home_news}]}
{:title "Climate Change" :file "more.html"
:sections [{:title "Essentials" :from :#essentials
:topics [{:title "What is Climate Change?", :from :#whatis, }
{:title "Evidence for Climate Change", :from :#evidence,}
{:title "Why is Climate Change Serious?", :from :#whyis, }
{:title "Climate Modelling", :from :#modelling}
{:title "Adaptation and Mitigation", :from :#adapt, }]}
{:title "Global Projections" :from :#project
:topics [{:title "Global and Regional Trends" :from :#project}
{:title "Climate change and Coasts" :from :#impacts
:subtopics [{:title "Sea level rise" :from :#sea_level_rise
:refs [:nic07 :nic11]}
{:title "Sea surface temperature" :from :#seasurfacetemp}
{:title "Water Salinity" :from :#salinity}
{:title "Ocean Acidification" :from :#acidification}
{:title "Storminess & Wave Height" :from :#storminess}
{:title "Coastal Erosion" :from :#coastalerosion}
{:title "Coastal Squeeze" :from :#squeeze}
{:title "Floods & Extreme Events" :from :#floods}
{:title "Ecosystems" :from :#ecosystems}]}]}
{:title "Irish Coasts" :from :#ireland
:topics [{:title "Climate change in Ireland" :from :#ireland}
{:title "Impacts on Irish coasts" :from :#irishcoastsimpacts
:subtopics [{:title "Sea level rise" :from :#impacts_sealevelrise}
{:title "Sea surface temperature" :from :#seatemp}
{:title "Salinity & Acidification" :from :#saltacid}
{:title "Storminess & Wave Height" :from :#impacts_storminess}
{:title "Coastal Erosion & Squeeze" :from :#impacts_squeeze}
{:title "Floods & Extreme Events" :from :#extremeevents}
{:title "Ecosystems" :from :#ecosystems}]}
{:title "Regions" :from :#regions}
{:title "Sectors" :from :#sectors}]}]}
{:title "Adaptation" :file "Adaptation.html"
:sections [{:title "Why Climate Adaptation?" :from :#whyadapt
:topics [{:title "What is climate adaptation?" :from :#whatis}
{:title "Why adapt?"}
{:title "How to approach it?"}]}
{:title "Adaptive Co-Management"
:topics [{:title "How can I do it?"}
{:title "What do I need?"}]}]}
{:title "Tools & Methods"
:sections [{:title "Tools & Methods"
:topics [{:title "Which Method Works?"}
{:title "Vulnerability Assessment"}
{:title "Scenario Development"}
{:title "Knowledge Integration"}
{:title "Implementation"}
{:title "Resources"}]}]}
{:title "Policy & Law"
:sections [{:title "How Adaptation Governance Works"
:topics [{:title "Challenges"}
{:title "Policy and legislation"}
{:title "Implementation"}]}
{:title "European Union"}
{:title "Ireland"}
{:title "Regions & Communities"}]}
{:title "Case Studies"
:sections [{:title "How do they manage?"
:topics [{:title "FIXME!"}]}
{:title "Ireland"
:topics [{:title "Tralee Bay Co.Kerry"}
{:title "Bantry Bay Co. Cork"}
{:title "Fingal Co. Dublin"}
{:title "Cork Harbour Co. Cork"}
{:title "Lough Swilly Co. Donegal"}]}
{:title "International"
:topics [{:title "CS 1"}
{:title "CS 2"}
{:title "CS 3"}]}
{:title "Look for your specific issue"}
{:title "Tell us about your experience!"}]}
{:title "Resources" :file "resources.html"
:sections [{:title "How I can build capacities for climate adaptation?"
:from :#res_cap}
{:title "Data and Information"
:topics [{:title "Climate Change"}
{:title "Sustainable Development"}
{:title "Irish Climate"}
{:title "Irish Coasts and Seas"}]}
{:title "Guidelines"}
{:title "Legal and Policy Support"}
{:title "Financial Support"}
{:title "Practical Measures"}
{:title "Communication and Presentations"}
{:title "Working with Communities"}
{:title "References" :from :#refs}]}
{:title "ICRN"
:sections [{:title "About ICRN"
:topics [{:title "FIXME!"}]}
{:title "National Advisory Panel"}
{:title "Regional Units"
:topics [{:title "Tralee"}
{:title "Bantry"}
{:title "Fingal"}]}
{:title "Vulnerability assessment"
:topics [{:title "Tralee"}
{:title "Bantry"}
{:title "Fingal"}]}
{:title "Local Scenarios"
:topics [{:title "Tralee"}
{:title "Bantry"}
{:title "Fingal"}]}
{:title "GIS Coastal Adaptation"}
{:title "Get Involved!"}]}])
(def references
{:nic07
{:title "Coastal systems and low-lying areas. Climate Change 2007: Impacts, Adaptation and Vulnerability"
:authors ["Nicholls, R.J" "P.P. Wong" "V.R. Burkett", "J.O. Codignotto", "J.E. Hay", "R.F. McLean",
"S. Ragoonaden" "C.D. Woodroffe"]
:published "Cambridge University Press, Cambridge, UK, 315-356"
:link "http://www.ipcc.ch/pdf/assessment-report/ar4/wg2/ar4-wg2-chapter6.pdf"}
:nic11
{:title "Planning for the impacts of sea level rise"
:authors ["Nicholls, R.J"]}}) | 51616 | (ns clad.views.site)
(def
^{:doc
"Sitemap: Structure
Page Title
Sections
Section Title
Headings
Heading Title
From selector
To selector"}
sitemap [{:title "Home" :file "Home.html"
:sections [{:title "Irish Coast and CC" :from :#home_ic}
{:title "How can I use this site?" :from :#home_how}
{:title "News and Events" :from :#home_news}]}
{:title "Climate Change" :file "more.html"
:sections [{:title "Essentials" :from :#essentials
:topics [{:title "What is Climate Change?", :from :#whatis, }
{:title "Evidence for Climate Change", :from :#evidence,}
{:title "Why is Climate Change Serious?", :from :#whyis, }
{:title "Climate Modelling", :from :#modelling}
{:title "Adaptation and Mitigation", :from :#adapt, }]}
{:title "Global Projections" :from :#project
:topics [{:title "Global and Regional Trends" :from :#project}
{:title "Climate change and Coasts" :from :#impacts
:subtopics [{:title "Sea level rise" :from :#sea_level_rise
:refs [:nic07 :nic11]}
{:title "Sea surface temperature" :from :#seasurfacetemp}
{:title "Water Salinity" :from :#salinity}
{:title "Ocean Acidification" :from :#acidification}
{:title "Storminess & Wave Height" :from :#storminess}
{:title "Coastal Erosion" :from :#coastalerosion}
{:title "Coastal Squeeze" :from :#squeeze}
{:title "Floods & Extreme Events" :from :#floods}
{:title "Ecosystems" :from :#ecosystems}]}]}
{:title "Irish Coasts" :from :#ireland
:topics [{:title "Climate change in Ireland" :from :#ireland}
{:title "Impacts on Irish coasts" :from :#irishcoastsimpacts
:subtopics [{:title "Sea level rise" :from :#impacts_sealevelrise}
{:title "Sea surface temperature" :from :#seatemp}
{:title "Salinity & Acidification" :from :#saltacid}
{:title "Storminess & Wave Height" :from :#impacts_storminess}
{:title "Coastal Erosion & Squeeze" :from :#impacts_squeeze}
{:title "Floods & Extreme Events" :from :#extremeevents}
{:title "Ecosystems" :from :#ecosystems}]}
{:title "Regions" :from :#regions}
{:title "Sectors" :from :#sectors}]}]}
{:title "Adaptation" :file "Adaptation.html"
:sections [{:title "Why Climate Adaptation?" :from :#whyadapt
:topics [{:title "What is climate adaptation?" :from :#whatis}
{:title "Why adapt?"}
{:title "How to approach it?"}]}
{:title "Adaptive Co-Management"
:topics [{:title "How can I do it?"}
{:title "What do I need?"}]}]}
{:title "Tools & Methods"
:sections [{:title "Tools & Methods"
:topics [{:title "Which Method Works?"}
{:title "Vulnerability Assessment"}
{:title "Scenario Development"}
{:title "Knowledge Integration"}
{:title "Implementation"}
{:title "Resources"}]}]}
{:title "Policy & Law"
:sections [{:title "How Adaptation Governance Works"
:topics [{:title "Challenges"}
{:title "Policy and legislation"}
{:title "Implementation"}]}
{:title "European Union"}
{:title "Ireland"}
{:title "Regions & Communities"}]}
{:title "Case Studies"
:sections [{:title "How do they manage?"
:topics [{:title "FIXME!"}]}
{:title "Ireland"
:topics [{:title "Tralee Bay Co.Kerry"}
{:title "Bantry Bay Co. Cork"}
{:title "Fingal Co. Dublin"}
{:title "Cork Harbour Co. Cork"}
{:title "Lough Swilly Co. Donegal"}]}
{:title "International"
:topics [{:title "CS 1"}
{:title "CS 2"}
{:title "CS 3"}]}
{:title "Look for your specific issue"}
{:title "Tell us about your experience!"}]}
{:title "Resources" :file "resources.html"
:sections [{:title "How I can build capacities for climate adaptation?"
:from :#res_cap}
{:title "Data and Information"
:topics [{:title "Climate Change"}
{:title "Sustainable Development"}
{:title "Irish Climate"}
{:title "Irish Coasts and Seas"}]}
{:title "Guidelines"}
{:title "Legal and Policy Support"}
{:title "Financial Support"}
{:title "Practical Measures"}
{:title "Communication and Presentations"}
{:title "Working with Communities"}
{:title "References" :from :#refs}]}
{:title "ICRN"
:sections [{:title "About ICRN"
:topics [{:title "FIXME!"}]}
{:title "National Advisory Panel"}
{:title "Regional Units"
:topics [{:title "Tralee"}
{:title "Bantry"}
{:title "Fingal"}]}
{:title "Vulnerability assessment"
:topics [{:title "Tralee"}
{:title "Bantry"}
{:title "Fingal"}]}
{:title "Local Scenarios"
:topics [{:title "Tralee"}
{:title "Bantry"}
{:title "Fingal"}]}
{:title "GIS Coastal Adaptation"}
{:title "Get Involved!"}]}])
(def references
{:nic07
{:title "Coastal systems and low-lying areas. Climate Change 2007: Impacts, Adaptation and Vulnerability"
:authors ["<NAME>" "<NAME>" "<NAME>", "<NAME>", "<NAME>", "<NAME>",
"<NAME>" "<NAME>"]
:published "Cambridge University Press, Cambridge, UK, 315-356"
:link "http://www.ipcc.ch/pdf/assessment-report/ar4/wg2/ar4-wg2-chapter6.pdf"}
:nic11
{:title "Planning for the impacts of sea level rise"
:authors ["<NAME>, <NAME>"]}}) | true | (ns clad.views.site)
(def
^{:doc
"Sitemap: Structure
Page Title
Sections
Section Title
Headings
Heading Title
From selector
To selector"}
sitemap [{:title "Home" :file "Home.html"
:sections [{:title "Irish Coast and CC" :from :#home_ic}
{:title "How can I use this site?" :from :#home_how}
{:title "News and Events" :from :#home_news}]}
{:title "Climate Change" :file "more.html"
:sections [{:title "Essentials" :from :#essentials
:topics [{:title "What is Climate Change?", :from :#whatis, }
{:title "Evidence for Climate Change", :from :#evidence,}
{:title "Why is Climate Change Serious?", :from :#whyis, }
{:title "Climate Modelling", :from :#modelling}
{:title "Adaptation and Mitigation", :from :#adapt, }]}
{:title "Global Projections" :from :#project
:topics [{:title "Global and Regional Trends" :from :#project}
{:title "Climate change and Coasts" :from :#impacts
:subtopics [{:title "Sea level rise" :from :#sea_level_rise
:refs [:nic07 :nic11]}
{:title "Sea surface temperature" :from :#seasurfacetemp}
{:title "Water Salinity" :from :#salinity}
{:title "Ocean Acidification" :from :#acidification}
{:title "Storminess & Wave Height" :from :#storminess}
{:title "Coastal Erosion" :from :#coastalerosion}
{:title "Coastal Squeeze" :from :#squeeze}
{:title "Floods & Extreme Events" :from :#floods}
{:title "Ecosystems" :from :#ecosystems}]}]}
{:title "Irish Coasts" :from :#ireland
:topics [{:title "Climate change in Ireland" :from :#ireland}
{:title "Impacts on Irish coasts" :from :#irishcoastsimpacts
:subtopics [{:title "Sea level rise" :from :#impacts_sealevelrise}
{:title "Sea surface temperature" :from :#seatemp}
{:title "Salinity & Acidification" :from :#saltacid}
{:title "Storminess & Wave Height" :from :#impacts_storminess}
{:title "Coastal Erosion & Squeeze" :from :#impacts_squeeze}
{:title "Floods & Extreme Events" :from :#extremeevents}
{:title "Ecosystems" :from :#ecosystems}]}
{:title "Regions" :from :#regions}
{:title "Sectors" :from :#sectors}]}]}
{:title "Adaptation" :file "Adaptation.html"
:sections [{:title "Why Climate Adaptation?" :from :#whyadapt
:topics [{:title "What is climate adaptation?" :from :#whatis}
{:title "Why adapt?"}
{:title "How to approach it?"}]}
{:title "Adaptive Co-Management"
:topics [{:title "How can I do it?"}
{:title "What do I need?"}]}]}
{:title "Tools & Methods"
:sections [{:title "Tools & Methods"
:topics [{:title "Which Method Works?"}
{:title "Vulnerability Assessment"}
{:title "Scenario Development"}
{:title "Knowledge Integration"}
{:title "Implementation"}
{:title "Resources"}]}]}
{:title "Policy & Law"
:sections [{:title "How Adaptation Governance Works"
:topics [{:title "Challenges"}
{:title "Policy and legislation"}
{:title "Implementation"}]}
{:title "European Union"}
{:title "Ireland"}
{:title "Regions & Communities"}]}
{:title "Case Studies"
:sections [{:title "How do they manage?"
:topics [{:title "FIXME!"}]}
{:title "Ireland"
:topics [{:title "Tralee Bay Co.Kerry"}
{:title "Bantry Bay Co. Cork"}
{:title "Fingal Co. Dublin"}
{:title "Cork Harbour Co. Cork"}
{:title "Lough Swilly Co. Donegal"}]}
{:title "International"
:topics [{:title "CS 1"}
{:title "CS 2"}
{:title "CS 3"}]}
{:title "Look for your specific issue"}
{:title "Tell us about your experience!"}]}
{:title "Resources" :file "resources.html"
:sections [{:title "How I can build capacities for climate adaptation?"
:from :#res_cap}
{:title "Data and Information"
:topics [{:title "Climate Change"}
{:title "Sustainable Development"}
{:title "Irish Climate"}
{:title "Irish Coasts and Seas"}]}
{:title "Guidelines"}
{:title "Legal and Policy Support"}
{:title "Financial Support"}
{:title "Practical Measures"}
{:title "Communication and Presentations"}
{:title "Working with Communities"}
{:title "References" :from :#refs}]}
{:title "ICRN"
:sections [{:title "About ICRN"
:topics [{:title "FIXME!"}]}
{:title "National Advisory Panel"}
{:title "Regional Units"
:topics [{:title "Tralee"}
{:title "Bantry"}
{:title "Fingal"}]}
{:title "Vulnerability assessment"
:topics [{:title "Tralee"}
{:title "Bantry"}
{:title "Fingal"}]}
{:title "Local Scenarios"
:topics [{:title "Tralee"}
{:title "Bantry"}
{:title "Fingal"}]}
{:title "GIS Coastal Adaptation"}
{:title "Get Involved!"}]}])
(def references
{:nic07
{:title "Coastal systems and low-lying areas. Climate Change 2007: Impacts, Adaptation and Vulnerability"
:authors ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI",
"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]
:published "Cambridge University Press, Cambridge, UK, 315-356"
:link "http://www.ipcc.ch/pdf/assessment-report/ar4/wg2/ar4-wg2-chapter6.pdf"}
:nic11
{:title "Planning for the impacts of sea level rise"
:authors ["PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI"]}}) |
[
{
"context": "bonacci\")\n :github-user \"BrunoBonacci\"\n :author \"Bruno Bo",
"end": 2561,
"score": 0.9992084503173828,
"start": 2549,
"tag": "USERNAME",
"value": "BrunoBonacci"
},
{
"context": "oBonacci\"\n :author \"Bruno Bonacci\"\n :bootstrap-version (:bootstr",
"end": 2616,
"score": 0.999886155128479,
"start": 2603,
"tag": "NAME",
"value": "Bruno Bonacci"
}
] | src/leiningen/new/my_project.clj | BrunoBonacci/my-project-template | 0 | (ns leiningen.new.my-project
(:require [leiningen.new.templates :refer [renderer name-to-path ->files]]
[leiningen.core.main :as main]
[clj-http.client :as http]
[clojure.string :as str]))
(def ^:const CLOJARS_URL "https://clojars.org/api/artifacts/%s")
(def ^:const MAVEN_URL "https://search.maven.org/solrsearch/select?q=g:\"%s\" AND a:\"%s\"&rows=1&wt=json&core=gav")
(def render (renderer "my-project"))
(defn sort-by-semantic-version [versions]
(->> versions
(map (partial re-find #"(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?(?:-(SNAPSHOT)|(.*))?"))
(filter identity)
(map (fn [[v a b c d sn alpha-beta]]
(let [->int (fnil read-string "-1")]
[(->int a) (->int b) (->int c) (->int d) (not= sn "SNAPSHOT") alpha-beta v])))
sort
(map last)))
(defn package-versions-clojars
[package]
(main/info "Searching for latest" package "version on Clojars.org ...")
(->> (:body (http/get (format CLOJARS_URL package) {:accept :edn :as :clojure}))
:recent_versions
(map :version)))
(defn package-versions-maven
[package]
(main/info "Searching for latest" package "version on Maven Central ...")
(let [[gid aid] (str/split package #"/")]
(->> (:body (http/get (format MAVEN_URL gid aid) {:accept :json :as :json}))
:response
:docs
(map :v))))
(defn package-versions
[package]
(if (str/includes? package "org.clojure/")
(package-versions-maven package) ;; clojure artifacts are not up-to-date in Clojars
(try
(package-versions-clojars package)
(catch Exception x
(package-versions-maven package)))))
(defn latest-version
[versions snapshot?]
(->> versions
sort-by-semantic-version
(filter #(if snapshot? true (not (re-find #"SNAPSHOT" %))))
last))
(defn latest-version-of [package snapshot?]
(let [versions (package-versions package)
latest (latest-version versions snapshot?)]
(main/info "Latest" package "version:" latest)
latest))
(defn my-project
"A leinengen template to create personal OSS projects."
[name & options]
(let [parsed (main/parse-options options)]
(if (not (:error parsed))
(let [data {:name name
:sanitized (name-to-path name)
:version (or (:version parsed) "0.1.0-SNAPSHOT")
:group-id "com.brunobonacci"
:sanitized-group (name-to-path "com.brunobonacci")
:github-user "BrunoBonacci"
:author "Bruno Bonacci"
:bootstrap-version (:bootstrap-version parsed)
:clojure-version (latest-version-of "org.clojure/clojure" false)
:midje-version (latest-version-of "midje" false)
:test-check-version (latest-version-of "org.clojure/test.check" false)
:criterium-version (latest-version-of "criterium" false)
:lein-midje-version (latest-version-of "lein-midje" false)
:lein-jmh-version (latest-version-of "lein-jmh" false)
:jmh-version (latest-version-of "jmh-clojure" false)
:clj-prof-ver (latest-version-of "com.clojure-goes-fast/clj-async-profiler" false)
:slf4j-log4j (latest-version-of "org.slf4j/slf4j-log4j12" false)
:year (format "%tY" (java.util.Date.))}]
(main/info "Generating fresh project.")
(->files data
["project.clj" (render "project.clj" data)]
[".midje.clj" (render "midje.clj" data)]
["src/{{sanitized-group}}/{{sanitized}}.clj" (render "core.clj" data)]
["test/{{sanitized-group}}/{{sanitized}}_test.clj" (render "core_test.clj" data)]
["README.md" (render "README.md" data)]
["LICENSE" (render "LICENSE")]
["doc/intro.md" (render "intro.md")]
[".gitignore" (render "gitignore")]
[".hgignore" (render "hgignore")]
["dev/user.clj" (render "user.clj" data)]
["dev/perf.clj" (render "perf.clj" data)]
["dev/perf/benchmarks.clj" (render "benchmarks.clj" data)]
["dev/perf/benchmarks.edn" (render "benchmarks.edn" data)]
["dev-resources/log4j.properties" (render "log4j.properties" data)]
"resources")
(main/info "All done.\n")
(main/info "To build and test:\n\t$ lein do clean, midje"))
(main/info (:error parsed)))))
| 19344 | (ns leiningen.new.my-project
(:require [leiningen.new.templates :refer [renderer name-to-path ->files]]
[leiningen.core.main :as main]
[clj-http.client :as http]
[clojure.string :as str]))
(def ^:const CLOJARS_URL "https://clojars.org/api/artifacts/%s")
(def ^:const MAVEN_URL "https://search.maven.org/solrsearch/select?q=g:\"%s\" AND a:\"%s\"&rows=1&wt=json&core=gav")
(def render (renderer "my-project"))
(defn sort-by-semantic-version [versions]
(->> versions
(map (partial re-find #"(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?(?:-(SNAPSHOT)|(.*))?"))
(filter identity)
(map (fn [[v a b c d sn alpha-beta]]
(let [->int (fnil read-string "-1")]
[(->int a) (->int b) (->int c) (->int d) (not= sn "SNAPSHOT") alpha-beta v])))
sort
(map last)))
(defn package-versions-clojars
[package]
(main/info "Searching for latest" package "version on Clojars.org ...")
(->> (:body (http/get (format CLOJARS_URL package) {:accept :edn :as :clojure}))
:recent_versions
(map :version)))
(defn package-versions-maven
[package]
(main/info "Searching for latest" package "version on Maven Central ...")
(let [[gid aid] (str/split package #"/")]
(->> (:body (http/get (format MAVEN_URL gid aid) {:accept :json :as :json}))
:response
:docs
(map :v))))
(defn package-versions
[package]
(if (str/includes? package "org.clojure/")
(package-versions-maven package) ;; clojure artifacts are not up-to-date in Clojars
(try
(package-versions-clojars package)
(catch Exception x
(package-versions-maven package)))))
(defn latest-version
[versions snapshot?]
(->> versions
sort-by-semantic-version
(filter #(if snapshot? true (not (re-find #"SNAPSHOT" %))))
last))
(defn latest-version-of [package snapshot?]
(let [versions (package-versions package)
latest (latest-version versions snapshot?)]
(main/info "Latest" package "version:" latest)
latest))
(defn my-project
"A leinengen template to create personal OSS projects."
[name & options]
(let [parsed (main/parse-options options)]
(if (not (:error parsed))
(let [data {:name name
:sanitized (name-to-path name)
:version (or (:version parsed) "0.1.0-SNAPSHOT")
:group-id "com.brunobonacci"
:sanitized-group (name-to-path "com.brunobonacci")
:github-user "BrunoBonacci"
:author "<NAME>"
:bootstrap-version (:bootstrap-version parsed)
:clojure-version (latest-version-of "org.clojure/clojure" false)
:midje-version (latest-version-of "midje" false)
:test-check-version (latest-version-of "org.clojure/test.check" false)
:criterium-version (latest-version-of "criterium" false)
:lein-midje-version (latest-version-of "lein-midje" false)
:lein-jmh-version (latest-version-of "lein-jmh" false)
:jmh-version (latest-version-of "jmh-clojure" false)
:clj-prof-ver (latest-version-of "com.clojure-goes-fast/clj-async-profiler" false)
:slf4j-log4j (latest-version-of "org.slf4j/slf4j-log4j12" false)
:year (format "%tY" (java.util.Date.))}]
(main/info "Generating fresh project.")
(->files data
["project.clj" (render "project.clj" data)]
[".midje.clj" (render "midje.clj" data)]
["src/{{sanitized-group}}/{{sanitized}}.clj" (render "core.clj" data)]
["test/{{sanitized-group}}/{{sanitized}}_test.clj" (render "core_test.clj" data)]
["README.md" (render "README.md" data)]
["LICENSE" (render "LICENSE")]
["doc/intro.md" (render "intro.md")]
[".gitignore" (render "gitignore")]
[".hgignore" (render "hgignore")]
["dev/user.clj" (render "user.clj" data)]
["dev/perf.clj" (render "perf.clj" data)]
["dev/perf/benchmarks.clj" (render "benchmarks.clj" data)]
["dev/perf/benchmarks.edn" (render "benchmarks.edn" data)]
["dev-resources/log4j.properties" (render "log4j.properties" data)]
"resources")
(main/info "All done.\n")
(main/info "To build and test:\n\t$ lein do clean, midje"))
(main/info (:error parsed)))))
| true | (ns leiningen.new.my-project
(:require [leiningen.new.templates :refer [renderer name-to-path ->files]]
[leiningen.core.main :as main]
[clj-http.client :as http]
[clojure.string :as str]))
(def ^:const CLOJARS_URL "https://clojars.org/api/artifacts/%s")
(def ^:const MAVEN_URL "https://search.maven.org/solrsearch/select?q=g:\"%s\" AND a:\"%s\"&rows=1&wt=json&core=gav")
(def render (renderer "my-project"))
(defn sort-by-semantic-version [versions]
(->> versions
(map (partial re-find #"(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?(?:-(SNAPSHOT)|(.*))?"))
(filter identity)
(map (fn [[v a b c d sn alpha-beta]]
(let [->int (fnil read-string "-1")]
[(->int a) (->int b) (->int c) (->int d) (not= sn "SNAPSHOT") alpha-beta v])))
sort
(map last)))
(defn package-versions-clojars
[package]
(main/info "Searching for latest" package "version on Clojars.org ...")
(->> (:body (http/get (format CLOJARS_URL package) {:accept :edn :as :clojure}))
:recent_versions
(map :version)))
(defn package-versions-maven
[package]
(main/info "Searching for latest" package "version on Maven Central ...")
(let [[gid aid] (str/split package #"/")]
(->> (:body (http/get (format MAVEN_URL gid aid) {:accept :json :as :json}))
:response
:docs
(map :v))))
(defn package-versions
[package]
(if (str/includes? package "org.clojure/")
(package-versions-maven package) ;; clojure artifacts are not up-to-date in Clojars
(try
(package-versions-clojars package)
(catch Exception x
(package-versions-maven package)))))
(defn latest-version
[versions snapshot?]
(->> versions
sort-by-semantic-version
(filter #(if snapshot? true (not (re-find #"SNAPSHOT" %))))
last))
(defn latest-version-of [package snapshot?]
(let [versions (package-versions package)
latest (latest-version versions snapshot?)]
(main/info "Latest" package "version:" latest)
latest))
(defn my-project
"A leinengen template to create personal OSS projects."
[name & options]
(let [parsed (main/parse-options options)]
(if (not (:error parsed))
(let [data {:name name
:sanitized (name-to-path name)
:version (or (:version parsed) "0.1.0-SNAPSHOT")
:group-id "com.brunobonacci"
:sanitized-group (name-to-path "com.brunobonacci")
:github-user "BrunoBonacci"
:author "PI:NAME:<NAME>END_PI"
:bootstrap-version (:bootstrap-version parsed)
:clojure-version (latest-version-of "org.clojure/clojure" false)
:midje-version (latest-version-of "midje" false)
:test-check-version (latest-version-of "org.clojure/test.check" false)
:criterium-version (latest-version-of "criterium" false)
:lein-midje-version (latest-version-of "lein-midje" false)
:lein-jmh-version (latest-version-of "lein-jmh" false)
:jmh-version (latest-version-of "jmh-clojure" false)
:clj-prof-ver (latest-version-of "com.clojure-goes-fast/clj-async-profiler" false)
:slf4j-log4j (latest-version-of "org.slf4j/slf4j-log4j12" false)
:year (format "%tY" (java.util.Date.))}]
(main/info "Generating fresh project.")
(->files data
["project.clj" (render "project.clj" data)]
[".midje.clj" (render "midje.clj" data)]
["src/{{sanitized-group}}/{{sanitized}}.clj" (render "core.clj" data)]
["test/{{sanitized-group}}/{{sanitized}}_test.clj" (render "core_test.clj" data)]
["README.md" (render "README.md" data)]
["LICENSE" (render "LICENSE")]
["doc/intro.md" (render "intro.md")]
[".gitignore" (render "gitignore")]
[".hgignore" (render "hgignore")]
["dev/user.clj" (render "user.clj" data)]
["dev/perf.clj" (render "perf.clj" data)]
["dev/perf/benchmarks.clj" (render "benchmarks.clj" data)]
["dev/perf/benchmarks.edn" (render "benchmarks.edn" data)]
["dev-resources/log4j.properties" (render "log4j.properties" data)]
"resources")
(main/info "All done.\n")
(main/info "To build and test:\n\t$ lein do clean, midje"))
(main/info (:error parsed)))))
|
[
{
"context": "(ns\n ^{:author edgar}\n clojure_tutorial.macro.start\n (require '(cloj",
"end": 21,
"score": 0.998816728591919,
"start": 16,
"tag": "USERNAME",
"value": "edgar"
},
{
"context": "e]\n (list 'println name))\n\n(macroexpand '(hello \"Brian\"))\n;;(println \"Brian\")\n\n\n\n;引述和语法引述\n;语法引述把无命名空间限定的",
"end": 1342,
"score": 0.9996709823608398,
"start": 1337,
"tag": "NAME",
"value": "Brian"
},
{
"context": "ame))\n\n(macroexpand '(hello \"Brian\"))\n;;(println \"Brian\")\n\n\n\n;引述和语法引述\n;语法引述把无命名空间限定的符号求值成当前命名空间的符号\n(def f",
"end": 1363,
"score": 0.9996604919433594,
"start": 1358,
"tag": "NAME",
"value": "Brian"
},
{
"context": "str \"Hello, \" ~x \"!\"))\n;它们在一些用法上表现是类似的\n(fn-hello \"Brian\")\n;;\"Hello, Brian!\"\n(macro-hello \"Brian\")\n;;\"Hell",
"end": 3519,
"score": 0.7543267011642456,
"start": 3514,
"tag": "NAME",
"value": "Brian"
},
{
"context": "\"!\"))\n;它们在一些用法上表现是类似的\n(fn-hello \"Brian\")\n;;\"Hello, Brian!\"\n(macro-hello \"Brian\")\n;;\"Hello, Brian!\"\n\n;而在另外一",
"end": 3537,
"score": 0.9750977754592896,
"start": 3532,
"tag": "NAME",
"value": "Brian"
},
{
"context": "n-hello \"Brian\")\n;;\"Hello, Brian!\"\n(macro-hello \"Brian\")\n;;\"Hello, Brian!\"\n\n;而在另外一些上下文中表现就不一样了\n(map fn-h",
"end": 3559,
"score": 0.8354143500328064,
"start": 3555,
"tag": "NAME",
"value": "rian"
},
{
"context": "\n;;\"Hello, Brian!\"\n(macro-hello \"Brian\")\n;;\"Hello, Brian!\"\n\n;而在另外一些上下文中表现就不一样了\n(map fn-hello [\"Brain\" \"Not",
"end": 3577,
"score": 0.9446592330932617,
"start": 3572,
"tag": "NAME",
"value": "Brian"
}
] | src/clojure_tutorial/macro/start.clj | edgar615/clojure-tutorial | 1 | (ns
^{:author edgar}
clojure_tutorial.macro.start
(require '(clojure [string :as str]
[walk :as walk])))
;(defmacro foreach [[sym coll] & body]
; `(loop [coll# ~coll]
; (when-let [[~sym & xs#] (seq coll#)]
; ~@body
; (recure xs#))))
;
;(foreach [x [1 2 3]]
; (println x))
(defmacro print-keyword [x]
`(println (keyword ~x)))
(print-keyword "foo")
;;foo
(defmacro reverse-it
[form]
(walk/postwalk #(if (symbol? %)
(symbol (str/reverse (name %)))
%)
form))
(reverse-it
(qesod [gra (egnar 5)]
(nltnirp (cni gra))))
;;1
;;2
;;3
;;4
;;5
;展开宏
(macroexpand-1 '(reverse-it
(qesod [gra (egnar 5)]
(nltnirp (cni gra)))))
;;(doseq [arg (range 5)] (println (inc arg)))
;macroexpand-1只会扩展宏一次,如果一个宏被扩展后还包含了对宏的调用的话,那么宏需要扩展多次
;如果宏扩展之后产生的是对另外一个宏的调用,而你想继续扩展这个宏到最顶级的形式不再是一个宏的话,使用macroexpand
(pprint (macroexpand '(reverse-it
(qesod [gra (egnar 5)]
(nltnirp (cni gra))))))
;完全宏扩展
;macroexpand-1和macroexpand都不会对嵌套的宏进行扩展。
(macroexpand '(cond a b c d))
;获得一个宏的彻底扩展
(walk/macroexpand-all '(cond a b c d))
;;(if a b (if c d nil))
;语法
;因为宏要返回Clojure数据结构,我们经常返回列表以表示进一步调用,
; 这个调用可能是对函数、特殊形式或者宏的调用。
(defmacro hello
[name]
(list 'println name))
(macroexpand '(hello "Brian"))
;;(println "Brian")
;引述和语法引述
;语法引述把无命名空间限定的符号求值成当前命名空间的符号
(def foo 123)
[foo (quote foo) 'foo `foo]
;;[123 foo foo user/foo]
;语法引述允许反引述:一个列表里面的某些元素可以被选择性地反引述,从而使得它们在语法引述的形式内被求值
;反引述与编接反引述
;在编写一个宏的骨架的时候,我们通常想保持列表里面的一些元素不进行求值,而另外一些元素则需要求值。
(list `map `println [foo])
;;(clojure.core/map clojure.core/println [123])
;一个更简短、更有可读性的办法是把整个列表进行语法引述,然后把其中那些需要求值的元素进行反引述
;可以通过~来反引述
`(map println [~foo])
;;(clojure.core/map clojure.core/println [123])
;反引述一个列表或者vector会把整个形式都反引述。
`(map println ~[foo])
;;(clojure.core/map clojure.core/println [123])
`(println ~(keyword (str foo)))
;;(clojure.core/println :123)
;引述
(def a 4)
'(1 2 3 a 5)
;;(1 2 3 a 5)
(list 1 2 3 a 5)
;;(1 2 3 4 5)
'a
;;a
;语法引述
(def a 4)
`(1 2 3 ~a 5)
;;(1 2 3 4 5)
`~a
;;4
'~a
;;(clojure.core/unquote a)
`~'a
;;a
`(1 2 3 '~a 5)
;;(1 2 3 (quote 4) 5)
`(1 2 3 (quote (clojure.core/unquote a)) 5)
;;(1 2 3 (quote 4) 5)
(def other-nums '(4 5 6 7))
`(1 2 3 ~other-nums 9 10)
;;(1 2 3 (4 5 6 7) 9 10)
`(1 2 3 ~@other-nums 9 10)
;;(1 2 3 4 5 6 7 9 10)
;有一个列表的形式,然后想把另外一个列表的内容解开加入到第一个列表里面去。
(let [defs '((def x 123)
(def y 456))]
(concat (list 'do) defs))
;;(do (def x 123) (def y 456))
;编接反引述操作符'@是一个更好的办法,它自动帮你做列表的链接
(let [defs '((def x 123)
(def y 456))]
`(do ~@defs))
;;(do (def x 123) (def y 456))
;一个接受多个形式作为“代码体”的宏大概是这样:
(defmacro foo
[& body]
`(do-something ~@body))
(macroexpand-1 '(foo (doseq [x (range 5)]
(println x))
:done))
;;(user/do-something (doseq [x (range 5)] (println x)) :done)
;宏的例子
(defmacro squares
[xs]
(list 'map '#(* % %) xs))
(squares (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
(defmacro squares2
[xs]
`(map #(* % %) ~xs))
(squares2 (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
(defmacro squares3
[xs]
`(map (fn [~'x] (* ~'x ~'x)) ~xs))
(squares3 (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
(defmacro make-adder
[x]
`(fn [~'y] (+ ~x ~'y)))
(macroexpand-1 '(make-adder 10))
;;(clojure.core/fn [y] (clojure.core/+ 10 y))
;什么时候使用宏
;宏是在编译期被调用的
(defn fn-hello [x]
(str "Hello, " x "!"))
(defmacro macro-hello [x]
`(str "Hello, " ~x "!"))
;它们在一些用法上表现是类似的
(fn-hello "Brian")
;;"Hello, Brian!"
(macro-hello "Brian")
;;"Hello, Brian!"
;而在另外一些上下文中表现就不一样了
(map fn-hello ["Brain" "Not Brian"])
;;("Hello, Brain!" "Hello, Not Brian!")
(map macro-hello ["Brain" "Not Brian"])
;;CompilerException java.lang.RuntimeException: Can't take value of a macro:
;宏不能作为值来进行组合或者传递。宏根本就没有运行时值的概念。
(defn square
[x]
(* x x))
(map square (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
(defmacro square-macro
[x]
`(* ~x ~x))
(map square-macro (range 10))
;如果想在这种上下文里面使用宏,需要把宏包在一个fn或者匿名函数字面量里面。
;这使得宏的应用又返回到编译期。
(map #(macro-hello %) ["Brain" "Not Brian"])
;;("Hello, Brain!" "Hello, Not Brian!")
(map (fn [x] (square-macro x)) (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
;应该只在需要自己的语言组件时才使用宏:只有在函数满足不了需要的时候才去使用宏。
;宏的使用场景主要有:
;需要特殊的求值语义
;需要自定义的语法
;需要在编译期提前计算一些中间值
;宏卫生
;宏产生的代码通常会被嵌在外部代码中使用,而且我们通常也会把一段用户代码作为参数传入宏。
;在任何一种情况下,有一些符号已经被用户代码绑定到一个值了。那么就会有这样一种可能:
;在宏里面使用的某个符号名跟外部代码或者传入的用户自定义代码里面的某个符号名字可能会发生冲突,这样的问题是很难定位的。
(defmacro unhygienic
[& body]
`(let [x :oops]
~@body))
(unhygienic (println "x:" x))
;;CompilerException java.lang.RuntimeException: Can't let qualified name: user/x,
(macroexpand-1 '(unhygienic (println "x:" x)))
;;(clojure.core/let [user/x :oops] (println "x:" x))
;使用引述、反引述修复上述错误
(defmacro still-unhygienic
[& body]
`(let [~'x :oops]
~@body))
(still-unhygienic (println "x:" x))
;;x: :oops
;~'x是使用反引述~来强制使用没有命名空间限定的符号x作为let里面绑定的名字
(let [x :this-is-important]
(still-unhygienic
(println "x:" x)))
;;x: :oops
;上述代码已经把x绑定到一个本地的值了,但是由宏产生的let会悄悄地把x绑定到另外一个值。
;Gensym
;当要在宏里面建立一个本地绑定的时候,我们希望可以动态产生一个永远不会跟外部代码或用户传入宏的代码冲突的名字。
;gensym函数返回一个保证唯一的符号。每次调用它都能返回一个新的符号
(gensym)
;;G__40
(gensym)
;;G__43
;gensym也可以接受一个参数,这个参数作为产生的符号的前缀
(gensym "sym")
;;sym46
(gensym "sym")
;;sym49
(defmacro hygienic
[& body]
(let [sym (gensym)]
`(let [~sym :macro-value]
~@body)))
(let [x :important-value]
(hygienic (println "x:" x)))
;;x: :important-value
;在语法引述里面任何以#结尾的符号都会被自动扩展,并且对于前缀相同的符号,它们都会被扩展成同一个符号的名字。
;这个被称为“自动gensym”
(defmacro hygienic
[& body]
`(let [x# :macro-value]
~@body))
(let [x :important-value]
(hygienic (println "x:" x)))
;;x: :important-value
;在同一个语法引述的形式里面,对于同一个前缀的所有自动gensym,它们会被转换成同一个符号
`(x# x#)
;;(x__83__auto__ x__83__auto__)
;在一个语法引述形式里面可以对一个gensym进行多次引用,而且读起来写起来都非常自然
(defmacro auto-gensyms
[& numbers]
`(let [x# (rand-int 10)]
(+ x# ~@numbers)))
(auto-gensyms 1 2 3 4 5)
;;21
(auto-gensyms 1 2 3 4 5)
;;17
(macroexpand-1 '(auto-gensyms 1 2 3 4 5))
;;(clojure.core/let [x__86__auto__ (clojure.core/rand-int 10)] (clojure.core/+ x__86__auto__ 1 2 3 4 5))
;对于自动gensym,只能保证在同一个语法引述的形式里面所产生的符号的名字是一样的
[`x# `x#]
;;[x__104__auto__ x__105__auto__]
;让宏的用户来选择名字
;因为宏并不对传给它的参数进行求值,因此我们可以很简单地传一个符号给宏,然后在宏产生的代码里面使用这个符号
(defmacro with
[name & body]
`(let [~name 5]
~@body))
(with bar (+ 10 bar))
;;15
(with foo (+ 40 foo))
;;45
;重复求值
;使用宏时一个普遍而又隐蔽的问题是重复求值。
;重复求值发生在当传给宏的参数在宏的扩展形式里面出现多次的情况下
(defmacro spy [x]
`(do
(println "spied" '~x ~x)
~x))
(spy 2)
;;spied 2 2
;;2
(spy (rand-int 10))
;;spied (rand-int 10) 1
;;3
(macroexpand-1 '(spy (rand-int 10)))
;;(do (clojure.core/println "spied" (quote (rand-int 10)) (rand-int 10)) (rand-int 10))
;要避免这种问题,可以引入一个本地绑定
(defmacro spy [x]
`(let [x# ~x]
(println "spied" '~x x#)
x#))
(macroexpand-1 '(spy (rand-int 10)))
;;clojure.core/let [x__131__auto__ (rand-int 10)] (clojure.core/println "spied" (quote (rand-int 10)) x__131__auto__) x__131__auto__)
(spy (rand-int 10))
;;spied (rand-int 10) 4
;;4
;重复求值的问题,意味着你把有些应该在函数里面实现的逻辑写到宏里面去了。
(defn spy-helper [expr value]
(println expr value)
value)
(defmacro spy [x]
`(spy-helper '~x ~x))
(spy (rand-int 10))
;;(rand-int 10) 5
;;5
;隐藏参数 &env和&form
;defmacro宏引入了两个隐藏的本地绑定:&env和&form
;&env是一个map,map的key是当前上下文所有本地绑定的名字(而对应的值是未定义的)
;&form里面的元素是当前被宏扩展的整个形式,也就是说,它是一个包含了宏的名字(用户代码里面引用宏的名字——可能被重命名了)
;以及传给宏的所有参数的一个列表。这个形式也就是reader在读入宏的时候所读入的形式。
(defmacro info-about-caller
[]
(pprint {:form &form :env &env})
`(println "macro was called!"))
(info-about-caller)
;;{:form (info-about-caller), :env nil}
;;macro was called!
(let [foo "bar"] (info-about-caller))
;;{:form (info-about-caller),
;;:env {foo #<LocalBinding clojure.lang.Compiler$LocalBinding@3d8d5c99>}}
;;macro was called!
(let [foo "bar" baz "quux"] (info-about-caller))
;;{:form (info-about-caller),
;; :env
;; {baz #<LocalBinding clojure.lang.Compiler$LocalBinding@54892e69>,
;; foo #<LocalBinding clojure.lang.Compiler$LocalBinding@3b1160b9>}}
;;macro was called!
;The &env value seems pretty magical: it’s a map of local variables,
; where the keys are symbols and the values are instances of some class in the Clojure compiler internals
(defmacro inspect-caller-locals []
(->> (keys &env)
(map (fn [k] [`'~k k]))
(into {})))
(inspect-caller-locals)
;;{}
(let [foo "bar" baz "quux"] (inspect-caller-locals))
;;{baz "quux", foo "bar"}
(defmacro spy-env []
(let [ks (keys &env)]
`(prn (zipmap '~ks [~@ks]))))
(let [x 1 y 2]
(spy-env)
(+ x y))
;;{x 1, y 2}
;;3
;在宏里面打印有用的错误信息
(defmacro ontology
[& triples]
(every? #(or (== 3 (count %))
(throw (IllegalArgumentException. "must have 3 elements")))
triples)
;;todo
)
(ontology ["Boston" :capital-of])
;;IllegalArgumentException must have 3 elements user/ontology/fn--158 (NO_SOURCE_FILE:113)
(pst)
;;IllegalArgumentException must have 3 elements
;;user/ontology/fn--158 (NO_SOURCE_FILE:113)
;这里显示的行号113从用户的角度来说是不对的,它是抛异常位置相对宏的源码定义开始的行号,而不是调用这个宏的代码的行号
(defmacro ontology
[& triples]
(every? #(or (== 3 (count %))
(throw (IllegalArgumentException.
(format "'%s' provided to '%s' on line %s has < 3 elements"
%
(first &form)
(-> &form meta :line)))))
triples)
;;todo
)
(ontology ["Boston" :capital-of])
;;IllegalArgumentException '["Boston" :capital-of]' provided to 'ontology' on line 131 has < 3 elements user/ontology/fn--169 (NO_SOURCE_FILE:127)
;用户在一个命名空间里面引入这个宏的时候可能利用refer之类的函数对宏进行了重命名,
; 它可以避免从别的空间里面引入函数、宏的时候与当前空间里面的函数、宏的名字发生冲突
(ns com.edgar.macros)
(refer 'user :rename '{ontology triples})
(triples ["Boston" :capital-of])
;;IllegalArgumentException '["Boston" :capital-of]' provided to 'triples' on line 134 has < 3 elements user/ontology/fn--169 (NO_SOURCE_FILE:127)
;深入->和->>
(defn ensure-seq [x]
(if (seq? x) x (list x)))
(ensure-seq 'x)
;;(x)
(ensure-seq '(x))
;;(x)
(defn insert-second
"Insert x as the seconde item in seq y."
[x ys]
(let [ys (ensure-seq ys)]
(concat (list (first ys) x)
(rest ys))))
;可以利用引述和反引述来更简洁地编写这段代码。引述不只可以在宏里面使用
(defn insert-second
"Insert x as the seconde item in seq y."
[x ys]
(let [ys (ensure-seq ys)]
`(~(first ys) ~x ~@(rest ys))))
;也可以利用list*来写得更简洁
(defn insert-second
"Insert x as the seconde item in seq y."
[x ys]
(let [ys (ensure-seq ys)]
(list* (first ys) x (rest ys))))
(defmacro thread
"Thread x through successive forms."
([x] x)
([x form] (insert-second x form))
([x form & more] `(thread (thread ~x ~form) ~@more)))
(thread [1 2 3] (conj 4) reverse println)
;;(4 3 2 1)
(-> [1 2 3] (conj 4) reverse println)
;;(4 3 2 1)
;->>
;->>和->很类似,只是它是把前面一个form插入到后面一个form的最后一个元素的位置上,而不是第二个元素的位置上
;这个宏经常被用来对一个序列或者其他数据结构进行转换
(->> (range 10) (map inc) (reduce +))
;;55
| 118196 | (ns
^{:author edgar}
clojure_tutorial.macro.start
(require '(clojure [string :as str]
[walk :as walk])))
;(defmacro foreach [[sym coll] & body]
; `(loop [coll# ~coll]
; (when-let [[~sym & xs#] (seq coll#)]
; ~@body
; (recure xs#))))
;
;(foreach [x [1 2 3]]
; (println x))
(defmacro print-keyword [x]
`(println (keyword ~x)))
(print-keyword "foo")
;;foo
(defmacro reverse-it
[form]
(walk/postwalk #(if (symbol? %)
(symbol (str/reverse (name %)))
%)
form))
(reverse-it
(qesod [gra (egnar 5)]
(nltnirp (cni gra))))
;;1
;;2
;;3
;;4
;;5
;展开宏
(macroexpand-1 '(reverse-it
(qesod [gra (egnar 5)]
(nltnirp (cni gra)))))
;;(doseq [arg (range 5)] (println (inc arg)))
;macroexpand-1只会扩展宏一次,如果一个宏被扩展后还包含了对宏的调用的话,那么宏需要扩展多次
;如果宏扩展之后产生的是对另外一个宏的调用,而你想继续扩展这个宏到最顶级的形式不再是一个宏的话,使用macroexpand
(pprint (macroexpand '(reverse-it
(qesod [gra (egnar 5)]
(nltnirp (cni gra))))))
;完全宏扩展
;macroexpand-1和macroexpand都不会对嵌套的宏进行扩展。
(macroexpand '(cond a b c d))
;获得一个宏的彻底扩展
(walk/macroexpand-all '(cond a b c d))
;;(if a b (if c d nil))
;语法
;因为宏要返回Clojure数据结构,我们经常返回列表以表示进一步调用,
; 这个调用可能是对函数、特殊形式或者宏的调用。
(defmacro hello
[name]
(list 'println name))
(macroexpand '(hello "<NAME>"))
;;(println "<NAME>")
;引述和语法引述
;语法引述把无命名空间限定的符号求值成当前命名空间的符号
(def foo 123)
[foo (quote foo) 'foo `foo]
;;[123 foo foo user/foo]
;语法引述允许反引述:一个列表里面的某些元素可以被选择性地反引述,从而使得它们在语法引述的形式内被求值
;反引述与编接反引述
;在编写一个宏的骨架的时候,我们通常想保持列表里面的一些元素不进行求值,而另外一些元素则需要求值。
(list `map `println [foo])
;;(clojure.core/map clojure.core/println [123])
;一个更简短、更有可读性的办法是把整个列表进行语法引述,然后把其中那些需要求值的元素进行反引述
;可以通过~来反引述
`(map println [~foo])
;;(clojure.core/map clojure.core/println [123])
;反引述一个列表或者vector会把整个形式都反引述。
`(map println ~[foo])
;;(clojure.core/map clojure.core/println [123])
`(println ~(keyword (str foo)))
;;(clojure.core/println :123)
;引述
(def a 4)
'(1 2 3 a 5)
;;(1 2 3 a 5)
(list 1 2 3 a 5)
;;(1 2 3 4 5)
'a
;;a
;语法引述
(def a 4)
`(1 2 3 ~a 5)
;;(1 2 3 4 5)
`~a
;;4
'~a
;;(clojure.core/unquote a)
`~'a
;;a
`(1 2 3 '~a 5)
;;(1 2 3 (quote 4) 5)
`(1 2 3 (quote (clojure.core/unquote a)) 5)
;;(1 2 3 (quote 4) 5)
(def other-nums '(4 5 6 7))
`(1 2 3 ~other-nums 9 10)
;;(1 2 3 (4 5 6 7) 9 10)
`(1 2 3 ~@other-nums 9 10)
;;(1 2 3 4 5 6 7 9 10)
;有一个列表的形式,然后想把另外一个列表的内容解开加入到第一个列表里面去。
(let [defs '((def x 123)
(def y 456))]
(concat (list 'do) defs))
;;(do (def x 123) (def y 456))
;编接反引述操作符'@是一个更好的办法,它自动帮你做列表的链接
(let [defs '((def x 123)
(def y 456))]
`(do ~@defs))
;;(do (def x 123) (def y 456))
;一个接受多个形式作为“代码体”的宏大概是这样:
(defmacro foo
[& body]
`(do-something ~@body))
(macroexpand-1 '(foo (doseq [x (range 5)]
(println x))
:done))
;;(user/do-something (doseq [x (range 5)] (println x)) :done)
;宏的例子
(defmacro squares
[xs]
(list 'map '#(* % %) xs))
(squares (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
(defmacro squares2
[xs]
`(map #(* % %) ~xs))
(squares2 (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
(defmacro squares3
[xs]
`(map (fn [~'x] (* ~'x ~'x)) ~xs))
(squares3 (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
(defmacro make-adder
[x]
`(fn [~'y] (+ ~x ~'y)))
(macroexpand-1 '(make-adder 10))
;;(clojure.core/fn [y] (clojure.core/+ 10 y))
;什么时候使用宏
;宏是在编译期被调用的
(defn fn-hello [x]
(str "Hello, " x "!"))
(defmacro macro-hello [x]
`(str "Hello, " ~x "!"))
;它们在一些用法上表现是类似的
(fn-hello "<NAME>")
;;"Hello, <NAME>!"
(macro-hello "B<NAME>")
;;"Hello, <NAME>!"
;而在另外一些上下文中表现就不一样了
(map fn-hello ["Brain" "Not Brian"])
;;("Hello, Brain!" "Hello, Not Brian!")
(map macro-hello ["Brain" "Not Brian"])
;;CompilerException java.lang.RuntimeException: Can't take value of a macro:
;宏不能作为值来进行组合或者传递。宏根本就没有运行时值的概念。
(defn square
[x]
(* x x))
(map square (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
(defmacro square-macro
[x]
`(* ~x ~x))
(map square-macro (range 10))
;如果想在这种上下文里面使用宏,需要把宏包在一个fn或者匿名函数字面量里面。
;这使得宏的应用又返回到编译期。
(map #(macro-hello %) ["Brain" "Not Brian"])
;;("Hello, Brain!" "Hello, Not Brian!")
(map (fn [x] (square-macro x)) (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
;应该只在需要自己的语言组件时才使用宏:只有在函数满足不了需要的时候才去使用宏。
;宏的使用场景主要有:
;需要特殊的求值语义
;需要自定义的语法
;需要在编译期提前计算一些中间值
;宏卫生
;宏产生的代码通常会被嵌在外部代码中使用,而且我们通常也会把一段用户代码作为参数传入宏。
;在任何一种情况下,有一些符号已经被用户代码绑定到一个值了。那么就会有这样一种可能:
;在宏里面使用的某个符号名跟外部代码或者传入的用户自定义代码里面的某个符号名字可能会发生冲突,这样的问题是很难定位的。
(defmacro unhygienic
[& body]
`(let [x :oops]
~@body))
(unhygienic (println "x:" x))
;;CompilerException java.lang.RuntimeException: Can't let qualified name: user/x,
(macroexpand-1 '(unhygienic (println "x:" x)))
;;(clojure.core/let [user/x :oops] (println "x:" x))
;使用引述、反引述修复上述错误
(defmacro still-unhygienic
[& body]
`(let [~'x :oops]
~@body))
(still-unhygienic (println "x:" x))
;;x: :oops
;~'x是使用反引述~来强制使用没有命名空间限定的符号x作为let里面绑定的名字
(let [x :this-is-important]
(still-unhygienic
(println "x:" x)))
;;x: :oops
;上述代码已经把x绑定到一个本地的值了,但是由宏产生的let会悄悄地把x绑定到另外一个值。
;Gensym
;当要在宏里面建立一个本地绑定的时候,我们希望可以动态产生一个永远不会跟外部代码或用户传入宏的代码冲突的名字。
;gensym函数返回一个保证唯一的符号。每次调用它都能返回一个新的符号
(gensym)
;;G__40
(gensym)
;;G__43
;gensym也可以接受一个参数,这个参数作为产生的符号的前缀
(gensym "sym")
;;sym46
(gensym "sym")
;;sym49
(defmacro hygienic
[& body]
(let [sym (gensym)]
`(let [~sym :macro-value]
~@body)))
(let [x :important-value]
(hygienic (println "x:" x)))
;;x: :important-value
;在语法引述里面任何以#结尾的符号都会被自动扩展,并且对于前缀相同的符号,它们都会被扩展成同一个符号的名字。
;这个被称为“自动gensym”
(defmacro hygienic
[& body]
`(let [x# :macro-value]
~@body))
(let [x :important-value]
(hygienic (println "x:" x)))
;;x: :important-value
;在同一个语法引述的形式里面,对于同一个前缀的所有自动gensym,它们会被转换成同一个符号
`(x# x#)
;;(x__83__auto__ x__83__auto__)
;在一个语法引述形式里面可以对一个gensym进行多次引用,而且读起来写起来都非常自然
(defmacro auto-gensyms
[& numbers]
`(let [x# (rand-int 10)]
(+ x# ~@numbers)))
(auto-gensyms 1 2 3 4 5)
;;21
(auto-gensyms 1 2 3 4 5)
;;17
(macroexpand-1 '(auto-gensyms 1 2 3 4 5))
;;(clojure.core/let [x__86__auto__ (clojure.core/rand-int 10)] (clojure.core/+ x__86__auto__ 1 2 3 4 5))
;对于自动gensym,只能保证在同一个语法引述的形式里面所产生的符号的名字是一样的
[`x# `x#]
;;[x__104__auto__ x__105__auto__]
;让宏的用户来选择名字
;因为宏并不对传给它的参数进行求值,因此我们可以很简单地传一个符号给宏,然后在宏产生的代码里面使用这个符号
(defmacro with
[name & body]
`(let [~name 5]
~@body))
(with bar (+ 10 bar))
;;15
(with foo (+ 40 foo))
;;45
;重复求值
;使用宏时一个普遍而又隐蔽的问题是重复求值。
;重复求值发生在当传给宏的参数在宏的扩展形式里面出现多次的情况下
(defmacro spy [x]
`(do
(println "spied" '~x ~x)
~x))
(spy 2)
;;spied 2 2
;;2
(spy (rand-int 10))
;;spied (rand-int 10) 1
;;3
(macroexpand-1 '(spy (rand-int 10)))
;;(do (clojure.core/println "spied" (quote (rand-int 10)) (rand-int 10)) (rand-int 10))
;要避免这种问题,可以引入一个本地绑定
(defmacro spy [x]
`(let [x# ~x]
(println "spied" '~x x#)
x#))
(macroexpand-1 '(spy (rand-int 10)))
;;clojure.core/let [x__131__auto__ (rand-int 10)] (clojure.core/println "spied" (quote (rand-int 10)) x__131__auto__) x__131__auto__)
(spy (rand-int 10))
;;spied (rand-int 10) 4
;;4
;重复求值的问题,意味着你把有些应该在函数里面实现的逻辑写到宏里面去了。
(defn spy-helper [expr value]
(println expr value)
value)
(defmacro spy [x]
`(spy-helper '~x ~x))
(spy (rand-int 10))
;;(rand-int 10) 5
;;5
;隐藏参数 &env和&form
;defmacro宏引入了两个隐藏的本地绑定:&env和&form
;&env是一个map,map的key是当前上下文所有本地绑定的名字(而对应的值是未定义的)
;&form里面的元素是当前被宏扩展的整个形式,也就是说,它是一个包含了宏的名字(用户代码里面引用宏的名字——可能被重命名了)
;以及传给宏的所有参数的一个列表。这个形式也就是reader在读入宏的时候所读入的形式。
(defmacro info-about-caller
[]
(pprint {:form &form :env &env})
`(println "macro was called!"))
(info-about-caller)
;;{:form (info-about-caller), :env nil}
;;macro was called!
(let [foo "bar"] (info-about-caller))
;;{:form (info-about-caller),
;;:env {foo #<LocalBinding clojure.lang.Compiler$LocalBinding@3d8d5c99>}}
;;macro was called!
(let [foo "bar" baz "quux"] (info-about-caller))
;;{:form (info-about-caller),
;; :env
;; {baz #<LocalBinding clojure.lang.Compiler$LocalBinding@54892e69>,
;; foo #<LocalBinding clojure.lang.Compiler$LocalBinding@3b1160b9>}}
;;macro was called!
;The &env value seems pretty magical: it’s a map of local variables,
; where the keys are symbols and the values are instances of some class in the Clojure compiler internals
(defmacro inspect-caller-locals []
(->> (keys &env)
(map (fn [k] [`'~k k]))
(into {})))
(inspect-caller-locals)
;;{}
(let [foo "bar" baz "quux"] (inspect-caller-locals))
;;{baz "quux", foo "bar"}
(defmacro spy-env []
(let [ks (keys &env)]
`(prn (zipmap '~ks [~@ks]))))
(let [x 1 y 2]
(spy-env)
(+ x y))
;;{x 1, y 2}
;;3
;在宏里面打印有用的错误信息
(defmacro ontology
[& triples]
(every? #(or (== 3 (count %))
(throw (IllegalArgumentException. "must have 3 elements")))
triples)
;;todo
)
(ontology ["Boston" :capital-of])
;;IllegalArgumentException must have 3 elements user/ontology/fn--158 (NO_SOURCE_FILE:113)
(pst)
;;IllegalArgumentException must have 3 elements
;;user/ontology/fn--158 (NO_SOURCE_FILE:113)
;这里显示的行号113从用户的角度来说是不对的,它是抛异常位置相对宏的源码定义开始的行号,而不是调用这个宏的代码的行号
(defmacro ontology
[& triples]
(every? #(or (== 3 (count %))
(throw (IllegalArgumentException.
(format "'%s' provided to '%s' on line %s has < 3 elements"
%
(first &form)
(-> &form meta :line)))))
triples)
;;todo
)
(ontology ["Boston" :capital-of])
;;IllegalArgumentException '["Boston" :capital-of]' provided to 'ontology' on line 131 has < 3 elements user/ontology/fn--169 (NO_SOURCE_FILE:127)
;用户在一个命名空间里面引入这个宏的时候可能利用refer之类的函数对宏进行了重命名,
; 它可以避免从别的空间里面引入函数、宏的时候与当前空间里面的函数、宏的名字发生冲突
(ns com.edgar.macros)
(refer 'user :rename '{ontology triples})
(triples ["Boston" :capital-of])
;;IllegalArgumentException '["Boston" :capital-of]' provided to 'triples' on line 134 has < 3 elements user/ontology/fn--169 (NO_SOURCE_FILE:127)
;深入->和->>
(defn ensure-seq [x]
(if (seq? x) x (list x)))
(ensure-seq 'x)
;;(x)
(ensure-seq '(x))
;;(x)
(defn insert-second
"Insert x as the seconde item in seq y."
[x ys]
(let [ys (ensure-seq ys)]
(concat (list (first ys) x)
(rest ys))))
;可以利用引述和反引述来更简洁地编写这段代码。引述不只可以在宏里面使用
(defn insert-second
"Insert x as the seconde item in seq y."
[x ys]
(let [ys (ensure-seq ys)]
`(~(first ys) ~x ~@(rest ys))))
;也可以利用list*来写得更简洁
(defn insert-second
"Insert x as the seconde item in seq y."
[x ys]
(let [ys (ensure-seq ys)]
(list* (first ys) x (rest ys))))
(defmacro thread
"Thread x through successive forms."
([x] x)
([x form] (insert-second x form))
([x form & more] `(thread (thread ~x ~form) ~@more)))
(thread [1 2 3] (conj 4) reverse println)
;;(4 3 2 1)
(-> [1 2 3] (conj 4) reverse println)
;;(4 3 2 1)
;->>
;->>和->很类似,只是它是把前面一个form插入到后面一个form的最后一个元素的位置上,而不是第二个元素的位置上
;这个宏经常被用来对一个序列或者其他数据结构进行转换
(->> (range 10) (map inc) (reduce +))
;;55
| true | (ns
^{:author edgar}
clojure_tutorial.macro.start
(require '(clojure [string :as str]
[walk :as walk])))
;(defmacro foreach [[sym coll] & body]
; `(loop [coll# ~coll]
; (when-let [[~sym & xs#] (seq coll#)]
; ~@body
; (recure xs#))))
;
;(foreach [x [1 2 3]]
; (println x))
(defmacro print-keyword [x]
`(println (keyword ~x)))
(print-keyword "foo")
;;foo
(defmacro reverse-it
[form]
(walk/postwalk #(if (symbol? %)
(symbol (str/reverse (name %)))
%)
form))
(reverse-it
(qesod [gra (egnar 5)]
(nltnirp (cni gra))))
;;1
;;2
;;3
;;4
;;5
;展开宏
(macroexpand-1 '(reverse-it
(qesod [gra (egnar 5)]
(nltnirp (cni gra)))))
;;(doseq [arg (range 5)] (println (inc arg)))
;macroexpand-1只会扩展宏一次,如果一个宏被扩展后还包含了对宏的调用的话,那么宏需要扩展多次
;如果宏扩展之后产生的是对另外一个宏的调用,而你想继续扩展这个宏到最顶级的形式不再是一个宏的话,使用macroexpand
(pprint (macroexpand '(reverse-it
(qesod [gra (egnar 5)]
(nltnirp (cni gra))))))
;完全宏扩展
;macroexpand-1和macroexpand都不会对嵌套的宏进行扩展。
(macroexpand '(cond a b c d))
;获得一个宏的彻底扩展
(walk/macroexpand-all '(cond a b c d))
;;(if a b (if c d nil))
;语法
;因为宏要返回Clojure数据结构,我们经常返回列表以表示进一步调用,
; 这个调用可能是对函数、特殊形式或者宏的调用。
(defmacro hello
[name]
(list 'println name))
(macroexpand '(hello "PI:NAME:<NAME>END_PI"))
;;(println "PI:NAME:<NAME>END_PI")
;引述和语法引述
;语法引述把无命名空间限定的符号求值成当前命名空间的符号
(def foo 123)
[foo (quote foo) 'foo `foo]
;;[123 foo foo user/foo]
;语法引述允许反引述:一个列表里面的某些元素可以被选择性地反引述,从而使得它们在语法引述的形式内被求值
;反引述与编接反引述
;在编写一个宏的骨架的时候,我们通常想保持列表里面的一些元素不进行求值,而另外一些元素则需要求值。
(list `map `println [foo])
;;(clojure.core/map clojure.core/println [123])
;一个更简短、更有可读性的办法是把整个列表进行语法引述,然后把其中那些需要求值的元素进行反引述
;可以通过~来反引述
`(map println [~foo])
;;(clojure.core/map clojure.core/println [123])
;反引述一个列表或者vector会把整个形式都反引述。
`(map println ~[foo])
;;(clojure.core/map clojure.core/println [123])
`(println ~(keyword (str foo)))
;;(clojure.core/println :123)
;引述
(def a 4)
'(1 2 3 a 5)
;;(1 2 3 a 5)
(list 1 2 3 a 5)
;;(1 2 3 4 5)
'a
;;a
;语法引述
(def a 4)
`(1 2 3 ~a 5)
;;(1 2 3 4 5)
`~a
;;4
'~a
;;(clojure.core/unquote a)
`~'a
;;a
`(1 2 3 '~a 5)
;;(1 2 3 (quote 4) 5)
`(1 2 3 (quote (clojure.core/unquote a)) 5)
;;(1 2 3 (quote 4) 5)
(def other-nums '(4 5 6 7))
`(1 2 3 ~other-nums 9 10)
;;(1 2 3 (4 5 6 7) 9 10)
`(1 2 3 ~@other-nums 9 10)
;;(1 2 3 4 5 6 7 9 10)
;有一个列表的形式,然后想把另外一个列表的内容解开加入到第一个列表里面去。
(let [defs '((def x 123)
(def y 456))]
(concat (list 'do) defs))
;;(do (def x 123) (def y 456))
;编接反引述操作符'@是一个更好的办法,它自动帮你做列表的链接
(let [defs '((def x 123)
(def y 456))]
`(do ~@defs))
;;(do (def x 123) (def y 456))
;一个接受多个形式作为“代码体”的宏大概是这样:
(defmacro foo
[& body]
`(do-something ~@body))
(macroexpand-1 '(foo (doseq [x (range 5)]
(println x))
:done))
;;(user/do-something (doseq [x (range 5)] (println x)) :done)
;宏的例子
(defmacro squares
[xs]
(list 'map '#(* % %) xs))
(squares (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
(defmacro squares2
[xs]
`(map #(* % %) ~xs))
(squares2 (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
(defmacro squares3
[xs]
`(map (fn [~'x] (* ~'x ~'x)) ~xs))
(squares3 (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
(defmacro make-adder
[x]
`(fn [~'y] (+ ~x ~'y)))
(macroexpand-1 '(make-adder 10))
;;(clojure.core/fn [y] (clojure.core/+ 10 y))
;什么时候使用宏
;宏是在编译期被调用的
(defn fn-hello [x]
(str "Hello, " x "!"))
(defmacro macro-hello [x]
`(str "Hello, " ~x "!"))
;它们在一些用法上表现是类似的
(fn-hello "PI:NAME:<NAME>END_PI")
;;"Hello, PI:NAME:<NAME>END_PI!"
(macro-hello "BPI:NAME:<NAME>END_PI")
;;"Hello, PI:NAME:<NAME>END_PI!"
;而在另外一些上下文中表现就不一样了
(map fn-hello ["Brain" "Not Brian"])
;;("Hello, Brain!" "Hello, Not Brian!")
(map macro-hello ["Brain" "Not Brian"])
;;CompilerException java.lang.RuntimeException: Can't take value of a macro:
;宏不能作为值来进行组合或者传递。宏根本就没有运行时值的概念。
(defn square
[x]
(* x x))
(map square (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
(defmacro square-macro
[x]
`(* ~x ~x))
(map square-macro (range 10))
;如果想在这种上下文里面使用宏,需要把宏包在一个fn或者匿名函数字面量里面。
;这使得宏的应用又返回到编译期。
(map #(macro-hello %) ["Brain" "Not Brian"])
;;("Hello, Brain!" "Hello, Not Brian!")
(map (fn [x] (square-macro x)) (range 10))
;;(0 1 4 9 16 25 36 49 64 81)
;应该只在需要自己的语言组件时才使用宏:只有在函数满足不了需要的时候才去使用宏。
;宏的使用场景主要有:
;需要特殊的求值语义
;需要自定义的语法
;需要在编译期提前计算一些中间值
;宏卫生
;宏产生的代码通常会被嵌在外部代码中使用,而且我们通常也会把一段用户代码作为参数传入宏。
;在任何一种情况下,有一些符号已经被用户代码绑定到一个值了。那么就会有这样一种可能:
;在宏里面使用的某个符号名跟外部代码或者传入的用户自定义代码里面的某个符号名字可能会发生冲突,这样的问题是很难定位的。
(defmacro unhygienic
[& body]
`(let [x :oops]
~@body))
(unhygienic (println "x:" x))
;;CompilerException java.lang.RuntimeException: Can't let qualified name: user/x,
(macroexpand-1 '(unhygienic (println "x:" x)))
;;(clojure.core/let [user/x :oops] (println "x:" x))
;使用引述、反引述修复上述错误
(defmacro still-unhygienic
[& body]
`(let [~'x :oops]
~@body))
(still-unhygienic (println "x:" x))
;;x: :oops
;~'x是使用反引述~来强制使用没有命名空间限定的符号x作为let里面绑定的名字
(let [x :this-is-important]
(still-unhygienic
(println "x:" x)))
;;x: :oops
;上述代码已经把x绑定到一个本地的值了,但是由宏产生的let会悄悄地把x绑定到另外一个值。
;Gensym
;当要在宏里面建立一个本地绑定的时候,我们希望可以动态产生一个永远不会跟外部代码或用户传入宏的代码冲突的名字。
;gensym函数返回一个保证唯一的符号。每次调用它都能返回一个新的符号
(gensym)
;;G__40
(gensym)
;;G__43
;gensym也可以接受一个参数,这个参数作为产生的符号的前缀
(gensym "sym")
;;sym46
(gensym "sym")
;;sym49
(defmacro hygienic
[& body]
(let [sym (gensym)]
`(let [~sym :macro-value]
~@body)))
(let [x :important-value]
(hygienic (println "x:" x)))
;;x: :important-value
;在语法引述里面任何以#结尾的符号都会被自动扩展,并且对于前缀相同的符号,它们都会被扩展成同一个符号的名字。
;这个被称为“自动gensym”
(defmacro hygienic
[& body]
`(let [x# :macro-value]
~@body))
(let [x :important-value]
(hygienic (println "x:" x)))
;;x: :important-value
;在同一个语法引述的形式里面,对于同一个前缀的所有自动gensym,它们会被转换成同一个符号
`(x# x#)
;;(x__83__auto__ x__83__auto__)
;在一个语法引述形式里面可以对一个gensym进行多次引用,而且读起来写起来都非常自然
(defmacro auto-gensyms
[& numbers]
`(let [x# (rand-int 10)]
(+ x# ~@numbers)))
(auto-gensyms 1 2 3 4 5)
;;21
(auto-gensyms 1 2 3 4 5)
;;17
(macroexpand-1 '(auto-gensyms 1 2 3 4 5))
;;(clojure.core/let [x__86__auto__ (clojure.core/rand-int 10)] (clojure.core/+ x__86__auto__ 1 2 3 4 5))
;对于自动gensym,只能保证在同一个语法引述的形式里面所产生的符号的名字是一样的
[`x# `x#]
;;[x__104__auto__ x__105__auto__]
;让宏的用户来选择名字
;因为宏并不对传给它的参数进行求值,因此我们可以很简单地传一个符号给宏,然后在宏产生的代码里面使用这个符号
(defmacro with
[name & body]
`(let [~name 5]
~@body))
(with bar (+ 10 bar))
;;15
(with foo (+ 40 foo))
;;45
;重复求值
;使用宏时一个普遍而又隐蔽的问题是重复求值。
;重复求值发生在当传给宏的参数在宏的扩展形式里面出现多次的情况下
(defmacro spy [x]
`(do
(println "spied" '~x ~x)
~x))
(spy 2)
;;spied 2 2
;;2
(spy (rand-int 10))
;;spied (rand-int 10) 1
;;3
(macroexpand-1 '(spy (rand-int 10)))
;;(do (clojure.core/println "spied" (quote (rand-int 10)) (rand-int 10)) (rand-int 10))
;要避免这种问题,可以引入一个本地绑定
(defmacro spy [x]
`(let [x# ~x]
(println "spied" '~x x#)
x#))
(macroexpand-1 '(spy (rand-int 10)))
;;clojure.core/let [x__131__auto__ (rand-int 10)] (clojure.core/println "spied" (quote (rand-int 10)) x__131__auto__) x__131__auto__)
(spy (rand-int 10))
;;spied (rand-int 10) 4
;;4
;重复求值的问题,意味着你把有些应该在函数里面实现的逻辑写到宏里面去了。
(defn spy-helper [expr value]
(println expr value)
value)
(defmacro spy [x]
`(spy-helper '~x ~x))
(spy (rand-int 10))
;;(rand-int 10) 5
;;5
;隐藏参数 &env和&form
;defmacro宏引入了两个隐藏的本地绑定:&env和&form
;&env是一个map,map的key是当前上下文所有本地绑定的名字(而对应的值是未定义的)
;&form里面的元素是当前被宏扩展的整个形式,也就是说,它是一个包含了宏的名字(用户代码里面引用宏的名字——可能被重命名了)
;以及传给宏的所有参数的一个列表。这个形式也就是reader在读入宏的时候所读入的形式。
(defmacro info-about-caller
[]
(pprint {:form &form :env &env})
`(println "macro was called!"))
(info-about-caller)
;;{:form (info-about-caller), :env nil}
;;macro was called!
(let [foo "bar"] (info-about-caller))
;;{:form (info-about-caller),
;;:env {foo #<LocalBinding clojure.lang.Compiler$LocalBinding@3d8d5c99>}}
;;macro was called!
(let [foo "bar" baz "quux"] (info-about-caller))
;;{:form (info-about-caller),
;; :env
;; {baz #<LocalBinding clojure.lang.Compiler$LocalBinding@54892e69>,
;; foo #<LocalBinding clojure.lang.Compiler$LocalBinding@3b1160b9>}}
;;macro was called!
;The &env value seems pretty magical: it’s a map of local variables,
; where the keys are symbols and the values are instances of some class in the Clojure compiler internals
(defmacro inspect-caller-locals []
(->> (keys &env)
(map (fn [k] [`'~k k]))
(into {})))
(inspect-caller-locals)
;;{}
(let [foo "bar" baz "quux"] (inspect-caller-locals))
;;{baz "quux", foo "bar"}
(defmacro spy-env []
(let [ks (keys &env)]
`(prn (zipmap '~ks [~@ks]))))
(let [x 1 y 2]
(spy-env)
(+ x y))
;;{x 1, y 2}
;;3
;在宏里面打印有用的错误信息
(defmacro ontology
[& triples]
(every? #(or (== 3 (count %))
(throw (IllegalArgumentException. "must have 3 elements")))
triples)
;;todo
)
(ontology ["Boston" :capital-of])
;;IllegalArgumentException must have 3 elements user/ontology/fn--158 (NO_SOURCE_FILE:113)
(pst)
;;IllegalArgumentException must have 3 elements
;;user/ontology/fn--158 (NO_SOURCE_FILE:113)
;这里显示的行号113从用户的角度来说是不对的,它是抛异常位置相对宏的源码定义开始的行号,而不是调用这个宏的代码的行号
(defmacro ontology
[& triples]
(every? #(or (== 3 (count %))
(throw (IllegalArgumentException.
(format "'%s' provided to '%s' on line %s has < 3 elements"
%
(first &form)
(-> &form meta :line)))))
triples)
;;todo
)
(ontology ["Boston" :capital-of])
;;IllegalArgumentException '["Boston" :capital-of]' provided to 'ontology' on line 131 has < 3 elements user/ontology/fn--169 (NO_SOURCE_FILE:127)
;用户在一个命名空间里面引入这个宏的时候可能利用refer之类的函数对宏进行了重命名,
; 它可以避免从别的空间里面引入函数、宏的时候与当前空间里面的函数、宏的名字发生冲突
(ns com.edgar.macros)
(refer 'user :rename '{ontology triples})
(triples ["Boston" :capital-of])
;;IllegalArgumentException '["Boston" :capital-of]' provided to 'triples' on line 134 has < 3 elements user/ontology/fn--169 (NO_SOURCE_FILE:127)
;深入->和->>
(defn ensure-seq [x]
(if (seq? x) x (list x)))
(ensure-seq 'x)
;;(x)
(ensure-seq '(x))
;;(x)
(defn insert-second
"Insert x as the seconde item in seq y."
[x ys]
(let [ys (ensure-seq ys)]
(concat (list (first ys) x)
(rest ys))))
;可以利用引述和反引述来更简洁地编写这段代码。引述不只可以在宏里面使用
(defn insert-second
"Insert x as the seconde item in seq y."
[x ys]
(let [ys (ensure-seq ys)]
`(~(first ys) ~x ~@(rest ys))))
;也可以利用list*来写得更简洁
(defn insert-second
"Insert x as the seconde item in seq y."
[x ys]
(let [ys (ensure-seq ys)]
(list* (first ys) x (rest ys))))
(defmacro thread
"Thread x through successive forms."
([x] x)
([x form] (insert-second x form))
([x form & more] `(thread (thread ~x ~form) ~@more)))
(thread [1 2 3] (conj 4) reverse println)
;;(4 3 2 1)
(-> [1 2 3] (conj 4) reverse println)
;;(4 3 2 1)
;->>
;->>和->很类似,只是它是把前面一个form插入到后面一个form的最后一个元素的位置上,而不是第二个元素的位置上
;这个宏经常被用来对一个序列或者其他数据结构进行转换
(->> (range 10) (map inc) (reduce +))
;;55
|
[
{
"context": " by the first name. For\ninstance, if the array [\\\"Ken\\\" \\\"Anderson\\\"] is passed in,\nthe key \\\"AndersonK",
"end": 800,
"score": 0.9948668479919434,
"start": 797,
"tag": "NAME",
"value": "Ken"
},
{
"context": "first name. For\ninstance, if the array [\\\"Ken\\\" \\\"Anderson\\\"] is passed in,\nthe key \\\"AndersonKen\\\" is retur",
"end": 813,
"score": 0.9962763786315918,
"start": 805,
"tag": "NAME",
"value": "Anderson"
},
{
"context": "ay [\\\"Ken\\\" \\\"Anderson\\\"] is passed in,\nthe key \\\"AndersonKen\\\" is returned.\" \n [[first last]]\n (str last ",
"end": 849,
"score": 0.9516187906265259,
"start": 841,
"tag": "NAME",
"value": "Anderson"
},
{
"context": "n\\\" \\\"Anderson\\\"] is passed in,\nthe key \\\"AndersonKen\\\" is returned.\" \n [[first last]]\n (str last f",
"end": 850,
"score": 0.8487280011177063,
"start": 849,
"tag": "USERNAME",
"value": "K"
},
{
"context": "\\\" \\\"Anderson\\\"] is passed in,\nthe key \\\"AndersonKen\\\" is returned.\" \n [[first last]]\n (str last fir",
"end": 852,
"score": 0.7806262969970703,
"start": 850,
"tag": "NAME",
"value": "en"
},
{
"context": " words, if the input vector\nlooks like this:\n\n[[\\\"Ken\\\" \\\"Anderson\\\"] [\\\"Bilbo\\\" \\\"Baggins\\\"]]\n\nthen pr",
"end": 1291,
"score": 0.9978747963905334,
"start": 1288,
"tag": "NAME",
"value": "Ken"
},
{
"context": "if the input vector\nlooks like this:\n\n[[\\\"Ken\\\" \\\"Anderson\\\"] [\\\"Bilbo\\\" \\\"Baggins\\\"]]\n\nthen produce an outp",
"end": 1304,
"score": 0.9981521368026733,
"start": 1296,
"tag": "NAME",
"value": "Anderson"
},
{
"context": "ctor\nlooks like this:\n\n[[\\\"Ken\\\" \\\"Anderson\\\"] [\\\"Bilbo\\\" \\\"Baggins\\\"]]\n\nthen produce an output vector th",
"end": 1316,
"score": 0.768710196018219,
"start": 1311,
"tag": "NAME",
"value": "Bilbo"
},
{
"context": "ke this:\n\n[[\\\"Ken\\\" \\\"Anderson\\\"] [\\\"Bilbo\\\" \\\"Baggins\\\"]]\n\nthen produce an output vector that looks lik",
"end": 1328,
"score": 0.7077330350875854,
"start": 1324,
"tag": "NAME",
"value": "gins"
},
{
"context": "oduce an output vector that looks like this:\n\n[[\\\"AndersonKen\\\" [\\\"Ken\\\" \\\"Anderson\\\"]] [\\\"BagginsBilbo\\\" [\\",
"end": 1399,
"score": 0.8090614080429077,
"start": 1391,
"tag": "NAME",
"value": "Anderson"
},
{
"context": " output vector that looks like this:\n\n[[\\\"AndersonKen\\\" [\\\"Ken\\\" \\\"Anderson\\\"]] [\\\"BagginsBilbo\\\" [\\\"",
"end": 1400,
"score": 0.8190200924873352,
"start": 1399,
"tag": "USERNAME",
"value": "K"
},
{
"context": "output vector that looks like this:\n\n[[\\\"AndersonKen\\\" [\\\"Ken\\\" \\\"Anderson\\\"]] [\\\"BagginsBilbo\\\" [\\\"Bi",
"end": 1402,
"score": 0.6838715076446533,
"start": 1400,
"tag": "NAME",
"value": "en"
},
{
"context": "ector that looks like this:\n\n[[\\\"AndersonKen\\\" [\\\"Ken\\\" \\\"Anderson\\\"]] [\\\"BagginsBilbo\\\" [\\\"Bilbo\\\" \\\"B",
"end": 1411,
"score": 0.989281415939331,
"start": 1408,
"tag": "NAME",
"value": "Ken"
},
{
"context": "at looks like this:\n\n[[\\\"AndersonKen\\\" [\\\"Ken\\\" \\\"Anderson\\\"]] [\\\"BagginsBilbo\\\" [\\\"Bilbo\\\" \\\"Baggins\\\"]]]\"\n",
"end": 1424,
"score": 0.994593620300293,
"start": 1416,
"tag": "NAME",
"value": "Anderson"
},
{
"context": " words, if the input\nvector looks like this:\n\n[[\\\"AndersonKen\\\" [\\\"Ken\\\" \\\"Anderson\\\"]] [\\\"BagginsBilbo\\\" [\\",
"end": 1784,
"score": 0.6301484107971191,
"start": 1776,
"tag": "NAME",
"value": "Anderson"
},
{
"context": "if the input\nvector looks like this:\n\n[[\\\"AndersonKen\\\" [\\\"Ken\\\" \\\"Anderson\\\"]] [\\\"BagginsBilbo\\\" [\\\"",
"end": 1785,
"score": 0.813798725605011,
"start": 1784,
"tag": "USERNAME",
"value": "K"
},
{
"context": "f the input\nvector looks like this:\n\n[[\\\"AndersonKen\\\" [\\\"Ken\\\" \\\"Anderson\\\"]] [\\\"BagginsBilbo\\\" [\\\"Bi",
"end": 1787,
"score": 0.6125531792640686,
"start": 1785,
"tag": "NAME",
"value": "en"
},
{
"context": "put\nvector looks like this:\n\n[[\\\"AndersonKen\\\" [\\\"Ken\\\" \\\"Anderson\\\"]] [\\\"BagginsBilbo\\\" [\\\"Bilbo\\\" \\\"B",
"end": 1796,
"score": 0.9415902495384216,
"start": 1793,
"tag": "NAME",
"value": "Ken"
},
{
"context": "or looks like this:\n\n[[\\\"AndersonKen\\\" [\\\"Ken\\\" \\\"Anderson\\\"]] [\\\"BagginsBilbo\\\" [\\\"Bilbo\\\" \\\"Baggins\\\"]]]\n\n",
"end": 1809,
"score": 0.9993125200271606,
"start": 1801,
"tag": "NAME",
"value": "Anderson"
},
{
"context": "is:\n\n[[\\\"AndersonKen\\\" [\\\"Ken\\\" \\\"Anderson\\\"]] [\\\"BagginsBilbo\\\" [\\\"Bilbo\\\" \\\"Baggins\\\"]]]\n\nthen produce an outp",
"end": 1829,
"score": 0.9810343384742737,
"start": 1817,
"tag": "NAME",
"value": "BagginsBilbo"
},
{
"context": "en\\\" [\\\"Ken\\\" \\\"Anderson\\\"]] [\\\"BagginsBilbo\\\" [\\\"Bilbo\\\" \\\"Baggins\\\"]]]\n\nthen produce an output vector t",
"end": 1840,
"score": 0.9347173571586609,
"start": 1835,
"tag": "NAME",
"value": "Bilbo"
},
{
"context": " \\\"Anderson\\\"]] [\\\"BagginsBilbo\\\" [\\\"Bilbo\\\" \\\"Baggins\\\"]]]\n\nthen produce an output vector that looks li",
"end": 1852,
"score": 0.9561329483985901,
"start": 1848,
"tag": "NAME",
"value": "gins"
},
{
"context": "oduce an output vector that looks like this:\n\n[[\\\"Ken\\\" \\\"Anderson\\\"] [\\\"Bilbo\\\" \\\"Baggins\\\"]]\"\n [sort",
"end": 1919,
"score": 0.999370813369751,
"start": 1916,
"tag": "NAME",
"value": "Ken"
},
{
"context": " output vector that looks like this:\n\n[[\\\"Ken\\\" \\\"Anderson\\\"] [\\\"Bilbo\\\" \\\"Baggins\\\"]]\"\n [sorted-names]\n (",
"end": 1932,
"score": 0.9993694424629211,
"start": 1924,
"tag": "NAME",
"value": "Anderson"
},
{
"context": "that looks like this:\n\n[[\\\"Ken\\\" \\\"Anderson\\\"] [\\\"Bilbo\\\" \\\"Baggins\\\"]]\"\n [sorted-names]\n (map (fn [[ke",
"end": 1944,
"score": 0.9982330799102783,
"start": 1939,
"tag": "NAME",
"value": "Bilbo"
},
{
"context": " like this:\n\n[[\\\"Ken\\\" \\\"Anderson\\\"] [\\\"Bilbo\\\" \\\"Baggins\\\"]]\"\n [sorted-names]\n (map (fn [[key name]] nam",
"end": 1956,
"score": 0.9924051761627197,
"start": 1949,
"tag": "NAME",
"value": "Baggins"
},
{
"context": ". Thus,\nif the input vector looks like this:\n\n[[\\\"Ken\\\" \\\"Anderson\\\"] [\\\"Bilbo\\\" \\\"Baggins\\\"]]\n\nthen pr",
"end": 2409,
"score": 0.9994332790374756,
"start": 2406,
"tag": "NAME",
"value": "Ken"
},
{
"context": "if the input vector looks like this:\n\n[[\\\"Ken\\\" \\\"Anderson\\\"] [\\\"Bilbo\\\" \\\"Baggins\\\"]]\n\nthen produce an outp",
"end": 2422,
"score": 0.9990095496177673,
"start": 2414,
"tag": "NAME",
"value": "Anderson"
},
{
"context": "ctor looks like this:\n\n[[\\\"Ken\\\" \\\"Anderson\\\"] [\\\"Bilbo\\\" \\\"Baggins\\\"]]\n\nthen produce an output string th",
"end": 2434,
"score": 0.998303234577179,
"start": 2429,
"tag": "NAME",
"value": "Bilbo"
},
{
"context": " like this:\n\n[[\\\"Ken\\\" \\\"Anderson\\\"] [\\\"Bilbo\\\" \\\"Baggins\\\"]]\n\nthen produce an output string that looks lik",
"end": 2446,
"score": 0.9337866902351379,
"start": 2439,
"tag": "NAME",
"value": "Baggins"
},
{
"context": "produce an output string that looks like this:\n\n\\\"Ken Anderson\\\\nBilbo Baggins\\\\n\\\"\"\n [sorted-names]\n ",
"end": 2510,
"score": 0.9990633726119995,
"start": 2507,
"tag": "NAME",
"value": "Ken"
},
{
"context": "duce an output string that looks like this:\n\n\\\"Ken Anderson\\\\nBilbo Baggins\\\\n\\\"\"\n [sorted-names]\n (reduce\n",
"end": 2519,
"score": 0.847231388092041,
"start": 2511,
"tag": "NAME",
"value": "Anderson"
},
{
"context": "put string that looks like this:\n\n\\\"Ken Anderson\\\\nBilbo Baggins\\\\n\\\"\"\n [sorted-names]\n (reduce\n (fn ",
"end": 2527,
"score": 0.953373908996582,
"start": 2521,
"tag": "NAME",
"value": "nBilbo"
},
{
"context": "ring that looks like this:\n\n\\\"Ken Anderson\\\\nBilbo Baggins\\\\n\\\"\"\n [sorted-names]\n (reduce\n (fn [content",
"end": 2535,
"score": 0.8673158288002014,
"start": 2528,
"tag": "NAME",
"value": "Baggins"
}
] | src/sort_names/core.clj | kenbod/sort_names | 0 | (ns sort-names.core)
(defn read-file
"Returns the contents of file f as a string."
[f]
(slurp f))
(defn lines
"Splits a string by line endings and returns a sequence of lines."
[body]
(clojure.string/split-lines body))
(defn parts
"
Takes a sequence of strings containing first and last names
and returns a sequence of vectors with the names split into
separate entries."
[lines]
(map #(clojure.string/split % #" ") lines))
(defn names
"
Reads the file and splits it into lines. Each line is then split
into an array containing the first and last name."
[file]
(parts (lines (read-file file))))
(defn get-key
"
Given a vector containing a first and last name, create a string
that lists the last name first followed by the first name. For
instance, if the array [\"Ken\" \"Anderson\"] is passed in,
the key \"AndersonKen\" is returned."
[[first last]]
(str last first))
(defn prepare-names
"
Given a vector of names where each name is itself a vector containing
a first name and a last name, transform the input vector such that
the output vector is a sequence of vectors where each vector has
a key as its first element and a vector containing a first and
last name as its second element. In other words, if the input vector
looks like this:
[[\"Ken\" \"Anderson\"] [\"Bilbo\" \"Baggins\"]]
then produce an output vector that looks like this:
[[\"AndersonKen\" [\"Ken\" \"Anderson\"]] [\"BagginsBilbo\" [\"Bilbo\" \"Baggins\"]]]"
[names]
(map (fn [name] [(get-key name) name]) names))
(defn extract-names
"
Given an input vector in the format produced by prepare-names,
produce an output vector where each element is simply a vector
containing a first and last name. In other words, if the input
vector looks like this:
[[\"AndersonKen\" [\"Ken\" \"Anderson\"]] [\"BagginsBilbo\" [\"Bilbo\" \"Baggins\"]]]
then produce an output vector that looks like this:
[[\"Ken\" \"Anderson\"] [\"Bilbo\" \"Baggins\"]]"
[sorted-names]
(map (fn [[key name]] name) sorted-names))
(defn process
"Process knits the functions above to sort the names."
[names]
(extract-names (sort (prepare-names names))))
(defn create-string
"
Given an input vector in the format produced by extract-names,
produce a single string where each name appears on its own
line and each line is separated by a new line character. Thus,
if the input vector looks like this:
[[\"Ken\" \"Anderson\"] [\"Bilbo\" \"Baggins\"]]
then produce an output string that looks like this:
\"Ken Anderson\\nBilbo Baggins\\n\""
[sorted-names]
(reduce
(fn [contents [first last]] (str contents first " " last "\n"))
""
sorted-names))
(defn sort-names
"
The main program:
1. Determine the input and output file names.
2. Read the names into a sequence of vectors of first and last names.
3. Prepare the names, sort them, and then extract the sorted names.
4. Create an output string.
5. Write the output string to disk and print a message that we're done."
[args]
(def input-name (first args))
(def output-name (first (rest args)))
(def items (names input-name))
(def sorted (process items))
(def output (create-string sorted))
(spit output-name output)
(println (str "Wrote sorted names to \"" output-name "\"")))
(defn -main
"Pass the arguments to sort-names. Time the whole operation."
[& args]
(time (sort-names args)))
| 47931 | (ns sort-names.core)
(defn read-file
"Returns the contents of file f as a string."
[f]
(slurp f))
(defn lines
"Splits a string by line endings and returns a sequence of lines."
[body]
(clojure.string/split-lines body))
(defn parts
"
Takes a sequence of strings containing first and last names
and returns a sequence of vectors with the names split into
separate entries."
[lines]
(map #(clojure.string/split % #" ") lines))
(defn names
"
Reads the file and splits it into lines. Each line is then split
into an array containing the first and last name."
[file]
(parts (lines (read-file file))))
(defn get-key
"
Given a vector containing a first and last name, create a string
that lists the last name first followed by the first name. For
instance, if the array [\"<NAME>\" \"<NAME>\"] is passed in,
the key \"<NAME>K<NAME>\" is returned."
[[first last]]
(str last first))
(defn prepare-names
"
Given a vector of names where each name is itself a vector containing
a first name and a last name, transform the input vector such that
the output vector is a sequence of vectors where each vector has
a key as its first element and a vector containing a first and
last name as its second element. In other words, if the input vector
looks like this:
[[\"<NAME>\" \"<NAME>\"] [\"<NAME>\" \"Bag<NAME>\"]]
then produce an output vector that looks like this:
[[\"<NAME>K<NAME>\" [\"<NAME>\" \"<NAME>\"]] [\"BagginsBilbo\" [\"Bilbo\" \"Baggins\"]]]"
[names]
(map (fn [name] [(get-key name) name]) names))
(defn extract-names
"
Given an input vector in the format produced by prepare-names,
produce an output vector where each element is simply a vector
containing a first and last name. In other words, if the input
vector looks like this:
[[\"<NAME>K<NAME>\" [\"<NAME>\" \"<NAME>\"]] [\"<NAME>\" [\"<NAME>\" \"Bag<NAME>\"]]]
then produce an output vector that looks like this:
[[\"<NAME>\" \"<NAME>\"] [\"<NAME>\" \"<NAME>\"]]"
[sorted-names]
(map (fn [[key name]] name) sorted-names))
(defn process
"Process knits the functions above to sort the names."
[names]
(extract-names (sort (prepare-names names))))
(defn create-string
"
Given an input vector in the format produced by extract-names,
produce a single string where each name appears on its own
line and each line is separated by a new line character. Thus,
if the input vector looks like this:
[[\"<NAME>\" \"<NAME>\"] [\"<NAME>\" \"<NAME>\"]]
then produce an output string that looks like this:
\"<NAME> <NAME>\\<NAME> <NAME>\\n\""
[sorted-names]
(reduce
(fn [contents [first last]] (str contents first " " last "\n"))
""
sorted-names))
(defn sort-names
"
The main program:
1. Determine the input and output file names.
2. Read the names into a sequence of vectors of first and last names.
3. Prepare the names, sort them, and then extract the sorted names.
4. Create an output string.
5. Write the output string to disk and print a message that we're done."
[args]
(def input-name (first args))
(def output-name (first (rest args)))
(def items (names input-name))
(def sorted (process items))
(def output (create-string sorted))
(spit output-name output)
(println (str "Wrote sorted names to \"" output-name "\"")))
(defn -main
"Pass the arguments to sort-names. Time the whole operation."
[& args]
(time (sort-names args)))
| true | (ns sort-names.core)
(defn read-file
"Returns the contents of file f as a string."
[f]
(slurp f))
(defn lines
"Splits a string by line endings and returns a sequence of lines."
[body]
(clojure.string/split-lines body))
(defn parts
"
Takes a sequence of strings containing first and last names
and returns a sequence of vectors with the names split into
separate entries."
[lines]
(map #(clojure.string/split % #" ") lines))
(defn names
"
Reads the file and splits it into lines. Each line is then split
into an array containing the first and last name."
[file]
(parts (lines (read-file file))))
(defn get-key
"
Given a vector containing a first and last name, create a string
that lists the last name first followed by the first name. For
instance, if the array [\"PI:NAME:<NAME>END_PI\" \"PI:NAME:<NAME>END_PI\"] is passed in,
the key \"PI:NAME:<NAME>END_PIKPI:NAME:<NAME>END_PI\" is returned."
[[first last]]
(str last first))
(defn prepare-names
"
Given a vector of names where each name is itself a vector containing
a first name and a last name, transform the input vector such that
the output vector is a sequence of vectors where each vector has
a key as its first element and a vector containing a first and
last name as its second element. In other words, if the input vector
looks like this:
[[\"PI:NAME:<NAME>END_PI\" \"PI:NAME:<NAME>END_PI\"] [\"PI:NAME:<NAME>END_PI\" \"BagPI:NAME:<NAME>END_PI\"]]
then produce an output vector that looks like this:
[[\"PI:NAME:<NAME>END_PIKPI:NAME:<NAME>END_PI\" [\"PI:NAME:<NAME>END_PI\" \"PI:NAME:<NAME>END_PI\"]] [\"BagginsBilbo\" [\"Bilbo\" \"Baggins\"]]]"
[names]
(map (fn [name] [(get-key name) name]) names))
(defn extract-names
"
Given an input vector in the format produced by prepare-names,
produce an output vector where each element is simply a vector
containing a first and last name. In other words, if the input
vector looks like this:
[[\"PI:NAME:<NAME>END_PIKPI:NAME:<NAME>END_PI\" [\"PI:NAME:<NAME>END_PI\" \"PI:NAME:<NAME>END_PI\"]] [\"PI:NAME:<NAME>END_PI\" [\"PI:NAME:<NAME>END_PI\" \"BagPI:NAME:<NAME>END_PI\"]]]
then produce an output vector that looks like this:
[[\"PI:NAME:<NAME>END_PI\" \"PI:NAME:<NAME>END_PI\"] [\"PI:NAME:<NAME>END_PI\" \"PI:NAME:<NAME>END_PI\"]]"
[sorted-names]
(map (fn [[key name]] name) sorted-names))
(defn process
"Process knits the functions above to sort the names."
[names]
(extract-names (sort (prepare-names names))))
(defn create-string
"
Given an input vector in the format produced by extract-names,
produce a single string where each name appears on its own
line and each line is separated by a new line character. Thus,
if the input vector looks like this:
[[\"PI:NAME:<NAME>END_PI\" \"PI:NAME:<NAME>END_PI\"] [\"PI:NAME:<NAME>END_PI\" \"PI:NAME:<NAME>END_PI\"]]
then produce an output string that looks like this:
\"PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI\\PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI\\n\""
[sorted-names]
(reduce
(fn [contents [first last]] (str contents first " " last "\n"))
""
sorted-names))
(defn sort-names
"
The main program:
1. Determine the input and output file names.
2. Read the names into a sequence of vectors of first and last names.
3. Prepare the names, sort them, and then extract the sorted names.
4. Create an output string.
5. Write the output string to disk and print a message that we're done."
[args]
(def input-name (first args))
(def output-name (first (rest args)))
(def items (names input-name))
(def sorted (process items))
(def output (create-string sorted))
(spit output-name output)
(println (str "Wrote sorted names to \"" output-name "\"")))
(defn -main
"Pass the arguments to sort-names. Time the whole operation."
[& args]
(time (sort-names args)))
|
[
{
"context": " :user_id (mt/user->id :crowberto)\n :model ",
"end": 1686,
"score": 0.9979169964790344,
"start": 1677,
"tag": "USERNAME",
"value": "crowberto"
},
{
"context": " :name \"Bwahahaha\"}\n :times",
"end": 1968,
"score": 0.9972118735313416,
"start": 1959,
"tag": "NAME",
"value": "Bwahahaha"
},
{
"context": "temp* [Card [card1 {:name \"rand-name\"\n :creato",
"end": 4352,
"score": 0.8422159552574158,
"start": 4348,
"tag": "NAME",
"value": "rand"
},
{
"context": " [Card [card1 {:name \"rand-name\"\n :creator_id ",
"end": 4357,
"score": 0.4832025468349457,
"start": 4353,
"tag": "NAME",
"value": "name"
},
{
"context": " Dashboard [dash1 {:name \"rand-name\"\n :descri",
"end": 4631,
"score": 0.561441957950592,
"start": 4627,
"tag": "NAME",
"value": "rand"
},
{
"context": " Card [card2 {:name \"rand-name\"\n :creato",
"end": 4840,
"score": 0.8569685220718384,
"start": 4836,
"tag": "NAME",
"value": "rand"
},
{
"context": " (:id card1))\n (create-view! (mt/user->id :crowberto) \"card\" 36478)\n (create-view! (mt/us",
"end": 5306,
"score": 0.4713277220726013,
"start": 5303,
"tag": "NAME",
"value": "row"
},
{
"context": " 1\n :user_id (mt/user->id :crowberto)\n :model \"dashboard\"\n ",
"end": 5925,
"score": 0.4886690378189087,
"start": 5917,
"tag": "NAME",
"value": "rowberto"
},
{
"context": " 1\n :user_id (mt/user->id :crowberto)\n :model \"card\"\n :",
"end": 6309,
"score": 0.9656141996383667,
"start": 6301,
"tag": "USERNAME",
"value": "rowberto"
},
{
"context": "ad the activity\"\n (mt/with-test-user :crowberto\n (is (models/can-read? activity",
"end": 10627,
"score": 0.5449908971786499,
"start": 10624,
"tag": "USERNAME",
"value": "row"
}
] | c#-metabase/test/metabase/api/activity_test.clj | hanakhry/Crime_Admin | 0 | (ns metabase.api.activity-test
"Tests for /api/activity endpoints."
(:require [clojure.test :refer :all]
[metabase.api.activity :as activity-api]
[metabase.db :as mdb]
[metabase.models.activity :refer [Activity]]
[metabase.models.card :refer [Card]]
[metabase.models.dashboard :refer [Dashboard]]
[metabase.models.interface :as models]
[metabase.models.view-log :refer [ViewLog]]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
[toucan.db :as db]))
(use-fixtures :once (fixtures/initialize :db))
;; GET /
;; Things we are testing for:
;; 1. ordered by timestamp DESC
;; 2. :user and :model_exists are hydrated
(def ^:private activity-defaults
{:model_exists false
:database_id nil
:database nil
:table_id nil
:table nil
:custom_id nil})
(defn- activity-user-info [user-kw]
(merge
{:id (mt/user->id user-kw)}
(select-keys
(mt/fetch-user user-kw)
[:common_name :date_joined :email :first_name :is_qbnewb :is_superuser :last_login :last_name :locale])))
;; NOTE: timestamp matching was being a real PITA so I cheated a bit. ideally we'd fix that
(deftest activity-list-test
(testing "GET /api/activity"
(mt/with-temp* [Activity [activity1 {:topic "install"
:details {}
:timestamp #t "2015-09-09T12:13:14.888Z[UTC]"}]
Activity [activity2 {:topic "dashboard-create"
:user_id (mt/user->id :crowberto)
:model "dashboard"
:model_id 1234
:details {:description "Because I can!"
:name "Bwahahaha"}
:timestamp #t "2015-09-10T18:53:01.632Z[UTC]"}]
Activity [activity3 {:topic "user-joined"
:user_id (mt/user->id :rasta)
:model "user"
:details {}
:timestamp #t "2015-09-10T05:33:43.641Z[UTC]"}]]
(letfn [(fetch-activity [activity]
(merge
activity-defaults
(db/select-one [Activity :id :user_id :details :model :model_id] :id (u/the-id activity))))]
(is (= [(merge
(fetch-activity activity2)
{:topic "dashboard-create"
:user (activity-user-info :crowberto)})
(merge
(fetch-activity activity3)
{:topic "user-joined"
:user (activity-user-info :rasta)})
(merge
(fetch-activity activity1)
{:topic "install"
:user_id nil
:user nil})]
;; remove other activities from the API response just in case -- we're not interested in those
(let [these-activity-ids (set (map u/the-id [activity1 activity2 activity3]))]
(for [activity (mt/user-http-request :crowberto :get 200 "activity")
:when (contains? these-activity-ids (u/the-id activity))]
(dissoc activity :timestamp)))))))))
;;; GET /recent_views
;; Things we are testing for:
;; 1. ordering is sorted by most recent
;; 2. results are filtered to current user
;; 3. `:model_object` is hydrated in each result
;; 4. we filter out entries where `:model_object` is nil (object doesn't exist)
(defn- create-view! [user model model-id]
(db/insert! ViewLog
:user_id user
:model model
:model_id model-id
:timestamp :%now)
;; we sleep a bit to ensure no events have the same timestamp
;; sadly, MySQL doesn't support milliseconds so we have to wait a second
;; otherwise our records are out of order and this test fails :(
(Thread/sleep (if (= (mdb/db-type) :mysql)
1000
10)))
(deftest recent-views-test
(mt/with-temp* [Card [card1 {:name "rand-name"
:creator_id (mt/user->id :crowberto)
:display "table"
:visualization_settings {}}]
Dashboard [dash1 {:name "rand-name"
:description "rand-name"
:creator_id (mt/user->id :crowberto)}]
Card [card2 {:name "rand-name"
:creator_id (mt/user->id :crowberto)
:display "table"
:visualization_settings {}}]]
(create-view! (mt/user->id :crowberto) "card" (:id card2))
(create-view! (mt/user->id :crowberto) "dashboard" (:id dash1))
(create-view! (mt/user->id :crowberto) "card" (:id card1))
(create-view! (mt/user->id :crowberto) "card" 36478)
(create-view! (mt/user->id :rasta) "card" (:id card1))
(is (= [{:cnt 1
:user_id (mt/user->id :crowberto)
:model "card"
:model_id (:id card1)
:model_object {:id (:id card1)
:name (:name card1)
:collection_id nil
:description (:description card1)
:display (name (:display card1))}}
{:cnt 1
:user_id (mt/user->id :crowberto)
:model "dashboard"
:model_id (:id dash1)
:model_object {:id (:id dash1)
:name (:name dash1)
:collection_id nil
:description (:description dash1)}}
{:cnt 1
:user_id (mt/user->id :crowberto)
:model "card"
:model_id (:id card2)
:model_object {:id (:id card2)
:name (:name card2)
:collection_id nil
:description (:description card2)
:display (name (:display card2))}}]
(for [recent-view (mt/user-http-request :crowberto :get 200 "activity/recent_views")]
(dissoc recent-view :max_ts))))))
;;; activities->referenced-objects, referenced-objects->existing-objects, add-model-exists-info
(def ^:private fake-activities
[{:model "dashboard", :model_id 43, :topic :dashboard-create, :details {}}
{:model "dashboard", :model_id 42, :topic :dashboard-create, :details {}}
{:model "card", :model_id 114, :topic :card-create, :details {}}
{:model "card", :model_id 113, :topic :card-create, :details {}}
{:model "card", :model_id 112, :topic :card-create, :details {}}
{:model "card", :model_id 111, :topic :card-create, :details {}}
{:model "dashboard", :model_id 41, :topic :dashboard-add-cards, :details {:dashcards [{:card_id 109}]}}
{:model "card", :model_id 109, :topic :card-create, :details {}}
{:model "dashboard", :model_id 41, :topic :dashboard-add-cards, :details {:dashcards [{:card_id 108}]}}
{:model "dashboard", :model_id 41, :topic :dashboard-create, :details {}}
{:model "card", :model_id 108, :topic :card-create, :details {}}
{:model "user", :model_id 90, :topic :user-joined, :details {}}
{:model nil, :model_id nil, :topic :install, :details {}}])
(deftest activities->referenced-objects-test
(is (= {"dashboard" #{41 43 42}
"card" #{113 108 109 111 112 114}
"user" #{90}}
(#'activity-api/activities->referenced-objects fake-activities))))
(deftest referenced-objects->existing-objects-test
(mt/with-temp Dashboard [{dashboard-id :id}]
(is (= {"dashboard" #{dashboard-id}, "card" nil}
(#'activity-api/referenced-objects->existing-objects {"dashboard" #{dashboard-id 0}
"card" #{0}})))))
(deftest add-model-exists-info-test
(mt/with-temp* [Dashboard [{dashboard-id :id}]
Card [{card-id :id}]]
(is (= [{:model "dashboard", :model_id dashboard-id, :model_exists true}
{:model "card", :model_id 0, :model_exists false}
{:model "dashboard"
:model_id 0
:model_exists false
:topic :dashboard-remove-cards
:details {:dashcards [{:card_id card-id, :exists true}
{:card_id 0, :exists false}]}}]
(#'activity-api/add-model-exists-info [{:model "dashboard", :model_id dashboard-id}
{:model "card", :model_id 0}
{:model "dashboard"
:model_id 0
:topic :dashboard-remove-cards
:details {:dashcards [{:card_id card-id}
{:card_id 0}]}}])))))
(deftest activity-visibility-test
;; clear out all existing Activity entries
;;
;; TODO -- this is a bad pattern -- test shouldn't wipe out a bunch of other stuff like this. Just fetch all the
;; activities and look for the presence of this specific one.
(db/delete! Activity)
(mt/with-temp Activity [activity {:topic "user-joined"
:details {}
:timestamp #t "2019-02-15T11:55:00.000Z"}]
(letfn [(user-can-see-user-joined-activity? [user]
(seq (mt/user-http-request user :get 200 "activity")))]
(testing "Only admins should get to see user-joined activities"
(testing "admin should see `:user-joined` activities"
(testing "Sanity check: admin should be able to read the activity"
(mt/with-test-user :crowberto
(is (models/can-read? activity))))
(is (user-can-see-user-joined-activity? :crowberto)))
(testing "non-admin should *not* see `:user-joined` activities"
(testing "Sanity check: non-admin should *not* be able to read the activity"
(mt/with-test-user :rasta
(is (not (models/can-read? activity)))))
(is (not (user-can-see-user-joined-activity? :rasta))))))))
| 78405 | (ns metabase.api.activity-test
"Tests for /api/activity endpoints."
(:require [clojure.test :refer :all]
[metabase.api.activity :as activity-api]
[metabase.db :as mdb]
[metabase.models.activity :refer [Activity]]
[metabase.models.card :refer [Card]]
[metabase.models.dashboard :refer [Dashboard]]
[metabase.models.interface :as models]
[metabase.models.view-log :refer [ViewLog]]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
[toucan.db :as db]))
(use-fixtures :once (fixtures/initialize :db))
;; GET /
;; Things we are testing for:
;; 1. ordered by timestamp DESC
;; 2. :user and :model_exists are hydrated
(def ^:private activity-defaults
{:model_exists false
:database_id nil
:database nil
:table_id nil
:table nil
:custom_id nil})
(defn- activity-user-info [user-kw]
(merge
{:id (mt/user->id user-kw)}
(select-keys
(mt/fetch-user user-kw)
[:common_name :date_joined :email :first_name :is_qbnewb :is_superuser :last_login :last_name :locale])))
;; NOTE: timestamp matching was being a real PITA so I cheated a bit. ideally we'd fix that
(deftest activity-list-test
(testing "GET /api/activity"
(mt/with-temp* [Activity [activity1 {:topic "install"
:details {}
:timestamp #t "2015-09-09T12:13:14.888Z[UTC]"}]
Activity [activity2 {:topic "dashboard-create"
:user_id (mt/user->id :crowberto)
:model "dashboard"
:model_id 1234
:details {:description "Because I can!"
:name "<NAME>"}
:timestamp #t "2015-09-10T18:53:01.632Z[UTC]"}]
Activity [activity3 {:topic "user-joined"
:user_id (mt/user->id :rasta)
:model "user"
:details {}
:timestamp #t "2015-09-10T05:33:43.641Z[UTC]"}]]
(letfn [(fetch-activity [activity]
(merge
activity-defaults
(db/select-one [Activity :id :user_id :details :model :model_id] :id (u/the-id activity))))]
(is (= [(merge
(fetch-activity activity2)
{:topic "dashboard-create"
:user (activity-user-info :crowberto)})
(merge
(fetch-activity activity3)
{:topic "user-joined"
:user (activity-user-info :rasta)})
(merge
(fetch-activity activity1)
{:topic "install"
:user_id nil
:user nil})]
;; remove other activities from the API response just in case -- we're not interested in those
(let [these-activity-ids (set (map u/the-id [activity1 activity2 activity3]))]
(for [activity (mt/user-http-request :crowberto :get 200 "activity")
:when (contains? these-activity-ids (u/the-id activity))]
(dissoc activity :timestamp)))))))))
;;; GET /recent_views
;; Things we are testing for:
;; 1. ordering is sorted by most recent
;; 2. results are filtered to current user
;; 3. `:model_object` is hydrated in each result
;; 4. we filter out entries where `:model_object` is nil (object doesn't exist)
(defn- create-view! [user model model-id]
(db/insert! ViewLog
:user_id user
:model model
:model_id model-id
:timestamp :%now)
;; we sleep a bit to ensure no events have the same timestamp
;; sadly, MySQL doesn't support milliseconds so we have to wait a second
;; otherwise our records are out of order and this test fails :(
(Thread/sleep (if (= (mdb/db-type) :mysql)
1000
10)))
(deftest recent-views-test
(mt/with-temp* [Card [card1 {:name "<NAME>-<NAME>"
:creator_id (mt/user->id :crowberto)
:display "table"
:visualization_settings {}}]
Dashboard [dash1 {:name "<NAME>-name"
:description "rand-name"
:creator_id (mt/user->id :crowberto)}]
Card [card2 {:name "<NAME>-name"
:creator_id (mt/user->id :crowberto)
:display "table"
:visualization_settings {}}]]
(create-view! (mt/user->id :crowberto) "card" (:id card2))
(create-view! (mt/user->id :crowberto) "dashboard" (:id dash1))
(create-view! (mt/user->id :crowberto) "card" (:id card1))
(create-view! (mt/user->id :c<NAME>berto) "card" 36478)
(create-view! (mt/user->id :rasta) "card" (:id card1))
(is (= [{:cnt 1
:user_id (mt/user->id :crowberto)
:model "card"
:model_id (:id card1)
:model_object {:id (:id card1)
:name (:name card1)
:collection_id nil
:description (:description card1)
:display (name (:display card1))}}
{:cnt 1
:user_id (mt/user->id :c<NAME>)
:model "dashboard"
:model_id (:id dash1)
:model_object {:id (:id dash1)
:name (:name dash1)
:collection_id nil
:description (:description dash1)}}
{:cnt 1
:user_id (mt/user->id :crowberto)
:model "card"
:model_id (:id card2)
:model_object {:id (:id card2)
:name (:name card2)
:collection_id nil
:description (:description card2)
:display (name (:display card2))}}]
(for [recent-view (mt/user-http-request :crowberto :get 200 "activity/recent_views")]
(dissoc recent-view :max_ts))))))
;;; activities->referenced-objects, referenced-objects->existing-objects, add-model-exists-info
(def ^:private fake-activities
[{:model "dashboard", :model_id 43, :topic :dashboard-create, :details {}}
{:model "dashboard", :model_id 42, :topic :dashboard-create, :details {}}
{:model "card", :model_id 114, :topic :card-create, :details {}}
{:model "card", :model_id 113, :topic :card-create, :details {}}
{:model "card", :model_id 112, :topic :card-create, :details {}}
{:model "card", :model_id 111, :topic :card-create, :details {}}
{:model "dashboard", :model_id 41, :topic :dashboard-add-cards, :details {:dashcards [{:card_id 109}]}}
{:model "card", :model_id 109, :topic :card-create, :details {}}
{:model "dashboard", :model_id 41, :topic :dashboard-add-cards, :details {:dashcards [{:card_id 108}]}}
{:model "dashboard", :model_id 41, :topic :dashboard-create, :details {}}
{:model "card", :model_id 108, :topic :card-create, :details {}}
{:model "user", :model_id 90, :topic :user-joined, :details {}}
{:model nil, :model_id nil, :topic :install, :details {}}])
(deftest activities->referenced-objects-test
(is (= {"dashboard" #{41 43 42}
"card" #{113 108 109 111 112 114}
"user" #{90}}
(#'activity-api/activities->referenced-objects fake-activities))))
(deftest referenced-objects->existing-objects-test
(mt/with-temp Dashboard [{dashboard-id :id}]
(is (= {"dashboard" #{dashboard-id}, "card" nil}
(#'activity-api/referenced-objects->existing-objects {"dashboard" #{dashboard-id 0}
"card" #{0}})))))
(deftest add-model-exists-info-test
(mt/with-temp* [Dashboard [{dashboard-id :id}]
Card [{card-id :id}]]
(is (= [{:model "dashboard", :model_id dashboard-id, :model_exists true}
{:model "card", :model_id 0, :model_exists false}
{:model "dashboard"
:model_id 0
:model_exists false
:topic :dashboard-remove-cards
:details {:dashcards [{:card_id card-id, :exists true}
{:card_id 0, :exists false}]}}]
(#'activity-api/add-model-exists-info [{:model "dashboard", :model_id dashboard-id}
{:model "card", :model_id 0}
{:model "dashboard"
:model_id 0
:topic :dashboard-remove-cards
:details {:dashcards [{:card_id card-id}
{:card_id 0}]}}])))))
(deftest activity-visibility-test
;; clear out all existing Activity entries
;;
;; TODO -- this is a bad pattern -- test shouldn't wipe out a bunch of other stuff like this. Just fetch all the
;; activities and look for the presence of this specific one.
(db/delete! Activity)
(mt/with-temp Activity [activity {:topic "user-joined"
:details {}
:timestamp #t "2019-02-15T11:55:00.000Z"}]
(letfn [(user-can-see-user-joined-activity? [user]
(seq (mt/user-http-request user :get 200 "activity")))]
(testing "Only admins should get to see user-joined activities"
(testing "admin should see `:user-joined` activities"
(testing "Sanity check: admin should be able to read the activity"
(mt/with-test-user :crowberto
(is (models/can-read? activity))))
(is (user-can-see-user-joined-activity? :crowberto)))
(testing "non-admin should *not* see `:user-joined` activities"
(testing "Sanity check: non-admin should *not* be able to read the activity"
(mt/with-test-user :rasta
(is (not (models/can-read? activity)))))
(is (not (user-can-see-user-joined-activity? :rasta))))))))
| true | (ns metabase.api.activity-test
"Tests for /api/activity endpoints."
(:require [clojure.test :refer :all]
[metabase.api.activity :as activity-api]
[metabase.db :as mdb]
[metabase.models.activity :refer [Activity]]
[metabase.models.card :refer [Card]]
[metabase.models.dashboard :refer [Dashboard]]
[metabase.models.interface :as models]
[metabase.models.view-log :refer [ViewLog]]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
[toucan.db :as db]))
(use-fixtures :once (fixtures/initialize :db))
;; GET /
;; Things we are testing for:
;; 1. ordered by timestamp DESC
;; 2. :user and :model_exists are hydrated
(def ^:private activity-defaults
{:model_exists false
:database_id nil
:database nil
:table_id nil
:table nil
:custom_id nil})
(defn- activity-user-info [user-kw]
(merge
{:id (mt/user->id user-kw)}
(select-keys
(mt/fetch-user user-kw)
[:common_name :date_joined :email :first_name :is_qbnewb :is_superuser :last_login :last_name :locale])))
;; NOTE: timestamp matching was being a real PITA so I cheated a bit. ideally we'd fix that
(deftest activity-list-test
(testing "GET /api/activity"
(mt/with-temp* [Activity [activity1 {:topic "install"
:details {}
:timestamp #t "2015-09-09T12:13:14.888Z[UTC]"}]
Activity [activity2 {:topic "dashboard-create"
:user_id (mt/user->id :crowberto)
:model "dashboard"
:model_id 1234
:details {:description "Because I can!"
:name "PI:NAME:<NAME>END_PI"}
:timestamp #t "2015-09-10T18:53:01.632Z[UTC]"}]
Activity [activity3 {:topic "user-joined"
:user_id (mt/user->id :rasta)
:model "user"
:details {}
:timestamp #t "2015-09-10T05:33:43.641Z[UTC]"}]]
(letfn [(fetch-activity [activity]
(merge
activity-defaults
(db/select-one [Activity :id :user_id :details :model :model_id] :id (u/the-id activity))))]
(is (= [(merge
(fetch-activity activity2)
{:topic "dashboard-create"
:user (activity-user-info :crowberto)})
(merge
(fetch-activity activity3)
{:topic "user-joined"
:user (activity-user-info :rasta)})
(merge
(fetch-activity activity1)
{:topic "install"
:user_id nil
:user nil})]
;; remove other activities from the API response just in case -- we're not interested in those
(let [these-activity-ids (set (map u/the-id [activity1 activity2 activity3]))]
(for [activity (mt/user-http-request :crowberto :get 200 "activity")
:when (contains? these-activity-ids (u/the-id activity))]
(dissoc activity :timestamp)))))))))
;;; GET /recent_views
;; Things we are testing for:
;; 1. ordering is sorted by most recent
;; 2. results are filtered to current user
;; 3. `:model_object` is hydrated in each result
;; 4. we filter out entries where `:model_object` is nil (object doesn't exist)
(defn- create-view! [user model model-id]
(db/insert! ViewLog
:user_id user
:model model
:model_id model-id
:timestamp :%now)
;; we sleep a bit to ensure no events have the same timestamp
;; sadly, MySQL doesn't support milliseconds so we have to wait a second
;; otherwise our records are out of order and this test fails :(
(Thread/sleep (if (= (mdb/db-type) :mysql)
1000
10)))
(deftest recent-views-test
(mt/with-temp* [Card [card1 {:name "PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI"
:creator_id (mt/user->id :crowberto)
:display "table"
:visualization_settings {}}]
Dashboard [dash1 {:name "PI:NAME:<NAME>END_PI-name"
:description "rand-name"
:creator_id (mt/user->id :crowberto)}]
Card [card2 {:name "PI:NAME:<NAME>END_PI-name"
:creator_id (mt/user->id :crowberto)
:display "table"
:visualization_settings {}}]]
(create-view! (mt/user->id :crowberto) "card" (:id card2))
(create-view! (mt/user->id :crowberto) "dashboard" (:id dash1))
(create-view! (mt/user->id :crowberto) "card" (:id card1))
(create-view! (mt/user->id :cPI:NAME:<NAME>END_PIberto) "card" 36478)
(create-view! (mt/user->id :rasta) "card" (:id card1))
(is (= [{:cnt 1
:user_id (mt/user->id :crowberto)
:model "card"
:model_id (:id card1)
:model_object {:id (:id card1)
:name (:name card1)
:collection_id nil
:description (:description card1)
:display (name (:display card1))}}
{:cnt 1
:user_id (mt/user->id :cPI:NAME:<NAME>END_PI)
:model "dashboard"
:model_id (:id dash1)
:model_object {:id (:id dash1)
:name (:name dash1)
:collection_id nil
:description (:description dash1)}}
{:cnt 1
:user_id (mt/user->id :crowberto)
:model "card"
:model_id (:id card2)
:model_object {:id (:id card2)
:name (:name card2)
:collection_id nil
:description (:description card2)
:display (name (:display card2))}}]
(for [recent-view (mt/user-http-request :crowberto :get 200 "activity/recent_views")]
(dissoc recent-view :max_ts))))))
;;; activities->referenced-objects, referenced-objects->existing-objects, add-model-exists-info
(def ^:private fake-activities
[{:model "dashboard", :model_id 43, :topic :dashboard-create, :details {}}
{:model "dashboard", :model_id 42, :topic :dashboard-create, :details {}}
{:model "card", :model_id 114, :topic :card-create, :details {}}
{:model "card", :model_id 113, :topic :card-create, :details {}}
{:model "card", :model_id 112, :topic :card-create, :details {}}
{:model "card", :model_id 111, :topic :card-create, :details {}}
{:model "dashboard", :model_id 41, :topic :dashboard-add-cards, :details {:dashcards [{:card_id 109}]}}
{:model "card", :model_id 109, :topic :card-create, :details {}}
{:model "dashboard", :model_id 41, :topic :dashboard-add-cards, :details {:dashcards [{:card_id 108}]}}
{:model "dashboard", :model_id 41, :topic :dashboard-create, :details {}}
{:model "card", :model_id 108, :topic :card-create, :details {}}
{:model "user", :model_id 90, :topic :user-joined, :details {}}
{:model nil, :model_id nil, :topic :install, :details {}}])
(deftest activities->referenced-objects-test
(is (= {"dashboard" #{41 43 42}
"card" #{113 108 109 111 112 114}
"user" #{90}}
(#'activity-api/activities->referenced-objects fake-activities))))
(deftest referenced-objects->existing-objects-test
(mt/with-temp Dashboard [{dashboard-id :id}]
(is (= {"dashboard" #{dashboard-id}, "card" nil}
(#'activity-api/referenced-objects->existing-objects {"dashboard" #{dashboard-id 0}
"card" #{0}})))))
(deftest add-model-exists-info-test
(mt/with-temp* [Dashboard [{dashboard-id :id}]
Card [{card-id :id}]]
(is (= [{:model "dashboard", :model_id dashboard-id, :model_exists true}
{:model "card", :model_id 0, :model_exists false}
{:model "dashboard"
:model_id 0
:model_exists false
:topic :dashboard-remove-cards
:details {:dashcards [{:card_id card-id, :exists true}
{:card_id 0, :exists false}]}}]
(#'activity-api/add-model-exists-info [{:model "dashboard", :model_id dashboard-id}
{:model "card", :model_id 0}
{:model "dashboard"
:model_id 0
:topic :dashboard-remove-cards
:details {:dashcards [{:card_id card-id}
{:card_id 0}]}}])))))
(deftest activity-visibility-test
;; clear out all existing Activity entries
;;
;; TODO -- this is a bad pattern -- test shouldn't wipe out a bunch of other stuff like this. Just fetch all the
;; activities and look for the presence of this specific one.
(db/delete! Activity)
(mt/with-temp Activity [activity {:topic "user-joined"
:details {}
:timestamp #t "2019-02-15T11:55:00.000Z"}]
(letfn [(user-can-see-user-joined-activity? [user]
(seq (mt/user-http-request user :get 200 "activity")))]
(testing "Only admins should get to see user-joined activities"
(testing "admin should see `:user-joined` activities"
(testing "Sanity check: admin should be able to read the activity"
(mt/with-test-user :crowberto
(is (models/can-read? activity))))
(is (user-can-see-user-joined-activity? :crowberto)))
(testing "non-admin should *not* see `:user-joined` activities"
(testing "Sanity check: non-admin should *not* be able to read the activity"
(mt/with-test-user :rasta
(is (not (models/can-read? activity)))))
(is (not (user-can-see-user-joined-activity? :rasta))))))))
|
[
{
"context": "{:subprotocol \"mysql\"\n; :subname \"//127.0.0.1:3306/clojure_test\"\n; :user \"clojure",
"end": 577,
"score": 0.9994456768035889,
"start": 568,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " :user \"clojure_test\"\n; :password \"clojure_test\"})\n\n;; TODO: dsl for query where conditions (s/an",
"end": 673,
"score": 0.9992758631706238,
"start": 661,
"tag": "PASSWORD",
"value": "clojure_test"
}
] | src/clj_datastore/sql.clj | theJenix/clj-datastore | 0 | (ns clj-datastore.sql
(:require [clojure.string :as s]
[clojure.tools.logging :as log]
[clj-datastore.datastore :as d]
[clojure.java.jdbc :as j]
[clj-datastore.sql-spec :refer :all]
[clj-datastore.util :refer [<-> seq-or-bust]])
(:import [java.sql BatchUpdateException])
)
;; FIXME: makes a lot of assumptions about an id primary key, but will accept
;; a table spec (model keys) that uses a different primary key. Should reconcile
; (def mysql-db {:subprotocol "mysql"
; :subname "//127.0.0.1:3306/clojure_test"
; :user "clojure_test"
; :password "clojure_test"})
;; TODO: dsl for query where conditions (s/and (s/eq :event types) (s/ge date-time sincets))
(defn- get-op-string [op]
(condp = op
:ge ">="
:gt ">"
:eq "="
:lt "<"
:le "<="
:ne "<>"
:like "LIKE"
)
)
(def quoted-name (comp quote-string-with-dash name))
(defn build-as-in-clause [v]
(or (set? v) (sequential? v)))
(defn build-one-where-condition [k v]
"Takes a field name k and value v and builds a where condition as a vector of
prepared statement and argument"
(let [qk (str "\"" (name k) "\"")]
(cond
(build-as-in-clause v)
(let [in-places (s/join "," (repeat (count v) "?"))
;; normalize v to be a sequence, because of how we're representing the value
seqv (seq v)]
(vector (str qk " in (" in-places ")") seqv))
(map? v)
(let [[op val] (first v)]
(vector (str qk " " (get-op-string op) " ?") val))
:else
(vector (str qk "= ?") v))
))
(defn where-clause-is-false [kvs]
"Tests if a where clause will be obviously false. Currently, this checks
for empty IN clauses, which will not return any rows and may result in an
error.
NOTE: if we change build-where-clause to support or conditions, this will
need to be modified."
(when (seq kvs)
(->> (apply map vector kvs)
second
(filter build-as-in-clause)
(map empty?)
(some true?))))
(defn build-where-clause [kvs]
(let [kvsp (remove #(= (namespace d/limit) (namespace (first %))) kvs)]
(if (empty? kvsp)
[nil []]
; First transpose, then build each clause, then transpose, then convert the first vector to a string clause
(->> (apply map vector kvsp)
(apply map build-one-where-condition)
(apply mapv vector)
(<-> update #(s/join " and " %) 0)
(<-> update flatten 1)))))
(defn- build-order-by-clause [kvs]
(let [order-by (get kvs d/order-by)
order (get kvs d/order)]
(if order-by
(cond-> ""
true (str " order by " (quoted-name order-by))
(= order d/order-desc) (str " DESC"))
"")))
(defn- build-limit-offset-clause [kvs]
(let [limit (get kvs d/limit)
offset (get kvs d/offset)]
(cond-> ""
limit (str " limit " limit)
offset (str " offset " offset))
))
(defn- do-count-records [db table & [kvs]]
(let [[wstr wargs] (build-where-clause kvs)
tablename (name table)
qstr (str "select count(*) from " tablename " where " (or wstr "true"))]
(-> (j/query db (concat [qstr] wargs))
first
:count)))
(defn- do-select-records [db field-map table & [kvs]]
(if (where-clause-is-false kvs)
(list)
(let [order-str (build-order-by-clause kvs)
limit-str (build-limit-offset-clause kvs)
[wstr wargs] (build-where-clause kvs)
fieldnames (->> (keys field-map)
(map quoted-name)
(s/join ","))
tablename (name table)
qstr (str "select " fieldnames " from " tablename " where " (or wstr "true") " " order-str " " limit-str)]
(log/debug "running query: " (concat [qstr wargs]))
;; We need to correct for the fact that the DB may strip a field name of it's casedness (make it all lowercase) by mapping the results back to the actual fields requested
(->> (j/query db (concat [qstr] wargs))
(map #(fix-field-names field-map %))))))
(defn- build-join-clause [[table1 table2] conds]
(let [tn1 (name table1)
tn2 (name table2)]
(->> conds
(map (fn [[x y]] [(name x) (name y)]))
(map (fn [[x y]] (str tn1 "." x "=" tn2 "." y)))
(s/join " and "))))
(defn- make-field-name [x]
(let [kw (keyword x)]
(if-let [n (namespace kw)]
(str n "." (name kw))
(name kw))))
;;TODO: not a bug, but something we should handle here:
;;(do-join-records db [:roles/id :actors/id :name] [:roles :actors] [[:id :role_id]])
;;(select roles.id,actors.id,name from roles,actors where roles.id=actors.role_id and true [])
;;({:id 4, :id_2 1, :name "Pre Op Nurse"})
;; the select returns non scoped fields, and resolves duplicates by appending _#. we should
;; line this back up with the fields that were requested.
;; for now, it's ok, the consumer can deal with it...
(defn- do-join-records [db field-map tables conds & [kvs]]
(let [[wstr wargs] (build-where-clause kvs)
jclause (build-join-clause tables conds)
fieldnames (->> (seq-or-bust (keys field-map))
(map (comp quote-string-with-dash make-field-name))
(s/join ","))
tablenames (->> (map name tables)
(s/join ","))
qstr (str "select " fieldnames " from " tablenames " where " jclause " and " (or wstr "true"))]
(log/debug "running query: "(concat [qstr wargs]))
(->> (j/query db (concat [qstr] wargs))
(map #(fix-field-names field-map %)))))
(defn- do-get-record [db field-map table id]
{:pre (some? id)}
(-> (do-select-records db field-map table {:id id})
first))
(defn- get-inserted-row
"Takes in the response from an insert! call and returns the row that was inserted into the database. This is needed because the return value of insert! is different for some databases (looking at you postgresql) than others."
[db field-map table res]
(condp = (:subprotocol db)
"postgresql" res ; Postgresql returns the whole row
(do-get-record db field-map table (:generated_key res))))
(defn- do-add-record [db field-set table kvs]
(log/debug "In do-add-record: " field-set table kvs)
(let [tablekw (keyword table)
kvs (filter-keys field-set kvs)]
(log/debug kvs)
(-> (j/insert! db tablekw kvs {:entities quote-string-with-dash})
first)))
(defn- do-delete-record [db table id]
{:pre (some? id)}
(let [tablekw (keyword table)
wclause (->> (build-where-clause {:id id})
flatten)] ;; delete! needs this sequence to be flattened
(assert (first wclause)) ;; Protection to make sure we don't delete the world!
;; TODO: test if dashed strings mess up where clause
(-> (j/delete! db tablekw wclause)
first
(= 1))))
(defn- do-update-record [db field-set table id kvs]
{:pre (some? id)}
(let [tablekw (keyword table)
kvs (filter-keys field-set kvs)
wclause (->> (build-where-clause {:id id})
flatten)] ;; update! needs this sequence to be flattened
(assert (first wclause)) ;; Protection to make sure we don't update the world!
(try
(-> (j/update! db tablekw kvs wclause {:entities quote-string-with-dash})
first
(= 1))
(catch BatchUpdateException e
(throw (.getNextException e))
)
)))
(defprotocol ISqlDatastore
(same-database? [db args]))
(defn make-sql-data-store [mks ns connargs]
;; First thing..make sure we have a table, and it conforms to our spec
;; FOR NOW: create a table if it doesnt exist, but throw an exception if the spec
;; doesnt match
;; NOTE: the query set of fields may be different than the modify set, if
;; we add an ID in
(check-table connargs ns mks true false)
(let [mk-set (set mks)
query-field-map (make-query-map mks)
modify-set (-> (make-modify-map mks)
keys
set)
kwspace (keyword ns)]
(reify
ISqlDatastore
(same-database? [_ args]
(= args connargs))
d/IDatastore
;; FIXME: this is not quite right, because mks may have schema definition (e.g. types, modifiers) that pollute "model-keys"
(model-keys [_] mks)
(nspace [_] kwspace)
(count-records [_ kvs]
(do-count-records connargs kwspace kvs))
(select-records [_ kvs]
(do-select-records connargs query-field-map kwspace kvs))
(list-records [_]
(do-select-records connargs query-field-map kwspace))
(add-record [_ kvs]
(when-let [res (do-add-record connargs modify-set kwspace kvs)]
(get-inserted-row connargs query-field-map kwspace res)))
(get-record [_ id]
(do-get-record connargs query-field-map kwspace id))
(update-record [ds id kvs]
(when (do-update-record connargs modify-set kwspace id kvs)
(do-get-record connargs query-field-map kwspace id)))
(delete-record [_ id]
(do-delete-record connargs kwspace id))
(join-record [_ other f-or-pair & pairs]
;; TODO may not work, but not needed for right now. WIP
; (when (and (satisfies? ISqlDatastore)
; (same-database? other connargs)
; (not (fn? f-or-pair)))
; (do-join-records connargs
; (concat mks (model-keys other))
; [ns (nspace other)]
; (concat [f-or-pair] pairs))))
nil)
;; can default back to old join-records...maybe
)))
| 1291 | (ns clj-datastore.sql
(:require [clojure.string :as s]
[clojure.tools.logging :as log]
[clj-datastore.datastore :as d]
[clojure.java.jdbc :as j]
[clj-datastore.sql-spec :refer :all]
[clj-datastore.util :refer [<-> seq-or-bust]])
(:import [java.sql BatchUpdateException])
)
;; FIXME: makes a lot of assumptions about an id primary key, but will accept
;; a table spec (model keys) that uses a different primary key. Should reconcile
; (def mysql-db {:subprotocol "mysql"
; :subname "//127.0.0.1:3306/clojure_test"
; :user "clojure_test"
; :password "<PASSWORD>"})
;; TODO: dsl for query where conditions (s/and (s/eq :event types) (s/ge date-time sincets))
(defn- get-op-string [op]
(condp = op
:ge ">="
:gt ">"
:eq "="
:lt "<"
:le "<="
:ne "<>"
:like "LIKE"
)
)
(def quoted-name (comp quote-string-with-dash name))
(defn build-as-in-clause [v]
(or (set? v) (sequential? v)))
(defn build-one-where-condition [k v]
"Takes a field name k and value v and builds a where condition as a vector of
prepared statement and argument"
(let [qk (str "\"" (name k) "\"")]
(cond
(build-as-in-clause v)
(let [in-places (s/join "," (repeat (count v) "?"))
;; normalize v to be a sequence, because of how we're representing the value
seqv (seq v)]
(vector (str qk " in (" in-places ")") seqv))
(map? v)
(let [[op val] (first v)]
(vector (str qk " " (get-op-string op) " ?") val))
:else
(vector (str qk "= ?") v))
))
(defn where-clause-is-false [kvs]
"Tests if a where clause will be obviously false. Currently, this checks
for empty IN clauses, which will not return any rows and may result in an
error.
NOTE: if we change build-where-clause to support or conditions, this will
need to be modified."
(when (seq kvs)
(->> (apply map vector kvs)
second
(filter build-as-in-clause)
(map empty?)
(some true?))))
(defn build-where-clause [kvs]
(let [kvsp (remove #(= (namespace d/limit) (namespace (first %))) kvs)]
(if (empty? kvsp)
[nil []]
; First transpose, then build each clause, then transpose, then convert the first vector to a string clause
(->> (apply map vector kvsp)
(apply map build-one-where-condition)
(apply mapv vector)
(<-> update #(s/join " and " %) 0)
(<-> update flatten 1)))))
(defn- build-order-by-clause [kvs]
(let [order-by (get kvs d/order-by)
order (get kvs d/order)]
(if order-by
(cond-> ""
true (str " order by " (quoted-name order-by))
(= order d/order-desc) (str " DESC"))
"")))
(defn- build-limit-offset-clause [kvs]
(let [limit (get kvs d/limit)
offset (get kvs d/offset)]
(cond-> ""
limit (str " limit " limit)
offset (str " offset " offset))
))
(defn- do-count-records [db table & [kvs]]
(let [[wstr wargs] (build-where-clause kvs)
tablename (name table)
qstr (str "select count(*) from " tablename " where " (or wstr "true"))]
(-> (j/query db (concat [qstr] wargs))
first
:count)))
(defn- do-select-records [db field-map table & [kvs]]
(if (where-clause-is-false kvs)
(list)
(let [order-str (build-order-by-clause kvs)
limit-str (build-limit-offset-clause kvs)
[wstr wargs] (build-where-clause kvs)
fieldnames (->> (keys field-map)
(map quoted-name)
(s/join ","))
tablename (name table)
qstr (str "select " fieldnames " from " tablename " where " (or wstr "true") " " order-str " " limit-str)]
(log/debug "running query: " (concat [qstr wargs]))
;; We need to correct for the fact that the DB may strip a field name of it's casedness (make it all lowercase) by mapping the results back to the actual fields requested
(->> (j/query db (concat [qstr] wargs))
(map #(fix-field-names field-map %))))))
(defn- build-join-clause [[table1 table2] conds]
(let [tn1 (name table1)
tn2 (name table2)]
(->> conds
(map (fn [[x y]] [(name x) (name y)]))
(map (fn [[x y]] (str tn1 "." x "=" tn2 "." y)))
(s/join " and "))))
(defn- make-field-name [x]
(let [kw (keyword x)]
(if-let [n (namespace kw)]
(str n "." (name kw))
(name kw))))
;;TODO: not a bug, but something we should handle here:
;;(do-join-records db [:roles/id :actors/id :name] [:roles :actors] [[:id :role_id]])
;;(select roles.id,actors.id,name from roles,actors where roles.id=actors.role_id and true [])
;;({:id 4, :id_2 1, :name "Pre Op Nurse"})
;; the select returns non scoped fields, and resolves duplicates by appending _#. we should
;; line this back up with the fields that were requested.
;; for now, it's ok, the consumer can deal with it...
(defn- do-join-records [db field-map tables conds & [kvs]]
(let [[wstr wargs] (build-where-clause kvs)
jclause (build-join-clause tables conds)
fieldnames (->> (seq-or-bust (keys field-map))
(map (comp quote-string-with-dash make-field-name))
(s/join ","))
tablenames (->> (map name tables)
(s/join ","))
qstr (str "select " fieldnames " from " tablenames " where " jclause " and " (or wstr "true"))]
(log/debug "running query: "(concat [qstr wargs]))
(->> (j/query db (concat [qstr] wargs))
(map #(fix-field-names field-map %)))))
(defn- do-get-record [db field-map table id]
{:pre (some? id)}
(-> (do-select-records db field-map table {:id id})
first))
(defn- get-inserted-row
"Takes in the response from an insert! call and returns the row that was inserted into the database. This is needed because the return value of insert! is different for some databases (looking at you postgresql) than others."
[db field-map table res]
(condp = (:subprotocol db)
"postgresql" res ; Postgresql returns the whole row
(do-get-record db field-map table (:generated_key res))))
(defn- do-add-record [db field-set table kvs]
(log/debug "In do-add-record: " field-set table kvs)
(let [tablekw (keyword table)
kvs (filter-keys field-set kvs)]
(log/debug kvs)
(-> (j/insert! db tablekw kvs {:entities quote-string-with-dash})
first)))
(defn- do-delete-record [db table id]
{:pre (some? id)}
(let [tablekw (keyword table)
wclause (->> (build-where-clause {:id id})
flatten)] ;; delete! needs this sequence to be flattened
(assert (first wclause)) ;; Protection to make sure we don't delete the world!
;; TODO: test if dashed strings mess up where clause
(-> (j/delete! db tablekw wclause)
first
(= 1))))
(defn- do-update-record [db field-set table id kvs]
{:pre (some? id)}
(let [tablekw (keyword table)
kvs (filter-keys field-set kvs)
wclause (->> (build-where-clause {:id id})
flatten)] ;; update! needs this sequence to be flattened
(assert (first wclause)) ;; Protection to make sure we don't update the world!
(try
(-> (j/update! db tablekw kvs wclause {:entities quote-string-with-dash})
first
(= 1))
(catch BatchUpdateException e
(throw (.getNextException e))
)
)))
(defprotocol ISqlDatastore
(same-database? [db args]))
(defn make-sql-data-store [mks ns connargs]
;; First thing..make sure we have a table, and it conforms to our spec
;; FOR NOW: create a table if it doesnt exist, but throw an exception if the spec
;; doesnt match
;; NOTE: the query set of fields may be different than the modify set, if
;; we add an ID in
(check-table connargs ns mks true false)
(let [mk-set (set mks)
query-field-map (make-query-map mks)
modify-set (-> (make-modify-map mks)
keys
set)
kwspace (keyword ns)]
(reify
ISqlDatastore
(same-database? [_ args]
(= args connargs))
d/IDatastore
;; FIXME: this is not quite right, because mks may have schema definition (e.g. types, modifiers) that pollute "model-keys"
(model-keys [_] mks)
(nspace [_] kwspace)
(count-records [_ kvs]
(do-count-records connargs kwspace kvs))
(select-records [_ kvs]
(do-select-records connargs query-field-map kwspace kvs))
(list-records [_]
(do-select-records connargs query-field-map kwspace))
(add-record [_ kvs]
(when-let [res (do-add-record connargs modify-set kwspace kvs)]
(get-inserted-row connargs query-field-map kwspace res)))
(get-record [_ id]
(do-get-record connargs query-field-map kwspace id))
(update-record [ds id kvs]
(when (do-update-record connargs modify-set kwspace id kvs)
(do-get-record connargs query-field-map kwspace id)))
(delete-record [_ id]
(do-delete-record connargs kwspace id))
(join-record [_ other f-or-pair & pairs]
;; TODO may not work, but not needed for right now. WIP
; (when (and (satisfies? ISqlDatastore)
; (same-database? other connargs)
; (not (fn? f-or-pair)))
; (do-join-records connargs
; (concat mks (model-keys other))
; [ns (nspace other)]
; (concat [f-or-pair] pairs))))
nil)
;; can default back to old join-records...maybe
)))
| true | (ns clj-datastore.sql
(:require [clojure.string :as s]
[clojure.tools.logging :as log]
[clj-datastore.datastore :as d]
[clojure.java.jdbc :as j]
[clj-datastore.sql-spec :refer :all]
[clj-datastore.util :refer [<-> seq-or-bust]])
(:import [java.sql BatchUpdateException])
)
;; FIXME: makes a lot of assumptions about an id primary key, but will accept
;; a table spec (model keys) that uses a different primary key. Should reconcile
; (def mysql-db {:subprotocol "mysql"
; :subname "//127.0.0.1:3306/clojure_test"
; :user "clojure_test"
; :password "PI:PASSWORD:<PASSWORD>END_PI"})
;; TODO: dsl for query where conditions (s/and (s/eq :event types) (s/ge date-time sincets))
(defn- get-op-string [op]
(condp = op
:ge ">="
:gt ">"
:eq "="
:lt "<"
:le "<="
:ne "<>"
:like "LIKE"
)
)
(def quoted-name (comp quote-string-with-dash name))
(defn build-as-in-clause [v]
(or (set? v) (sequential? v)))
(defn build-one-where-condition [k v]
"Takes a field name k and value v and builds a where condition as a vector of
prepared statement and argument"
(let [qk (str "\"" (name k) "\"")]
(cond
(build-as-in-clause v)
(let [in-places (s/join "," (repeat (count v) "?"))
;; normalize v to be a sequence, because of how we're representing the value
seqv (seq v)]
(vector (str qk " in (" in-places ")") seqv))
(map? v)
(let [[op val] (first v)]
(vector (str qk " " (get-op-string op) " ?") val))
:else
(vector (str qk "= ?") v))
))
(defn where-clause-is-false [kvs]
"Tests if a where clause will be obviously false. Currently, this checks
for empty IN clauses, which will not return any rows and may result in an
error.
NOTE: if we change build-where-clause to support or conditions, this will
need to be modified."
(when (seq kvs)
(->> (apply map vector kvs)
second
(filter build-as-in-clause)
(map empty?)
(some true?))))
(defn build-where-clause [kvs]
(let [kvsp (remove #(= (namespace d/limit) (namespace (first %))) kvs)]
(if (empty? kvsp)
[nil []]
; First transpose, then build each clause, then transpose, then convert the first vector to a string clause
(->> (apply map vector kvsp)
(apply map build-one-where-condition)
(apply mapv vector)
(<-> update #(s/join " and " %) 0)
(<-> update flatten 1)))))
(defn- build-order-by-clause [kvs]
(let [order-by (get kvs d/order-by)
order (get kvs d/order)]
(if order-by
(cond-> ""
true (str " order by " (quoted-name order-by))
(= order d/order-desc) (str " DESC"))
"")))
(defn- build-limit-offset-clause [kvs]
(let [limit (get kvs d/limit)
offset (get kvs d/offset)]
(cond-> ""
limit (str " limit " limit)
offset (str " offset " offset))
))
(defn- do-count-records [db table & [kvs]]
(let [[wstr wargs] (build-where-clause kvs)
tablename (name table)
qstr (str "select count(*) from " tablename " where " (or wstr "true"))]
(-> (j/query db (concat [qstr] wargs))
first
:count)))
(defn- do-select-records [db field-map table & [kvs]]
(if (where-clause-is-false kvs)
(list)
(let [order-str (build-order-by-clause kvs)
limit-str (build-limit-offset-clause kvs)
[wstr wargs] (build-where-clause kvs)
fieldnames (->> (keys field-map)
(map quoted-name)
(s/join ","))
tablename (name table)
qstr (str "select " fieldnames " from " tablename " where " (or wstr "true") " " order-str " " limit-str)]
(log/debug "running query: " (concat [qstr wargs]))
;; We need to correct for the fact that the DB may strip a field name of it's casedness (make it all lowercase) by mapping the results back to the actual fields requested
(->> (j/query db (concat [qstr] wargs))
(map #(fix-field-names field-map %))))))
(defn- build-join-clause [[table1 table2] conds]
(let [tn1 (name table1)
tn2 (name table2)]
(->> conds
(map (fn [[x y]] [(name x) (name y)]))
(map (fn [[x y]] (str tn1 "." x "=" tn2 "." y)))
(s/join " and "))))
(defn- make-field-name [x]
(let [kw (keyword x)]
(if-let [n (namespace kw)]
(str n "." (name kw))
(name kw))))
;;TODO: not a bug, but something we should handle here:
;;(do-join-records db [:roles/id :actors/id :name] [:roles :actors] [[:id :role_id]])
;;(select roles.id,actors.id,name from roles,actors where roles.id=actors.role_id and true [])
;;({:id 4, :id_2 1, :name "Pre Op Nurse"})
;; the select returns non scoped fields, and resolves duplicates by appending _#. we should
;; line this back up with the fields that were requested.
;; for now, it's ok, the consumer can deal with it...
(defn- do-join-records [db field-map tables conds & [kvs]]
(let [[wstr wargs] (build-where-clause kvs)
jclause (build-join-clause tables conds)
fieldnames (->> (seq-or-bust (keys field-map))
(map (comp quote-string-with-dash make-field-name))
(s/join ","))
tablenames (->> (map name tables)
(s/join ","))
qstr (str "select " fieldnames " from " tablenames " where " jclause " and " (or wstr "true"))]
(log/debug "running query: "(concat [qstr wargs]))
(->> (j/query db (concat [qstr] wargs))
(map #(fix-field-names field-map %)))))
(defn- do-get-record [db field-map table id]
{:pre (some? id)}
(-> (do-select-records db field-map table {:id id})
first))
(defn- get-inserted-row
"Takes in the response from an insert! call and returns the row that was inserted into the database. This is needed because the return value of insert! is different for some databases (looking at you postgresql) than others."
[db field-map table res]
(condp = (:subprotocol db)
"postgresql" res ; Postgresql returns the whole row
(do-get-record db field-map table (:generated_key res))))
(defn- do-add-record [db field-set table kvs]
(log/debug "In do-add-record: " field-set table kvs)
(let [tablekw (keyword table)
kvs (filter-keys field-set kvs)]
(log/debug kvs)
(-> (j/insert! db tablekw kvs {:entities quote-string-with-dash})
first)))
(defn- do-delete-record [db table id]
{:pre (some? id)}
(let [tablekw (keyword table)
wclause (->> (build-where-clause {:id id})
flatten)] ;; delete! needs this sequence to be flattened
(assert (first wclause)) ;; Protection to make sure we don't delete the world!
;; TODO: test if dashed strings mess up where clause
(-> (j/delete! db tablekw wclause)
first
(= 1))))
(defn- do-update-record [db field-set table id kvs]
{:pre (some? id)}
(let [tablekw (keyword table)
kvs (filter-keys field-set kvs)
wclause (->> (build-where-clause {:id id})
flatten)] ;; update! needs this sequence to be flattened
(assert (first wclause)) ;; Protection to make sure we don't update the world!
(try
(-> (j/update! db tablekw kvs wclause {:entities quote-string-with-dash})
first
(= 1))
(catch BatchUpdateException e
(throw (.getNextException e))
)
)))
(defprotocol ISqlDatastore
(same-database? [db args]))
(defn make-sql-data-store [mks ns connargs]
;; First thing..make sure we have a table, and it conforms to our spec
;; FOR NOW: create a table if it doesnt exist, but throw an exception if the spec
;; doesnt match
;; NOTE: the query set of fields may be different than the modify set, if
;; we add an ID in
(check-table connargs ns mks true false)
(let [mk-set (set mks)
query-field-map (make-query-map mks)
modify-set (-> (make-modify-map mks)
keys
set)
kwspace (keyword ns)]
(reify
ISqlDatastore
(same-database? [_ args]
(= args connargs))
d/IDatastore
;; FIXME: this is not quite right, because mks may have schema definition (e.g. types, modifiers) that pollute "model-keys"
(model-keys [_] mks)
(nspace [_] kwspace)
(count-records [_ kvs]
(do-count-records connargs kwspace kvs))
(select-records [_ kvs]
(do-select-records connargs query-field-map kwspace kvs))
(list-records [_]
(do-select-records connargs query-field-map kwspace))
(add-record [_ kvs]
(when-let [res (do-add-record connargs modify-set kwspace kvs)]
(get-inserted-row connargs query-field-map kwspace res)))
(get-record [_ id]
(do-get-record connargs query-field-map kwspace id))
(update-record [ds id kvs]
(when (do-update-record connargs modify-set kwspace id kvs)
(do-get-record connargs query-field-map kwspace id)))
(delete-record [_ id]
(do-delete-record connargs kwspace id))
(join-record [_ other f-or-pair & pairs]
;; TODO may not work, but not needed for right now. WIP
; (when (and (satisfies? ISqlDatastore)
; (same-database? other connargs)
; (not (fn? f-or-pair)))
; (do-join-records connargs
; (concat mks (model-keys other))
; [ns (nspace other)]
; (concat [f-or-pair] pairs))))
nil)
;; can default back to old join-records...maybe
)))
|
[
{
"context": "a swagger definition.\"\n :url \"https://github.com/zalando/swagger1st\"\n\n :license {:name \"ISC License\"\n ",
"end": 168,
"score": 0.9997127056121826,
"start": 161,
"tag": "USERNAME",
"value": "zalando"
},
{
"context": "\"\n :distribution :repo}\n\n :scm {:url \"git@github.com:zalando/swagger1st.git\"}\n\n :min-lein-version \"2.",
"end": 330,
"score": 0.9924171566963196,
"start": 316,
"tag": "EMAIL",
"value": "git@github.com"
},
{
"context": "distribution :repo}\n\n :scm {:url \"git@github.com:zalando/swagger1st.git\"}\n\n :min-lein-version \"2.0.0\"\n\n ",
"end": 338,
"score": 0.999326229095459,
"start": 331,
"tag": "USERNAME",
"value": "zalando"
},
{
"context": " [:developer\n [:name \"Tobias Sarnowski\"]\n [:url \"http://www.sarnowski.i",
"end": 1926,
"score": 0.9998511075973511,
"start": 1910,
"tag": "NAME",
"value": "Tobias Sarnowski"
},
{
"context": "p://www.sarnowski.io\"]\n [:email \"tobias@sarnowski.io\"]\n [:timezone \"+1\"]]\n ",
"end": 2026,
"score": 0.9999316930770874,
"start": 2007,
"tag": "EMAIL",
"value": "tobias@sarnowski.io"
},
{
"context": " [:developer\n [:name \"Andre Hartmann\"]\n [:email \"andre.hartmann@zalan",
"end": 2134,
"score": 0.9998434782028198,
"start": 2120,
"tag": "NAME",
"value": "Andre Hartmann"
},
{
"context": "name \"Andre Hartmann\"]\n [:email \"andre.hartmann@zalando.de\"]\n [:timezone \"+1\"]]]\n\n :deploy",
"end": 2189,
"score": 0.9999235272407532,
"start": 2164,
"tag": "EMAIL",
"value": "andre.hartmann@zalando.de"
}
] | project.clj | oporkka/swagger1st | 0 | (defproject org.zalando/swagger1st "0.26.0-SNAPSHOT"
:description "A ring handler that does routing based on a swagger definition."
:url "https://github.com/zalando/swagger1st"
:license {:name "ISC License"
:url "http://opensource.org/licenses/ISC"
:distribution :repo}
:scm {:url "git@github.com:zalando/swagger1st.git"}
:min-lein-version "2.0.0"
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/tools.logging "0.4.0"]
[circleci/clj-yaml "0.5.5"]
[prismatic/schema "1.1.6"]
[clj-time "0.13.0"]
[ring-basic-authentication "1.0.5"]
[clj-http "3.6.1"]
[cheshire "5.7.1"]]
:plugins [[lein-cloverage "1.0.9"]]
:profiles {:dev {:dependencies [[ring/ring-core "1.6.1"]
[ring/ring-devel "1.6.1"]
[ring/ring-mock "0.3.1"]
[javax.servlet/servlet-api "2.5"]
[org.slf4j/slf4j-api "1.7.25"]
[org.slf4j/jul-to-slf4j "1.7.25"]
[org.slf4j/jcl-over-slf4j "1.7.25"]
[org.apache.logging.log4j/log4j-api "2.8.2"]
[org.apache.logging.log4j/log4j-core "2.8.2"]
[org.apache.logging.log4j/log4j-slf4j-impl "2.8.2"]
[whitepages/expect-call "0.1.0"]
[criterium "0.4.4"]
[com.newrelic.agent.java/newrelic-api "3.40.0"]]}}
:test-selectors {:default (complement :performance)
:performance :performance
:all (constantly true)}
:pom-addition [:developers
[:developer
[:name "Tobias Sarnowski"]
[:url "http://www.sarnowski.io"]
[:email "tobias@sarnowski.io"]
[:timezone "+1"]]
[:developer
[:name "Andre Hartmann"]
[:email "andre.hartmann@zalando.de"]
[:timezone "+1"]]]
:deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2/" :creds :gpg}
"snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots/" :creds :gpg}})
| 29349 | (defproject org.zalando/swagger1st "0.26.0-SNAPSHOT"
:description "A ring handler that does routing based on a swagger definition."
:url "https://github.com/zalando/swagger1st"
:license {:name "ISC License"
:url "http://opensource.org/licenses/ISC"
:distribution :repo}
:scm {:url "<EMAIL>:zalando/swagger1st.git"}
:min-lein-version "2.0.0"
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/tools.logging "0.4.0"]
[circleci/clj-yaml "0.5.5"]
[prismatic/schema "1.1.6"]
[clj-time "0.13.0"]
[ring-basic-authentication "1.0.5"]
[clj-http "3.6.1"]
[cheshire "5.7.1"]]
:plugins [[lein-cloverage "1.0.9"]]
:profiles {:dev {:dependencies [[ring/ring-core "1.6.1"]
[ring/ring-devel "1.6.1"]
[ring/ring-mock "0.3.1"]
[javax.servlet/servlet-api "2.5"]
[org.slf4j/slf4j-api "1.7.25"]
[org.slf4j/jul-to-slf4j "1.7.25"]
[org.slf4j/jcl-over-slf4j "1.7.25"]
[org.apache.logging.log4j/log4j-api "2.8.2"]
[org.apache.logging.log4j/log4j-core "2.8.2"]
[org.apache.logging.log4j/log4j-slf4j-impl "2.8.2"]
[whitepages/expect-call "0.1.0"]
[criterium "0.4.4"]
[com.newrelic.agent.java/newrelic-api "3.40.0"]]}}
:test-selectors {:default (complement :performance)
:performance :performance
:all (constantly true)}
:pom-addition [:developers
[:developer
[:name "<NAME>"]
[:url "http://www.sarnowski.io"]
[:email "<EMAIL>"]
[:timezone "+1"]]
[:developer
[:name "<NAME>"]
[:email "<EMAIL>"]
[:timezone "+1"]]]
:deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2/" :creds :gpg}
"snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots/" :creds :gpg}})
| true | (defproject org.zalando/swagger1st "0.26.0-SNAPSHOT"
:description "A ring handler that does routing based on a swagger definition."
:url "https://github.com/zalando/swagger1st"
:license {:name "ISC License"
:url "http://opensource.org/licenses/ISC"
:distribution :repo}
:scm {:url "PI:EMAIL:<EMAIL>END_PI:zalando/swagger1st.git"}
:min-lein-version "2.0.0"
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/tools.logging "0.4.0"]
[circleci/clj-yaml "0.5.5"]
[prismatic/schema "1.1.6"]
[clj-time "0.13.0"]
[ring-basic-authentication "1.0.5"]
[clj-http "3.6.1"]
[cheshire "5.7.1"]]
:plugins [[lein-cloverage "1.0.9"]]
:profiles {:dev {:dependencies [[ring/ring-core "1.6.1"]
[ring/ring-devel "1.6.1"]
[ring/ring-mock "0.3.1"]
[javax.servlet/servlet-api "2.5"]
[org.slf4j/slf4j-api "1.7.25"]
[org.slf4j/jul-to-slf4j "1.7.25"]
[org.slf4j/jcl-over-slf4j "1.7.25"]
[org.apache.logging.log4j/log4j-api "2.8.2"]
[org.apache.logging.log4j/log4j-core "2.8.2"]
[org.apache.logging.log4j/log4j-slf4j-impl "2.8.2"]
[whitepages/expect-call "0.1.0"]
[criterium "0.4.4"]
[com.newrelic.agent.java/newrelic-api "3.40.0"]]}}
:test-selectors {:default (complement :performance)
:performance :performance
:all (constantly true)}
:pom-addition [:developers
[:developer
[:name "PI:NAME:<NAME>END_PI"]
[:url "http://www.sarnowski.io"]
[:email "PI:EMAIL:<EMAIL>END_PI"]
[:timezone "+1"]]
[:developer
[:name "PI:NAME:<NAME>END_PI"]
[:email "PI:EMAIL:<EMAIL>END_PI"]
[:timezone "+1"]]]
:deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2/" :creds :gpg}
"snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots/" :creds :gpg}})
|
[
{
"context": "nfig/load!)]\n (send-email\n {:from \"noreply@spreadviz.org\"\n :to \"fbielejec@gmail.com\"\n ",
"end": 1600,
"score": 0.9999111294746399,
"start": 1579,
"tag": "EMAIL",
"value": "noreply@spreadviz.org"
},
{
"context": " \"noreply@spreadviz.org\"\n :to \"fbielejec@gmail.com\"\n :template-id template-id\n :dynamic-",
"end": 1642,
"score": 0.999930739402771,
"start": 1623,
"tag": "EMAIL",
"value": "fbielejec@gmail.com"
}
] | src/clj/api/emailer/sendgrid.clj | fbielejec/SPREAD | 12 | (ns api.emailer.sendgrid
(:require [clj-http.client :as http]))
(defonce ^:private sendgrid-public-api "https://api.sendgrid.com/v3/mail/send")
(defn send-email
[{:keys [from to subject content dynamic-template-data template-id api-key print-mode?]}]
(if (and (not api-key)
(not print-mode?))
(throw (Error. "Missing api-key to send email to sendgrid"))
(if print-mode?
(do
(prn "Would send email:")
(prn "From:" from)
(prn "To:" to)
(prn "Subject:" subject)
(prn "Content:" content)
(prn "Dynamic template data:" dynamic-template-data))
(let [body (cond-> {:from {:email from}
:personalizations [(cond-> {:to [{:email to}]}
dynamic-template-data
(assoc "dynamic_template_data"
dynamic-template-data))]}
subject (assoc :subject subject)
template-id (assoc :template_id template-id)
content (assoc :content [{:type "text/html"
:value content}]))]
(http/post sendgrid-public-api
{:form-params body
:headers {"Authorization" (str "Bearer " api-key)}
:content-type :json
:accept :json})))))
(comment
(let [{{:keys [api-key template-id]} :sendgrid} (api.config/load!)]
(send-email
{:from "noreply@spreadviz.org"
:to "fbielejec@gmail.com"
:template-id template-id
:dynamic-template-data
{"header" "Login to Spread"
"body" "You requested a login link to Spread. Click on the button below"
"button-title" "Login"
"button-href" "http://nodrama.io"}
:api-key api-key})))
| 56738 | (ns api.emailer.sendgrid
(:require [clj-http.client :as http]))
(defonce ^:private sendgrid-public-api "https://api.sendgrid.com/v3/mail/send")
(defn send-email
[{:keys [from to subject content dynamic-template-data template-id api-key print-mode?]}]
(if (and (not api-key)
(not print-mode?))
(throw (Error. "Missing api-key to send email to sendgrid"))
(if print-mode?
(do
(prn "Would send email:")
(prn "From:" from)
(prn "To:" to)
(prn "Subject:" subject)
(prn "Content:" content)
(prn "Dynamic template data:" dynamic-template-data))
(let [body (cond-> {:from {:email from}
:personalizations [(cond-> {:to [{:email to}]}
dynamic-template-data
(assoc "dynamic_template_data"
dynamic-template-data))]}
subject (assoc :subject subject)
template-id (assoc :template_id template-id)
content (assoc :content [{:type "text/html"
:value content}]))]
(http/post sendgrid-public-api
{:form-params body
:headers {"Authorization" (str "Bearer " api-key)}
:content-type :json
:accept :json})))))
(comment
(let [{{:keys [api-key template-id]} :sendgrid} (api.config/load!)]
(send-email
{:from "<EMAIL>"
:to "<EMAIL>"
:template-id template-id
:dynamic-template-data
{"header" "Login to Spread"
"body" "You requested a login link to Spread. Click on the button below"
"button-title" "Login"
"button-href" "http://nodrama.io"}
:api-key api-key})))
| true | (ns api.emailer.sendgrid
(:require [clj-http.client :as http]))
(defonce ^:private sendgrid-public-api "https://api.sendgrid.com/v3/mail/send")
(defn send-email
[{:keys [from to subject content dynamic-template-data template-id api-key print-mode?]}]
(if (and (not api-key)
(not print-mode?))
(throw (Error. "Missing api-key to send email to sendgrid"))
(if print-mode?
(do
(prn "Would send email:")
(prn "From:" from)
(prn "To:" to)
(prn "Subject:" subject)
(prn "Content:" content)
(prn "Dynamic template data:" dynamic-template-data))
(let [body (cond-> {:from {:email from}
:personalizations [(cond-> {:to [{:email to}]}
dynamic-template-data
(assoc "dynamic_template_data"
dynamic-template-data))]}
subject (assoc :subject subject)
template-id (assoc :template_id template-id)
content (assoc :content [{:type "text/html"
:value content}]))]
(http/post sendgrid-public-api
{:form-params body
:headers {"Authorization" (str "Bearer " api-key)}
:content-type :json
:accept :json})))))
(comment
(let [{{:keys [api-key template-id]} :sendgrid} (api.config/load!)]
(send-email
{:from "PI:EMAIL:<EMAIL>END_PI"
:to "PI:EMAIL:<EMAIL>END_PI"
:template-id template-id
:dynamic-template-data
{"header" "Login to Spread"
"body" "You requested a login link to Spread. Click on the button below"
"button-title" "Login"
"button-href" "http://nodrama.io"}
:api-key api-key})))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.